clang API Documentation
00001 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Expr constant evaluator. 00011 // 00012 // Constant expression evaluation produces four main results: 00013 // 00014 // * A success/failure flag indicating whether constant folding was successful. 00015 // This is the 'bool' return value used by most of the code in this file. A 00016 // 'false' return value indicates that constant folding has failed, and any 00017 // appropriate diagnostic has already been produced. 00018 // 00019 // * An evaluated result, valid only if constant folding has not failed. 00020 // 00021 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 00022 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 00023 // where it is possible to determine the evaluated result regardless. 00024 // 00025 // * A set of notes indicating why the evaluation was not a constant expression 00026 // (under the C++11 rules only, at the moment), or, if folding failed too, 00027 // why the expression could not be folded. 00028 // 00029 // If we are checking for a potential constant expression, failure to constant 00030 // fold a potential constant sub-expression will be indicated by a 'false' 00031 // return value (the expression could not be folded) and no diagnostic (the 00032 // expression is not necessarily non-constant). 00033 // 00034 //===----------------------------------------------------------------------===// 00035 00036 #include "clang/AST/APValue.h" 00037 #include "clang/AST/ASTContext.h" 00038 #include "clang/AST/CharUnits.h" 00039 #include "clang/AST/RecordLayout.h" 00040 #include "clang/AST/StmtVisitor.h" 00041 #include "clang/AST/TypeLoc.h" 00042 #include "clang/AST/ASTDiagnostic.h" 00043 #include "clang/AST/Expr.h" 00044 #include "clang/Basic/Builtins.h" 00045 #include "clang/Basic/TargetInfo.h" 00046 #include "llvm/ADT/SmallString.h" 00047 #include <cstring> 00048 #include <functional> 00049 00050 using namespace clang; 00051 using llvm::APSInt; 00052 using llvm::APFloat; 00053 00054 static bool IsGlobalLValue(APValue::LValueBase B); 00055 00056 namespace { 00057 struct LValue; 00058 struct CallStackFrame; 00059 struct EvalInfo; 00060 00061 static QualType getType(APValue::LValueBase B) { 00062 if (!B) return QualType(); 00063 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) 00064 return D->getType(); 00065 return B.get<const Expr*>()->getType(); 00066 } 00067 00068 /// Get an LValue path entry, which is known to not be an array index, as a 00069 /// field or base class. 00070 static 00071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 00072 APValue::BaseOrMemberType Value; 00073 Value.setFromOpaqueValue(E.BaseOrMember); 00074 return Value; 00075 } 00076 00077 /// Get an LValue path entry, which is known to not be an array index, as a 00078 /// field declaration. 00079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 00080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 00081 } 00082 /// Get an LValue path entry, which is known to not be an array index, as a 00083 /// base class declaration. 00084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 00085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 00086 } 00087 /// Determine whether this LValue path entry for a base class names a virtual 00088 /// base class. 00089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 00090 return getAsBaseOrMember(E).getInt(); 00091 } 00092 00093 /// Find the path length and type of the most-derived subobject in the given 00094 /// path, and find the size of the containing array, if any. 00095 static 00096 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base, 00097 ArrayRef<APValue::LValuePathEntry> Path, 00098 uint64_t &ArraySize, QualType &Type) { 00099 unsigned MostDerivedLength = 0; 00100 Type = Base; 00101 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 00102 if (Type->isArrayType()) { 00103 const ConstantArrayType *CAT = 00104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type)); 00105 Type = CAT->getElementType(); 00106 ArraySize = CAT->getSize().getZExtValue(); 00107 MostDerivedLength = I + 1; 00108 } else if (Type->isAnyComplexType()) { 00109 const ComplexType *CT = Type->castAs<ComplexType>(); 00110 Type = CT->getElementType(); 00111 ArraySize = 2; 00112 MostDerivedLength = I + 1; 00113 } else if (const FieldDecl *FD = getAsField(Path[I])) { 00114 Type = FD->getType(); 00115 ArraySize = 0; 00116 MostDerivedLength = I + 1; 00117 } else { 00118 // Path[I] describes a base class. 00119 ArraySize = 0; 00120 } 00121 } 00122 return MostDerivedLength; 00123 } 00124 00125 // The order of this enum is important for diagnostics. 00126 enum CheckSubobjectKind { 00127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 00128 CSK_This, CSK_Real, CSK_Imag 00129 }; 00130 00131 /// A path from a glvalue to a subobject of that glvalue. 00132 struct SubobjectDesignator { 00133 /// True if the subobject was named in a manner not supported by C++11. Such 00134 /// lvalues can still be folded, but they are not core constant expressions 00135 /// and we cannot perform lvalue-to-rvalue conversions on them. 00136 bool Invalid : 1; 00137 00138 /// Is this a pointer one past the end of an object? 00139 bool IsOnePastTheEnd : 1; 00140 00141 /// The length of the path to the most-derived object of which this is a 00142 /// subobject. 00143 unsigned MostDerivedPathLength : 30; 00144 00145 /// The size of the array of which the most-derived object is an element, or 00146 /// 0 if the most-derived object is not an array element. 00147 uint64_t MostDerivedArraySize; 00148 00149 /// The type of the most derived object referred to by this address. 00150 QualType MostDerivedType; 00151 00152 typedef APValue::LValuePathEntry PathEntry; 00153 00154 /// The entries on the path from the glvalue to the designated subobject. 00155 SmallVector<PathEntry, 8> Entries; 00156 00157 SubobjectDesignator() : Invalid(true) {} 00158 00159 explicit SubobjectDesignator(QualType T) 00160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0), 00161 MostDerivedArraySize(0), MostDerivedType(T) {} 00162 00163 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 00164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 00165 MostDerivedPathLength(0), MostDerivedArraySize(0) { 00166 if (!Invalid) { 00167 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 00168 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 00169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 00170 if (V.getLValueBase()) 00171 MostDerivedPathLength = 00172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()), 00173 V.getLValuePath(), MostDerivedArraySize, 00174 MostDerivedType); 00175 } 00176 } 00177 00178 void setInvalid() { 00179 Invalid = true; 00180 Entries.clear(); 00181 } 00182 00183 /// Determine whether this is a one-past-the-end pointer. 00184 bool isOnePastTheEnd() const { 00185 if (IsOnePastTheEnd) 00186 return true; 00187 if (MostDerivedArraySize && 00188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 00189 return true; 00190 return false; 00191 } 00192 00193 /// Check that this refers to a valid subobject. 00194 bool isValidSubobject() const { 00195 if (Invalid) 00196 return false; 00197 return !isOnePastTheEnd(); 00198 } 00199 /// Check that this refers to a valid subobject, and if not, produce a 00200 /// relevant diagnostic and set the designator as invalid. 00201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 00202 00203 /// Update this designator to refer to the first element within this array. 00204 void addArrayUnchecked(const ConstantArrayType *CAT) { 00205 PathEntry Entry; 00206 Entry.ArrayIndex = 0; 00207 Entries.push_back(Entry); 00208 00209 // This is a most-derived object. 00210 MostDerivedType = CAT->getElementType(); 00211 MostDerivedArraySize = CAT->getSize().getZExtValue(); 00212 MostDerivedPathLength = Entries.size(); 00213 } 00214 /// Update this designator to refer to the given base or member of this 00215 /// object. 00216 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 00217 PathEntry Entry; 00218 APValue::BaseOrMemberType Value(D, Virtual); 00219 Entry.BaseOrMember = Value.getOpaqueValue(); 00220 Entries.push_back(Entry); 00221 00222 // If this isn't a base class, it's a new most-derived object. 00223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 00224 MostDerivedType = FD->getType(); 00225 MostDerivedArraySize = 0; 00226 MostDerivedPathLength = Entries.size(); 00227 } 00228 } 00229 /// Update this designator to refer to the given complex component. 00230 void addComplexUnchecked(QualType EltTy, bool Imag) { 00231 PathEntry Entry; 00232 Entry.ArrayIndex = Imag; 00233 Entries.push_back(Entry); 00234 00235 // This is technically a most-derived object, though in practice this 00236 // is unlikely to matter. 00237 MostDerivedType = EltTy; 00238 MostDerivedArraySize = 2; 00239 MostDerivedPathLength = Entries.size(); 00240 } 00241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N); 00242 /// Add N to the address of this subobject. 00243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 00244 if (Invalid) return; 00245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) { 00246 Entries.back().ArrayIndex += N; 00247 if (Entries.back().ArrayIndex > MostDerivedArraySize) { 00248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex); 00249 setInvalid(); 00250 } 00251 return; 00252 } 00253 // [expr.add]p4: For the purposes of these operators, a pointer to a 00254 // nonarray object behaves the same as a pointer to the first element of 00255 // an array of length one with the type of the object as its element type. 00256 if (IsOnePastTheEnd && N == (uint64_t)-1) 00257 IsOnePastTheEnd = false; 00258 else if (!IsOnePastTheEnd && N == 1) 00259 IsOnePastTheEnd = true; 00260 else if (N != 0) { 00261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N); 00262 setInvalid(); 00263 } 00264 } 00265 }; 00266 00267 /// A stack frame in the constexpr call stack. 00268 struct CallStackFrame { 00269 EvalInfo &Info; 00270 00271 /// Parent - The caller of this stack frame. 00272 CallStackFrame *Caller; 00273 00274 /// CallLoc - The location of the call expression for this call. 00275 SourceLocation CallLoc; 00276 00277 /// Callee - The function which was called. 00278 const FunctionDecl *Callee; 00279 00280 /// Index - The call index of this call. 00281 unsigned Index; 00282 00283 /// This - The binding for the this pointer in this call, if any. 00284 const LValue *This; 00285 00286 /// ParmBindings - Parameter bindings for this function call, indexed by 00287 /// parameters' function scope indices. 00288 const APValue *Arguments; 00289 00290 typedef llvm::DenseMap<const Expr*, APValue> MapTy; 00291 typedef MapTy::const_iterator temp_iterator; 00292 /// Temporaries - Temporary lvalues materialized within this stack frame. 00293 MapTy Temporaries; 00294 00295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 00296 const FunctionDecl *Callee, const LValue *This, 00297 const APValue *Arguments); 00298 ~CallStackFrame(); 00299 }; 00300 00301 /// A partial diagnostic which we might know in advance that we are not going 00302 /// to emit. 00303 class OptionalDiagnostic { 00304 PartialDiagnostic *Diag; 00305 00306 public: 00307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {} 00308 00309 template<typename T> 00310 OptionalDiagnostic &operator<<(const T &v) { 00311 if (Diag) 00312 *Diag << v; 00313 return *this; 00314 } 00315 00316 OptionalDiagnostic &operator<<(const APSInt &I) { 00317 if (Diag) { 00318 llvm::SmallVector<char, 32> Buffer; 00319 I.toString(Buffer); 00320 *Diag << StringRef(Buffer.data(), Buffer.size()); 00321 } 00322 return *this; 00323 } 00324 00325 OptionalDiagnostic &operator<<(const APFloat &F) { 00326 if (Diag) { 00327 llvm::SmallVector<char, 32> Buffer; 00328 F.toString(Buffer); 00329 *Diag << StringRef(Buffer.data(), Buffer.size()); 00330 } 00331 return *this; 00332 } 00333 }; 00334 00335 /// EvalInfo - This is a private struct used by the evaluator to capture 00336 /// information about a subexpression as it is folded. It retains information 00337 /// about the AST context, but also maintains information about the folded 00338 /// expression. 00339 /// 00340 /// If an expression could be evaluated, it is still possible it is not a C 00341 /// "integer constant expression" or constant expression. If not, this struct 00342 /// captures information about how and why not. 00343 /// 00344 /// One bit of information passed *into* the request for constant folding 00345 /// indicates whether the subexpression is "evaluated" or not according to C 00346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 00347 /// evaluate the expression regardless of what the RHS is, but C only allows 00348 /// certain things in certain situations. 00349 struct EvalInfo { 00350 ASTContext &Ctx; 00351 00352 /// EvalStatus - Contains information about the evaluation. 00353 Expr::EvalStatus &EvalStatus; 00354 00355 /// CurrentCall - The top of the constexpr call stack. 00356 CallStackFrame *CurrentCall; 00357 00358 /// CallStackDepth - The number of calls in the call stack right now. 00359 unsigned CallStackDepth; 00360 00361 /// NextCallIndex - The next call index to assign. 00362 unsigned NextCallIndex; 00363 00364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy; 00365 /// OpaqueValues - Values used as the common expression in a 00366 /// BinaryConditionalOperator. 00367 MapTy OpaqueValues; 00368 00369 /// BottomFrame - The frame in which evaluation started. This must be 00370 /// initialized after CurrentCall and CallStackDepth. 00371 CallStackFrame BottomFrame; 00372 00373 /// EvaluatingDecl - This is the declaration whose initializer is being 00374 /// evaluated, if any. 00375 const VarDecl *EvaluatingDecl; 00376 00377 /// EvaluatingDeclValue - This is the value being constructed for the 00378 /// declaration whose initializer is being evaluated, if any. 00379 APValue *EvaluatingDeclValue; 00380 00381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 00382 /// notes attached to it will also be stored, otherwise they will not be. 00383 bool HasActiveDiagnostic; 00384 00385 /// CheckingPotentialConstantExpression - Are we checking whether the 00386 /// expression is a potential constant expression? If so, some diagnostics 00387 /// are suppressed. 00388 bool CheckingPotentialConstantExpression; 00389 00390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S) 00391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0), 00392 CallStackDepth(0), NextCallIndex(1), 00393 BottomFrame(*this, SourceLocation(), 0, 0, 0), 00394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false), 00395 CheckingPotentialConstantExpression(false) {} 00396 00397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const { 00398 MapTy::const_iterator i = OpaqueValues.find(e); 00399 if (i == OpaqueValues.end()) return 0; 00400 return &i->second; 00401 } 00402 00403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) { 00404 EvaluatingDecl = VD; 00405 EvaluatingDeclValue = &Value; 00406 } 00407 00408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 00409 00410 bool CheckCallLimit(SourceLocation Loc) { 00411 // Don't perform any constexpr calls (other than the call we're checking) 00412 // when checking a potential constant expression. 00413 if (CheckingPotentialConstantExpression && CallStackDepth > 1) 00414 return false; 00415 if (NextCallIndex == 0) { 00416 // NextCallIndex has wrapped around. 00417 Diag(Loc, diag::note_constexpr_call_limit_exceeded); 00418 return false; 00419 } 00420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 00421 return true; 00422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded) 00423 << getLangOpts().ConstexprCallDepth; 00424 return false; 00425 } 00426 00427 CallStackFrame *getCallFrame(unsigned CallIndex) { 00428 assert(CallIndex && "no call index in getCallFrame"); 00429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 00430 // be null in this loop. 00431 CallStackFrame *Frame = CurrentCall; 00432 while (Frame->Index > CallIndex) 00433 Frame = Frame->Caller; 00434 return (Frame->Index == CallIndex) ? Frame : 0; 00435 } 00436 00437 private: 00438 /// Add a diagnostic to the diagnostics list. 00439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 00440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 00441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 00442 return EvalStatus.Diag->back().second; 00443 } 00444 00445 /// Add notes containing a call stack to the current point of evaluation. 00446 void addCallStack(unsigned Limit); 00447 00448 public: 00449 /// Diagnose that the evaluation cannot be folded. 00450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId 00451 = diag::note_invalid_subexpr_in_const_expr, 00452 unsigned ExtraNotes = 0) { 00453 // If we have a prior diagnostic, it will be noting that the expression 00454 // isn't a constant expression. This diagnostic is more important. 00455 // FIXME: We might want to show both diagnostics to the user. 00456 if (EvalStatus.Diag) { 00457 unsigned CallStackNotes = CallStackDepth - 1; 00458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 00459 if (Limit) 00460 CallStackNotes = std::min(CallStackNotes, Limit + 1); 00461 if (CheckingPotentialConstantExpression) 00462 CallStackNotes = 0; 00463 00464 HasActiveDiagnostic = true; 00465 EvalStatus.Diag->clear(); 00466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 00467 addDiag(Loc, DiagId); 00468 if (!CheckingPotentialConstantExpression) 00469 addCallStack(Limit); 00470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 00471 } 00472 HasActiveDiagnostic = false; 00473 return OptionalDiagnostic(); 00474 } 00475 00476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId 00477 = diag::note_invalid_subexpr_in_const_expr, 00478 unsigned ExtraNotes = 0) { 00479 if (EvalStatus.Diag) 00480 return Diag(E->getExprLoc(), DiagId, ExtraNotes); 00481 HasActiveDiagnostic = false; 00482 return OptionalDiagnostic(); 00483 } 00484 00485 /// Diagnose that the evaluation does not produce a C++11 core constant 00486 /// expression. 00487 template<typename LocArg> 00488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId 00489 = diag::note_invalid_subexpr_in_const_expr, 00490 unsigned ExtraNotes = 0) { 00491 // Don't override a previous diagnostic. 00492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 00493 HasActiveDiagnostic = false; 00494 return OptionalDiagnostic(); 00495 } 00496 return Diag(Loc, DiagId, ExtraNotes); 00497 } 00498 00499 /// Add a note to a prior diagnostic. 00500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 00501 if (!HasActiveDiagnostic) 00502 return OptionalDiagnostic(); 00503 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 00504 } 00505 00506 /// Add a stack of notes to a prior diagnostic. 00507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 00508 if (HasActiveDiagnostic) { 00509 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 00510 Diags.begin(), Diags.end()); 00511 } 00512 } 00513 00514 /// Should we continue evaluation as much as possible after encountering a 00515 /// construct which can't be folded? 00516 bool keepEvaluatingAfterFailure() { 00517 return CheckingPotentialConstantExpression && 00518 EvalStatus.Diag && EvalStatus.Diag->empty(); 00519 } 00520 }; 00521 00522 /// Object used to treat all foldable expressions as constant expressions. 00523 struct FoldConstant { 00524 bool Enabled; 00525 00526 explicit FoldConstant(EvalInfo &Info) 00527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() && 00528 !Info.EvalStatus.HasSideEffects) { 00529 } 00530 // Treat the value we've computed since this object was created as constant. 00531 void Fold(EvalInfo &Info) { 00532 if (Enabled && !Info.EvalStatus.Diag->empty() && 00533 !Info.EvalStatus.HasSideEffects) 00534 Info.EvalStatus.Diag->clear(); 00535 } 00536 }; 00537 00538 /// RAII object used to suppress diagnostics and side-effects from a 00539 /// speculative evaluation. 00540 class SpeculativeEvaluationRAII { 00541 EvalInfo &Info; 00542 Expr::EvalStatus Old; 00543 00544 public: 00545 SpeculativeEvaluationRAII(EvalInfo &Info, 00546 llvm::SmallVectorImpl<PartialDiagnosticAt> 00547 *NewDiag = 0) 00548 : Info(Info), Old(Info.EvalStatus) { 00549 Info.EvalStatus.Diag = NewDiag; 00550 } 00551 ~SpeculativeEvaluationRAII() { 00552 Info.EvalStatus = Old; 00553 } 00554 }; 00555 } 00556 00557 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 00558 CheckSubobjectKind CSK) { 00559 if (Invalid) 00560 return false; 00561 if (isOnePastTheEnd()) { 00562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 00563 << CSK; 00564 setInvalid(); 00565 return false; 00566 } 00567 return true; 00568 } 00569 00570 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 00571 const Expr *E, uint64_t N) { 00572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) 00573 Info.CCEDiag(E, diag::note_constexpr_array_index) 00574 << static_cast<int>(N) << /*array*/ 0 00575 << static_cast<unsigned>(MostDerivedArraySize); 00576 else 00577 Info.CCEDiag(E, diag::note_constexpr_array_index) 00578 << static_cast<int>(N) << /*non-array*/ 1; 00579 setInvalid(); 00580 } 00581 00582 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 00583 const FunctionDecl *Callee, const LValue *This, 00584 const APValue *Arguments) 00585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee), 00586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) { 00587 Info.CurrentCall = this; 00588 ++Info.CallStackDepth; 00589 } 00590 00591 CallStackFrame::~CallStackFrame() { 00592 assert(Info.CurrentCall == this && "calls retired out of order"); 00593 --Info.CallStackDepth; 00594 Info.CurrentCall = Caller; 00595 } 00596 00597 /// Produce a string describing the given constexpr call. 00598 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) { 00599 unsigned ArgIndex = 0; 00600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 00601 !isa<CXXConstructorDecl>(Frame->Callee) && 00602 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 00603 00604 if (!IsMemberCall) 00605 Out << *Frame->Callee << '('; 00606 00607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 00608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 00609 if (ArgIndex > (unsigned)IsMemberCall) 00610 Out << ", "; 00611 00612 const ParmVarDecl *Param = *I; 00613 const APValue &Arg = Frame->Arguments[ArgIndex]; 00614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 00615 00616 if (ArgIndex == 0 && IsMemberCall) 00617 Out << "->" << *Frame->Callee << '('; 00618 } 00619 00620 Out << ')'; 00621 } 00622 00623 void EvalInfo::addCallStack(unsigned Limit) { 00624 // Determine which calls to skip, if any. 00625 unsigned ActiveCalls = CallStackDepth - 1; 00626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 00627 if (Limit && Limit < ActiveCalls) { 00628 SkipStart = Limit / 2 + Limit % 2; 00629 SkipEnd = ActiveCalls - Limit / 2; 00630 } 00631 00632 // Walk the call stack and add the diagnostics. 00633 unsigned CallIdx = 0; 00634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 00635 Frame = Frame->Caller, ++CallIdx) { 00636 // Skip this call? 00637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 00638 if (CallIdx == SkipStart) { 00639 // Note that we're skipping calls. 00640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 00641 << unsigned(ActiveCalls - Limit); 00642 } 00643 continue; 00644 } 00645 00646 llvm::SmallVector<char, 128> Buffer; 00647 llvm::raw_svector_ostream Out(Buffer); 00648 describeCall(Frame, Out); 00649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 00650 } 00651 } 00652 00653 namespace { 00654 struct ComplexValue { 00655 private: 00656 bool IsInt; 00657 00658 public: 00659 APSInt IntReal, IntImag; 00660 APFloat FloatReal, FloatImag; 00661 00662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 00663 00664 void makeComplexFloat() { IsInt = false; } 00665 bool isComplexFloat() const { return !IsInt; } 00666 APFloat &getComplexFloatReal() { return FloatReal; } 00667 APFloat &getComplexFloatImag() { return FloatImag; } 00668 00669 void makeComplexInt() { IsInt = true; } 00670 bool isComplexInt() const { return IsInt; } 00671 APSInt &getComplexIntReal() { return IntReal; } 00672 APSInt &getComplexIntImag() { return IntImag; } 00673 00674 void moveInto(APValue &v) const { 00675 if (isComplexFloat()) 00676 v = APValue(FloatReal, FloatImag); 00677 else 00678 v = APValue(IntReal, IntImag); 00679 } 00680 void setFrom(const APValue &v) { 00681 assert(v.isComplexFloat() || v.isComplexInt()); 00682 if (v.isComplexFloat()) { 00683 makeComplexFloat(); 00684 FloatReal = v.getComplexFloatReal(); 00685 FloatImag = v.getComplexFloatImag(); 00686 } else { 00687 makeComplexInt(); 00688 IntReal = v.getComplexIntReal(); 00689 IntImag = v.getComplexIntImag(); 00690 } 00691 } 00692 }; 00693 00694 struct LValue { 00695 APValue::LValueBase Base; 00696 CharUnits Offset; 00697 unsigned CallIndex; 00698 SubobjectDesignator Designator; 00699 00700 const APValue::LValueBase getLValueBase() const { return Base; } 00701 CharUnits &getLValueOffset() { return Offset; } 00702 const CharUnits &getLValueOffset() const { return Offset; } 00703 unsigned getLValueCallIndex() const { return CallIndex; } 00704 SubobjectDesignator &getLValueDesignator() { return Designator; } 00705 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 00706 00707 void moveInto(APValue &V) const { 00708 if (Designator.Invalid) 00709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex); 00710 else 00711 V = APValue(Base, Offset, Designator.Entries, 00712 Designator.IsOnePastTheEnd, CallIndex); 00713 } 00714 void setFrom(ASTContext &Ctx, const APValue &V) { 00715 assert(V.isLValue()); 00716 Base = V.getLValueBase(); 00717 Offset = V.getLValueOffset(); 00718 CallIndex = V.getLValueCallIndex(); 00719 Designator = SubobjectDesignator(Ctx, V); 00720 } 00721 00722 void set(APValue::LValueBase B, unsigned I = 0) { 00723 Base = B; 00724 Offset = CharUnits::Zero(); 00725 CallIndex = I; 00726 Designator = SubobjectDesignator(getType(B)); 00727 } 00728 00729 // Check that this LValue is not based on a null pointer. If it is, produce 00730 // a diagnostic and mark the designator as invalid. 00731 bool checkNullPointer(EvalInfo &Info, const Expr *E, 00732 CheckSubobjectKind CSK) { 00733 if (Designator.Invalid) 00734 return false; 00735 if (!Base) { 00736 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 00737 << CSK; 00738 Designator.setInvalid(); 00739 return false; 00740 } 00741 return true; 00742 } 00743 00744 // Check this LValue refers to an object. If not, set the designator to be 00745 // invalid and emit a diagnostic. 00746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 00747 // Outside C++11, do not build a designator referring to a subobject of 00748 // any object: we won't use such a designator for anything. 00749 if (!Info.getLangOpts().CPlusPlus0x) 00750 Designator.setInvalid(); 00751 return checkNullPointer(Info, E, CSK) && 00752 Designator.checkSubobject(Info, E, CSK); 00753 } 00754 00755 void addDecl(EvalInfo &Info, const Expr *E, 00756 const Decl *D, bool Virtual = false) { 00757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 00758 Designator.addDeclUnchecked(D, Virtual); 00759 } 00760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 00761 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 00762 Designator.addArrayUnchecked(CAT); 00763 } 00764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 00765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 00766 Designator.addComplexUnchecked(EltTy, Imag); 00767 } 00768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 00769 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 00770 Designator.adjustIndex(Info, E, N); 00771 } 00772 }; 00773 00774 struct MemberPtr { 00775 MemberPtr() {} 00776 explicit MemberPtr(const ValueDecl *Decl) : 00777 DeclAndIsDerivedMember(Decl, false), Path() {} 00778 00779 /// The member or (direct or indirect) field referred to by this member 00780 /// pointer, or 0 if this is a null member pointer. 00781 const ValueDecl *getDecl() const { 00782 return DeclAndIsDerivedMember.getPointer(); 00783 } 00784 /// Is this actually a member of some type derived from the relevant class? 00785 bool isDerivedMember() const { 00786 return DeclAndIsDerivedMember.getInt(); 00787 } 00788 /// Get the class which the declaration actually lives in. 00789 const CXXRecordDecl *getContainingRecord() const { 00790 return cast<CXXRecordDecl>( 00791 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 00792 } 00793 00794 void moveInto(APValue &V) const { 00795 V = APValue(getDecl(), isDerivedMember(), Path); 00796 } 00797 void setFrom(const APValue &V) { 00798 assert(V.isMemberPointer()); 00799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 00800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 00801 Path.clear(); 00802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 00803 Path.insert(Path.end(), P.begin(), P.end()); 00804 } 00805 00806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 00807 /// whether the member is a member of some class derived from the class type 00808 /// of the member pointer. 00809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 00810 /// Path - The path of base/derived classes from the member declaration's 00811 /// class (exclusive) to the class type of the member pointer (inclusive). 00812 SmallVector<const CXXRecordDecl*, 4> Path; 00813 00814 /// Perform a cast towards the class of the Decl (either up or down the 00815 /// hierarchy). 00816 bool castBack(const CXXRecordDecl *Class) { 00817 assert(!Path.empty()); 00818 const CXXRecordDecl *Expected; 00819 if (Path.size() >= 2) 00820 Expected = Path[Path.size() - 2]; 00821 else 00822 Expected = getContainingRecord(); 00823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 00824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 00825 // if B does not contain the original member and is not a base or 00826 // derived class of the class containing the original member, the result 00827 // of the cast is undefined. 00828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 00829 // (D::*). We consider that to be a language defect. 00830 return false; 00831 } 00832 Path.pop_back(); 00833 return true; 00834 } 00835 /// Perform a base-to-derived member pointer cast. 00836 bool castToDerived(const CXXRecordDecl *Derived) { 00837 if (!getDecl()) 00838 return true; 00839 if (!isDerivedMember()) { 00840 Path.push_back(Derived); 00841 return true; 00842 } 00843 if (!castBack(Derived)) 00844 return false; 00845 if (Path.empty()) 00846 DeclAndIsDerivedMember.setInt(false); 00847 return true; 00848 } 00849 /// Perform a derived-to-base member pointer cast. 00850 bool castToBase(const CXXRecordDecl *Base) { 00851 if (!getDecl()) 00852 return true; 00853 if (Path.empty()) 00854 DeclAndIsDerivedMember.setInt(true); 00855 if (isDerivedMember()) { 00856 Path.push_back(Base); 00857 return true; 00858 } 00859 return castBack(Base); 00860 } 00861 }; 00862 00863 /// Compare two member pointers, which are assumed to be of the same type. 00864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 00865 if (!LHS.getDecl() || !RHS.getDecl()) 00866 return !LHS.getDecl() && !RHS.getDecl(); 00867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 00868 return false; 00869 return LHS.Path == RHS.Path; 00870 } 00871 00872 /// Kinds of constant expression checking, for diagnostics. 00873 enum CheckConstantExpressionKind { 00874 CCEK_Constant, ///< A normal constant. 00875 CCEK_ReturnValue, ///< A constexpr function return value. 00876 CCEK_MemberInit ///< A constexpr constructor mem-initializer. 00877 }; 00878 } 00879 00880 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 00881 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 00882 const LValue &This, const Expr *E, 00883 CheckConstantExpressionKind CCEK = CCEK_Constant, 00884 bool AllowNonLiteralTypes = false); 00885 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 00886 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 00887 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 00888 EvalInfo &Info); 00889 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 00890 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 00891 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 00892 EvalInfo &Info); 00893 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 00894 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 00895 00896 //===----------------------------------------------------------------------===// 00897 // Misc utilities 00898 //===----------------------------------------------------------------------===// 00899 00900 /// Should this call expression be treated as a string literal? 00901 static bool IsStringLiteralCall(const CallExpr *E) { 00902 unsigned Builtin = E->isBuiltinCall(); 00903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 00904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 00905 } 00906 00907 static bool IsGlobalLValue(APValue::LValueBase B) { 00908 // C++11 [expr.const]p3 An address constant expression is a prvalue core 00909 // constant expression of pointer type that evaluates to... 00910 00911 // ... a null pointer value, or a prvalue core constant expression of type 00912 // std::nullptr_t. 00913 if (!B) return true; 00914 00915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 00916 // ... the address of an object with static storage duration, 00917 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 00918 return VD->hasGlobalStorage(); 00919 // ... the address of a function, 00920 return isa<FunctionDecl>(D); 00921 } 00922 00923 const Expr *E = B.get<const Expr*>(); 00924 switch (E->getStmtClass()) { 00925 default: 00926 return false; 00927 case Expr::CompoundLiteralExprClass: { 00928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 00929 return CLE->isFileScope() && CLE->isLValue(); 00930 } 00931 // A string literal has static storage duration. 00932 case Expr::StringLiteralClass: 00933 case Expr::PredefinedExprClass: 00934 case Expr::ObjCStringLiteralClass: 00935 case Expr::ObjCEncodeExprClass: 00936 case Expr::CXXTypeidExprClass: 00937 case Expr::CXXUuidofExprClass: 00938 return true; 00939 case Expr::CallExprClass: 00940 return IsStringLiteralCall(cast<CallExpr>(E)); 00941 // For GCC compatibility, &&label has static storage duration. 00942 case Expr::AddrLabelExprClass: 00943 return true; 00944 // A Block literal expression may be used as the initialization value for 00945 // Block variables at global or local static scope. 00946 case Expr::BlockExprClass: 00947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 00948 case Expr::ImplicitValueInitExprClass: 00949 // FIXME: 00950 // We can never form an lvalue with an implicit value initialization as its 00951 // base through expression evaluation, so these only appear in one case: the 00952 // implicit variable declaration we invent when checking whether a constexpr 00953 // constructor can produce a constant expression. We must assume that such 00954 // an expression might be a global lvalue. 00955 return true; 00956 } 00957 } 00958 00959 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 00960 assert(Base && "no location for a null lvalue"); 00961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 00962 if (VD) 00963 Info.Note(VD->getLocation(), diag::note_declared_at); 00964 else 00965 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(), 00966 diag::note_constexpr_temporary_here); 00967 } 00968 00969 /// Check that this reference or pointer core constant expression is a valid 00970 /// value for an address or reference constant expression. Return true if we 00971 /// can fold this expression, whether or not it's a constant expression. 00972 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 00973 QualType Type, const LValue &LVal) { 00974 bool IsReferenceType = Type->isReferenceType(); 00975 00976 APValue::LValueBase Base = LVal.getLValueBase(); 00977 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 00978 00979 // Check that the object is a global. Note that the fake 'this' object we 00980 // manufacture when checking potential constant expressions is conservatively 00981 // assumed to be global here. 00982 if (!IsGlobalLValue(Base)) { 00983 if (Info.getLangOpts().CPlusPlus0x) { 00984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 00985 Info.Diag(Loc, diag::note_constexpr_non_global, 1) 00986 << IsReferenceType << !Designator.Entries.empty() 00987 << !!VD << VD; 00988 NoteLValueLocation(Info, Base); 00989 } else { 00990 Info.Diag(Loc); 00991 } 00992 // Don't allow references to temporaries to escape. 00993 return false; 00994 } 00995 assert((Info.CheckingPotentialConstantExpression || 00996 LVal.getLValueCallIndex() == 0) && 00997 "have call index for global lvalue"); 00998 00999 // Allow address constant expressions to be past-the-end pointers. This is 01000 // an extension: the standard requires them to point to an object. 01001 if (!IsReferenceType) 01002 return true; 01003 01004 // A reference constant expression must refer to an object. 01005 if (!Base) { 01006 // FIXME: diagnostic 01007 Info.CCEDiag(Loc); 01008 return true; 01009 } 01010 01011 // Does this refer one past the end of some object? 01012 if (Designator.isOnePastTheEnd()) { 01013 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 01014 Info.Diag(Loc, diag::note_constexpr_past_end, 1) 01015 << !Designator.Entries.empty() << !!VD << VD; 01016 NoteLValueLocation(Info, Base); 01017 } 01018 01019 return true; 01020 } 01021 01022 /// Check that this core constant expression is of literal type, and if not, 01023 /// produce an appropriate diagnostic. 01024 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) { 01025 if (!E->isRValue() || E->getType()->isLiteralType()) 01026 return true; 01027 01028 // Prvalue constant expressions must be of literal types. 01029 if (Info.getLangOpts().CPlusPlus0x) 01030 Info.Diag(E, diag::note_constexpr_nonliteral) 01031 << E->getType(); 01032 else 01033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01034 return false; 01035 } 01036 01037 /// Check that this core constant expression value is a valid value for a 01038 /// constant expression. If not, report an appropriate diagnostic. Does not 01039 /// check that the expression is of literal type. 01040 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 01041 QualType Type, const APValue &Value) { 01042 // Core issue 1454: For a literal constant expression of array or class type, 01043 // each subobject of its value shall have been initialized by a constant 01044 // expression. 01045 if (Value.isArray()) { 01046 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 01047 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 01048 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 01049 Value.getArrayInitializedElt(I))) 01050 return false; 01051 } 01052 if (!Value.hasArrayFiller()) 01053 return true; 01054 return CheckConstantExpression(Info, DiagLoc, EltTy, 01055 Value.getArrayFiller()); 01056 } 01057 if (Value.isUnion() && Value.getUnionField()) { 01058 return CheckConstantExpression(Info, DiagLoc, 01059 Value.getUnionField()->getType(), 01060 Value.getUnionValue()); 01061 } 01062 if (Value.isStruct()) { 01063 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 01064 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 01065 unsigned BaseIndex = 0; 01066 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 01067 End = CD->bases_end(); I != End; ++I, ++BaseIndex) { 01068 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 01069 Value.getStructBase(BaseIndex))) 01070 return false; 01071 } 01072 } 01073 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 01074 I != E; ++I) { 01075 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 01076 Value.getStructField(I->getFieldIndex()))) 01077 return false; 01078 } 01079 } 01080 01081 if (Value.isLValue()) { 01082 LValue LVal; 01083 LVal.setFrom(Info.Ctx, Value); 01084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal); 01085 } 01086 01087 // Everything else is fine. 01088 return true; 01089 } 01090 01091 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 01092 return LVal.Base.dyn_cast<const ValueDecl*>(); 01093 } 01094 01095 static bool IsLiteralLValue(const LValue &Value) { 01096 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex; 01097 } 01098 01099 static bool IsWeakLValue(const LValue &Value) { 01100 const ValueDecl *Decl = GetLValueBaseDecl(Value); 01101 return Decl && Decl->isWeak(); 01102 } 01103 01104 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 01105 // A null base expression indicates a null pointer. These are always 01106 // evaluatable, and they are false unless the offset is zero. 01107 if (!Value.getLValueBase()) { 01108 Result = !Value.getLValueOffset().isZero(); 01109 return true; 01110 } 01111 01112 // We have a non-null base. These are generally known to be true, but if it's 01113 // a weak declaration it can be null at runtime. 01114 Result = true; 01115 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 01116 return !Decl || !Decl->isWeak(); 01117 } 01118 01119 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 01120 switch (Val.getKind()) { 01121 case APValue::Uninitialized: 01122 return false; 01123 case APValue::Int: 01124 Result = Val.getInt().getBoolValue(); 01125 return true; 01126 case APValue::Float: 01127 Result = !Val.getFloat().isZero(); 01128 return true; 01129 case APValue::ComplexInt: 01130 Result = Val.getComplexIntReal().getBoolValue() || 01131 Val.getComplexIntImag().getBoolValue(); 01132 return true; 01133 case APValue::ComplexFloat: 01134 Result = !Val.getComplexFloatReal().isZero() || 01135 !Val.getComplexFloatImag().isZero(); 01136 return true; 01137 case APValue::LValue: 01138 return EvalPointerValueAsBool(Val, Result); 01139 case APValue::MemberPointer: 01140 Result = Val.getMemberPointerDecl(); 01141 return true; 01142 case APValue::Vector: 01143 case APValue::Array: 01144 case APValue::Struct: 01145 case APValue::Union: 01146 case APValue::AddrLabelDiff: 01147 return false; 01148 } 01149 01150 llvm_unreachable("unknown APValue kind"); 01151 } 01152 01153 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 01154 EvalInfo &Info) { 01155 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 01156 APValue Val; 01157 if (!Evaluate(Val, Info, E)) 01158 return false; 01159 return HandleConversionToBool(Val, Result); 01160 } 01161 01162 template<typename T> 01163 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 01164 const T &SrcValue, QualType DestType) { 01165 Info.Diag(E, diag::note_constexpr_overflow) 01166 << SrcValue << DestType; 01167 return false; 01168 } 01169 01170 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 01171 QualType SrcType, const APFloat &Value, 01172 QualType DestType, APSInt &Result) { 01173 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 01174 // Determine whether we are converting to unsigned or signed. 01175 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 01176 01177 Result = APSInt(DestWidth, !DestSigned); 01178 bool ignored; 01179 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 01180 & APFloat::opInvalidOp) 01181 return HandleOverflow(Info, E, Value, DestType); 01182 return true; 01183 } 01184 01185 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 01186 QualType SrcType, QualType DestType, 01187 APFloat &Result) { 01188 APFloat Value = Result; 01189 bool ignored; 01190 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 01191 APFloat::rmNearestTiesToEven, &ignored) 01192 & APFloat::opOverflow) 01193 return HandleOverflow(Info, E, Value, DestType); 01194 return true; 01195 } 01196 01197 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 01198 QualType DestType, QualType SrcType, 01199 APSInt &Value) { 01200 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 01201 APSInt Result = Value; 01202 // Figure out if this is a truncate, extend or noop cast. 01203 // If the input is signed, do a sign extend, noop, or truncate. 01204 Result = Result.extOrTrunc(DestWidth); 01205 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 01206 return Result; 01207 } 01208 01209 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 01210 QualType SrcType, const APSInt &Value, 01211 QualType DestType, APFloat &Result) { 01212 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 01213 if (Result.convertFromAPInt(Value, Value.isSigned(), 01214 APFloat::rmNearestTiesToEven) 01215 & APFloat::opOverflow) 01216 return HandleOverflow(Info, E, Value, DestType); 01217 return true; 01218 } 01219 01220 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 01221 llvm::APInt &Res) { 01222 APValue SVal; 01223 if (!Evaluate(SVal, Info, E)) 01224 return false; 01225 if (SVal.isInt()) { 01226 Res = SVal.getInt(); 01227 return true; 01228 } 01229 if (SVal.isFloat()) { 01230 Res = SVal.getFloat().bitcastToAPInt(); 01231 return true; 01232 } 01233 if (SVal.isVector()) { 01234 QualType VecTy = E->getType(); 01235 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 01236 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 01237 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 01238 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 01239 Res = llvm::APInt::getNullValue(VecSize); 01240 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 01241 APValue &Elt = SVal.getVectorElt(i); 01242 llvm::APInt EltAsInt; 01243 if (Elt.isInt()) { 01244 EltAsInt = Elt.getInt(); 01245 } else if (Elt.isFloat()) { 01246 EltAsInt = Elt.getFloat().bitcastToAPInt(); 01247 } else { 01248 // Don't try to handle vectors of anything other than int or float 01249 // (not sure if it's possible to hit this case). 01250 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01251 return false; 01252 } 01253 unsigned BaseEltSize = EltAsInt.getBitWidth(); 01254 if (BigEndian) 01255 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 01256 else 01257 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 01258 } 01259 return true; 01260 } 01261 // Give up if the input isn't an int, float, or vector. For example, we 01262 // reject "(v4i16)(intptr_t)&a". 01263 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01264 return false; 01265 } 01266 01267 /// Cast an lvalue referring to a base subobject to a derived class, by 01268 /// truncating the lvalue's path to the given length. 01269 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 01270 const RecordDecl *TruncatedType, 01271 unsigned TruncatedElements) { 01272 SubobjectDesignator &D = Result.Designator; 01273 01274 // Check we actually point to a derived class object. 01275 if (TruncatedElements == D.Entries.size()) 01276 return true; 01277 assert(TruncatedElements >= D.MostDerivedPathLength && 01278 "not casting to a derived class"); 01279 if (!Result.checkSubobject(Info, E, CSK_Derived)) 01280 return false; 01281 01282 // Truncate the path to the subobject, and remove any derived-to-base offsets. 01283 const RecordDecl *RD = TruncatedType; 01284 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 01285 if (RD->isInvalidDecl()) return false; 01286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 01287 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 01288 if (isVirtualBaseClass(D.Entries[I])) 01289 Result.Offset -= Layout.getVBaseClassOffset(Base); 01290 else 01291 Result.Offset -= Layout.getBaseClassOffset(Base); 01292 RD = Base; 01293 } 01294 D.Entries.resize(TruncatedElements); 01295 return true; 01296 } 01297 01298 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 01299 const CXXRecordDecl *Derived, 01300 const CXXRecordDecl *Base, 01301 const ASTRecordLayout *RL = 0) { 01302 if (!RL) { 01303 if (Derived->isInvalidDecl()) return false; 01304 RL = &Info.Ctx.getASTRecordLayout(Derived); 01305 } 01306 01307 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 01308 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 01309 return true; 01310 } 01311 01312 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 01313 const CXXRecordDecl *DerivedDecl, 01314 const CXXBaseSpecifier *Base) { 01315 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 01316 01317 if (!Base->isVirtual()) 01318 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 01319 01320 SubobjectDesignator &D = Obj.Designator; 01321 if (D.Invalid) 01322 return false; 01323 01324 // Extract most-derived object and corresponding type. 01325 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 01326 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 01327 return false; 01328 01329 // Find the virtual base class. 01330 if (DerivedDecl->isInvalidDecl()) return false; 01331 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 01332 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 01333 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 01334 return true; 01335 } 01336 01337 /// Update LVal to refer to the given field, which must be a member of the type 01338 /// currently described by LVal. 01339 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 01340 const FieldDecl *FD, 01341 const ASTRecordLayout *RL = 0) { 01342 if (!RL) { 01343 if (FD->getParent()->isInvalidDecl()) return false; 01344 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 01345 } 01346 01347 unsigned I = FD->getFieldIndex(); 01348 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)); 01349 LVal.addDecl(Info, E, FD); 01350 return true; 01351 } 01352 01353 /// Update LVal to refer to the given indirect field. 01354 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 01355 LValue &LVal, 01356 const IndirectFieldDecl *IFD) { 01357 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(), 01358 CE = IFD->chain_end(); C != CE; ++C) 01359 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C))) 01360 return false; 01361 return true; 01362 } 01363 01364 /// Get the size of the given type in char units. 01365 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 01366 QualType Type, CharUnits &Size) { 01367 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 01368 // extension. 01369 if (Type->isVoidType() || Type->isFunctionType()) { 01370 Size = CharUnits::One(); 01371 return true; 01372 } 01373 01374 if (!Type->isConstantSizeType()) { 01375 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 01376 // FIXME: Better diagnostic. 01377 Info.Diag(Loc); 01378 return false; 01379 } 01380 01381 Size = Info.Ctx.getTypeSizeInChars(Type); 01382 return true; 01383 } 01384 01385 /// Update a pointer value to model pointer arithmetic. 01386 /// \param Info - Information about the ongoing evaluation. 01387 /// \param E - The expression being evaluated, for diagnostic purposes. 01388 /// \param LVal - The pointer value to be updated. 01389 /// \param EltTy - The pointee type represented by LVal. 01390 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 01391 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 01392 LValue &LVal, QualType EltTy, 01393 int64_t Adjustment) { 01394 CharUnits SizeOfPointee; 01395 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 01396 return false; 01397 01398 // Compute the new offset in the appropriate width. 01399 LVal.Offset += Adjustment * SizeOfPointee; 01400 LVal.adjustIndex(Info, E, Adjustment); 01401 return true; 01402 } 01403 01404 /// Update an lvalue to refer to a component of a complex number. 01405 /// \param Info - Information about the ongoing evaluation. 01406 /// \param LVal - The lvalue to be updated. 01407 /// \param EltTy - The complex number's component type. 01408 /// \param Imag - False for the real component, true for the imaginary. 01409 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 01410 LValue &LVal, QualType EltTy, 01411 bool Imag) { 01412 if (Imag) { 01413 CharUnits SizeOfComponent; 01414 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 01415 return false; 01416 LVal.Offset += SizeOfComponent; 01417 } 01418 LVal.addComplex(Info, E, EltTy, Imag); 01419 return true; 01420 } 01421 01422 /// Try to evaluate the initializer for a variable declaration. 01423 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E, 01424 const VarDecl *VD, 01425 CallStackFrame *Frame, APValue &Result) { 01426 // If this is a parameter to an active constexpr function call, perform 01427 // argument substitution. 01428 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 01429 // Assume arguments of a potential constant expression are unknown 01430 // constant expressions. 01431 if (Info.CheckingPotentialConstantExpression) 01432 return false; 01433 if (!Frame || !Frame->Arguments) { 01434 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01435 return false; 01436 } 01437 Result = Frame->Arguments[PVD->getFunctionScopeIndex()]; 01438 return true; 01439 } 01440 01441 // Dig out the initializer, and use the declaration which it's attached to. 01442 const Expr *Init = VD->getAnyInitializer(VD); 01443 if (!Init || Init->isValueDependent()) { 01444 // If we're checking a potential constant expression, the variable could be 01445 // initialized later. 01446 if (!Info.CheckingPotentialConstantExpression) 01447 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01448 return false; 01449 } 01450 01451 // If we're currently evaluating the initializer of this declaration, use that 01452 // in-flight value. 01453 if (Info.EvaluatingDecl == VD) { 01454 Result = *Info.EvaluatingDeclValue; 01455 return !Result.isUninit(); 01456 } 01457 01458 // Never evaluate the initializer of a weak variable. We can't be sure that 01459 // this is the definition which will be used. 01460 if (VD->isWeak()) { 01461 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01462 return false; 01463 } 01464 01465 // Check that we can fold the initializer. In C++, we will have already done 01466 // this in the cases where it matters for conformance. 01467 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 01468 if (!VD->evaluateValue(Notes)) { 01469 Info.Diag(E, diag::note_constexpr_var_init_non_constant, 01470 Notes.size() + 1) << VD; 01471 Info.Note(VD->getLocation(), diag::note_declared_at); 01472 Info.addNotes(Notes); 01473 return false; 01474 } else if (!VD->checkInitIsICE()) { 01475 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 01476 Notes.size() + 1) << VD; 01477 Info.Note(VD->getLocation(), diag::note_declared_at); 01478 Info.addNotes(Notes); 01479 } 01480 01481 Result = *VD->getEvaluatedValue(); 01482 return true; 01483 } 01484 01485 static bool IsConstNonVolatile(QualType T) { 01486 Qualifiers Quals = T.getQualifiers(); 01487 return Quals.hasConst() && !Quals.hasVolatile(); 01488 } 01489 01490 /// Get the base index of the given base class within an APValue representing 01491 /// the given derived class. 01492 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 01493 const CXXRecordDecl *Base) { 01494 Base = Base->getCanonicalDecl(); 01495 unsigned Index = 0; 01496 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 01497 E = Derived->bases_end(); I != E; ++I, ++Index) { 01498 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 01499 return Index; 01500 } 01501 01502 llvm_unreachable("base class missing from derived class's bases list"); 01503 } 01504 01505 /// Extract the value of a character from a string literal. CharType is used to 01506 /// determine the expected signedness of the result -- a string literal used to 01507 /// initialize an array of 'signed char' or 'unsigned char' might contain chars 01508 /// of the wrong signedness. 01509 static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 01510 uint64_t Index, QualType CharType) { 01511 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant 01512 const StringLiteral *S = dyn_cast<StringLiteral>(Lit); 01513 assert(S && "unexpected string literal expression kind"); 01514 assert(CharType->isIntegerType() && "unexpected character type"); 01515 01516 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 01517 CharType->isUnsignedIntegerType()); 01518 if (Index < S->getLength()) 01519 Value = S->getCodeUnit(Index); 01520 return Value; 01521 } 01522 01523 /// Extract the designated sub-object of an rvalue. 01524 static bool ExtractSubobject(EvalInfo &Info, const Expr *E, 01525 APValue &Obj, QualType ObjType, 01526 const SubobjectDesignator &Sub, QualType SubType) { 01527 if (Sub.Invalid) 01528 // A diagnostic will have already been produced. 01529 return false; 01530 if (Sub.isOnePastTheEnd()) { 01531 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ? 01532 (unsigned)diag::note_constexpr_read_past_end : 01533 (unsigned)diag::note_invalid_subexpr_in_const_expr); 01534 return false; 01535 } 01536 if (Sub.Entries.empty()) 01537 return true; 01538 if (Info.CheckingPotentialConstantExpression && Obj.isUninit()) 01539 // This object might be initialized later. 01540 return false; 01541 01542 APValue *O = &Obj; 01543 // Walk the designator's path to find the subobject. 01544 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) { 01545 if (ObjType->isArrayType()) { 01546 // Next subobject is an array element. 01547 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 01548 assert(CAT && "vla in literal type?"); 01549 uint64_t Index = Sub.Entries[I].ArrayIndex; 01550 if (CAT->getSize().ule(Index)) { 01551 // Note, it should not be possible to form a pointer with a valid 01552 // designator which points more than one past the end of the array. 01553 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ? 01554 (unsigned)diag::note_constexpr_read_past_end : 01555 (unsigned)diag::note_invalid_subexpr_in_const_expr); 01556 return false; 01557 } 01558 // An array object is represented as either an Array APValue or as an 01559 // LValue which refers to a string literal. 01560 if (O->isLValue()) { 01561 assert(I == N - 1 && "extracting subobject of character?"); 01562 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 01563 Obj = APValue(ExtractStringLiteralCharacter( 01564 Info, O->getLValueBase().get<const Expr*>(), Index, SubType)); 01565 return true; 01566 } else if (O->getArrayInitializedElts() > Index) 01567 O = &O->getArrayInitializedElt(Index); 01568 else 01569 O = &O->getArrayFiller(); 01570 ObjType = CAT->getElementType(); 01571 } else if (ObjType->isAnyComplexType()) { 01572 // Next subobject is a complex number. 01573 uint64_t Index = Sub.Entries[I].ArrayIndex; 01574 if (Index > 1) { 01575 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ? 01576 (unsigned)diag::note_constexpr_read_past_end : 01577 (unsigned)diag::note_invalid_subexpr_in_const_expr); 01578 return false; 01579 } 01580 assert(I == N - 1 && "extracting subobject of scalar?"); 01581 if (O->isComplexInt()) { 01582 Obj = APValue(Index ? O->getComplexIntImag() 01583 : O->getComplexIntReal()); 01584 } else { 01585 assert(O->isComplexFloat()); 01586 Obj = APValue(Index ? O->getComplexFloatImag() 01587 : O->getComplexFloatReal()); 01588 } 01589 return true; 01590 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 01591 if (Field->isMutable()) { 01592 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) 01593 << Field; 01594 Info.Note(Field->getLocation(), diag::note_declared_at); 01595 return false; 01596 } 01597 01598 // Next subobject is a class, struct or union field. 01599 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 01600 if (RD->isUnion()) { 01601 const FieldDecl *UnionField = O->getUnionField(); 01602 if (!UnionField || 01603 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 01604 Info.Diag(E, diag::note_constexpr_read_inactive_union_member) 01605 << Field << !UnionField << UnionField; 01606 return false; 01607 } 01608 O = &O->getUnionValue(); 01609 } else 01610 O = &O->getStructField(Field->getFieldIndex()); 01611 ObjType = Field->getType(); 01612 01613 if (ObjType.isVolatileQualified()) { 01614 if (Info.getLangOpts().CPlusPlus) { 01615 // FIXME: Include a description of the path to the volatile subobject. 01616 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1) 01617 << 2 << Field; 01618 Info.Note(Field->getLocation(), diag::note_declared_at); 01619 } else { 01620 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 01621 } 01622 return false; 01623 } 01624 } else { 01625 // Next subobject is a base class. 01626 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 01627 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 01628 O = &O->getStructBase(getBaseIndex(Derived, Base)); 01629 ObjType = Info.Ctx.getRecordType(Base); 01630 } 01631 01632 if (O->isUninit()) { 01633 if (!Info.CheckingPotentialConstantExpression) 01634 Info.Diag(E, diag::note_constexpr_read_uninit); 01635 return false; 01636 } 01637 } 01638 01639 // This may look super-stupid, but it serves an important purpose: if we just 01640 // swapped Obj and *O, we'd create an object which had itself as a subobject. 01641 // To avoid the leak, we ensure that Tmp ends up owning the original complete 01642 // object, which is destroyed by Tmp's destructor. 01643 APValue Tmp; 01644 O->swap(Tmp); 01645 Obj.swap(Tmp); 01646 return true; 01647 } 01648 01649 /// Find the position where two subobject designators diverge, or equivalently 01650 /// the length of the common initial subsequence. 01651 static unsigned FindDesignatorMismatch(QualType ObjType, 01652 const SubobjectDesignator &A, 01653 const SubobjectDesignator &B, 01654 bool &WasArrayIndex) { 01655 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 01656 for (/**/; I != N; ++I) { 01657 if (!ObjType.isNull() && 01658 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 01659 // Next subobject is an array element. 01660 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 01661 WasArrayIndex = true; 01662 return I; 01663 } 01664 if (ObjType->isAnyComplexType()) 01665 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 01666 else 01667 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 01668 } else { 01669 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 01670 WasArrayIndex = false; 01671 return I; 01672 } 01673 if (const FieldDecl *FD = getAsField(A.Entries[I])) 01674 // Next subobject is a field. 01675 ObjType = FD->getType(); 01676 else 01677 // Next subobject is a base class. 01678 ObjType = QualType(); 01679 } 01680 } 01681 WasArrayIndex = false; 01682 return I; 01683 } 01684 01685 /// Determine whether the given subobject designators refer to elements of the 01686 /// same array object. 01687 static bool AreElementsOfSameArray(QualType ObjType, 01688 const SubobjectDesignator &A, 01689 const SubobjectDesignator &B) { 01690 if (A.Entries.size() != B.Entries.size()) 01691 return false; 01692 01693 bool IsArray = A.MostDerivedArraySize != 0; 01694 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 01695 // A is a subobject of the array element. 01696 return false; 01697 01698 // If A (and B) designates an array element, the last entry will be the array 01699 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 01700 // of length 1' case, and the entire path must match. 01701 bool WasArrayIndex; 01702 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 01703 return CommonLength >= A.Entries.size() - IsArray; 01704 } 01705 01706 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on 01707 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions 01708 /// for looking up the glvalue referred to by an entity of reference type. 01709 /// 01710 /// \param Info - Information about the ongoing evaluation. 01711 /// \param Conv - The expression for which we are performing the conversion. 01712 /// Used for diagnostics. 01713 /// \param Type - The type we expect this conversion to produce, before 01714 /// stripping cv-qualifiers in the case of a non-clas type. 01715 /// \param LVal - The glvalue on which we are attempting to perform this action. 01716 /// \param RVal - The produced value will be placed here. 01717 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 01718 QualType Type, 01719 const LValue &LVal, APValue &RVal) { 01720 if (LVal.Designator.Invalid) 01721 // A diagnostic will have already been produced. 01722 return false; 01723 01724 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 01725 01726 if (!LVal.Base) { 01727 // FIXME: Indirection through a null pointer deserves a specific diagnostic. 01728 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr); 01729 return false; 01730 } 01731 01732 CallStackFrame *Frame = 0; 01733 if (LVal.CallIndex) { 01734 Frame = Info.getCallFrame(LVal.CallIndex); 01735 if (!Frame) { 01736 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base; 01737 NoteLValueLocation(Info, LVal.Base); 01738 return false; 01739 } 01740 } 01741 01742 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 01743 // is not a constant expression (even if the object is non-volatile). We also 01744 // apply this rule to C++98, in order to conform to the expected 'volatile' 01745 // semantics. 01746 if (Type.isVolatileQualified()) { 01747 if (Info.getLangOpts().CPlusPlus) 01748 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type; 01749 else 01750 Info.Diag(Conv); 01751 return false; 01752 } 01753 01754 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 01755 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 01756 // In C++11, constexpr, non-volatile variables initialized with constant 01757 // expressions are constant expressions too. Inside constexpr functions, 01758 // parameters are constant expressions even if they're non-const. 01759 // In C, such things can also be folded, although they are not ICEs. 01760 const VarDecl *VD = dyn_cast<VarDecl>(D); 01761 if (VD) { 01762 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 01763 VD = VDef; 01764 } 01765 if (!VD || VD->isInvalidDecl()) { 01766 Info.Diag(Conv); 01767 return false; 01768 } 01769 01770 // DR1313: If the object is volatile-qualified but the glvalue was not, 01771 // behavior is undefined so the result is not a constant expression. 01772 QualType VT = VD->getType(); 01773 if (VT.isVolatileQualified()) { 01774 if (Info.getLangOpts().CPlusPlus) { 01775 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD; 01776 Info.Note(VD->getLocation(), diag::note_declared_at); 01777 } else { 01778 Info.Diag(Conv); 01779 } 01780 return false; 01781 } 01782 01783 if (!isa<ParmVarDecl>(VD)) { 01784 if (VD->isConstexpr()) { 01785 // OK, we can read this variable. 01786 } else if (VT->isIntegralOrEnumerationType()) { 01787 if (!VT.isConstQualified()) { 01788 if (Info.getLangOpts().CPlusPlus) { 01789 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD; 01790 Info.Note(VD->getLocation(), diag::note_declared_at); 01791 } else { 01792 Info.Diag(Conv); 01793 } 01794 return false; 01795 } 01796 } else if (VT->isFloatingType() && VT.isConstQualified()) { 01797 // We support folding of const floating-point types, in order to make 01798 // static const data members of such types (supported as an extension) 01799 // more useful. 01800 if (Info.getLangOpts().CPlusPlus0x) { 01801 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 01802 Info.Note(VD->getLocation(), diag::note_declared_at); 01803 } else { 01804 Info.CCEDiag(Conv); 01805 } 01806 } else { 01807 // FIXME: Allow folding of values of any literal type in all languages. 01808 if (Info.getLangOpts().CPlusPlus0x) { 01809 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 01810 Info.Note(VD->getLocation(), diag::note_declared_at); 01811 } else { 01812 Info.Diag(Conv); 01813 } 01814 return false; 01815 } 01816 } 01817 01818 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal)) 01819 return false; 01820 01821 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue()) 01822 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type); 01823 01824 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue 01825 // conversion. This happens when the declaration and the lvalue should be 01826 // considered synonymous, for instance when initializing an array of char 01827 // from a string literal. Continue as if the initializer lvalue was the 01828 // value we were originally given. 01829 assert(RVal.getLValueOffset().isZero() && 01830 "offset for lvalue init of non-reference"); 01831 Base = RVal.getLValueBase().get<const Expr*>(); 01832 01833 if (unsigned CallIndex = RVal.getLValueCallIndex()) { 01834 Frame = Info.getCallFrame(CallIndex); 01835 if (!Frame) { 01836 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base; 01837 NoteLValueLocation(Info, RVal.getLValueBase()); 01838 return false; 01839 } 01840 } else { 01841 Frame = 0; 01842 } 01843 } 01844 01845 // Volatile temporary objects cannot be read in constant expressions. 01846 if (Base->getType().isVolatileQualified()) { 01847 if (Info.getLangOpts().CPlusPlus) { 01848 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0; 01849 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 01850 } else { 01851 Info.Diag(Conv); 01852 } 01853 return false; 01854 } 01855 01856 if (Frame) { 01857 // If this is a temporary expression with a nontrivial initializer, grab the 01858 // value from the relevant stack frame. 01859 RVal = Frame->Temporaries[Base]; 01860 } else if (const CompoundLiteralExpr *CLE 01861 = dyn_cast<CompoundLiteralExpr>(Base)) { 01862 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 01863 // initializer until now for such expressions. Such an expression can't be 01864 // an ICE in C, so this only matters for fold. 01865 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 01866 if (!Evaluate(RVal, Info, CLE->getInitializer())) 01867 return false; 01868 } else if (isa<StringLiteral>(Base)) { 01869 // We represent a string literal array as an lvalue pointing at the 01870 // corresponding expression, rather than building an array of chars. 01871 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant 01872 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 01873 } else { 01874 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr); 01875 return false; 01876 } 01877 01878 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator, 01879 Type); 01880 } 01881 01882 /// Build an lvalue for the object argument of a member function call. 01883 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 01884 LValue &This) { 01885 if (Object->getType()->isPointerType()) 01886 return EvaluatePointer(Object, This, Info); 01887 01888 if (Object->isGLValue()) 01889 return EvaluateLValue(Object, This, Info); 01890 01891 if (Object->getType()->isLiteralType()) 01892 return EvaluateTemporary(Object, This, Info); 01893 01894 return false; 01895 } 01896 01897 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 01898 /// lvalue referring to the result. 01899 /// 01900 /// \param Info - Information about the ongoing evaluation. 01901 /// \param BO - The member pointer access operation. 01902 /// \param LV - Filled in with a reference to the resulting object. 01903 /// \param IncludeMember - Specifies whether the member itself is included in 01904 /// the resulting LValue subobject designator. This is not possible when 01905 /// creating a bound member function. 01906 /// \return The field or method declaration to which the member pointer refers, 01907 /// or 0 if evaluation fails. 01908 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 01909 const BinaryOperator *BO, 01910 LValue &LV, 01911 bool IncludeMember = true) { 01912 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 01913 01914 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV); 01915 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure()) 01916 return 0; 01917 01918 MemberPtr MemPtr; 01919 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info)) 01920 return 0; 01921 01922 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 01923 // member value, the behavior is undefined. 01924 if (!MemPtr.getDecl()) 01925 return 0; 01926 01927 if (!EvalObjOK) 01928 return 0; 01929 01930 if (MemPtr.isDerivedMember()) { 01931 // This is a member of some derived class. Truncate LV appropriately. 01932 // The end of the derived-to-base path for the base object must match the 01933 // derived-to-base path for the member pointer. 01934 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 01935 LV.Designator.Entries.size()) 01936 return 0; 01937 unsigned PathLengthToMember = 01938 LV.Designator.Entries.size() - MemPtr.Path.size(); 01939 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 01940 const CXXRecordDecl *LVDecl = getAsBaseClass( 01941 LV.Designator.Entries[PathLengthToMember + I]); 01942 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 01943 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) 01944 return 0; 01945 } 01946 01947 // Truncate the lvalue to the appropriate derived class. 01948 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(), 01949 PathLengthToMember)) 01950 return 0; 01951 } else if (!MemPtr.Path.empty()) { 01952 // Extend the LValue path with the member pointer's path. 01953 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 01954 MemPtr.Path.size() + IncludeMember); 01955 01956 // Walk down to the appropriate base class. 01957 QualType LVType = BO->getLHS()->getType(); 01958 if (const PointerType *PT = LVType->getAs<PointerType>()) 01959 LVType = PT->getPointeeType(); 01960 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 01961 assert(RD && "member pointer access on non-class-type expression"); 01962 // The first class in the path is that of the lvalue. 01963 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 01964 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 01965 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base)) 01966 return 0; 01967 RD = Base; 01968 } 01969 // Finally cast to the class containing the member. 01970 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord())) 01971 return 0; 01972 } 01973 01974 // Add the member. Note that we cannot build bound member functions here. 01975 if (IncludeMember) { 01976 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 01977 if (!HandleLValueMember(Info, BO, LV, FD)) 01978 return 0; 01979 } else if (const IndirectFieldDecl *IFD = 01980 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 01981 if (!HandleLValueIndirectMember(Info, BO, LV, IFD)) 01982 return 0; 01983 } else { 01984 llvm_unreachable("can't construct reference to bound member function"); 01985 } 01986 } 01987 01988 return MemPtr.getDecl(); 01989 } 01990 01991 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 01992 /// the provided lvalue, which currently refers to the base object. 01993 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 01994 LValue &Result) { 01995 SubobjectDesignator &D = Result.Designator; 01996 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 01997 return false; 01998 01999 QualType TargetQT = E->getType(); 02000 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 02001 TargetQT = PT->getPointeeType(); 02002 02003 // Check this cast lands within the final derived-to-base subobject path. 02004 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 02005 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 02006 << D.MostDerivedType << TargetQT; 02007 return false; 02008 } 02009 02010 // Check the type of the final cast. We don't need to check the path, 02011 // since a cast can only be formed if the path is unique. 02012 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 02013 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 02014 const CXXRecordDecl *FinalType; 02015 if (NewEntriesSize == D.MostDerivedPathLength) 02016 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 02017 else 02018 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 02019 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 02020 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 02021 << D.MostDerivedType << TargetQT; 02022 return false; 02023 } 02024 02025 // Truncate the lvalue to the appropriate derived class. 02026 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 02027 } 02028 02029 namespace { 02030 enum EvalStmtResult { 02031 /// Evaluation failed. 02032 ESR_Failed, 02033 /// Hit a 'return' statement. 02034 ESR_Returned, 02035 /// Evaluation succeeded. 02036 ESR_Succeeded 02037 }; 02038 } 02039 02040 // Evaluate a statement. 02041 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info, 02042 const Stmt *S) { 02043 switch (S->getStmtClass()) { 02044 default: 02045 return ESR_Failed; 02046 02047 case Stmt::NullStmtClass: 02048 case Stmt::DeclStmtClass: 02049 return ESR_Succeeded; 02050 02051 case Stmt::ReturnStmtClass: { 02052 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 02053 if (!Evaluate(Result, Info, RetExpr)) 02054 return ESR_Failed; 02055 return ESR_Returned; 02056 } 02057 02058 case Stmt::CompoundStmtClass: { 02059 const CompoundStmt *CS = cast<CompoundStmt>(S); 02060 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 02061 BE = CS->body_end(); BI != BE; ++BI) { 02062 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 02063 if (ESR != ESR_Succeeded) 02064 return ESR; 02065 } 02066 return ESR_Succeeded; 02067 } 02068 } 02069 } 02070 02071 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 02072 /// default constructor. If so, we'll fold it whether or not it's marked as 02073 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 02074 /// so we need special handling. 02075 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 02076 const CXXConstructorDecl *CD, 02077 bool IsValueInitialization) { 02078 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 02079 return false; 02080 02081 // Value-initialization does not call a trivial default constructor, so such a 02082 // call is a core constant expression whether or not the constructor is 02083 // constexpr. 02084 if (!CD->isConstexpr() && !IsValueInitialization) { 02085 if (Info.getLangOpts().CPlusPlus0x) { 02086 // FIXME: If DiagDecl is an implicitly-declared special member function, 02087 // we should be much more explicit about why it's not constexpr. 02088 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 02089 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 02090 Info.Note(CD->getLocation(), diag::note_declared_at); 02091 } else { 02092 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 02093 } 02094 } 02095 return true; 02096 } 02097 02098 /// CheckConstexprFunction - Check that a function can be called in a constant 02099 /// expression. 02100 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 02101 const FunctionDecl *Declaration, 02102 const FunctionDecl *Definition) { 02103 // Potential constant expressions can contain calls to declared, but not yet 02104 // defined, constexpr functions. 02105 if (Info.CheckingPotentialConstantExpression && !Definition && 02106 Declaration->isConstexpr()) 02107 return false; 02108 02109 // Can we evaluate this function call? 02110 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl()) 02111 return true; 02112 02113 if (Info.getLangOpts().CPlusPlus0x) { 02114 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 02115 // FIXME: If DiagDecl is an implicitly-declared special member function, we 02116 // should be much more explicit about why it's not constexpr. 02117 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1) 02118 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl) 02119 << DiagDecl; 02120 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 02121 } else { 02122 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 02123 } 02124 return false; 02125 } 02126 02127 namespace { 02128 typedef SmallVector<APValue, 8> ArgVector; 02129 } 02130 02131 /// EvaluateArgs - Evaluate the arguments to a function call. 02132 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 02133 EvalInfo &Info) { 02134 bool Success = true; 02135 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 02136 I != E; ++I) { 02137 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 02138 // If we're checking for a potential constant expression, evaluate all 02139 // initializers even if some of them fail. 02140 if (!Info.keepEvaluatingAfterFailure()) 02141 return false; 02142 Success = false; 02143 } 02144 } 02145 return Success; 02146 } 02147 02148 /// Evaluate a function call. 02149 static bool HandleFunctionCall(SourceLocation CallLoc, 02150 const FunctionDecl *Callee, const LValue *This, 02151 ArrayRef<const Expr*> Args, const Stmt *Body, 02152 EvalInfo &Info, APValue &Result) { 02153 ArgVector ArgValues(Args.size()); 02154 if (!EvaluateArgs(Args, ArgValues, Info)) 02155 return false; 02156 02157 if (!Info.CheckCallLimit(CallLoc)) 02158 return false; 02159 02160 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 02161 return EvaluateStmt(Result, Info, Body) == ESR_Returned; 02162 } 02163 02164 /// Evaluate a constructor call. 02165 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This, 02166 ArrayRef<const Expr*> Args, 02167 const CXXConstructorDecl *Definition, 02168 EvalInfo &Info, APValue &Result) { 02169 ArgVector ArgValues(Args.size()); 02170 if (!EvaluateArgs(Args, ArgValues, Info)) 02171 return false; 02172 02173 if (!Info.CheckCallLimit(CallLoc)) 02174 return false; 02175 02176 const CXXRecordDecl *RD = Definition->getParent(); 02177 if (RD->getNumVBases()) { 02178 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD; 02179 return false; 02180 } 02181 02182 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data()); 02183 02184 // If it's a delegating constructor, just delegate. 02185 if (Definition->isDelegatingConstructor()) { 02186 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 02187 return EvaluateInPlace(Result, Info, This, (*I)->getInit()); 02188 } 02189 02190 // For a trivial copy or move constructor, perform an APValue copy. This is 02191 // essential for unions, where the operations performed by the constructor 02192 // cannot be represented by ctor-initializers. 02193 if (Definition->isDefaulted() && 02194 ((Definition->isCopyConstructor() && Definition->isTrivial()) || 02195 (Definition->isMoveConstructor() && Definition->isTrivial()))) { 02196 LValue RHS; 02197 RHS.setFrom(Info.Ctx, ArgValues[0]); 02198 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 02199 RHS, Result); 02200 } 02201 02202 // Reserve space for the struct members. 02203 if (!RD->isUnion() && Result.isUninit()) 02204 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 02205 std::distance(RD->field_begin(), RD->field_end())); 02206 02207 if (RD->isInvalidDecl()) return false; 02208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 02209 02210 bool Success = true; 02211 unsigned BasesSeen = 0; 02212 #ifndef NDEBUG 02213 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 02214 #endif 02215 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(), 02216 E = Definition->init_end(); I != E; ++I) { 02217 LValue Subobject = This; 02218 APValue *Value = &Result; 02219 02220 // Determine the subobject to initialize. 02221 if ((*I)->isBaseInitializer()) { 02222 QualType BaseType((*I)->getBaseClass(), 0); 02223 #ifndef NDEBUG 02224 // Non-virtual base classes are initialized in the order in the class 02225 // definition. We have already checked for virtual base classes. 02226 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 02227 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 02228 "base class initializers not in expected order"); 02229 ++BaseIt; 02230 #endif 02231 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD, 02232 BaseType->getAsCXXRecordDecl(), &Layout)) 02233 return false; 02234 Value = &Result.getStructBase(BasesSeen++); 02235 } else if (FieldDecl *FD = (*I)->getMember()) { 02236 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout)) 02237 return false; 02238 if (RD->isUnion()) { 02239 Result = APValue(FD); 02240 Value = &Result.getUnionValue(); 02241 } else { 02242 Value = &Result.getStructField(FD->getFieldIndex()); 02243 } 02244 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) { 02245 // Walk the indirect field decl's chain to find the object to initialize, 02246 // and make sure we've initialized every step along it. 02247 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(), 02248 CE = IFD->chain_end(); 02249 C != CE; ++C) { 02250 FieldDecl *FD = cast<FieldDecl>(*C); 02251 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 02252 // Switch the union field if it differs. This happens if we had 02253 // preceding zero-initialization, and we're now initializing a union 02254 // subobject other than the first. 02255 // FIXME: In this case, the values of the other subobjects are 02256 // specified, since zero-initialization sets all padding bits to zero. 02257 if (Value->isUninit() || 02258 (Value->isUnion() && Value->getUnionField() != FD)) { 02259 if (CD->isUnion()) 02260 *Value = APValue(FD); 02261 else 02262 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 02263 std::distance(CD->field_begin(), CD->field_end())); 02264 } 02265 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD)) 02266 return false; 02267 if (CD->isUnion()) 02268 Value = &Value->getUnionValue(); 02269 else 02270 Value = &Value->getStructField(FD->getFieldIndex()); 02271 } 02272 } else { 02273 llvm_unreachable("unknown base initializer kind"); 02274 } 02275 02276 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(), 02277 (*I)->isBaseInitializer() 02278 ? CCEK_Constant : CCEK_MemberInit)) { 02279 // If we're checking for a potential constant expression, evaluate all 02280 // initializers even if some of them fail. 02281 if (!Info.keepEvaluatingAfterFailure()) 02282 return false; 02283 Success = false; 02284 } 02285 } 02286 02287 return Success; 02288 } 02289 02290 namespace { 02291 class HasSideEffect 02292 : public ConstStmtVisitor<HasSideEffect, bool> { 02293 const ASTContext &Ctx; 02294 public: 02295 02296 HasSideEffect(const ASTContext &C) : Ctx(C) {} 02297 02298 // Unhandled nodes conservatively default to having side effects. 02299 bool VisitStmt(const Stmt *S) { 02300 return true; 02301 } 02302 02303 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } 02304 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) { 02305 return Visit(E->getResultExpr()); 02306 } 02307 bool VisitDeclRefExpr(const DeclRefExpr *E) { 02308 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 02309 return true; 02310 return false; 02311 } 02312 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) { 02313 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 02314 return true; 02315 return false; 02316 } 02317 02318 // We don't want to evaluate BlockExprs multiple times, as they generate 02319 // a ton of code. 02320 bool VisitBlockExpr(const BlockExpr *E) { return true; } 02321 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; } 02322 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) 02323 { return Visit(E->getInitializer()); } 02324 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); } 02325 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; } 02326 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; } 02327 bool VisitStringLiteral(const StringLiteral *E) { return false; } 02328 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; } 02329 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) 02330 { return false; } 02331 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E) 02332 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 02333 bool VisitChooseExpr(const ChooseExpr *E) 02334 { return Visit(E->getChosenSubExpr(Ctx)); } 02335 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); } 02336 bool VisitBinAssign(const BinaryOperator *E) { return true; } 02337 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; } 02338 bool VisitBinaryOperator(const BinaryOperator *E) 02339 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 02340 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; } 02341 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; } 02342 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; } 02343 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; } 02344 bool VisitUnaryDeref(const UnaryOperator *E) { 02345 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 02346 return true; 02347 return Visit(E->getSubExpr()); 02348 } 02349 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); } 02350 02351 // Has side effects if any element does. 02352 bool VisitInitListExpr(const InitListExpr *E) { 02353 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i) 02354 if (Visit(E->getInit(i))) return true; 02355 if (const Expr *filler = E->getArrayFiller()) 02356 return Visit(filler); 02357 return false; 02358 } 02359 02360 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; } 02361 }; 02362 02363 class OpaqueValueEvaluation { 02364 EvalInfo &info; 02365 OpaqueValueExpr *opaqueValue; 02366 02367 public: 02368 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue, 02369 Expr *value) 02370 : info(info), opaqueValue(opaqueValue) { 02371 02372 // If evaluation fails, fail immediately. 02373 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) { 02374 this->opaqueValue = 0; 02375 return; 02376 } 02377 } 02378 02379 bool hasError() const { return opaqueValue == 0; } 02380 02381 ~OpaqueValueEvaluation() { 02382 // FIXME: For a recursive constexpr call, an outer stack frame might have 02383 // been using this opaque value too, and will now have to re-evaluate the 02384 // source expression. 02385 if (opaqueValue) info.OpaqueValues.erase(opaqueValue); 02386 } 02387 }; 02388 02389 } // end anonymous namespace 02390 02391 //===----------------------------------------------------------------------===// 02392 // Generic Evaluation 02393 //===----------------------------------------------------------------------===// 02394 namespace { 02395 02396 // FIXME: RetTy is always bool. Remove it. 02397 template <class Derived, typename RetTy=bool> 02398 class ExprEvaluatorBase 02399 : public ConstStmtVisitor<Derived, RetTy> { 02400 private: 02401 RetTy DerivedSuccess(const APValue &V, const Expr *E) { 02402 return static_cast<Derived*>(this)->Success(V, E); 02403 } 02404 RetTy DerivedZeroInitialization(const Expr *E) { 02405 return static_cast<Derived*>(this)->ZeroInitialization(E); 02406 } 02407 02408 // Check whether a conditional operator with a non-constant condition is a 02409 // potential constant expression. If neither arm is a potential constant 02410 // expression, then the conditional operator is not either. 02411 template<typename ConditionalOperator> 02412 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 02413 assert(Info.CheckingPotentialConstantExpression); 02414 02415 // Speculatively evaluate both arms. 02416 { 02417 llvm::SmallVector<PartialDiagnosticAt, 8> Diag; 02418 SpeculativeEvaluationRAII Speculate(Info, &Diag); 02419 02420 StmtVisitorTy::Visit(E->getFalseExpr()); 02421 if (Diag.empty()) 02422 return; 02423 02424 Diag.clear(); 02425 StmtVisitorTy::Visit(E->getTrueExpr()); 02426 if (Diag.empty()) 02427 return; 02428 } 02429 02430 Error(E, diag::note_constexpr_conditional_never_const); 02431 } 02432 02433 02434 template<typename ConditionalOperator> 02435 bool HandleConditionalOperator(const ConditionalOperator *E) { 02436 bool BoolResult; 02437 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 02438 if (Info.CheckingPotentialConstantExpression) 02439 CheckPotentialConstantConditional(E); 02440 return false; 02441 } 02442 02443 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 02444 return StmtVisitorTy::Visit(EvalExpr); 02445 } 02446 02447 protected: 02448 EvalInfo &Info; 02449 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy; 02450 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 02451 02452 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 02453 return Info.CCEDiag(E, D); 02454 } 02455 02456 RetTy ZeroInitialization(const Expr *E) { return Error(E); } 02457 02458 public: 02459 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 02460 02461 EvalInfo &getEvalInfo() { return Info; } 02462 02463 /// Report an evaluation error. This should only be called when an error is 02464 /// first discovered. When propagating an error, just return false. 02465 bool Error(const Expr *E, diag::kind D) { 02466 Info.Diag(E, D); 02467 return false; 02468 } 02469 bool Error(const Expr *E) { 02470 return Error(E, diag::note_invalid_subexpr_in_const_expr); 02471 } 02472 02473 RetTy VisitStmt(const Stmt *) { 02474 llvm_unreachable("Expression evaluator should not be called on stmts"); 02475 } 02476 RetTy VisitExpr(const Expr *E) { 02477 return Error(E); 02478 } 02479 02480 RetTy VisitParenExpr(const ParenExpr *E) 02481 { return StmtVisitorTy::Visit(E->getSubExpr()); } 02482 RetTy VisitUnaryExtension(const UnaryOperator *E) 02483 { return StmtVisitorTy::Visit(E->getSubExpr()); } 02484 RetTy VisitUnaryPlus(const UnaryOperator *E) 02485 { return StmtVisitorTy::Visit(E->getSubExpr()); } 02486 RetTy VisitChooseExpr(const ChooseExpr *E) 02487 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); } 02488 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E) 02489 { return StmtVisitorTy::Visit(E->getResultExpr()); } 02490 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 02491 { return StmtVisitorTy::Visit(E->getReplacement()); } 02492 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 02493 { return StmtVisitorTy::Visit(E->getExpr()); } 02494 // We cannot create any objects for which cleanups are required, so there is 02495 // nothing to do here; all cleanups must come from unevaluated subexpressions. 02496 RetTy VisitExprWithCleanups(const ExprWithCleanups *E) 02497 { return StmtVisitorTy::Visit(E->getSubExpr()); } 02498 02499 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 02500 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 02501 return static_cast<Derived*>(this)->VisitCastExpr(E); 02502 } 02503 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 02504 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 02505 return static_cast<Derived*>(this)->VisitCastExpr(E); 02506 } 02507 02508 RetTy VisitBinaryOperator(const BinaryOperator *E) { 02509 switch (E->getOpcode()) { 02510 default: 02511 return Error(E); 02512 02513 case BO_Comma: 02514 VisitIgnoredValue(E->getLHS()); 02515 return StmtVisitorTy::Visit(E->getRHS()); 02516 02517 case BO_PtrMemD: 02518 case BO_PtrMemI: { 02519 LValue Obj; 02520 if (!HandleMemberPointerAccess(Info, E, Obj)) 02521 return false; 02522 APValue Result; 02523 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 02524 return false; 02525 return DerivedSuccess(Result, E); 02526 } 02527 } 02528 } 02529 02530 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 02531 // Cache the value of the common expression. 02532 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon()); 02533 if (opaque.hasError()) 02534 return false; 02535 02536 return HandleConditionalOperator(E); 02537 } 02538 02539 RetTy VisitConditionalOperator(const ConditionalOperator *E) { 02540 bool IsBcpCall = false; 02541 // If the condition (ignoring parens) is a __builtin_constant_p call, 02542 // the result is a constant expression if it can be folded without 02543 // side-effects. This is an important GNU extension. See GCC PR38377 02544 // for discussion. 02545 if (const CallExpr *CallCE = 02546 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 02547 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) 02548 IsBcpCall = true; 02549 02550 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 02551 // constant expression; we can't check whether it's potentially foldable. 02552 if (Info.CheckingPotentialConstantExpression && IsBcpCall) 02553 return false; 02554 02555 FoldConstant Fold(Info); 02556 02557 if (!HandleConditionalOperator(E)) 02558 return false; 02559 02560 if (IsBcpCall) 02561 Fold.Fold(Info); 02562 02563 return true; 02564 } 02565 02566 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 02567 const APValue *Value = Info.getOpaqueValue(E); 02568 if (!Value) { 02569 const Expr *Source = E->getSourceExpr(); 02570 if (!Source) 02571 return Error(E); 02572 if (Source == E) { // sanity checking. 02573 assert(0 && "OpaqueValueExpr recursively refers to itself"); 02574 return Error(E); 02575 } 02576 return StmtVisitorTy::Visit(Source); 02577 } 02578 return DerivedSuccess(*Value, E); 02579 } 02580 02581 RetTy VisitCallExpr(const CallExpr *E) { 02582 const Expr *Callee = E->getCallee()->IgnoreParens(); 02583 QualType CalleeType = Callee->getType(); 02584 02585 const FunctionDecl *FD = 0; 02586 LValue *This = 0, ThisVal; 02587 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 02588 bool HasQualifier = false; 02589 02590 // Extract function decl and 'this' pointer from the callee. 02591 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 02592 const ValueDecl *Member = 0; 02593 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 02594 // Explicit bound member calls, such as x.f() or p->g(); 02595 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 02596 return false; 02597 Member = ME->getMemberDecl(); 02598 This = &ThisVal; 02599 HasQualifier = ME->hasQualifier(); 02600 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 02601 // Indirect bound member calls ('.*' or '->*'). 02602 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 02603 if (!Member) return false; 02604 This = &ThisVal; 02605 } else 02606 return Error(Callee); 02607 02608 FD = dyn_cast<FunctionDecl>(Member); 02609 if (!FD) 02610 return Error(Callee); 02611 } else if (CalleeType->isFunctionPointerType()) { 02612 LValue Call; 02613 if (!EvaluatePointer(Callee, Call, Info)) 02614 return false; 02615 02616 if (!Call.getLValueOffset().isZero()) 02617 return Error(Callee); 02618 FD = dyn_cast_or_null<FunctionDecl>( 02619 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 02620 if (!FD) 02621 return Error(Callee); 02622 02623 // Overloaded operator calls to member functions are represented as normal 02624 // calls with '*this' as the first argument. 02625 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 02626 if (MD && !MD->isStatic()) { 02627 // FIXME: When selecting an implicit conversion for an overloaded 02628 // operator delete, we sometimes try to evaluate calls to conversion 02629 // operators without a 'this' parameter! 02630 if (Args.empty()) 02631 return Error(E); 02632 02633 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 02634 return false; 02635 This = &ThisVal; 02636 Args = Args.slice(1); 02637 } 02638 02639 // Don't call function pointers which have been cast to some other type. 02640 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType())) 02641 return Error(E); 02642 } else 02643 return Error(E); 02644 02645 if (This && !This->checkSubobject(Info, E, CSK_This)) 02646 return false; 02647 02648 // DR1358 allows virtual constexpr functions in some cases. Don't allow 02649 // calls to such functions in constant expressions. 02650 if (This && !HasQualifier && 02651 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 02652 return Error(E, diag::note_constexpr_virtual_call); 02653 02654 const FunctionDecl *Definition = 0; 02655 Stmt *Body = FD->getBody(Definition); 02656 APValue Result; 02657 02658 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) || 02659 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, 02660 Info, Result)) 02661 return false; 02662 02663 return DerivedSuccess(Result, E); 02664 } 02665 02666 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 02667 return StmtVisitorTy::Visit(E->getInitializer()); 02668 } 02669 RetTy VisitInitListExpr(const InitListExpr *E) { 02670 if (E->getNumInits() == 0) 02671 return DerivedZeroInitialization(E); 02672 if (E->getNumInits() == 1) 02673 return StmtVisitorTy::Visit(E->getInit(0)); 02674 return Error(E); 02675 } 02676 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 02677 return DerivedZeroInitialization(E); 02678 } 02679 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 02680 return DerivedZeroInitialization(E); 02681 } 02682 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 02683 return DerivedZeroInitialization(E); 02684 } 02685 02686 /// A member expression where the object is a prvalue is itself a prvalue. 02687 RetTy VisitMemberExpr(const MemberExpr *E) { 02688 assert(!E->isArrow() && "missing call to bound member function?"); 02689 02690 APValue Val; 02691 if (!Evaluate(Val, Info, E->getBase())) 02692 return false; 02693 02694 QualType BaseTy = E->getBase()->getType(); 02695 02696 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 02697 if (!FD) return Error(E); 02698 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 02699 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 02700 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 02701 02702 SubobjectDesignator Designator(BaseTy); 02703 Designator.addDeclUnchecked(FD); 02704 02705 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) && 02706 DerivedSuccess(Val, E); 02707 } 02708 02709 RetTy VisitCastExpr(const CastExpr *E) { 02710 switch (E->getCastKind()) { 02711 default: 02712 break; 02713 02714 case CK_AtomicToNonAtomic: 02715 case CK_NonAtomicToAtomic: 02716 case CK_NoOp: 02717 case CK_UserDefinedConversion: 02718 return StmtVisitorTy::Visit(E->getSubExpr()); 02719 02720 case CK_LValueToRValue: { 02721 LValue LVal; 02722 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 02723 return false; 02724 APValue RVal; 02725 // Note, we use the subexpression's type in order to retain cv-qualifiers. 02726 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 02727 LVal, RVal)) 02728 return false; 02729 return DerivedSuccess(RVal, E); 02730 } 02731 } 02732 02733 return Error(E); 02734 } 02735 02736 /// Visit a value which is evaluated, but whose value is ignored. 02737 void VisitIgnoredValue(const Expr *E) { 02738 APValue Scratch; 02739 if (!Evaluate(Scratch, Info, E)) 02740 Info.EvalStatus.HasSideEffects = true; 02741 } 02742 }; 02743 02744 } 02745 02746 //===----------------------------------------------------------------------===// 02747 // Common base class for lvalue and temporary evaluation. 02748 //===----------------------------------------------------------------------===// 02749 namespace { 02750 template<class Derived> 02751 class LValueExprEvaluatorBase 02752 : public ExprEvaluatorBase<Derived, bool> { 02753 protected: 02754 LValue &Result; 02755 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 02756 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy; 02757 02758 bool Success(APValue::LValueBase B) { 02759 Result.set(B); 02760 return true; 02761 } 02762 02763 public: 02764 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) : 02765 ExprEvaluatorBaseTy(Info), Result(Result) {} 02766 02767 bool Success(const APValue &V, const Expr *E) { 02768 Result.setFrom(this->Info.Ctx, V); 02769 return true; 02770 } 02771 02772 bool VisitMemberExpr(const MemberExpr *E) { 02773 // Handle non-static data members. 02774 QualType BaseTy; 02775 if (E->isArrow()) { 02776 if (!EvaluatePointer(E->getBase(), Result, this->Info)) 02777 return false; 02778 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType(); 02779 } else if (E->getBase()->isRValue()) { 02780 assert(E->getBase()->getType()->isRecordType()); 02781 if (!EvaluateTemporary(E->getBase(), Result, this->Info)) 02782 return false; 02783 BaseTy = E->getBase()->getType(); 02784 } else { 02785 if (!this->Visit(E->getBase())) 02786 return false; 02787 BaseTy = E->getBase()->getType(); 02788 } 02789 02790 const ValueDecl *MD = E->getMemberDecl(); 02791 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 02792 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 02793 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 02794 (void)BaseTy; 02795 if (!HandleLValueMember(this->Info, E, Result, FD)) 02796 return false; 02797 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 02798 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 02799 return false; 02800 } else 02801 return this->Error(E); 02802 02803 if (MD->getType()->isReferenceType()) { 02804 APValue RefValue; 02805 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 02806 RefValue)) 02807 return false; 02808 return Success(RefValue, E); 02809 } 02810 return true; 02811 } 02812 02813 bool VisitBinaryOperator(const BinaryOperator *E) { 02814 switch (E->getOpcode()) { 02815 default: 02816 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 02817 02818 case BO_PtrMemD: 02819 case BO_PtrMemI: 02820 return HandleMemberPointerAccess(this->Info, E, Result); 02821 } 02822 } 02823 02824 bool VisitCastExpr(const CastExpr *E) { 02825 switch (E->getCastKind()) { 02826 default: 02827 return ExprEvaluatorBaseTy::VisitCastExpr(E); 02828 02829 case CK_DerivedToBase: 02830 case CK_UncheckedDerivedToBase: { 02831 if (!this->Visit(E->getSubExpr())) 02832 return false; 02833 02834 // Now figure out the necessary offset to add to the base LV to get from 02835 // the derived class to the base class. 02836 QualType Type = E->getSubExpr()->getType(); 02837 02838 for (CastExpr::path_const_iterator PathI = E->path_begin(), 02839 PathE = E->path_end(); PathI != PathE; ++PathI) { 02840 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(), 02841 *PathI)) 02842 return false; 02843 Type = (*PathI)->getType(); 02844 } 02845 02846 return true; 02847 } 02848 } 02849 } 02850 }; 02851 } 02852 02853 //===----------------------------------------------------------------------===// 02854 // LValue Evaluation 02855 // 02856 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 02857 // function designators (in C), decl references to void objects (in C), and 02858 // temporaries (if building with -Wno-address-of-temporary). 02859 // 02860 // LValue evaluation produces values comprising a base expression of one of the 02861 // following types: 02862 // - Declarations 02863 // * VarDecl 02864 // * FunctionDecl 02865 // - Literals 02866 // * CompoundLiteralExpr in C 02867 // * StringLiteral 02868 // * CXXTypeidExpr 02869 // * PredefinedExpr 02870 // * ObjCStringLiteralExpr 02871 // * ObjCEncodeExpr 02872 // * AddrLabelExpr 02873 // * BlockExpr 02874 // * CallExpr for a MakeStringConstant builtin 02875 // - Locals and temporaries 02876 // * Any Expr, with a CallIndex indicating the function in which the temporary 02877 // was evaluated. 02878 // plus an offset in bytes. 02879 //===----------------------------------------------------------------------===// 02880 namespace { 02881 class LValueExprEvaluator 02882 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 02883 public: 02884 LValueExprEvaluator(EvalInfo &Info, LValue &Result) : 02885 LValueExprEvaluatorBaseTy(Info, Result) {} 02886 02887 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 02888 02889 bool VisitDeclRefExpr(const DeclRefExpr *E); 02890 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 02891 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 02892 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 02893 bool VisitMemberExpr(const MemberExpr *E); 02894 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 02895 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 02896 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 02897 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 02898 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 02899 bool VisitUnaryDeref(const UnaryOperator *E); 02900 bool VisitUnaryReal(const UnaryOperator *E); 02901 bool VisitUnaryImag(const UnaryOperator *E); 02902 02903 bool VisitCastExpr(const CastExpr *E) { 02904 switch (E->getCastKind()) { 02905 default: 02906 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 02907 02908 case CK_LValueBitCast: 02909 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 02910 if (!Visit(E->getSubExpr())) 02911 return false; 02912 Result.Designator.setInvalid(); 02913 return true; 02914 02915 case CK_BaseToDerived: 02916 if (!Visit(E->getSubExpr())) 02917 return false; 02918 return HandleBaseToDerivedCast(Info, E, Result); 02919 } 02920 } 02921 }; 02922 } // end anonymous namespace 02923 02924 /// Evaluate an expression as an lvalue. This can be legitimately called on 02925 /// expressions which are not glvalues, in a few cases: 02926 /// * function designators in C, 02927 /// * "extern void" objects, 02928 /// * temporaries, if building with -Wno-address-of-temporary. 02929 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) { 02930 assert((E->isGLValue() || E->getType()->isFunctionType() || 02931 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) && 02932 "can't evaluate expression as an lvalue"); 02933 return LValueExprEvaluator(Info, Result).Visit(E); 02934 } 02935 02936 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 02937 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 02938 return Success(FD); 02939 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 02940 return VisitVarDecl(E, VD); 02941 return Error(E); 02942 } 02943 02944 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 02945 if (!VD->getType()->isReferenceType()) { 02946 if (isa<ParmVarDecl>(VD)) { 02947 Result.set(VD, Info.CurrentCall->Index); 02948 return true; 02949 } 02950 return Success(VD); 02951 } 02952 02953 APValue V; 02954 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V)) 02955 return false; 02956 return Success(V, E); 02957 } 02958 02959 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 02960 const MaterializeTemporaryExpr *E) { 02961 if (E->GetTemporaryExpr()->isRValue()) { 02962 if (E->getType()->isRecordType()) 02963 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info); 02964 02965 Result.set(E, Info.CurrentCall->Index); 02966 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, 02967 Result, E->GetTemporaryExpr()); 02968 } 02969 02970 // Materialization of an lvalue temporary occurs when we need to force a copy 02971 // (for instance, if it's a bitfield). 02972 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases. 02973 if (!Visit(E->GetTemporaryExpr())) 02974 return false; 02975 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result, 02976 Info.CurrentCall->Temporaries[E])) 02977 return false; 02978 Result.set(E, Info.CurrentCall->Index); 02979 return true; 02980 } 02981 02982 bool 02983 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 02984 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 02985 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 02986 // only see this when folding in C, so there's no standard to follow here. 02987 return Success(E); 02988 } 02989 02990 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 02991 if (E->isTypeOperand()) 02992 return Success(E); 02993 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl(); 02994 if (RD && RD->isPolymorphic()) { 02995 Info.Diag(E, diag::note_constexpr_typeid_polymorphic) 02996 << E->getExprOperand()->getType() 02997 << E->getExprOperand()->getSourceRange(); 02998 return false; 02999 } 03000 return Success(E); 03001 } 03002 03003 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 03004 return Success(E); 03005 } 03006 03007 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 03008 // Handle static data members. 03009 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 03010 VisitIgnoredValue(E->getBase()); 03011 return VisitVarDecl(E, VD); 03012 } 03013 03014 // Handle static member functions. 03015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 03016 if (MD->isStatic()) { 03017 VisitIgnoredValue(E->getBase()); 03018 return Success(MD); 03019 } 03020 } 03021 03022 // Handle non-static data members. 03023 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 03024 } 03025 03026 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 03027 // FIXME: Deal with vectors as array subscript bases. 03028 if (E->getBase()->getType()->isVectorType()) 03029 return Error(E); 03030 03031 if (!EvaluatePointer(E->getBase(), Result, Info)) 03032 return false; 03033 03034 APSInt Index; 03035 if (!EvaluateInteger(E->getIdx(), Index, Info)) 03036 return false; 03037 int64_t IndexValue 03038 = Index.isSigned() ? Index.getSExtValue() 03039 : static_cast<int64_t>(Index.getZExtValue()); 03040 03041 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue); 03042 } 03043 03044 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 03045 return EvaluatePointer(E->getSubExpr(), Result, Info); 03046 } 03047 03048 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 03049 if (!Visit(E->getSubExpr())) 03050 return false; 03051 // __real is a no-op on scalar lvalues. 03052 if (E->getSubExpr()->getType()->isAnyComplexType()) 03053 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 03054 return true; 03055 } 03056 03057 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 03058 assert(E->getSubExpr()->getType()->isAnyComplexType() && 03059 "lvalue __imag__ on scalar?"); 03060 if (!Visit(E->getSubExpr())) 03061 return false; 03062 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 03063 return true; 03064 } 03065 03066 //===----------------------------------------------------------------------===// 03067 // Pointer Evaluation 03068 //===----------------------------------------------------------------------===// 03069 03070 namespace { 03071 class PointerExprEvaluator 03072 : public ExprEvaluatorBase<PointerExprEvaluator, bool> { 03073 LValue &Result; 03074 03075 bool Success(const Expr *E) { 03076 Result.set(E); 03077 return true; 03078 } 03079 public: 03080 03081 PointerExprEvaluator(EvalInfo &info, LValue &Result) 03082 : ExprEvaluatorBaseTy(info), Result(Result) {} 03083 03084 bool Success(const APValue &V, const Expr *E) { 03085 Result.setFrom(Info.Ctx, V); 03086 return true; 03087 } 03088 bool ZeroInitialization(const Expr *E) { 03089 return Success((Expr*)0); 03090 } 03091 03092 bool VisitBinaryOperator(const BinaryOperator *E); 03093 bool VisitCastExpr(const CastExpr* E); 03094 bool VisitUnaryAddrOf(const UnaryOperator *E); 03095 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 03096 { return Success(E); } 03097 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) 03098 { return Success(E); } 03099 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 03100 { return Success(E); } 03101 bool VisitCallExpr(const CallExpr *E); 03102 bool VisitBlockExpr(const BlockExpr *E) { 03103 if (!E->getBlockDecl()->hasCaptures()) 03104 return Success(E); 03105 return Error(E); 03106 } 03107 bool VisitCXXThisExpr(const CXXThisExpr *E) { 03108 if (!Info.CurrentCall->This) 03109 return Error(E); 03110 Result = *Info.CurrentCall->This; 03111 return true; 03112 } 03113 03114 // FIXME: Missing: @protocol, @selector 03115 }; 03116 } // end anonymous namespace 03117 03118 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 03119 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 03120 return PointerExprEvaluator(Info, Result).Visit(E); 03121 } 03122 03123 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 03124 if (E->getOpcode() != BO_Add && 03125 E->getOpcode() != BO_Sub) 03126 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 03127 03128 const Expr *PExp = E->getLHS(); 03129 const Expr *IExp = E->getRHS(); 03130 if (IExp->getType()->isPointerType()) 03131 std::swap(PExp, IExp); 03132 03133 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info); 03134 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure()) 03135 return false; 03136 03137 llvm::APSInt Offset; 03138 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 03139 return false; 03140 int64_t AdditionalOffset 03141 = Offset.isSigned() ? Offset.getSExtValue() 03142 : static_cast<int64_t>(Offset.getZExtValue()); 03143 if (E->getOpcode() == BO_Sub) 03144 AdditionalOffset = -AdditionalOffset; 03145 03146 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType(); 03147 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, 03148 AdditionalOffset); 03149 } 03150 03151 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 03152 return EvaluateLValue(E->getSubExpr(), Result, Info); 03153 } 03154 03155 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 03156 const Expr* SubExpr = E->getSubExpr(); 03157 03158 switch (E->getCastKind()) { 03159 default: 03160 break; 03161 03162 case CK_BitCast: 03163 case CK_CPointerToObjCPointerCast: 03164 case CK_BlockPointerToObjCPointerCast: 03165 case CK_AnyPointerToBlockPointerCast: 03166 if (!Visit(SubExpr)) 03167 return false; 03168 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 03169 // permitted in constant expressions in C++11. Bitcasts from cv void* are 03170 // also static_casts, but we disallow them as a resolution to DR1312. 03171 if (!E->getType()->isVoidPointerType()) { 03172 Result.Designator.setInvalid(); 03173 if (SubExpr->getType()->isVoidPointerType()) 03174 CCEDiag(E, diag::note_constexpr_invalid_cast) 03175 << 3 << SubExpr->getType(); 03176 else 03177 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 03178 } 03179 return true; 03180 03181 case CK_DerivedToBase: 03182 case CK_UncheckedDerivedToBase: { 03183 if (!EvaluatePointer(E->getSubExpr(), Result, Info)) 03184 return false; 03185 if (!Result.Base && Result.Offset.isZero()) 03186 return true; 03187 03188 // Now figure out the necessary offset to add to the base LV to get from 03189 // the derived class to the base class. 03190 QualType Type = 03191 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 03192 03193 for (CastExpr::path_const_iterator PathI = E->path_begin(), 03194 PathE = E->path_end(); PathI != PathE; ++PathI) { 03195 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 03196 *PathI)) 03197 return false; 03198 Type = (*PathI)->getType(); 03199 } 03200 03201 return true; 03202 } 03203 03204 case CK_BaseToDerived: 03205 if (!Visit(E->getSubExpr())) 03206 return false; 03207 if (!Result.Base && Result.Offset.isZero()) 03208 return true; 03209 return HandleBaseToDerivedCast(Info, E, Result); 03210 03211 case CK_NullToPointer: 03212 VisitIgnoredValue(E->getSubExpr()); 03213 return ZeroInitialization(E); 03214 03215 case CK_IntegralToPointer: { 03216 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 03217 03218 APValue Value; 03219 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 03220 break; 03221 03222 if (Value.isInt()) { 03223 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 03224 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 03225 Result.Base = (Expr*)0; 03226 Result.Offset = CharUnits::fromQuantity(N); 03227 Result.CallIndex = 0; 03228 Result.Designator.setInvalid(); 03229 return true; 03230 } else { 03231 // Cast is of an lvalue, no need to change value. 03232 Result.setFrom(Info.Ctx, Value); 03233 return true; 03234 } 03235 } 03236 case CK_ArrayToPointerDecay: 03237 if (SubExpr->isGLValue()) { 03238 if (!EvaluateLValue(SubExpr, Result, Info)) 03239 return false; 03240 } else { 03241 Result.set(SubExpr, Info.CurrentCall->Index); 03242 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr], 03243 Info, Result, SubExpr)) 03244 return false; 03245 } 03246 // The result is a pointer to the first element of the array. 03247 if (const ConstantArrayType *CAT 03248 = Info.Ctx.getAsConstantArrayType(SubExpr->getType())) 03249 Result.addArray(Info, E, CAT); 03250 else 03251 Result.Designator.setInvalid(); 03252 return true; 03253 03254 case CK_FunctionToPointerDecay: 03255 return EvaluateLValue(SubExpr, Result, Info); 03256 } 03257 03258 return ExprEvaluatorBaseTy::VisitCastExpr(E); 03259 } 03260 03261 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 03262 if (IsStringLiteralCall(E)) 03263 return Success(E); 03264 03265 return ExprEvaluatorBaseTy::VisitCallExpr(E); 03266 } 03267 03268 //===----------------------------------------------------------------------===// 03269 // Member Pointer Evaluation 03270 //===----------------------------------------------------------------------===// 03271 03272 namespace { 03273 class MemberPointerExprEvaluator 03274 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> { 03275 MemberPtr &Result; 03276 03277 bool Success(const ValueDecl *D) { 03278 Result = MemberPtr(D); 03279 return true; 03280 } 03281 public: 03282 03283 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 03284 : ExprEvaluatorBaseTy(Info), Result(Result) {} 03285 03286 bool Success(const APValue &V, const Expr *E) { 03287 Result.setFrom(V); 03288 return true; 03289 } 03290 bool ZeroInitialization(const Expr *E) { 03291 return Success((const ValueDecl*)0); 03292 } 03293 03294 bool VisitCastExpr(const CastExpr *E); 03295 bool VisitUnaryAddrOf(const UnaryOperator *E); 03296 }; 03297 } // end anonymous namespace 03298 03299 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 03300 EvalInfo &Info) { 03301 assert(E->isRValue() && E->getType()->isMemberPointerType()); 03302 return MemberPointerExprEvaluator(Info, Result).Visit(E); 03303 } 03304 03305 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 03306 switch (E->getCastKind()) { 03307 default: 03308 return ExprEvaluatorBaseTy::VisitCastExpr(E); 03309 03310 case CK_NullToMemberPointer: 03311 VisitIgnoredValue(E->getSubExpr()); 03312 return ZeroInitialization(E); 03313 03314 case CK_BaseToDerivedMemberPointer: { 03315 if (!Visit(E->getSubExpr())) 03316 return false; 03317 if (E->path_empty()) 03318 return true; 03319 // Base-to-derived member pointer casts store the path in derived-to-base 03320 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 03321 // the wrong end of the derived->base arc, so stagger the path by one class. 03322 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 03323 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 03324 PathI != PathE; ++PathI) { 03325 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 03326 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 03327 if (!Result.castToDerived(Derived)) 03328 return Error(E); 03329 } 03330 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 03331 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 03332 return Error(E); 03333 return true; 03334 } 03335 03336 case CK_DerivedToBaseMemberPointer: 03337 if (!Visit(E->getSubExpr())) 03338 return false; 03339 for (CastExpr::path_const_iterator PathI = E->path_begin(), 03340 PathE = E->path_end(); PathI != PathE; ++PathI) { 03341 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 03342 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 03343 if (!Result.castToBase(Base)) 03344 return Error(E); 03345 } 03346 return true; 03347 } 03348 } 03349 03350 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 03351 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 03352 // member can be formed. 03353 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 03354 } 03355 03356 //===----------------------------------------------------------------------===// 03357 // Record Evaluation 03358 //===----------------------------------------------------------------------===// 03359 03360 namespace { 03361 class RecordExprEvaluator 03362 : public ExprEvaluatorBase<RecordExprEvaluator, bool> { 03363 const LValue &This; 03364 APValue &Result; 03365 public: 03366 03367 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 03368 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 03369 03370 bool Success(const APValue &V, const Expr *E) { 03371 Result = V; 03372 return true; 03373 } 03374 bool ZeroInitialization(const Expr *E); 03375 03376 bool VisitCastExpr(const CastExpr *E); 03377 bool VisitInitListExpr(const InitListExpr *E); 03378 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 03379 }; 03380 } 03381 03382 /// Perform zero-initialization on an object of non-union class type. 03383 /// C++11 [dcl.init]p5: 03384 /// To zero-initialize an object or reference of type T means: 03385 /// [...] 03386 /// -- if T is a (possibly cv-qualified) non-union class type, 03387 /// each non-static data member and each base-class subobject is 03388 /// zero-initialized 03389 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 03390 const RecordDecl *RD, 03391 const LValue &This, APValue &Result) { 03392 assert(!RD->isUnion() && "Expected non-union class type"); 03393 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 03394 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 03395 std::distance(RD->field_begin(), RD->field_end())); 03396 03397 if (RD->isInvalidDecl()) return false; 03398 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 03399 03400 if (CD) { 03401 unsigned Index = 0; 03402 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 03403 End = CD->bases_end(); I != End; ++I, ++Index) { 03404 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 03405 LValue Subobject = This; 03406 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 03407 return false; 03408 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 03409 Result.getStructBase(Index))) 03410 return false; 03411 } 03412 } 03413 03414 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end(); 03415 I != End; ++I) { 03416 // -- if T is a reference type, no initialization is performed. 03417 if (I->getType()->isReferenceType()) 03418 continue; 03419 03420 LValue Subobject = This; 03421 if (!HandleLValueMember(Info, E, Subobject, &*I, &Layout)) 03422 return false; 03423 03424 ImplicitValueInitExpr VIE(I->getType()); 03425 if (!EvaluateInPlace( 03426 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 03427 return false; 03428 } 03429 03430 return true; 03431 } 03432 03433 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) { 03434 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 03435 if (RD->isInvalidDecl()) return false; 03436 if (RD->isUnion()) { 03437 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 03438 // object's first non-static named data member is zero-initialized 03439 RecordDecl::field_iterator I = RD->field_begin(); 03440 if (I == RD->field_end()) { 03441 Result = APValue((const FieldDecl*)0); 03442 return true; 03443 } 03444 03445 LValue Subobject = This; 03446 if (!HandleLValueMember(Info, E, Subobject, &*I)) 03447 return false; 03448 Result = APValue(&*I); 03449 ImplicitValueInitExpr VIE(I->getType()); 03450 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 03451 } 03452 03453 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 03454 Info.Diag(E, diag::note_constexpr_virtual_base) << RD; 03455 return false; 03456 } 03457 03458 return HandleClassZeroInitialization(Info, E, RD, This, Result); 03459 } 03460 03461 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 03462 switch (E->getCastKind()) { 03463 default: 03464 return ExprEvaluatorBaseTy::VisitCastExpr(E); 03465 03466 case CK_ConstructorConversion: 03467 return Visit(E->getSubExpr()); 03468 03469 case CK_DerivedToBase: 03470 case CK_UncheckedDerivedToBase: { 03471 APValue DerivedObject; 03472 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 03473 return false; 03474 if (!DerivedObject.isStruct()) 03475 return Error(E->getSubExpr()); 03476 03477 // Derived-to-base rvalue conversion: just slice off the derived part. 03478 APValue *Value = &DerivedObject; 03479 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 03480 for (CastExpr::path_const_iterator PathI = E->path_begin(), 03481 PathE = E->path_end(); PathI != PathE; ++PathI) { 03482 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 03483 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 03484 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 03485 RD = Base; 03486 } 03487 Result = *Value; 03488 return true; 03489 } 03490 } 03491 } 03492 03493 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 03494 // Cannot constant-evaluate std::initializer_list inits. 03495 if (E->initializesStdInitializerList()) 03496 return false; 03497 03498 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 03499 if (RD->isInvalidDecl()) return false; 03500 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 03501 03502 if (RD->isUnion()) { 03503 const FieldDecl *Field = E->getInitializedFieldInUnion(); 03504 Result = APValue(Field); 03505 if (!Field) 03506 return true; 03507 03508 // If the initializer list for a union does not contain any elements, the 03509 // first element of the union is value-initialized. 03510 ImplicitValueInitExpr VIE(Field->getType()); 03511 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 03512 03513 LValue Subobject = This; 03514 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 03515 return false; 03516 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 03517 } 03518 03519 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) && 03520 "initializer list for class with base classes"); 03521 Result = APValue(APValue::UninitStruct(), 0, 03522 std::distance(RD->field_begin(), RD->field_end())); 03523 unsigned ElementNo = 0; 03524 bool Success = true; 03525 for (RecordDecl::field_iterator Field = RD->field_begin(), 03526 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { 03527 // Anonymous bit-fields are not considered members of the class for 03528 // purposes of aggregate initialization. 03529 if (Field->isUnnamedBitfield()) 03530 continue; 03531 03532 LValue Subobject = This; 03533 03534 bool HaveInit = ElementNo < E->getNumInits(); 03535 03536 // FIXME: Diagnostics here should point to the end of the initializer 03537 // list, not the start. 03538 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 03539 Subobject, &*Field, &Layout)) 03540 return false; 03541 03542 // Perform an implicit value-initialization for members beyond the end of 03543 // the initializer list. 03544 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 03545 03546 if (!EvaluateInPlace( 03547 Result.getStructField(Field->getFieldIndex()), 03548 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) { 03549 if (!Info.keepEvaluatingAfterFailure()) 03550 return false; 03551 Success = false; 03552 } 03553 } 03554 03555 return Success; 03556 } 03557 03558 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 03559 const CXXConstructorDecl *FD = E->getConstructor(); 03560 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 03561 03562 bool ZeroInit = E->requiresZeroInitialization(); 03563 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 03564 // If we've already performed zero-initialization, we're already done. 03565 if (!Result.isUninit()) 03566 return true; 03567 03568 if (ZeroInit) 03569 return ZeroInitialization(E); 03570 03571 const CXXRecordDecl *RD = FD->getParent(); 03572 if (RD->isUnion()) 03573 Result = APValue((FieldDecl*)0); 03574 else 03575 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 03576 std::distance(RD->field_begin(), RD->field_end())); 03577 return true; 03578 } 03579 03580 const FunctionDecl *Definition = 0; 03581 FD->getBody(Definition); 03582 03583 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition)) 03584 return false; 03585 03586 // Avoid materializing a temporary for an elidable copy/move constructor. 03587 if (E->isElidable() && !ZeroInit) 03588 if (const MaterializeTemporaryExpr *ME 03589 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 03590 return Visit(ME->GetTemporaryExpr()); 03591 03592 if (ZeroInit && !ZeroInitialization(E)) 03593 return false; 03594 03595 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 03596 return HandleConstructorCall(E->getExprLoc(), This, Args, 03597 cast<CXXConstructorDecl>(Definition), Info, 03598 Result); 03599 } 03600 03601 static bool EvaluateRecord(const Expr *E, const LValue &This, 03602 APValue &Result, EvalInfo &Info) { 03603 assert(E->isRValue() && E->getType()->isRecordType() && 03604 "can't evaluate expression as a record rvalue"); 03605 return RecordExprEvaluator(Info, This, Result).Visit(E); 03606 } 03607 03608 //===----------------------------------------------------------------------===// 03609 // Temporary Evaluation 03610 // 03611 // Temporaries are represented in the AST as rvalues, but generally behave like 03612 // lvalues. The full-object of which the temporary is a subobject is implicitly 03613 // materialized so that a reference can bind to it. 03614 //===----------------------------------------------------------------------===// 03615 namespace { 03616 class TemporaryExprEvaluator 03617 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 03618 public: 03619 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 03620 LValueExprEvaluatorBaseTy(Info, Result) {} 03621 03622 /// Visit an expression which constructs the value of this temporary. 03623 bool VisitConstructExpr(const Expr *E) { 03624 Result.set(E, Info.CurrentCall->Index); 03625 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E); 03626 } 03627 03628 bool VisitCastExpr(const CastExpr *E) { 03629 switch (E->getCastKind()) { 03630 default: 03631 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 03632 03633 case CK_ConstructorConversion: 03634 return VisitConstructExpr(E->getSubExpr()); 03635 } 03636 } 03637 bool VisitInitListExpr(const InitListExpr *E) { 03638 return VisitConstructExpr(E); 03639 } 03640 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 03641 return VisitConstructExpr(E); 03642 } 03643 bool VisitCallExpr(const CallExpr *E) { 03644 return VisitConstructExpr(E); 03645 } 03646 }; 03647 } // end anonymous namespace 03648 03649 /// Evaluate an expression of record type as a temporary. 03650 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 03651 assert(E->isRValue() && E->getType()->isRecordType()); 03652 return TemporaryExprEvaluator(Info, Result).Visit(E); 03653 } 03654 03655 //===----------------------------------------------------------------------===// 03656 // Vector Evaluation 03657 //===----------------------------------------------------------------------===// 03658 03659 namespace { 03660 class VectorExprEvaluator 03661 : public ExprEvaluatorBase<VectorExprEvaluator, bool> { 03662 APValue &Result; 03663 public: 03664 03665 VectorExprEvaluator(EvalInfo &info, APValue &Result) 03666 : ExprEvaluatorBaseTy(info), Result(Result) {} 03667 03668 bool Success(const ArrayRef<APValue> &V, const Expr *E) { 03669 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 03670 // FIXME: remove this APValue copy. 03671 Result = APValue(V.data(), V.size()); 03672 return true; 03673 } 03674 bool Success(const APValue &V, const Expr *E) { 03675 assert(V.isVector()); 03676 Result = V; 03677 return true; 03678 } 03679 bool ZeroInitialization(const Expr *E); 03680 03681 bool VisitUnaryReal(const UnaryOperator *E) 03682 { return Visit(E->getSubExpr()); } 03683 bool VisitCastExpr(const CastExpr* E); 03684 bool VisitInitListExpr(const InitListExpr *E); 03685 bool VisitUnaryImag(const UnaryOperator *E); 03686 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 03687 // binary comparisons, binary and/or/xor, 03688 // shufflevector, ExtVectorElementExpr 03689 }; 03690 } // end anonymous namespace 03691 03692 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 03693 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 03694 return VectorExprEvaluator(Info, Result).Visit(E); 03695 } 03696 03697 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 03698 const VectorType *VTy = E->getType()->castAs<VectorType>(); 03699 unsigned NElts = VTy->getNumElements(); 03700 03701 const Expr *SE = E->getSubExpr(); 03702 QualType SETy = SE->getType(); 03703 03704 switch (E->getCastKind()) { 03705 case CK_VectorSplat: { 03706 APValue Val = APValue(); 03707 if (SETy->isIntegerType()) { 03708 APSInt IntResult; 03709 if (!EvaluateInteger(SE, IntResult, Info)) 03710 return false; 03711 Val = APValue(IntResult); 03712 } else if (SETy->isRealFloatingType()) { 03713 APFloat F(0.0); 03714 if (!EvaluateFloat(SE, F, Info)) 03715 return false; 03716 Val = APValue(F); 03717 } else { 03718 return Error(E); 03719 } 03720 03721 // Splat and create vector APValue. 03722 SmallVector<APValue, 4> Elts(NElts, Val); 03723 return Success(Elts, E); 03724 } 03725 case CK_BitCast: { 03726 // Evaluate the operand into an APInt we can extract from. 03727 llvm::APInt SValInt; 03728 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 03729 return false; 03730 // Extract the elements 03731 QualType EltTy = VTy->getElementType(); 03732 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 03733 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 03734 SmallVector<APValue, 4> Elts; 03735 if (EltTy->isRealFloatingType()) { 03736 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 03737 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble; 03738 unsigned FloatEltSize = EltSize; 03739 if (&Sem == &APFloat::x87DoubleExtended) 03740 FloatEltSize = 80; 03741 for (unsigned i = 0; i < NElts; i++) { 03742 llvm::APInt Elt; 03743 if (BigEndian) 03744 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 03745 else 03746 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 03747 Elts.push_back(APValue(APFloat(Elt, isIEESem))); 03748 } 03749 } else if (EltTy->isIntegerType()) { 03750 for (unsigned i = 0; i < NElts; i++) { 03751 llvm::APInt Elt; 03752 if (BigEndian) 03753 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 03754 else 03755 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 03756 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 03757 } 03758 } else { 03759 return Error(E); 03760 } 03761 return Success(Elts, E); 03762 } 03763 default: 03764 return ExprEvaluatorBaseTy::VisitCastExpr(E); 03765 } 03766 } 03767 03768 bool 03769 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 03770 const VectorType *VT = E->getType()->castAs<VectorType>(); 03771 unsigned NumInits = E->getNumInits(); 03772 unsigned NumElements = VT->getNumElements(); 03773 03774 QualType EltTy = VT->getElementType(); 03775 SmallVector<APValue, 4> Elements; 03776 03777 // The number of initializers can be less than the number of 03778 // vector elements. For OpenCL, this can be due to nested vector 03779 // initialization. For GCC compatibility, missing trailing elements 03780 // should be initialized with zeroes. 03781 unsigned CountInits = 0, CountElts = 0; 03782 while (CountElts < NumElements) { 03783 // Handle nested vector initialization. 03784 if (CountInits < NumInits 03785 && E->getInit(CountInits)->getType()->isExtVectorType()) { 03786 APValue v; 03787 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 03788 return Error(E); 03789 unsigned vlen = v.getVectorLength(); 03790 for (unsigned j = 0; j < vlen; j++) 03791 Elements.push_back(v.getVectorElt(j)); 03792 CountElts += vlen; 03793 } else if (EltTy->isIntegerType()) { 03794 llvm::APSInt sInt(32); 03795 if (CountInits < NumInits) { 03796 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 03797 return false; 03798 } else // trailing integer zero. 03799 sInt = Info.Ctx.MakeIntValue(0, EltTy); 03800 Elements.push_back(APValue(sInt)); 03801 CountElts++; 03802 } else { 03803 llvm::APFloat f(0.0); 03804 if (CountInits < NumInits) { 03805 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 03806 return false; 03807 } else // trailing float zero. 03808 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 03809 Elements.push_back(APValue(f)); 03810 CountElts++; 03811 } 03812 CountInits++; 03813 } 03814 return Success(Elements, E); 03815 } 03816 03817 bool 03818 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 03819 const VectorType *VT = E->getType()->getAs<VectorType>(); 03820 QualType EltTy = VT->getElementType(); 03821 APValue ZeroElement; 03822 if (EltTy->isIntegerType()) 03823 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 03824 else 03825 ZeroElement = 03826 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 03827 03828 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 03829 return Success(Elements, E); 03830 } 03831 03832 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 03833 VisitIgnoredValue(E->getSubExpr()); 03834 return ZeroInitialization(E); 03835 } 03836 03837 //===----------------------------------------------------------------------===// 03838 // Array Evaluation 03839 //===----------------------------------------------------------------------===// 03840 03841 namespace { 03842 class ArrayExprEvaluator 03843 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> { 03844 const LValue &This; 03845 APValue &Result; 03846 public: 03847 03848 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 03849 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 03850 03851 bool Success(const APValue &V, const Expr *E) { 03852 assert((V.isArray() || V.isLValue()) && 03853 "expected array or string literal"); 03854 Result = V; 03855 return true; 03856 } 03857 03858 bool ZeroInitialization(const Expr *E) { 03859 const ConstantArrayType *CAT = 03860 Info.Ctx.getAsConstantArrayType(E->getType()); 03861 if (!CAT) 03862 return Error(E); 03863 03864 Result = APValue(APValue::UninitArray(), 0, 03865 CAT->getSize().getZExtValue()); 03866 if (!Result.hasArrayFiller()) return true; 03867 03868 // Zero-initialize all elements. 03869 LValue Subobject = This; 03870 Subobject.addArray(Info, E, CAT); 03871 ImplicitValueInitExpr VIE(CAT->getElementType()); 03872 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 03873 } 03874 03875 bool VisitInitListExpr(const InitListExpr *E); 03876 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 03877 }; 03878 } // end anonymous namespace 03879 03880 static bool EvaluateArray(const Expr *E, const LValue &This, 03881 APValue &Result, EvalInfo &Info) { 03882 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 03883 return ArrayExprEvaluator(Info, This, Result).Visit(E); 03884 } 03885 03886 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 03887 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 03888 if (!CAT) 03889 return Error(E); 03890 03891 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 03892 // an appropriately-typed string literal enclosed in braces. 03893 if (E->isStringLiteralInit()) { 03894 LValue LV; 03895 if (!EvaluateLValue(E->getInit(0), LV, Info)) 03896 return false; 03897 APValue Val; 03898 LV.moveInto(Val); 03899 return Success(Val, E); 03900 } 03901 03902 bool Success = true; 03903 03904 Result = APValue(APValue::UninitArray(), E->getNumInits(), 03905 CAT->getSize().getZExtValue()); 03906 LValue Subobject = This; 03907 Subobject.addArray(Info, E, CAT); 03908 unsigned Index = 0; 03909 for (InitListExpr::const_iterator I = E->begin(), End = E->end(); 03910 I != End; ++I, ++Index) { 03911 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 03912 Info, Subobject, cast<Expr>(*I)) || 03913 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject, 03914 CAT->getElementType(), 1)) { 03915 if (!Info.keepEvaluatingAfterFailure()) 03916 return false; 03917 Success = false; 03918 } 03919 } 03920 03921 if (!Result.hasArrayFiller()) return Success; 03922 assert(E->hasArrayFiller() && "no array filler for incomplete init list"); 03923 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 03924 // but sometimes does: 03925 // struct S { constexpr S() : p(&p) {} void *p; }; 03926 // S s[10] = {}; 03927 return EvaluateInPlace(Result.getArrayFiller(), Info, 03928 Subobject, E->getArrayFiller()) && Success; 03929 } 03930 03931 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 03932 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 03933 if (!CAT) 03934 return Error(E); 03935 03936 bool HadZeroInit = !Result.isUninit(); 03937 if (!HadZeroInit) 03938 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue()); 03939 if (!Result.hasArrayFiller()) 03940 return true; 03941 03942 const CXXConstructorDecl *FD = E->getConstructor(); 03943 03944 bool ZeroInit = E->requiresZeroInitialization(); 03945 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 03946 if (HadZeroInit) 03947 return true; 03948 03949 if (ZeroInit) { 03950 LValue Subobject = This; 03951 Subobject.addArray(Info, E, CAT); 03952 ImplicitValueInitExpr VIE(CAT->getElementType()); 03953 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 03954 } 03955 03956 const CXXRecordDecl *RD = FD->getParent(); 03957 if (RD->isUnion()) 03958 Result.getArrayFiller() = APValue((FieldDecl*)0); 03959 else 03960 Result.getArrayFiller() = 03961 APValue(APValue::UninitStruct(), RD->getNumBases(), 03962 std::distance(RD->field_begin(), RD->field_end())); 03963 return true; 03964 } 03965 03966 const FunctionDecl *Definition = 0; 03967 FD->getBody(Definition); 03968 03969 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition)) 03970 return false; 03971 03972 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 03973 // but sometimes does: 03974 // struct S { constexpr S() : p(&p) {} void *p; }; 03975 // S s[10]; 03976 LValue Subobject = This; 03977 Subobject.addArray(Info, E, CAT); 03978 03979 if (ZeroInit && !HadZeroInit) { 03980 ImplicitValueInitExpr VIE(CAT->getElementType()); 03981 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE)) 03982 return false; 03983 } 03984 03985 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 03986 return HandleConstructorCall(E->getExprLoc(), Subobject, Args, 03987 cast<CXXConstructorDecl>(Definition), 03988 Info, Result.getArrayFiller()); 03989 } 03990 03991 //===----------------------------------------------------------------------===// 03992 // Integer Evaluation 03993 // 03994 // As a GNU extension, we support casting pointers to sufficiently-wide integer 03995 // types and back in constant folding. Integer values are thus represented 03996 // either as an integer-valued APValue, or as an lvalue-valued APValue. 03997 //===----------------------------------------------------------------------===// 03998 03999 namespace { 04000 class IntExprEvaluator 04001 : public ExprEvaluatorBase<IntExprEvaluator, bool> { 04002 APValue &Result; 04003 public: 04004 IntExprEvaluator(EvalInfo &info, APValue &result) 04005 : ExprEvaluatorBaseTy(info), Result(result) {} 04006 04007 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 04008 assert(E->getType()->isIntegralOrEnumerationType() && 04009 "Invalid evaluation result."); 04010 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 04011 "Invalid evaluation result."); 04012 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 04013 "Invalid evaluation result."); 04014 Result = APValue(SI); 04015 return true; 04016 } 04017 bool Success(const llvm::APSInt &SI, const Expr *E) { 04018 return Success(SI, E, Result); 04019 } 04020 04021 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 04022 assert(E->getType()->isIntegralOrEnumerationType() && 04023 "Invalid evaluation result."); 04024 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 04025 "Invalid evaluation result."); 04026 Result = APValue(APSInt(I)); 04027 Result.getInt().setIsUnsigned( 04028 E->getType()->isUnsignedIntegerOrEnumerationType()); 04029 return true; 04030 } 04031 bool Success(const llvm::APInt &I, const Expr *E) { 04032 return Success(I, E, Result); 04033 } 04034 04035 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 04036 assert(E->getType()->isIntegralOrEnumerationType() && 04037 "Invalid evaluation result."); 04038 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 04039 return true; 04040 } 04041 bool Success(uint64_t Value, const Expr *E) { 04042 return Success(Value, E, Result); 04043 } 04044 04045 bool Success(CharUnits Size, const Expr *E) { 04046 return Success(Size.getQuantity(), E); 04047 } 04048 04049 bool Success(const APValue &V, const Expr *E) { 04050 if (V.isLValue() || V.isAddrLabelDiff()) { 04051 Result = V; 04052 return true; 04053 } 04054 return Success(V.getInt(), E); 04055 } 04056 04057 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 04058 04059 //===--------------------------------------------------------------------===// 04060 // Visitor Methods 04061 //===--------------------------------------------------------------------===// 04062 04063 bool VisitIntegerLiteral(const IntegerLiteral *E) { 04064 return Success(E->getValue(), E); 04065 } 04066 bool VisitCharacterLiteral(const CharacterLiteral *E) { 04067 return Success(E->getValue(), E); 04068 } 04069 04070 bool CheckReferencedDecl(const Expr *E, const Decl *D); 04071 bool VisitDeclRefExpr(const DeclRefExpr *E) { 04072 if (CheckReferencedDecl(E, E->getDecl())) 04073 return true; 04074 04075 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 04076 } 04077 bool VisitMemberExpr(const MemberExpr *E) { 04078 if (CheckReferencedDecl(E, E->getMemberDecl())) { 04079 VisitIgnoredValue(E->getBase()); 04080 return true; 04081 } 04082 04083 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 04084 } 04085 04086 bool VisitCallExpr(const CallExpr *E); 04087 bool VisitBinaryOperator(const BinaryOperator *E); 04088 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 04089 bool VisitUnaryOperator(const UnaryOperator *E); 04090 04091 bool VisitCastExpr(const CastExpr* E); 04092 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 04093 04094 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 04095 return Success(E->getValue(), E); 04096 } 04097 04098 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 04099 return Success(E->getValue(), E); 04100 } 04101 04102 // Note, GNU defines __null as an integer, not a pointer. 04103 bool VisitGNUNullExpr(const GNUNullExpr *E) { 04104 return ZeroInitialization(E); 04105 } 04106 04107 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 04108 return Success(E->getValue(), E); 04109 } 04110 04111 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 04112 return Success(E->getValue(), E); 04113 } 04114 04115 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 04116 return Success(E->getValue(), E); 04117 } 04118 04119 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 04120 return Success(E->getValue(), E); 04121 } 04122 04123 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 04124 return Success(E->getValue(), E); 04125 } 04126 04127 bool VisitUnaryReal(const UnaryOperator *E); 04128 bool VisitUnaryImag(const UnaryOperator *E); 04129 04130 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 04131 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 04132 04133 private: 04134 CharUnits GetAlignOfExpr(const Expr *E); 04135 CharUnits GetAlignOfType(QualType T); 04136 static QualType GetObjectType(APValue::LValueBase B); 04137 bool TryEvaluateBuiltinObjectSize(const CallExpr *E); 04138 // FIXME: Missing: array subscript of vector, member of vector 04139 }; 04140 } // end anonymous namespace 04141 04142 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 04143 /// produce either the integer value or a pointer. 04144 /// 04145 /// GCC has a heinous extension which folds casts between pointer types and 04146 /// pointer-sized integral types. We support this by allowing the evaluation of 04147 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 04148 /// Some simple arithmetic on such values is supported (they are treated much 04149 /// like char*). 04150 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 04151 EvalInfo &Info) { 04152 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 04153 return IntExprEvaluator(Info, Result).Visit(E); 04154 } 04155 04156 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 04157 APValue Val; 04158 if (!EvaluateIntegerOrLValue(E, Val, Info)) 04159 return false; 04160 if (!Val.isInt()) { 04161 // FIXME: It would be better to produce the diagnostic for casting 04162 // a pointer to an integer. 04163 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 04164 return false; 04165 } 04166 Result = Val.getInt(); 04167 return true; 04168 } 04169 04170 /// Check whether the given declaration can be directly converted to an integral 04171 /// rvalue. If not, no diagnostic is produced; there are other things we can 04172 /// try. 04173 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 04174 // Enums are integer constant exprs. 04175 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 04176 // Check for signedness/width mismatches between E type and ECD value. 04177 bool SameSign = (ECD->getInitVal().isSigned() 04178 == E->getType()->isSignedIntegerOrEnumerationType()); 04179 bool SameWidth = (ECD->getInitVal().getBitWidth() 04180 == Info.Ctx.getIntWidth(E->getType())); 04181 if (SameSign && SameWidth) 04182 return Success(ECD->getInitVal(), E); 04183 else { 04184 // Get rid of mismatch (otherwise Success assertions will fail) 04185 // by computing a new value matching the type of E. 04186 llvm::APSInt Val = ECD->getInitVal(); 04187 if (!SameSign) 04188 Val.setIsSigned(!ECD->getInitVal().isSigned()); 04189 if (!SameWidth) 04190 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 04191 return Success(Val, E); 04192 } 04193 } 04194 return false; 04195 } 04196 04197 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 04198 /// as GCC. 04199 static int EvaluateBuiltinClassifyType(const CallExpr *E) { 04200 // The following enum mimics the values returned by GCC. 04201 // FIXME: Does GCC differ between lvalue and rvalue references here? 04202 enum gcc_type_class { 04203 no_type_class = -1, 04204 void_type_class, integer_type_class, char_type_class, 04205 enumeral_type_class, boolean_type_class, 04206 pointer_type_class, reference_type_class, offset_type_class, 04207 real_type_class, complex_type_class, 04208 function_type_class, method_type_class, 04209 record_type_class, union_type_class, 04210 array_type_class, string_type_class, 04211 lang_type_class 04212 }; 04213 04214 // If no argument was supplied, default to "no_type_class". This isn't 04215 // ideal, however it is what gcc does. 04216 if (E->getNumArgs() == 0) 04217 return no_type_class; 04218 04219 QualType ArgTy = E->getArg(0)->getType(); 04220 if (ArgTy->isVoidType()) 04221 return void_type_class; 04222 else if (ArgTy->isEnumeralType()) 04223 return enumeral_type_class; 04224 else if (ArgTy->isBooleanType()) 04225 return boolean_type_class; 04226 else if (ArgTy->isCharType()) 04227 return string_type_class; // gcc doesn't appear to use char_type_class 04228 else if (ArgTy->isIntegerType()) 04229 return integer_type_class; 04230 else if (ArgTy->isPointerType()) 04231 return pointer_type_class; 04232 else if (ArgTy->isReferenceType()) 04233 return reference_type_class; 04234 else if (ArgTy->isRealType()) 04235 return real_type_class; 04236 else if (ArgTy->isComplexType()) 04237 return complex_type_class; 04238 else if (ArgTy->isFunctionType()) 04239 return function_type_class; 04240 else if (ArgTy->isStructureOrClassType()) 04241 return record_type_class; 04242 else if (ArgTy->isUnionType()) 04243 return union_type_class; 04244 else if (ArgTy->isArrayType()) 04245 return array_type_class; 04246 else if (ArgTy->isUnionType()) 04247 return union_type_class; 04248 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 04249 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 04250 } 04251 04252 /// EvaluateBuiltinConstantPForLValue - Determine the result of 04253 /// __builtin_constant_p when applied to the given lvalue. 04254 /// 04255 /// An lvalue is only "constant" if it is a pointer or reference to the first 04256 /// character of a string literal. 04257 template<typename LValue> 04258 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 04259 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 04260 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 04261 } 04262 04263 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 04264 /// GCC as we can manage. 04265 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 04266 QualType ArgType = Arg->getType(); 04267 04268 // __builtin_constant_p always has one operand. The rules which gcc follows 04269 // are not precisely documented, but are as follows: 04270 // 04271 // - If the operand is of integral, floating, complex or enumeration type, 04272 // and can be folded to a known value of that type, it returns 1. 04273 // - If the operand and can be folded to a pointer to the first character 04274 // of a string literal (or such a pointer cast to an integral type), it 04275 // returns 1. 04276 // 04277 // Otherwise, it returns 0. 04278 // 04279 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 04280 // its support for this does not currently work. 04281 if (ArgType->isIntegralOrEnumerationType()) { 04282 Expr::EvalResult Result; 04283 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 04284 return false; 04285 04286 APValue &V = Result.Val; 04287 if (V.getKind() == APValue::Int) 04288 return true; 04289 04290 return EvaluateBuiltinConstantPForLValue(V); 04291 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 04292 return Arg->isEvaluatable(Ctx); 04293 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 04294 LValue LV; 04295 Expr::EvalStatus Status; 04296 EvalInfo Info(Ctx, Status); 04297 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 04298 : EvaluatePointer(Arg, LV, Info)) && 04299 !Status.HasSideEffects) 04300 return EvaluateBuiltinConstantPForLValue(LV); 04301 } 04302 04303 // Anything else isn't considered to be sufficiently constant. 04304 return false; 04305 } 04306 04307 /// Retrieves the "underlying object type" of the given expression, 04308 /// as used by __builtin_object_size. 04309 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) { 04310 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 04311 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 04312 return VD->getType(); 04313 } else if (const Expr *E = B.get<const Expr*>()) { 04314 if (isa<CompoundLiteralExpr>(E)) 04315 return E->getType(); 04316 } 04317 04318 return QualType(); 04319 } 04320 04321 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) { 04322 // TODO: Perhaps we should let LLVM lower this? 04323 LValue Base; 04324 if (!EvaluatePointer(E->getArg(0), Base, Info)) 04325 return false; 04326 04327 // If we can prove the base is null, lower to zero now. 04328 if (!Base.getLValueBase()) return Success(0, E); 04329 04330 QualType T = GetObjectType(Base.getLValueBase()); 04331 if (T.isNull() || 04332 T->isIncompleteType() || 04333 T->isFunctionType() || 04334 T->isVariablyModifiedType() || 04335 T->isDependentType()) 04336 return Error(E); 04337 04338 CharUnits Size = Info.Ctx.getTypeSizeInChars(T); 04339 CharUnits Offset = Base.getLValueOffset(); 04340 04341 if (!Offset.isNegative() && Offset <= Size) 04342 Size -= Offset; 04343 else 04344 Size = CharUnits::Zero(); 04345 return Success(Size, E); 04346 } 04347 04348 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 04349 switch (unsigned BuiltinOp = E->isBuiltinCall()) { 04350 default: 04351 return ExprEvaluatorBaseTy::VisitCallExpr(E); 04352 04353 case Builtin::BI__builtin_object_size: { 04354 if (TryEvaluateBuiltinObjectSize(E)) 04355 return true; 04356 04357 // If evaluating the argument has side-effects we can't determine 04358 // the size of the object and lower it to unknown now. 04359 if (E->getArg(0)->HasSideEffects(Info.Ctx)) { 04360 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1) 04361 return Success(-1ULL, E); 04362 return Success(0, E); 04363 } 04364 04365 return Error(E); 04366 } 04367 04368 case Builtin::BI__builtin_classify_type: 04369 return Success(EvaluateBuiltinClassifyType(E), E); 04370 04371 case Builtin::BI__builtin_constant_p: 04372 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 04373 04374 case Builtin::BI__builtin_eh_return_data_regno: { 04375 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 04376 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 04377 return Success(Operand, E); 04378 } 04379 04380 case Builtin::BI__builtin_expect: 04381 return Visit(E->getArg(0)); 04382 04383 case Builtin::BIstrlen: 04384 // A call to strlen is not a constant expression. 04385 if (Info.getLangOpts().CPlusPlus0x) 04386 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 04387 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'"; 04388 else 04389 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 04390 // Fall through. 04391 case Builtin::BI__builtin_strlen: 04392 // As an extension, we support strlen() and __builtin_strlen() as constant 04393 // expressions when the argument is a string literal. 04394 if (const StringLiteral *S 04395 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) { 04396 // The string literal may have embedded null characters. Find the first 04397 // one and truncate there. 04398 StringRef Str = S->getString(); 04399 StringRef::size_type Pos = Str.find(0); 04400 if (Pos != StringRef::npos) 04401 Str = Str.substr(0, Pos); 04402 04403 return Success(Str.size(), E); 04404 } 04405 04406 return Error(E); 04407 04408 case Builtin::BI__atomic_always_lock_free: 04409 case Builtin::BI__atomic_is_lock_free: 04410 case Builtin::BI__c11_atomic_is_lock_free: { 04411 APSInt SizeVal; 04412 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 04413 return false; 04414 04415 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 04416 // of two less than the maximum inline atomic width, we know it is 04417 // lock-free. If the size isn't a power of two, or greater than the 04418 // maximum alignment where we promote atomics, we know it is not lock-free 04419 // (at least not in the sense of atomic_is_lock_free). Otherwise, 04420 // the answer can only be determined at runtime; for example, 16-byte 04421 // atomics have lock-free implementations on some, but not all, 04422 // x86-64 processors. 04423 04424 // Check power-of-two. 04425 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 04426 if (Size.isPowerOfTwo()) { 04427 // Check against inlining width. 04428 unsigned InlineWidthBits = 04429 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 04430 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 04431 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 04432 Size == CharUnits::One() || 04433 E->getArg(1)->isNullPointerConstant(Info.Ctx, 04434 Expr::NPC_NeverValueDependent)) 04435 // OK, we will inline appropriately-aligned operations of this size, 04436 // and _Atomic(T) is appropriately-aligned. 04437 return Success(1, E); 04438 04439 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 04440 castAs<PointerType>()->getPointeeType(); 04441 if (!PointeeType->isIncompleteType() && 04442 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 04443 // OK, we will inline operations on this object. 04444 return Success(1, E); 04445 } 04446 } 04447 } 04448 04449 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 04450 Success(0, E) : Error(E); 04451 } 04452 } 04453 } 04454 04455 static bool HasSameBase(const LValue &A, const LValue &B) { 04456 if (!A.getLValueBase()) 04457 return !B.getLValueBase(); 04458 if (!B.getLValueBase()) 04459 return false; 04460 04461 if (A.getLValueBase().getOpaqueValue() != 04462 B.getLValueBase().getOpaqueValue()) { 04463 const Decl *ADecl = GetLValueBaseDecl(A); 04464 if (!ADecl) 04465 return false; 04466 const Decl *BDecl = GetLValueBaseDecl(B); 04467 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 04468 return false; 04469 } 04470 04471 return IsGlobalLValue(A.getLValueBase()) || 04472 A.getLValueCallIndex() == B.getLValueCallIndex(); 04473 } 04474 04475 /// Perform the given integer operation, which is known to need at most BitWidth 04476 /// bits, and check for overflow in the original type (if that type was not an 04477 /// unsigned type). 04478 template<typename Operation> 04479 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 04480 const APSInt &LHS, const APSInt &RHS, 04481 unsigned BitWidth, Operation Op) { 04482 if (LHS.isUnsigned()) 04483 return Op(LHS, RHS); 04484 04485 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 04486 APSInt Result = Value.trunc(LHS.getBitWidth()); 04487 if (Result.extend(BitWidth) != Value) 04488 HandleOverflow(Info, E, Value, E->getType()); 04489 return Result; 04490 } 04491 04492 namespace { 04493 04494 /// \brief Data recursive integer evaluator of certain binary operators. 04495 /// 04496 /// We use a data recursive algorithm for binary operators so that we are able 04497 /// to handle extreme cases of chained binary operators without causing stack 04498 /// overflow. 04499 class DataRecursiveIntBinOpEvaluator { 04500 struct EvalResult { 04501 APValue Val; 04502 bool Failed; 04503 04504 EvalResult() : Failed(false) { } 04505 04506 void swap(EvalResult &RHS) { 04507 Val.swap(RHS.Val); 04508 Failed = RHS.Failed; 04509 RHS.Failed = false; 04510 } 04511 }; 04512 04513 struct Job { 04514 const Expr *E; 04515 EvalResult LHSResult; // meaningful only for binary operator expression. 04516 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 04517 04518 Job() : StoredInfo(0) { } 04519 void startSpeculativeEval(EvalInfo &Info) { 04520 OldEvalStatus = Info.EvalStatus; 04521 Info.EvalStatus.Diag = 0; 04522 StoredInfo = &Info; 04523 } 04524 ~Job() { 04525 if (StoredInfo) { 04526 StoredInfo->EvalStatus = OldEvalStatus; 04527 } 04528 } 04529 private: 04530 EvalInfo *StoredInfo; // non-null if status changed. 04531 Expr::EvalStatus OldEvalStatus; 04532 }; 04533 04534 SmallVector<Job, 16> Queue; 04535 04536 IntExprEvaluator &IntEval; 04537 EvalInfo &Info; 04538 APValue &FinalResult; 04539 04540 public: 04541 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 04542 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 04543 04544 /// \brief True if \param E is a binary operator that we are going to handle 04545 /// data recursively. 04546 /// We handle binary operators that are comma, logical, or that have operands 04547 /// with integral or enumeration type. 04548 static bool shouldEnqueue(const BinaryOperator *E) { 04549 return E->getOpcode() == BO_Comma || 04550 E->isLogicalOp() || 04551 (E->getLHS()->getType()->isIntegralOrEnumerationType() && 04552 E->getRHS()->getType()->isIntegralOrEnumerationType()); 04553 } 04554 04555 bool Traverse(const BinaryOperator *E) { 04556 enqueue(E); 04557 EvalResult PrevResult; 04558 while (!Queue.empty()) 04559 process(PrevResult); 04560 04561 if (PrevResult.Failed) return false; 04562 04563 FinalResult.swap(PrevResult.Val); 04564 return true; 04565 } 04566 04567 private: 04568 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 04569 return IntEval.Success(Value, E, Result); 04570 } 04571 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 04572 return IntEval.Success(Value, E, Result); 04573 } 04574 bool Error(const Expr *E) { 04575 return IntEval.Error(E); 04576 } 04577 bool Error(const Expr *E, diag::kind D) { 04578 return IntEval.Error(E, D); 04579 } 04580 04581 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 04582 return Info.CCEDiag(E, D); 04583 } 04584 04585 // \brief Returns true if visiting the RHS is necessary, false otherwise. 04586 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 04587 bool &SuppressRHSDiags); 04588 04589 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 04590 const BinaryOperator *E, APValue &Result); 04591 04592 void EvaluateExpr(const Expr *E, EvalResult &Result) { 04593 Result.Failed = !Evaluate(Result.Val, Info, E); 04594 if (Result.Failed) 04595 Result.Val = APValue(); 04596 } 04597 04598 void process(EvalResult &Result); 04599 04600 void enqueue(const Expr *E) { 04601 E = E->IgnoreParens(); 04602 Queue.resize(Queue.size()+1); 04603 Queue.back().E = E; 04604 Queue.back().Kind = Job::AnyExprKind; 04605 } 04606 }; 04607 04608 } 04609 04610 bool DataRecursiveIntBinOpEvaluator:: 04611 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 04612 bool &SuppressRHSDiags) { 04613 if (E->getOpcode() == BO_Comma) { 04614 // Ignore LHS but note if we could not evaluate it. 04615 if (LHSResult.Failed) 04616 Info.EvalStatus.HasSideEffects = true; 04617 return true; 04618 } 04619 04620 if (E->isLogicalOp()) { 04621 bool lhsResult; 04622 if (HandleConversionToBool(LHSResult.Val, lhsResult)) { 04623 // We were able to evaluate the LHS, see if we can get away with not 04624 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 04625 if (lhsResult == (E->getOpcode() == BO_LOr)) { 04626 Success(lhsResult, E, LHSResult.Val); 04627 return false; // Ignore RHS 04628 } 04629 } else { 04630 // Since we weren't able to evaluate the left hand side, it 04631 // must have had side effects. 04632 Info.EvalStatus.HasSideEffects = true; 04633 04634 // We can't evaluate the LHS; however, sometimes the result 04635 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 04636 // Don't ignore RHS and suppress diagnostics from this arm. 04637 SuppressRHSDiags = true; 04638 } 04639 04640 return true; 04641 } 04642 04643 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 04644 E->getRHS()->getType()->isIntegralOrEnumerationType()); 04645 04646 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure()) 04647 return false; // Ignore RHS; 04648 04649 return true; 04650 } 04651 04652 bool DataRecursiveIntBinOpEvaluator:: 04653 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 04654 const BinaryOperator *E, APValue &Result) { 04655 if (E->getOpcode() == BO_Comma) { 04656 if (RHSResult.Failed) 04657 return false; 04658 Result = RHSResult.Val; 04659 return true; 04660 } 04661 04662 if (E->isLogicalOp()) { 04663 bool lhsResult, rhsResult; 04664 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 04665 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 04666 04667 if (LHSIsOK) { 04668 if (RHSIsOK) { 04669 if (E->getOpcode() == BO_LOr) 04670 return Success(lhsResult || rhsResult, E, Result); 04671 else 04672 return Success(lhsResult && rhsResult, E, Result); 04673 } 04674 } else { 04675 if (RHSIsOK) { 04676 // We can't evaluate the LHS; however, sometimes the result 04677 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 04678 if (rhsResult == (E->getOpcode() == BO_LOr)) 04679 return Success(rhsResult, E, Result); 04680 } 04681 } 04682 04683 return false; 04684 } 04685 04686 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 04687 E->getRHS()->getType()->isIntegralOrEnumerationType()); 04688 04689 if (LHSResult.Failed || RHSResult.Failed) 04690 return false; 04691 04692 const APValue &LHSVal = LHSResult.Val; 04693 const APValue &RHSVal = RHSResult.Val; 04694 04695 // Handle cases like (unsigned long)&a + 4. 04696 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 04697 Result = LHSVal; 04698 CharUnits AdditionalOffset = CharUnits::fromQuantity( 04699 RHSVal.getInt().getZExtValue()); 04700 if (E->getOpcode() == BO_Add) 04701 Result.getLValueOffset() += AdditionalOffset; 04702 else 04703 Result.getLValueOffset() -= AdditionalOffset; 04704 return true; 04705 } 04706 04707 // Handle cases like 4 + (unsigned long)&a 04708 if (E->getOpcode() == BO_Add && 04709 RHSVal.isLValue() && LHSVal.isInt()) { 04710 Result = RHSVal; 04711 Result.getLValueOffset() += CharUnits::fromQuantity( 04712 LHSVal.getInt().getZExtValue()); 04713 return true; 04714 } 04715 04716 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 04717 // Handle (intptr_t)&&A - (intptr_t)&&B. 04718 if (!LHSVal.getLValueOffset().isZero() || 04719 !RHSVal.getLValueOffset().isZero()) 04720 return false; 04721 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 04722 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 04723 if (!LHSExpr || !RHSExpr) 04724 return false; 04725 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 04726 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 04727 if (!LHSAddrExpr || !RHSAddrExpr) 04728 return false; 04729 // Make sure both labels come from the same function. 04730 if (LHSAddrExpr->getLabel()->getDeclContext() != 04731 RHSAddrExpr->getLabel()->getDeclContext()) 04732 return false; 04733 Result = APValue(LHSAddrExpr, RHSAddrExpr); 04734 return true; 04735 } 04736 04737 // All the following cases expect both operands to be an integer 04738 if (!LHSVal.isInt() || !RHSVal.isInt()) 04739 return Error(E); 04740 04741 const APSInt &LHS = LHSVal.getInt(); 04742 APSInt RHS = RHSVal.getInt(); 04743 04744 switch (E->getOpcode()) { 04745 default: 04746 return Error(E); 04747 case BO_Mul: 04748 return Success(CheckedIntArithmetic(Info, E, LHS, RHS, 04749 LHS.getBitWidth() * 2, 04750 std::multiplies<APSInt>()), E, 04751 Result); 04752 case BO_Add: 04753 return Success(CheckedIntArithmetic(Info, E, LHS, RHS, 04754 LHS.getBitWidth() + 1, 04755 std::plus<APSInt>()), E, Result); 04756 case BO_Sub: 04757 return Success(CheckedIntArithmetic(Info, E, LHS, RHS, 04758 LHS.getBitWidth() + 1, 04759 std::minus<APSInt>()), E, Result); 04760 case BO_And: return Success(LHS & RHS, E, Result); 04761 case BO_Xor: return Success(LHS ^ RHS, E, Result); 04762 case BO_Or: return Success(LHS | RHS, E, Result); 04763 case BO_Div: 04764 case BO_Rem: 04765 if (RHS == 0) 04766 return Error(E, diag::note_expr_divide_by_zero); 04767 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is 04768 // not actually undefined behavior in C++11 due to a language defect. 04769 if (RHS.isNegative() && RHS.isAllOnesValue() && 04770 LHS.isSigned() && LHS.isMinSignedValue()) 04771 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); 04772 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E, 04773 Result); 04774 case BO_Shl: { 04775 // During constant-folding, a negative shift is an opposite shift. Such 04776 // a shift is not a constant expression. 04777 if (RHS.isSigned() && RHS.isNegative()) { 04778 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 04779 RHS = -RHS; 04780 goto shift_right; 04781 } 04782 04783 shift_left: 04784 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 04785 // the shifted type. 04786 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 04787 if (SA != RHS) { 04788 CCEDiag(E, diag::note_constexpr_large_shift) 04789 << RHS << E->getType() << LHS.getBitWidth(); 04790 } else if (LHS.isSigned()) { 04791 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 04792 // operand, and must not overflow the corresponding unsigned type. 04793 if (LHS.isNegative()) 04794 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 04795 else if (LHS.countLeadingZeros() < SA) 04796 CCEDiag(E, diag::note_constexpr_lshift_discards); 04797 } 04798 04799 return Success(LHS << SA, E, Result); 04800 } 04801 case BO_Shr: { 04802 // During constant-folding, a negative shift is an opposite shift. Such a 04803 // shift is not a constant expression. 04804 if (RHS.isSigned() && RHS.isNegative()) { 04805 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 04806 RHS = -RHS; 04807 goto shift_left; 04808 } 04809 04810 shift_right: 04811 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 04812 // shifted type. 04813 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 04814 if (SA != RHS) 04815 CCEDiag(E, diag::note_constexpr_large_shift) 04816 << RHS << E->getType() << LHS.getBitWidth(); 04817 04818 return Success(LHS >> SA, E, Result); 04819 } 04820 04821 case BO_LT: return Success(LHS < RHS, E, Result); 04822 case BO_GT: return Success(LHS > RHS, E, Result); 04823 case BO_LE: return Success(LHS <= RHS, E, Result); 04824 case BO_GE: return Success(LHS >= RHS, E, Result); 04825 case BO_EQ: return Success(LHS == RHS, E, Result); 04826 case BO_NE: return Success(LHS != RHS, E, Result); 04827 } 04828 } 04829 04830 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 04831 Job &job = Queue.back(); 04832 04833 switch (job.Kind) { 04834 case Job::AnyExprKind: { 04835 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 04836 if (shouldEnqueue(Bop)) { 04837 job.Kind = Job::BinOpKind; 04838 enqueue(Bop->getLHS()); 04839 return; 04840 } 04841 } 04842 04843 EvaluateExpr(job.E, Result); 04844 Queue.pop_back(); 04845 return; 04846 } 04847 04848 case Job::BinOpKind: { 04849 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 04850 bool SuppressRHSDiags = false; 04851 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 04852 Queue.pop_back(); 04853 return; 04854 } 04855 if (SuppressRHSDiags) 04856 job.startSpeculativeEval(Info); 04857 job.LHSResult.swap(Result); 04858 job.Kind = Job::BinOpVisitedLHSKind; 04859 enqueue(Bop->getRHS()); 04860 return; 04861 } 04862 04863 case Job::BinOpVisitedLHSKind: { 04864 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 04865 EvalResult RHS; 04866 RHS.swap(Result); 04867 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 04868 Queue.pop_back(); 04869 return; 04870 } 04871 } 04872 04873 llvm_unreachable("Invalid Job::Kind!"); 04874 } 04875 04876 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 04877 if (E->isAssignmentOp()) 04878 return Error(E); 04879 04880 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 04881 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 04882 04883 QualType LHSTy = E->getLHS()->getType(); 04884 QualType RHSTy = E->getRHS()->getType(); 04885 04886 if (LHSTy->isAnyComplexType()) { 04887 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 04888 ComplexValue LHS, RHS; 04889 04890 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 04891 if (!LHSOK && !Info.keepEvaluatingAfterFailure()) 04892 return false; 04893 04894 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 04895 return false; 04896 04897 if (LHS.isComplexFloat()) { 04898 APFloat::cmpResult CR_r = 04899 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 04900 APFloat::cmpResult CR_i = 04901 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 04902 04903 if (E->getOpcode() == BO_EQ) 04904 return Success((CR_r == APFloat::cmpEqual && 04905 CR_i == APFloat::cmpEqual), E); 04906 else { 04907 assert(E->getOpcode() == BO_NE && 04908 "Invalid complex comparison."); 04909 return Success(((CR_r == APFloat::cmpGreaterThan || 04910 CR_r == APFloat::cmpLessThan || 04911 CR_r == APFloat::cmpUnordered) || 04912 (CR_i == APFloat::cmpGreaterThan || 04913 CR_i == APFloat::cmpLessThan || 04914 CR_i == APFloat::cmpUnordered)), E); 04915 } 04916 } else { 04917 if (E->getOpcode() == BO_EQ) 04918 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 04919 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 04920 else { 04921 assert(E->getOpcode() == BO_NE && 04922 "Invalid compex comparison."); 04923 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 04924 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 04925 } 04926 } 04927 } 04928 04929 if (LHSTy->isRealFloatingType() && 04930 RHSTy->isRealFloatingType()) { 04931 APFloat RHS(0.0), LHS(0.0); 04932 04933 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 04934 if (!LHSOK && !Info.keepEvaluatingAfterFailure()) 04935 return false; 04936 04937 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 04938 return false; 04939 04940 APFloat::cmpResult CR = LHS.compare(RHS); 04941 04942 switch (E->getOpcode()) { 04943 default: 04944 llvm_unreachable("Invalid binary operator!"); 04945 case BO_LT: 04946 return Success(CR == APFloat::cmpLessThan, E); 04947 case BO_GT: 04948 return Success(CR == APFloat::cmpGreaterThan, E); 04949 case BO_LE: 04950 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 04951 case BO_GE: 04952 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 04953 E); 04954 case BO_EQ: 04955 return Success(CR == APFloat::cmpEqual, E); 04956 case BO_NE: 04957 return Success(CR == APFloat::cmpGreaterThan 04958 || CR == APFloat::cmpLessThan 04959 || CR == APFloat::cmpUnordered, E); 04960 } 04961 } 04962 04963 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 04964 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 04965 LValue LHSValue, RHSValue; 04966 04967 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 04968 if (!LHSOK && Info.keepEvaluatingAfterFailure()) 04969 return false; 04970 04971 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 04972 return false; 04973 04974 // Reject differing bases from the normal codepath; we special-case 04975 // comparisons to null. 04976 if (!HasSameBase(LHSValue, RHSValue)) { 04977 if (E->getOpcode() == BO_Sub) { 04978 // Handle &&A - &&B. 04979 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 04980 return false; 04981 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 04982 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 04983 if (!LHSExpr || !RHSExpr) 04984 return false; 04985 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 04986 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 04987 if (!LHSAddrExpr || !RHSAddrExpr) 04988 return false; 04989 // Make sure both labels come from the same function. 04990 if (LHSAddrExpr->getLabel()->getDeclContext() != 04991 RHSAddrExpr->getLabel()->getDeclContext()) 04992 return false; 04993 Result = APValue(LHSAddrExpr, RHSAddrExpr); 04994 return true; 04995 } 04996 // Inequalities and subtractions between unrelated pointers have 04997 // unspecified or undefined behavior. 04998 if (!E->isEqualityOp()) 04999 return Error(E); 05000 // A constant address may compare equal to the address of a symbol. 05001 // The one exception is that address of an object cannot compare equal 05002 // to a null pointer constant. 05003 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 05004 (!RHSValue.Base && !RHSValue.Offset.isZero())) 05005 return Error(E); 05006 // It's implementation-defined whether distinct literals will have 05007 // distinct addresses. In clang, the result of such a comparison is 05008 // unspecified, so it is not a constant expression. However, we do know 05009 // that the address of a literal will be non-null. 05010 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 05011 LHSValue.Base && RHSValue.Base) 05012 return Error(E); 05013 // We can't tell whether weak symbols will end up pointing to the same 05014 // object. 05015 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 05016 return Error(E); 05017 // Pointers with different bases cannot represent the same object. 05018 // (Note that clang defaults to -fmerge-all-constants, which can 05019 // lead to inconsistent results for comparisons involving the address 05020 // of a constant; this generally doesn't matter in practice.) 05021 return Success(E->getOpcode() == BO_NE, E); 05022 } 05023 05024 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 05025 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 05026 05027 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 05028 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 05029 05030 if (E->getOpcode() == BO_Sub) { 05031 // C++11 [expr.add]p6: 05032 // Unless both pointers point to elements of the same array object, or 05033 // one past the last element of the array object, the behavior is 05034 // undefined. 05035 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 05036 !AreElementsOfSameArray(getType(LHSValue.Base), 05037 LHSDesignator, RHSDesignator)) 05038 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 05039 05040 QualType Type = E->getLHS()->getType(); 05041 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 05042 05043 CharUnits ElementSize; 05044 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 05045 return false; 05046 05047 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 05048 // and produce incorrect results when it overflows. Such behavior 05049 // appears to be non-conforming, but is common, so perhaps we should 05050 // assume the standard intended for such cases to be undefined behavior 05051 // and check for them. 05052 05053 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 05054 // overflow in the final conversion to ptrdiff_t. 05055 APSInt LHS( 05056 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 05057 APSInt RHS( 05058 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 05059 APSInt ElemSize( 05060 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false); 05061 APSInt TrueResult = (LHS - RHS) / ElemSize; 05062 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 05063 05064 if (Result.extend(65) != TrueResult) 05065 HandleOverflow(Info, E, TrueResult, E->getType()); 05066 return Success(Result, E); 05067 } 05068 05069 // C++11 [expr.rel]p3: 05070 // Pointers to void (after pointer conversions) can be compared, with a 05071 // result defined as follows: If both pointers represent the same 05072 // address or are both the null pointer value, the result is true if the 05073 // operator is <= or >= and false otherwise; otherwise the result is 05074 // unspecified. 05075 // We interpret this as applying to pointers to *cv* void. 05076 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && 05077 E->isRelationalOp()) 05078 CCEDiag(E, diag::note_constexpr_void_comparison); 05079 05080 // C++11 [expr.rel]p2: 05081 // - If two pointers point to non-static data members of the same object, 05082 // or to subobjects or array elements fo such members, recursively, the 05083 // pointer to the later declared member compares greater provided the 05084 // two members have the same access control and provided their class is 05085 // not a union. 05086 // [...] 05087 // - Otherwise pointer comparisons are unspecified. 05088 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 05089 E->isRelationalOp()) { 05090 bool WasArrayIndex; 05091 unsigned Mismatch = 05092 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator, 05093 RHSDesignator, WasArrayIndex); 05094 // At the point where the designators diverge, the comparison has a 05095 // specified value if: 05096 // - we are comparing array indices 05097 // - we are comparing fields of a union, or fields with the same access 05098 // Otherwise, the result is unspecified and thus the comparison is not a 05099 // constant expression. 05100 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 05101 Mismatch < RHSDesignator.Entries.size()) { 05102 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 05103 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 05104 if (!LF && !RF) 05105 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 05106 else if (!LF) 05107 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 05108 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 05109 << RF->getParent() << RF; 05110 else if (!RF) 05111 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 05112 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 05113 << LF->getParent() << LF; 05114 else if (!LF->getParent()->isUnion() && 05115 LF->getAccess() != RF->getAccess()) 05116 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access) 05117 << LF << LF->getAccess() << RF << RF->getAccess() 05118 << LF->getParent(); 05119 } 05120 } 05121 05122 // The comparison here must be unsigned, and performed with the same 05123 // width as the pointer. 05124 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 05125 uint64_t CompareLHS = LHSOffset.getQuantity(); 05126 uint64_t CompareRHS = RHSOffset.getQuantity(); 05127 assert(PtrSize <= 64 && "Unexpected pointer width"); 05128 uint64_t Mask = ~0ULL >> (64 - PtrSize); 05129 CompareLHS &= Mask; 05130 CompareRHS &= Mask; 05131 05132 // If there is a base and this is a relational operator, we can only 05133 // compare pointers within the object in question; otherwise, the result 05134 // depends on where the object is located in memory. 05135 if (!LHSValue.Base.isNull() && E->isRelationalOp()) { 05136 QualType BaseTy = getType(LHSValue.Base); 05137 if (BaseTy->isIncompleteType()) 05138 return Error(E); 05139 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 05140 uint64_t OffsetLimit = Size.getQuantity(); 05141 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 05142 return Error(E); 05143 } 05144 05145 switch (E->getOpcode()) { 05146 default: llvm_unreachable("missing comparison operator"); 05147 case BO_LT: return Success(CompareLHS < CompareRHS, E); 05148 case BO_GT: return Success(CompareLHS > CompareRHS, E); 05149 case BO_LE: return Success(CompareLHS <= CompareRHS, E); 05150 case BO_GE: return Success(CompareLHS >= CompareRHS, E); 05151 case BO_EQ: return Success(CompareLHS == CompareRHS, E); 05152 case BO_NE: return Success(CompareLHS != CompareRHS, E); 05153 } 05154 } 05155 } 05156 05157 if (LHSTy->isMemberPointerType()) { 05158 assert(E->isEqualityOp() && "unexpected member pointer operation"); 05159 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 05160 05161 MemberPtr LHSValue, RHSValue; 05162 05163 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 05164 if (!LHSOK && Info.keepEvaluatingAfterFailure()) 05165 return false; 05166 05167 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 05168 return false; 05169 05170 // C++11 [expr.eq]p2: 05171 // If both operands are null, they compare equal. Otherwise if only one is 05172 // null, they compare unequal. 05173 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 05174 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 05175 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 05176 } 05177 05178 // Otherwise if either is a pointer to a virtual member function, the 05179 // result is unspecified. 05180 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 05181 if (MD->isVirtual()) 05182 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 05183 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 05184 if (MD->isVirtual()) 05185 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 05186 05187 // Otherwise they compare equal if and only if they would refer to the 05188 // same member of the same most derived object or the same subobject if 05189 // they were dereferenced with a hypothetical object of the associated 05190 // class type. 05191 bool Equal = LHSValue == RHSValue; 05192 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 05193 } 05194 05195 if (LHSTy->isNullPtrType()) { 05196 assert(E->isComparisonOp() && "unexpected nullptr operation"); 05197 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 05198 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 05199 // are compared, the result is true of the operator is <=, >= or ==, and 05200 // false otherwise. 05201 BinaryOperator::Opcode Opcode = E->getOpcode(); 05202 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E); 05203 } 05204 05205 assert((!LHSTy->isIntegralOrEnumerationType() || 05206 !RHSTy->isIntegralOrEnumerationType()) && 05207 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 05208 // We can't continue from here for non-integral types. 05209 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 05210 } 05211 05212 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) { 05213 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 05214 // result shall be the alignment of the referenced type." 05215 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 05216 T = Ref->getPointeeType(); 05217 05218 // __alignof is defined to return the preferred alignment. 05219 return Info.Ctx.toCharUnitsFromBits( 05220 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 05221 } 05222 05223 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 05224 E = E->IgnoreParens(); 05225 05226 // alignof decl is always accepted, even if it doesn't make sense: we default 05227 // to 1 in those cases. 05228 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 05229 return Info.Ctx.getDeclAlign(DRE->getDecl(), 05230 /*RefAsPointee*/true); 05231 05232 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 05233 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 05234 /*RefAsPointee*/true); 05235 05236 return GetAlignOfType(E->getType()); 05237 } 05238 05239 05240 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 05241 /// a result as the expression's type. 05242 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 05243 const UnaryExprOrTypeTraitExpr *E) { 05244 switch(E->getKind()) { 05245 case UETT_AlignOf: { 05246 if (E->isArgumentType()) 05247 return Success(GetAlignOfType(E->getArgumentType()), E); 05248 else 05249 return Success(GetAlignOfExpr(E->getArgumentExpr()), E); 05250 } 05251 05252 case UETT_VecStep: { 05253 QualType Ty = E->getTypeOfArgument(); 05254 05255 if (Ty->isVectorType()) { 05256 unsigned n = Ty->getAs<VectorType>()->getNumElements(); 05257 05258 // The vec_step built-in functions that take a 3-component 05259 // vector return 4. (OpenCL 1.1 spec 6.11.12) 05260 if (n == 3) 05261 n = 4; 05262 05263 return Success(n, E); 05264 } else 05265 return Success(1, E); 05266 } 05267 05268 case UETT_SizeOf: { 05269 QualType SrcTy = E->getTypeOfArgument(); 05270 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 05271 // the result is the size of the referenced type." 05272 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 05273 SrcTy = Ref->getPointeeType(); 05274 05275 CharUnits Sizeof; 05276 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 05277 return false; 05278 return Success(Sizeof, E); 05279 } 05280 } 05281 05282 llvm_unreachable("unknown expr/type trait"); 05283 } 05284 05285 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 05286 CharUnits Result; 05287 unsigned n = OOE->getNumComponents(); 05288 if (n == 0) 05289 return Error(OOE); 05290 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 05291 for (unsigned i = 0; i != n; ++i) { 05292 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i); 05293 switch (ON.getKind()) { 05294 case OffsetOfExpr::OffsetOfNode::Array: { 05295 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 05296 APSInt IdxResult; 05297 if (!EvaluateInteger(Idx, IdxResult, Info)) 05298 return false; 05299 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 05300 if (!AT) 05301 return Error(OOE); 05302 CurrentType = AT->getElementType(); 05303 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 05304 Result += IdxResult.getSExtValue() * ElementSize; 05305 break; 05306 } 05307 05308 case OffsetOfExpr::OffsetOfNode::Field: { 05309 FieldDecl *MemberDecl = ON.getField(); 05310 const RecordType *RT = CurrentType->getAs<RecordType>(); 05311 if (!RT) 05312 return Error(OOE); 05313 RecordDecl *RD = RT->getDecl(); 05314 if (RD->isInvalidDecl()) return false; 05315 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 05316 unsigned i = MemberDecl->getFieldIndex(); 05317 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 05318 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 05319 CurrentType = MemberDecl->getType().getNonReferenceType(); 05320 break; 05321 } 05322 05323 case OffsetOfExpr::OffsetOfNode::Identifier: 05324 llvm_unreachable("dependent __builtin_offsetof"); 05325 05326 case OffsetOfExpr::OffsetOfNode::Base: { 05327 CXXBaseSpecifier *BaseSpec = ON.getBase(); 05328 if (BaseSpec->isVirtual()) 05329 return Error(OOE); 05330 05331 // Find the layout of the class whose base we are looking into. 05332 const RecordType *RT = CurrentType->getAs<RecordType>(); 05333 if (!RT) 05334 return Error(OOE); 05335 RecordDecl *RD = RT->getDecl(); 05336 if (RD->isInvalidDecl()) return false; 05337 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 05338 05339 // Find the base class itself. 05340 CurrentType = BaseSpec->getType(); 05341 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 05342 if (!BaseRT) 05343 return Error(OOE); 05344 05345 // Add the offset to the base. 05346 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 05347 break; 05348 } 05349 } 05350 } 05351 return Success(Result, OOE); 05352 } 05353 05354 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 05355 switch (E->getOpcode()) { 05356 default: 05357 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 05358 // See C99 6.6p3. 05359 return Error(E); 05360 case UO_Extension: 05361 // FIXME: Should extension allow i-c-e extension expressions in its scope? 05362 // If so, we could clear the diagnostic ID. 05363 return Visit(E->getSubExpr()); 05364 case UO_Plus: 05365 // The result is just the value. 05366 return Visit(E->getSubExpr()); 05367 case UO_Minus: { 05368 if (!Visit(E->getSubExpr())) 05369 return false; 05370 if (!Result.isInt()) return Error(E); 05371 const APSInt &Value = Result.getInt(); 05372 if (Value.isSigned() && Value.isMinSignedValue()) 05373 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 05374 E->getType()); 05375 return Success(-Value, E); 05376 } 05377 case UO_Not: { 05378 if (!Visit(E->getSubExpr())) 05379 return false; 05380 if (!Result.isInt()) return Error(E); 05381 return Success(~Result.getInt(), E); 05382 } 05383 case UO_LNot: { 05384 bool bres; 05385 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 05386 return false; 05387 return Success(!bres, E); 05388 } 05389 } 05390 } 05391 05392 /// HandleCast - This is used to evaluate implicit or explicit casts where the 05393 /// result type is integer. 05394 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 05395 const Expr *SubExpr = E->getSubExpr(); 05396 QualType DestType = E->getType(); 05397 QualType SrcType = SubExpr->getType(); 05398 05399 switch (E->getCastKind()) { 05400 case CK_BaseToDerived: 05401 case CK_DerivedToBase: 05402 case CK_UncheckedDerivedToBase: 05403 case CK_Dynamic: 05404 case CK_ToUnion: 05405 case CK_ArrayToPointerDecay: 05406 case CK_FunctionToPointerDecay: 05407 case CK_NullToPointer: 05408 case CK_NullToMemberPointer: 05409 case CK_BaseToDerivedMemberPointer: 05410 case CK_DerivedToBaseMemberPointer: 05411 case CK_ReinterpretMemberPointer: 05412 case CK_ConstructorConversion: 05413 case CK_IntegralToPointer: 05414 case CK_ToVoid: 05415 case CK_VectorSplat: 05416 case CK_IntegralToFloating: 05417 case CK_FloatingCast: 05418 case CK_CPointerToObjCPointerCast: 05419 case CK_BlockPointerToObjCPointerCast: 05420 case CK_AnyPointerToBlockPointerCast: 05421 case CK_ObjCObjectLValueCast: 05422 case CK_FloatingRealToComplex: 05423 case CK_FloatingComplexToReal: 05424 case CK_FloatingComplexCast: 05425 case CK_FloatingComplexToIntegralComplex: 05426 case CK_IntegralRealToComplex: 05427 case CK_IntegralComplexCast: 05428 case CK_IntegralComplexToFloatingComplex: 05429 llvm_unreachable("invalid cast kind for integral value"); 05430 05431 case CK_BitCast: 05432 case CK_Dependent: 05433 case CK_LValueBitCast: 05434 case CK_ARCProduceObject: 05435 case CK_ARCConsumeObject: 05436 case CK_ARCReclaimReturnedObject: 05437 case CK_ARCExtendBlockObject: 05438 case CK_CopyAndAutoreleaseBlockObject: 05439 return Error(E); 05440 05441 case CK_UserDefinedConversion: 05442 case CK_LValueToRValue: 05443 case CK_AtomicToNonAtomic: 05444 case CK_NonAtomicToAtomic: 05445 case CK_NoOp: 05446 return ExprEvaluatorBaseTy::VisitCastExpr(E); 05447 05448 case CK_MemberPointerToBoolean: 05449 case CK_PointerToBoolean: 05450 case CK_IntegralToBoolean: 05451 case CK_FloatingToBoolean: 05452 case CK_FloatingComplexToBoolean: 05453 case CK_IntegralComplexToBoolean: { 05454 bool BoolResult; 05455 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 05456 return false; 05457 return Success(BoolResult, E); 05458 } 05459 05460 case CK_IntegralCast: { 05461 if (!Visit(SubExpr)) 05462 return false; 05463 05464 if (!Result.isInt()) { 05465 // Allow casts of address-of-label differences if they are no-ops 05466 // or narrowing. (The narrowing case isn't actually guaranteed to 05467 // be constant-evaluatable except in some narrow cases which are hard 05468 // to detect here. We let it through on the assumption the user knows 05469 // what they are doing.) 05470 if (Result.isAddrLabelDiff()) 05471 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 05472 // Only allow casts of lvalues if they are lossless. 05473 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 05474 } 05475 05476 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 05477 Result.getInt()), E); 05478 } 05479 05480 case CK_PointerToIntegral: { 05481 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 05482 05483 LValue LV; 05484 if (!EvaluatePointer(SubExpr, LV, Info)) 05485 return false; 05486 05487 if (LV.getLValueBase()) { 05488 // Only allow based lvalue casts if they are lossless. 05489 // FIXME: Allow a larger integer size than the pointer size, and allow 05490 // narrowing back down to pointer width in subsequent integral casts. 05491 // FIXME: Check integer type's active bits, not its type size. 05492 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 05493 return Error(E); 05494 05495 LV.Designator.setInvalid(); 05496 LV.moveInto(Result); 05497 return true; 05498 } 05499 05500 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 05501 SrcType); 05502 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 05503 } 05504 05505 case CK_IntegralComplexToReal: { 05506 ComplexValue C; 05507 if (!EvaluateComplex(SubExpr, C, Info)) 05508 return false; 05509 return Success(C.getComplexIntReal(), E); 05510 } 05511 05512 case CK_FloatingToIntegral: { 05513 APFloat F(0.0); 05514 if (!EvaluateFloat(SubExpr, F, Info)) 05515 return false; 05516 05517 APSInt Value; 05518 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 05519 return false; 05520 return Success(Value, E); 05521 } 05522 } 05523 05524 llvm_unreachable("unknown cast resulting in integral value"); 05525 } 05526 05527 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 05528 if (E->getSubExpr()->getType()->isAnyComplexType()) { 05529 ComplexValue LV; 05530 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 05531 return false; 05532 if (!LV.isComplexInt()) 05533 return Error(E); 05534 return Success(LV.getComplexIntReal(), E); 05535 } 05536 05537 return Visit(E->getSubExpr()); 05538 } 05539 05540 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 05541 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 05542 ComplexValue LV; 05543 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 05544 return false; 05545 if (!LV.isComplexInt()) 05546 return Error(E); 05547 return Success(LV.getComplexIntImag(), E); 05548 } 05549 05550 VisitIgnoredValue(E->getSubExpr()); 05551 return Success(0, E); 05552 } 05553 05554 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 05555 return Success(E->getPackLength(), E); 05556 } 05557 05558 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 05559 return Success(E->getValue(), E); 05560 } 05561 05562 //===----------------------------------------------------------------------===// 05563 // Float Evaluation 05564 //===----------------------------------------------------------------------===// 05565 05566 namespace { 05567 class FloatExprEvaluator 05568 : public ExprEvaluatorBase<FloatExprEvaluator, bool> { 05569 APFloat &Result; 05570 public: 05571 FloatExprEvaluator(EvalInfo &info, APFloat &result) 05572 : ExprEvaluatorBaseTy(info), Result(result) {} 05573 05574 bool Success(const APValue &V, const Expr *e) { 05575 Result = V.getFloat(); 05576 return true; 05577 } 05578 05579 bool ZeroInitialization(const Expr *E) { 05580 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 05581 return true; 05582 } 05583 05584 bool VisitCallExpr(const CallExpr *E); 05585 05586 bool VisitUnaryOperator(const UnaryOperator *E); 05587 bool VisitBinaryOperator(const BinaryOperator *E); 05588 bool VisitFloatingLiteral(const FloatingLiteral *E); 05589 bool VisitCastExpr(const CastExpr *E); 05590 05591 bool VisitUnaryReal(const UnaryOperator *E); 05592 bool VisitUnaryImag(const UnaryOperator *E); 05593 05594 // FIXME: Missing: array subscript of vector, member of vector 05595 }; 05596 } // end anonymous namespace 05597 05598 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 05599 assert(E->isRValue() && E->getType()->isRealFloatingType()); 05600 return FloatExprEvaluator(Info, Result).Visit(E); 05601 } 05602 05603 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 05604 QualType ResultTy, 05605 const Expr *Arg, 05606 bool SNaN, 05607 llvm::APFloat &Result) { 05608 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 05609 if (!S) return false; 05610 05611 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 05612 05613 llvm::APInt fill; 05614 05615 // Treat empty strings as if they were zero. 05616 if (S->getString().empty()) 05617 fill = llvm::APInt(32, 0); 05618 else if (S->getString().getAsInteger(0, fill)) 05619 return false; 05620 05621 if (SNaN) 05622 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 05623 else 05624 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 05625 return true; 05626 } 05627 05628 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 05629 switch (E->isBuiltinCall()) { 05630 default: 05631 return ExprEvaluatorBaseTy::VisitCallExpr(E); 05632 05633 case Builtin::BI__builtin_huge_val: 05634 case Builtin::BI__builtin_huge_valf: 05635 case Builtin::BI__builtin_huge_vall: 05636 case Builtin::BI__builtin_inf: 05637 case Builtin::BI__builtin_inff: 05638 case Builtin::BI__builtin_infl: { 05639 const llvm::fltSemantics &Sem = 05640 Info.Ctx.getFloatTypeSemantics(E->getType()); 05641 Result = llvm::APFloat::getInf(Sem); 05642 return true; 05643 } 05644 05645 case Builtin::BI__builtin_nans: 05646 case Builtin::BI__builtin_nansf: 05647 case Builtin::BI__builtin_nansl: 05648 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 05649 true, Result)) 05650 return Error(E); 05651 return true; 05652 05653 case Builtin::BI__builtin_nan: 05654 case Builtin::BI__builtin_nanf: 05655 case Builtin::BI__builtin_nanl: 05656 // If this is __builtin_nan() turn this into a nan, otherwise we 05657 // can't constant fold it. 05658 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 05659 false, Result)) 05660 return Error(E); 05661 return true; 05662 05663 case Builtin::BI__builtin_fabs: 05664 case Builtin::BI__builtin_fabsf: 05665 case Builtin::BI__builtin_fabsl: 05666 if (!EvaluateFloat(E->getArg(0), Result, Info)) 05667 return false; 05668 05669 if (Result.isNegative()) 05670 Result.changeSign(); 05671 return true; 05672 05673 case Builtin::BI__builtin_copysign: 05674 case Builtin::BI__builtin_copysignf: 05675 case Builtin::BI__builtin_copysignl: { 05676 APFloat RHS(0.); 05677 if (!EvaluateFloat(E->getArg(0), Result, Info) || 05678 !EvaluateFloat(E->getArg(1), RHS, Info)) 05679 return false; 05680 Result.copySign(RHS); 05681 return true; 05682 } 05683 } 05684 } 05685 05686 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 05687 if (E->getSubExpr()->getType()->isAnyComplexType()) { 05688 ComplexValue CV; 05689 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 05690 return false; 05691 Result = CV.FloatReal; 05692 return true; 05693 } 05694 05695 return Visit(E->getSubExpr()); 05696 } 05697 05698 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 05699 if (E->getSubExpr()->getType()->isAnyComplexType()) { 05700 ComplexValue CV; 05701 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 05702 return false; 05703 Result = CV.FloatImag; 05704 return true; 05705 } 05706 05707 VisitIgnoredValue(E->getSubExpr()); 05708 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 05709 Result = llvm::APFloat::getZero(Sem); 05710 return true; 05711 } 05712 05713 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 05714 switch (E->getOpcode()) { 05715 default: return Error(E); 05716 case UO_Plus: 05717 return EvaluateFloat(E->getSubExpr(), Result, Info); 05718 case UO_Minus: 05719 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 05720 return false; 05721 Result.changeSign(); 05722 return true; 05723 } 05724 } 05725 05726 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 05727 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 05728 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 05729 05730 APFloat RHS(0.0); 05731 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 05732 if (!LHSOK && !Info.keepEvaluatingAfterFailure()) 05733 return false; 05734 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK) 05735 return false; 05736 05737 switch (E->getOpcode()) { 05738 default: return Error(E); 05739 case BO_Mul: 05740 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 05741 break; 05742 case BO_Add: 05743 Result.add(RHS, APFloat::rmNearestTiesToEven); 05744 break; 05745 case BO_Sub: 05746 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 05747 break; 05748 case BO_Div: 05749 Result.divide(RHS, APFloat::rmNearestTiesToEven); 05750 break; 05751 } 05752 05753 if (Result.isInfinity() || Result.isNaN()) 05754 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN(); 05755 return true; 05756 } 05757 05758 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 05759 Result = E->getValue(); 05760 return true; 05761 } 05762 05763 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 05764 const Expr* SubExpr = E->getSubExpr(); 05765 05766 switch (E->getCastKind()) { 05767 default: 05768 return ExprEvaluatorBaseTy::VisitCastExpr(E); 05769 05770 case CK_IntegralToFloating: { 05771 APSInt IntResult; 05772 return EvaluateInteger(SubExpr, IntResult, Info) && 05773 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 05774 E->getType(), Result); 05775 } 05776 05777 case CK_FloatingCast: { 05778 if (!Visit(SubExpr)) 05779 return false; 05780 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 05781 Result); 05782 } 05783 05784 case CK_FloatingComplexToReal: { 05785 ComplexValue V; 05786 if (!EvaluateComplex(SubExpr, V, Info)) 05787 return false; 05788 Result = V.getComplexFloatReal(); 05789 return true; 05790 } 05791 } 05792 } 05793 05794 //===----------------------------------------------------------------------===// 05795 // Complex Evaluation (for float and integer) 05796 //===----------------------------------------------------------------------===// 05797 05798 namespace { 05799 class ComplexExprEvaluator 05800 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> { 05801 ComplexValue &Result; 05802 05803 public: 05804 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 05805 : ExprEvaluatorBaseTy(info), Result(Result) {} 05806 05807 bool Success(const APValue &V, const Expr *e) { 05808 Result.setFrom(V); 05809 return true; 05810 } 05811 05812 bool ZeroInitialization(const Expr *E); 05813 05814 //===--------------------------------------------------------------------===// 05815 // Visitor Methods 05816 //===--------------------------------------------------------------------===// 05817 05818 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 05819 bool VisitCastExpr(const CastExpr *E); 05820 bool VisitBinaryOperator(const BinaryOperator *E); 05821 bool VisitUnaryOperator(const UnaryOperator *E); 05822 bool VisitInitListExpr(const InitListExpr *E); 05823 }; 05824 } // end anonymous namespace 05825 05826 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 05827 EvalInfo &Info) { 05828 assert(E->isRValue() && E->getType()->isAnyComplexType()); 05829 return ComplexExprEvaluator(Info, Result).Visit(E); 05830 } 05831 05832 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 05833 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 05834 if (ElemTy->isRealFloatingType()) { 05835 Result.makeComplexFloat(); 05836 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 05837 Result.FloatReal = Zero; 05838 Result.FloatImag = Zero; 05839 } else { 05840 Result.makeComplexInt(); 05841 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 05842 Result.IntReal = Zero; 05843 Result.IntImag = Zero; 05844 } 05845 return true; 05846 } 05847 05848 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 05849 const Expr* SubExpr = E->getSubExpr(); 05850 05851 if (SubExpr->getType()->isRealFloatingType()) { 05852 Result.makeComplexFloat(); 05853 APFloat &Imag = Result.FloatImag; 05854 if (!EvaluateFloat(SubExpr, Imag, Info)) 05855 return false; 05856 05857 Result.FloatReal = APFloat(Imag.getSemantics()); 05858 return true; 05859 } else { 05860 assert(SubExpr->getType()->isIntegerType() && 05861 "Unexpected imaginary literal."); 05862 05863 Result.makeComplexInt(); 05864 APSInt &Imag = Result.IntImag; 05865 if (!EvaluateInteger(SubExpr, Imag, Info)) 05866 return false; 05867 05868 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 05869 return true; 05870 } 05871 } 05872 05873 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 05874 05875 switch (E->getCastKind()) { 05876 case CK_BitCast: 05877 case CK_BaseToDerived: 05878 case CK_DerivedToBase: 05879 case CK_UncheckedDerivedToBase: 05880 case CK_Dynamic: 05881 case CK_ToUnion: 05882 case CK_ArrayToPointerDecay: 05883 case CK_FunctionToPointerDecay: 05884 case CK_NullToPointer: 05885 case CK_NullToMemberPointer: 05886 case CK_BaseToDerivedMemberPointer: 05887 case CK_DerivedToBaseMemberPointer: 05888 case CK_MemberPointerToBoolean: 05889 case CK_ReinterpretMemberPointer: 05890 case CK_ConstructorConversion: 05891 case CK_IntegralToPointer: 05892 case CK_PointerToIntegral: 05893 case CK_PointerToBoolean: 05894 case CK_ToVoid: 05895 case CK_VectorSplat: 05896 case CK_IntegralCast: 05897 case CK_IntegralToBoolean: 05898 case CK_IntegralToFloating: 05899 case CK_FloatingToIntegral: 05900 case CK_FloatingToBoolean: 05901 case CK_FloatingCast: 05902 case CK_CPointerToObjCPointerCast: 05903 case CK_BlockPointerToObjCPointerCast: 05904 case CK_AnyPointerToBlockPointerCast: 05905 case CK_ObjCObjectLValueCast: 05906 case CK_FloatingComplexToReal: 05907 case CK_FloatingComplexToBoolean: 05908 case CK_IntegralComplexToReal: 05909 case CK_IntegralComplexToBoolean: 05910 case CK_ARCProduceObject: 05911 case CK_ARCConsumeObject: 05912 case CK_ARCReclaimReturnedObject: 05913 case CK_ARCExtendBlockObject: 05914 case CK_CopyAndAutoreleaseBlockObject: 05915 llvm_unreachable("invalid cast kind for complex value"); 05916 05917 case CK_LValueToRValue: 05918 case CK_AtomicToNonAtomic: 05919 case CK_NonAtomicToAtomic: 05920 case CK_NoOp: 05921 return ExprEvaluatorBaseTy::VisitCastExpr(E); 05922 05923 case CK_Dependent: 05924 case CK_LValueBitCast: 05925 case CK_UserDefinedConversion: 05926 return Error(E); 05927 05928 case CK_FloatingRealToComplex: { 05929 APFloat &Real = Result.FloatReal; 05930 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 05931 return false; 05932 05933 Result.makeComplexFloat(); 05934 Result.FloatImag = APFloat(Real.getSemantics()); 05935 return true; 05936 } 05937 05938 case CK_FloatingComplexCast: { 05939 if (!Visit(E->getSubExpr())) 05940 return false; 05941 05942 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 05943 QualType From 05944 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 05945 05946 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 05947 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 05948 } 05949 05950 case CK_FloatingComplexToIntegralComplex: { 05951 if (!Visit(E->getSubExpr())) 05952 return false; 05953 05954 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 05955 QualType From 05956 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 05957 Result.makeComplexInt(); 05958 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 05959 To, Result.IntReal) && 05960 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 05961 To, Result.IntImag); 05962 } 05963 05964 case CK_IntegralRealToComplex: { 05965 APSInt &Real = Result.IntReal; 05966 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 05967 return false; 05968 05969 Result.makeComplexInt(); 05970 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 05971 return true; 05972 } 05973 05974 case CK_IntegralComplexCast: { 05975 if (!Visit(E->getSubExpr())) 05976 return false; 05977 05978 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 05979 QualType From 05980 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 05981 05982 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 05983 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 05984 return true; 05985 } 05986 05987 case CK_IntegralComplexToFloatingComplex: { 05988 if (!Visit(E->getSubExpr())) 05989 return false; 05990 05991 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 05992 QualType From 05993 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 05994 Result.makeComplexFloat(); 05995 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 05996 To, Result.FloatReal) && 05997 HandleIntToFloatCast(Info, E, From, Result.IntImag, 05998 To, Result.FloatImag); 05999 } 06000 } 06001 06002 llvm_unreachable("unknown cast resulting in complex value"); 06003 } 06004 06005 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 06006 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 06007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 06008 06009 bool LHSOK = Visit(E->getLHS()); 06010 if (!LHSOK && !Info.keepEvaluatingAfterFailure()) 06011 return false; 06012 06013 ComplexValue RHS; 06014 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 06015 return false; 06016 06017 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 06018 "Invalid operands to binary operator."); 06019 switch (E->getOpcode()) { 06020 default: return Error(E); 06021 case BO_Add: 06022 if (Result.isComplexFloat()) { 06023 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 06024 APFloat::rmNearestTiesToEven); 06025 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 06026 APFloat::rmNearestTiesToEven); 06027 } else { 06028 Result.getComplexIntReal() += RHS.getComplexIntReal(); 06029 Result.getComplexIntImag() += RHS.getComplexIntImag(); 06030 } 06031 break; 06032 case BO_Sub: 06033 if (Result.isComplexFloat()) { 06034 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 06035 APFloat::rmNearestTiesToEven); 06036 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 06037 APFloat::rmNearestTiesToEven); 06038 } else { 06039 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 06040 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 06041 } 06042 break; 06043 case BO_Mul: 06044 if (Result.isComplexFloat()) { 06045 ComplexValue LHS = Result; 06046 APFloat &LHS_r = LHS.getComplexFloatReal(); 06047 APFloat &LHS_i = LHS.getComplexFloatImag(); 06048 APFloat &RHS_r = RHS.getComplexFloatReal(); 06049 APFloat &RHS_i = RHS.getComplexFloatImag(); 06050 06051 APFloat Tmp = LHS_r; 06052 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 06053 Result.getComplexFloatReal() = Tmp; 06054 Tmp = LHS_i; 06055 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 06056 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 06057 06058 Tmp = LHS_r; 06059 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 06060 Result.getComplexFloatImag() = Tmp; 06061 Tmp = LHS_i; 06062 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 06063 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 06064 } else { 06065 ComplexValue LHS = Result; 06066 Result.getComplexIntReal() = 06067 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 06068 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 06069 Result.getComplexIntImag() = 06070 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 06071 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 06072 } 06073 break; 06074 case BO_Div: 06075 if (Result.isComplexFloat()) { 06076 ComplexValue LHS = Result; 06077 APFloat &LHS_r = LHS.getComplexFloatReal(); 06078 APFloat &LHS_i = LHS.getComplexFloatImag(); 06079 APFloat &RHS_r = RHS.getComplexFloatReal(); 06080 APFloat &RHS_i = RHS.getComplexFloatImag(); 06081 APFloat &Res_r = Result.getComplexFloatReal(); 06082 APFloat &Res_i = Result.getComplexFloatImag(); 06083 06084 APFloat Den = RHS_r; 06085 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven); 06086 APFloat Tmp = RHS_i; 06087 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 06088 Den.add(Tmp, APFloat::rmNearestTiesToEven); 06089 06090 Res_r = LHS_r; 06091 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven); 06092 Tmp = LHS_i; 06093 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 06094 Res_r.add(Tmp, APFloat::rmNearestTiesToEven); 06095 Res_r.divide(Den, APFloat::rmNearestTiesToEven); 06096 06097 Res_i = LHS_i; 06098 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven); 06099 Tmp = LHS_r; 06100 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 06101 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven); 06102 Res_i.divide(Den, APFloat::rmNearestTiesToEven); 06103 } else { 06104 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 06105 return Error(E, diag::note_expr_divide_by_zero); 06106 06107 ComplexValue LHS = Result; 06108 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 06109 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 06110 Result.getComplexIntReal() = 06111 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 06112 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 06113 Result.getComplexIntImag() = 06114 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 06115 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 06116 } 06117 break; 06118 } 06119 06120 return true; 06121 } 06122 06123 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 06124 // Get the operand value into 'Result'. 06125 if (!Visit(E->getSubExpr())) 06126 return false; 06127 06128 switch (E->getOpcode()) { 06129 default: 06130 return Error(E); 06131 case UO_Extension: 06132 return true; 06133 case UO_Plus: 06134 // The result is always just the subexpr. 06135 return true; 06136 case UO_Minus: 06137 if (Result.isComplexFloat()) { 06138 Result.getComplexFloatReal().changeSign(); 06139 Result.getComplexFloatImag().changeSign(); 06140 } 06141 else { 06142 Result.getComplexIntReal() = -Result.getComplexIntReal(); 06143 Result.getComplexIntImag() = -Result.getComplexIntImag(); 06144 } 06145 return true; 06146 case UO_Not: 06147 if (Result.isComplexFloat()) 06148 Result.getComplexFloatImag().changeSign(); 06149 else 06150 Result.getComplexIntImag() = -Result.getComplexIntImag(); 06151 return true; 06152 } 06153 } 06154 06155 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 06156 if (E->getNumInits() == 2) { 06157 if (E->getType()->isComplexType()) { 06158 Result.makeComplexFloat(); 06159 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 06160 return false; 06161 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 06162 return false; 06163 } else { 06164 Result.makeComplexInt(); 06165 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 06166 return false; 06167 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 06168 return false; 06169 } 06170 return true; 06171 } 06172 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 06173 } 06174 06175 //===----------------------------------------------------------------------===// 06176 // Void expression evaluation, primarily for a cast to void on the LHS of a 06177 // comma operator 06178 //===----------------------------------------------------------------------===// 06179 06180 namespace { 06181 class VoidExprEvaluator 06182 : public ExprEvaluatorBase<VoidExprEvaluator, bool> { 06183 public: 06184 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 06185 06186 bool Success(const APValue &V, const Expr *e) { return true; } 06187 06188 bool VisitCastExpr(const CastExpr *E) { 06189 switch (E->getCastKind()) { 06190 default: 06191 return ExprEvaluatorBaseTy::VisitCastExpr(E); 06192 case CK_ToVoid: 06193 VisitIgnoredValue(E->getSubExpr()); 06194 return true; 06195 } 06196 } 06197 }; 06198 } // end anonymous namespace 06199 06200 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 06201 assert(E->isRValue() && E->getType()->isVoidType()); 06202 return VoidExprEvaluator(Info).Visit(E); 06203 } 06204 06205 //===----------------------------------------------------------------------===// 06206 // Top level Expr::EvaluateAsRValue method. 06207 //===----------------------------------------------------------------------===// 06208 06209 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 06210 // In C, function designators are not lvalues, but we evaluate them as if they 06211 // are. 06212 if (E->isGLValue() || E->getType()->isFunctionType()) { 06213 LValue LV; 06214 if (!EvaluateLValue(E, LV, Info)) 06215 return false; 06216 LV.moveInto(Result); 06217 } else if (E->getType()->isVectorType()) { 06218 if (!EvaluateVector(E, Result, Info)) 06219 return false; 06220 } else if (E->getType()->isIntegralOrEnumerationType()) { 06221 if (!IntExprEvaluator(Info, Result).Visit(E)) 06222 return false; 06223 } else if (E->getType()->hasPointerRepresentation()) { 06224 LValue LV; 06225 if (!EvaluatePointer(E, LV, Info)) 06226 return false; 06227 LV.moveInto(Result); 06228 } else if (E->getType()->isRealFloatingType()) { 06229 llvm::APFloat F(0.0); 06230 if (!EvaluateFloat(E, F, Info)) 06231 return false; 06232 Result = APValue(F); 06233 } else if (E->getType()->isAnyComplexType()) { 06234 ComplexValue C; 06235 if (!EvaluateComplex(E, C, Info)) 06236 return false; 06237 C.moveInto(Result); 06238 } else if (E->getType()->isMemberPointerType()) { 06239 MemberPtr P; 06240 if (!EvaluateMemberPointer(E, P, Info)) 06241 return false; 06242 P.moveInto(Result); 06243 return true; 06244 } else if (E->getType()->isArrayType()) { 06245 LValue LV; 06246 LV.set(E, Info.CurrentCall->Index); 06247 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info)) 06248 return false; 06249 Result = Info.CurrentCall->Temporaries[E]; 06250 } else if (E->getType()->isRecordType()) { 06251 LValue LV; 06252 LV.set(E, Info.CurrentCall->Index); 06253 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info)) 06254 return false; 06255 Result = Info.CurrentCall->Temporaries[E]; 06256 } else if (E->getType()->isVoidType()) { 06257 if (Info.getLangOpts().CPlusPlus0x) 06258 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 06259 << E->getType(); 06260 else 06261 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 06262 if (!EvaluateVoid(E, Info)) 06263 return false; 06264 } else if (Info.getLangOpts().CPlusPlus0x) { 06265 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType(); 06266 return false; 06267 } else { 06268 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr); 06269 return false; 06270 } 06271 06272 return true; 06273 } 06274 06275 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 06276 /// cases, the in-place evaluation is essential, since later initializers for 06277 /// an object can indirectly refer to subobjects which were initialized earlier. 06278 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 06279 const Expr *E, CheckConstantExpressionKind CCEK, 06280 bool AllowNonLiteralTypes) { 06281 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E)) 06282 return false; 06283 06284 if (E->isRValue()) { 06285 // Evaluate arrays and record types in-place, so that later initializers can 06286 // refer to earlier-initialized members of the object. 06287 if (E->getType()->isArrayType()) 06288 return EvaluateArray(E, This, Result, Info); 06289 else if (E->getType()->isRecordType()) 06290 return EvaluateRecord(E, This, Result, Info); 06291 } 06292 06293 // For any other type, in-place evaluation is unimportant. 06294 return Evaluate(Result, Info, E); 06295 } 06296 06297 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 06298 /// lvalue-to-rvalue cast if it is an lvalue. 06299 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 06300 if (!CheckLiteralType(Info, E)) 06301 return false; 06302 06303 if (!::Evaluate(Result, Info, E)) 06304 return false; 06305 06306 if (E->isGLValue()) { 06307 LValue LV; 06308 LV.setFrom(Info.Ctx, Result); 06309 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 06310 return false; 06311 } 06312 06313 // Check this core constant expression is a constant expression. 06314 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 06315 } 06316 06317 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 06318 /// any crazy technique (that has nothing to do with language standards) that 06319 /// we want to. If this function returns true, it returns the folded constant 06320 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 06321 /// will be applied to the result. 06322 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 06323 // Fast-path evaluations of integer literals, since we sometimes see files 06324 // containing vast quantities of these. 06325 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) { 06326 Result.Val = APValue(APSInt(L->getValue(), 06327 L->getType()->isUnsignedIntegerType())); 06328 return true; 06329 } 06330 06331 // FIXME: Evaluating values of large array and record types can cause 06332 // performance problems. Only do so in C++11 for now. 06333 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 06334 !Ctx.getLangOpts().CPlusPlus0x) 06335 return false; 06336 06337 EvalInfo Info(Ctx, Result); 06338 return ::EvaluateAsRValue(Info, this, Result.Val); 06339 } 06340 06341 bool Expr::EvaluateAsBooleanCondition(bool &Result, 06342 const ASTContext &Ctx) const { 06343 EvalResult Scratch; 06344 return EvaluateAsRValue(Scratch, Ctx) && 06345 HandleConversionToBool(Scratch.Val, Result); 06346 } 06347 06348 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 06349 SideEffectsKind AllowSideEffects) const { 06350 if (!getType()->isIntegralOrEnumerationType()) 06351 return false; 06352 06353 EvalResult ExprResult; 06354 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 06355 (!AllowSideEffects && ExprResult.HasSideEffects)) 06356 return false; 06357 06358 Result = ExprResult.Val.getInt(); 06359 return true; 06360 } 06361 06362 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 06363 EvalInfo Info(Ctx, Result); 06364 06365 LValue LV; 06366 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 06367 !CheckLValueConstantExpression(Info, getExprLoc(), 06368 Ctx.getLValueReferenceType(getType()), LV)) 06369 return false; 06370 06371 LV.moveInto(Result.Val); 06372 return true; 06373 } 06374 06375 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 06376 const VarDecl *VD, 06377 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 06378 // FIXME: Evaluating initializers for large array and record types can cause 06379 // performance problems. Only do so in C++11 for now. 06380 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 06381 !Ctx.getLangOpts().CPlusPlus0x) 06382 return false; 06383 06384 Expr::EvalStatus EStatus; 06385 EStatus.Diag = &Notes; 06386 06387 EvalInfo InitInfo(Ctx, EStatus); 06388 InitInfo.setEvaluatingDecl(VD, Value); 06389 06390 LValue LVal; 06391 LVal.set(VD); 06392 06393 // C++11 [basic.start.init]p2: 06394 // Variables with static storage duration or thread storage duration shall be 06395 // zero-initialized before any other initialization takes place. 06396 // This behavior is not present in C. 06397 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 06398 !VD->getType()->isReferenceType()) { 06399 ImplicitValueInitExpr VIE(VD->getType()); 06400 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant, 06401 /*AllowNonLiteralTypes=*/true)) 06402 return false; 06403 } 06404 06405 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant, 06406 /*AllowNonLiteralTypes=*/true) || 06407 EStatus.HasSideEffects) 06408 return false; 06409 06410 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 06411 Value); 06412 } 06413 06414 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 06415 /// constant folded, but discard the result. 06416 bool Expr::isEvaluatable(const ASTContext &Ctx) const { 06417 EvalResult Result; 06418 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects; 06419 } 06420 06421 bool Expr::HasSideEffects(const ASTContext &Ctx) const { 06422 return HasSideEffect(Ctx).Visit(this); 06423 } 06424 06425 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const { 06426 EvalResult EvalResult; 06427 bool Result = EvaluateAsRValue(EvalResult, Ctx); 06428 (void)Result; 06429 assert(Result && "Could not evaluate expression"); 06430 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 06431 06432 return EvalResult.Val.getInt(); 06433 } 06434 06435 bool Expr::EvalResult::isGlobalLValue() const { 06436 assert(Val.isLValue()); 06437 return IsGlobalLValue(Val.getLValueBase()); 06438 } 06439 06440 06441 /// isIntegerConstantExpr - this recursive routine will test if an expression is 06442 /// an integer constant expression. 06443 06444 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 06445 /// comma, etc 06446 /// 06447 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 06448 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 06449 /// cast+dereference. 06450 06451 // CheckICE - This function does the fundamental ICE checking: the returned 06452 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 06453 // Note that to reduce code duplication, this helper does no evaluation 06454 // itself; the caller checks whether the expression is evaluatable, and 06455 // in the rare cases where CheckICE actually cares about the evaluated 06456 // value, it calls into Evalute. 06457 // 06458 // Meanings of Val: 06459 // 0: This expression is an ICE. 06460 // 1: This expression is not an ICE, but if it isn't evaluated, it's 06461 // a legal subexpression for an ICE. This return value is used to handle 06462 // the comma operator in C99 mode. 06463 // 2: This expression is not an ICE, and is not a legal subexpression for one. 06464 06465 namespace { 06466 06467 struct ICEDiag { 06468 unsigned Val; 06469 SourceLocation Loc; 06470 06471 public: 06472 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 06473 ICEDiag() : Val(0) {} 06474 }; 06475 06476 } 06477 06478 static ICEDiag NoDiag() { return ICEDiag(); } 06479 06480 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 06481 Expr::EvalResult EVResult; 06482 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 06483 !EVResult.Val.isInt()) { 06484 return ICEDiag(2, E->getLocStart()); 06485 } 06486 return NoDiag(); 06487 } 06488 06489 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 06490 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 06491 if (!E->getType()->isIntegralOrEnumerationType()) { 06492 return ICEDiag(2, E->getLocStart()); 06493 } 06494 06495 switch (E->getStmtClass()) { 06496 #define ABSTRACT_STMT(Node) 06497 #define STMT(Node, Base) case Expr::Node##Class: 06498 #define EXPR(Node, Base) 06499 #include "clang/AST/StmtNodes.inc" 06500 case Expr::PredefinedExprClass: 06501 case Expr::FloatingLiteralClass: 06502 case Expr::ImaginaryLiteralClass: 06503 case Expr::StringLiteralClass: 06504 case Expr::ArraySubscriptExprClass: 06505 case Expr::MemberExprClass: 06506 case Expr::CompoundAssignOperatorClass: 06507 case Expr::CompoundLiteralExprClass: 06508 case Expr::ExtVectorElementExprClass: 06509 case Expr::DesignatedInitExprClass: 06510 case Expr::ImplicitValueInitExprClass: 06511 case Expr::ParenListExprClass: 06512 case Expr::VAArgExprClass: 06513 case Expr::AddrLabelExprClass: 06514 case Expr::StmtExprClass: 06515 case Expr::CXXMemberCallExprClass: 06516 case Expr::CUDAKernelCallExprClass: 06517 case Expr::CXXDynamicCastExprClass: 06518 case Expr::CXXTypeidExprClass: 06519 case Expr::CXXUuidofExprClass: 06520 case Expr::CXXNullPtrLiteralExprClass: 06521 case Expr::UserDefinedLiteralClass: 06522 case Expr::CXXThisExprClass: 06523 case Expr::CXXThrowExprClass: 06524 case Expr::CXXNewExprClass: 06525 case Expr::CXXDeleteExprClass: 06526 case Expr::CXXPseudoDestructorExprClass: 06527 case Expr::UnresolvedLookupExprClass: 06528 case Expr::DependentScopeDeclRefExprClass: 06529 case Expr::CXXConstructExprClass: 06530 case Expr::CXXBindTemporaryExprClass: 06531 case Expr::ExprWithCleanupsClass: 06532 case Expr::CXXTemporaryObjectExprClass: 06533 case Expr::CXXUnresolvedConstructExprClass: 06534 case Expr::CXXDependentScopeMemberExprClass: 06535 case Expr::UnresolvedMemberExprClass: 06536 case Expr::ObjCStringLiteralClass: 06537 case Expr::ObjCBoxedExprClass: 06538 case Expr::ObjCArrayLiteralClass: 06539 case Expr::ObjCDictionaryLiteralClass: 06540 case Expr::ObjCEncodeExprClass: 06541 case Expr::ObjCMessageExprClass: 06542 case Expr::ObjCSelectorExprClass: 06543 case Expr::ObjCProtocolExprClass: 06544 case Expr::ObjCIvarRefExprClass: 06545 case Expr::ObjCPropertyRefExprClass: 06546 case Expr::ObjCSubscriptRefExprClass: 06547 case Expr::ObjCIsaExprClass: 06548 case Expr::ShuffleVectorExprClass: 06549 case Expr::BlockExprClass: 06550 case Expr::NoStmtClass: 06551 case Expr::OpaqueValueExprClass: 06552 case Expr::PackExpansionExprClass: 06553 case Expr::SubstNonTypeTemplateParmPackExprClass: 06554 case Expr::AsTypeExprClass: 06555 case Expr::ObjCIndirectCopyRestoreExprClass: 06556 case Expr::MaterializeTemporaryExprClass: 06557 case Expr::PseudoObjectExprClass: 06558 case Expr::AtomicExprClass: 06559 case Expr::InitListExprClass: 06560 case Expr::LambdaExprClass: 06561 return ICEDiag(2, E->getLocStart()); 06562 06563 case Expr::SizeOfPackExprClass: 06564 case Expr::GNUNullExprClass: 06565 // GCC considers the GNU __null value to be an integral constant expression. 06566 return NoDiag(); 06567 06568 case Expr::SubstNonTypeTemplateParmExprClass: 06569 return 06570 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 06571 06572 case Expr::ParenExprClass: 06573 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 06574 case Expr::GenericSelectionExprClass: 06575 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 06576 case Expr::IntegerLiteralClass: 06577 case Expr::CharacterLiteralClass: 06578 case Expr::ObjCBoolLiteralExprClass: 06579 case Expr::CXXBoolLiteralExprClass: 06580 case Expr::CXXScalarValueInitExprClass: 06581 case Expr::UnaryTypeTraitExprClass: 06582 case Expr::BinaryTypeTraitExprClass: 06583 case Expr::TypeTraitExprClass: 06584 case Expr::ArrayTypeTraitExprClass: 06585 case Expr::ExpressionTraitExprClass: 06586 case Expr::CXXNoexceptExprClass: 06587 return NoDiag(); 06588 case Expr::CallExprClass: 06589 case Expr::CXXOperatorCallExprClass: { 06590 // C99 6.6/3 allows function calls within unevaluated subexpressions of 06591 // constant expressions, but they can never be ICEs because an ICE cannot 06592 // contain an operand of (pointer to) function type. 06593 const CallExpr *CE = cast<CallExpr>(E); 06594 if (CE->isBuiltinCall()) 06595 return CheckEvalInICE(E, Ctx); 06596 return ICEDiag(2, E->getLocStart()); 06597 } 06598 case Expr::DeclRefExprClass: { 06599 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 06600 return NoDiag(); 06601 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl()); 06602 if (Ctx.getLangOpts().CPlusPlus && 06603 D && IsConstNonVolatile(D->getType())) { 06604 // Parameter variables are never constants. Without this check, 06605 // getAnyInitializer() can find a default argument, which leads 06606 // to chaos. 06607 if (isa<ParmVarDecl>(D)) 06608 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 06609 06610 // C++ 7.1.5.1p2 06611 // A variable of non-volatile const-qualified integral or enumeration 06612 // type initialized by an ICE can be used in ICEs. 06613 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 06614 if (!Dcl->getType()->isIntegralOrEnumerationType()) 06615 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 06616 06617 const VarDecl *VD; 06618 // Look for a declaration of this variable that has an initializer, and 06619 // check whether it is an ICE. 06620 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 06621 return NoDiag(); 06622 else 06623 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 06624 } 06625 } 06626 return ICEDiag(2, E->getLocStart()); 06627 } 06628 case Expr::UnaryOperatorClass: { 06629 const UnaryOperator *Exp = cast<UnaryOperator>(E); 06630 switch (Exp->getOpcode()) { 06631 case UO_PostInc: 06632 case UO_PostDec: 06633 case UO_PreInc: 06634 case UO_PreDec: 06635 case UO_AddrOf: 06636 case UO_Deref: 06637 // C99 6.6/3 allows increment and decrement within unevaluated 06638 // subexpressions of constant expressions, but they can never be ICEs 06639 // because an ICE cannot contain an lvalue operand. 06640 return ICEDiag(2, E->getLocStart()); 06641 case UO_Extension: 06642 case UO_LNot: 06643 case UO_Plus: 06644 case UO_Minus: 06645 case UO_Not: 06646 case UO_Real: 06647 case UO_Imag: 06648 return CheckICE(Exp->getSubExpr(), Ctx); 06649 } 06650 06651 // OffsetOf falls through here. 06652 } 06653 case Expr::OffsetOfExprClass: { 06654 // Note that per C99, offsetof must be an ICE. And AFAIK, using 06655 // EvaluateAsRValue matches the proposed gcc behavior for cases like 06656 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 06657 // compliance: we should warn earlier for offsetof expressions with 06658 // array subscripts that aren't ICEs, and if the array subscripts 06659 // are ICEs, the value of the offsetof must be an integer constant. 06660 return CheckEvalInICE(E, Ctx); 06661 } 06662 case Expr::UnaryExprOrTypeTraitExprClass: { 06663 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 06664 if ((Exp->getKind() == UETT_SizeOf) && 06665 Exp->getTypeOfArgument()->isVariableArrayType()) 06666 return ICEDiag(2, E->getLocStart()); 06667 return NoDiag(); 06668 } 06669 case Expr::BinaryOperatorClass: { 06670 const BinaryOperator *Exp = cast<BinaryOperator>(E); 06671 switch (Exp->getOpcode()) { 06672 case BO_PtrMemD: 06673 case BO_PtrMemI: 06674 case BO_Assign: 06675 case BO_MulAssign: 06676 case BO_DivAssign: 06677 case BO_RemAssign: 06678 case BO_AddAssign: 06679 case BO_SubAssign: 06680 case BO_ShlAssign: 06681 case BO_ShrAssign: 06682 case BO_AndAssign: 06683 case BO_XorAssign: 06684 case BO_OrAssign: 06685 // C99 6.6/3 allows assignments within unevaluated subexpressions of 06686 // constant expressions, but they can never be ICEs because an ICE cannot 06687 // contain an lvalue operand. 06688 return ICEDiag(2, E->getLocStart()); 06689 06690 case BO_Mul: 06691 case BO_Div: 06692 case BO_Rem: 06693 case BO_Add: 06694 case BO_Sub: 06695 case BO_Shl: 06696 case BO_Shr: 06697 case BO_LT: 06698 case BO_GT: 06699 case BO_LE: 06700 case BO_GE: 06701 case BO_EQ: 06702 case BO_NE: 06703 case BO_And: 06704 case BO_Xor: 06705 case BO_Or: 06706 case BO_Comma: { 06707 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 06708 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 06709 if (Exp->getOpcode() == BO_Div || 06710 Exp->getOpcode() == BO_Rem) { 06711 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 06712 // we don't evaluate one. 06713 if (LHSResult.Val == 0 && RHSResult.Val == 0) { 06714 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 06715 if (REval == 0) 06716 return ICEDiag(1, E->getLocStart()); 06717 if (REval.isSigned() && REval.isAllOnesValue()) { 06718 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 06719 if (LEval.isMinSignedValue()) 06720 return ICEDiag(1, E->getLocStart()); 06721 } 06722 } 06723 } 06724 if (Exp->getOpcode() == BO_Comma) { 06725 if (Ctx.getLangOpts().C99) { 06726 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 06727 // if it isn't evaluated. 06728 if (LHSResult.Val == 0 && RHSResult.Val == 0) 06729 return ICEDiag(1, E->getLocStart()); 06730 } else { 06731 // In both C89 and C++, commas in ICEs are illegal. 06732 return ICEDiag(2, E->getLocStart()); 06733 } 06734 } 06735 if (LHSResult.Val >= RHSResult.Val) 06736 return LHSResult; 06737 return RHSResult; 06738 } 06739 case BO_LAnd: 06740 case BO_LOr: { 06741 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 06742 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 06743 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 06744 // Rare case where the RHS has a comma "side-effect"; we need 06745 // to actually check the condition to see whether the side 06746 // with the comma is evaluated. 06747 if ((Exp->getOpcode() == BO_LAnd) != 06748 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 06749 return RHSResult; 06750 return NoDiag(); 06751 } 06752 06753 if (LHSResult.Val >= RHSResult.Val) 06754 return LHSResult; 06755 return RHSResult; 06756 } 06757 } 06758 } 06759 case Expr::ImplicitCastExprClass: 06760 case Expr::CStyleCastExprClass: 06761 case Expr::CXXFunctionalCastExprClass: 06762 case Expr::CXXStaticCastExprClass: 06763 case Expr::CXXReinterpretCastExprClass: 06764 case Expr::CXXConstCastExprClass: 06765 case Expr::ObjCBridgedCastExprClass: { 06766 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 06767 if (isa<ExplicitCastExpr>(E)) { 06768 if (const FloatingLiteral *FL 06769 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 06770 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 06771 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 06772 APSInt IgnoredVal(DestWidth, !DestSigned); 06773 bool Ignored; 06774 // If the value does not fit in the destination type, the behavior is 06775 // undefined, so we are not required to treat it as a constant 06776 // expression. 06777 if (FL->getValue().convertToInteger(IgnoredVal, 06778 llvm::APFloat::rmTowardZero, 06779 &Ignored) & APFloat::opInvalidOp) 06780 return ICEDiag(2, E->getLocStart()); 06781 return NoDiag(); 06782 } 06783 } 06784 switch (cast<CastExpr>(E)->getCastKind()) { 06785 case CK_LValueToRValue: 06786 case CK_AtomicToNonAtomic: 06787 case CK_NonAtomicToAtomic: 06788 case CK_NoOp: 06789 case CK_IntegralToBoolean: 06790 case CK_IntegralCast: 06791 return CheckICE(SubExpr, Ctx); 06792 default: 06793 return ICEDiag(2, E->getLocStart()); 06794 } 06795 } 06796 case Expr::BinaryConditionalOperatorClass: { 06797 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 06798 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 06799 if (CommonResult.Val == 2) return CommonResult; 06800 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 06801 if (FalseResult.Val == 2) return FalseResult; 06802 if (CommonResult.Val == 1) return CommonResult; 06803 if (FalseResult.Val == 1 && 06804 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag(); 06805 return FalseResult; 06806 } 06807 case Expr::ConditionalOperatorClass: { 06808 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 06809 // If the condition (ignoring parens) is a __builtin_constant_p call, 06810 // then only the true side is actually considered in an integer constant 06811 // expression, and it is fully evaluated. This is an important GNU 06812 // extension. See GCC PR38377 for discussion. 06813 if (const CallExpr *CallCE 06814 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 06815 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) 06816 return CheckEvalInICE(E, Ctx); 06817 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 06818 if (CondResult.Val == 2) 06819 return CondResult; 06820 06821 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 06822 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 06823 06824 if (TrueResult.Val == 2) 06825 return TrueResult; 06826 if (FalseResult.Val == 2) 06827 return FalseResult; 06828 if (CondResult.Val == 1) 06829 return CondResult; 06830 if (TrueResult.Val == 0 && FalseResult.Val == 0) 06831 return NoDiag(); 06832 // Rare case where the diagnostics depend on which side is evaluated 06833 // Note that if we get here, CondResult is 0, and at least one of 06834 // TrueResult and FalseResult is non-zero. 06835 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) { 06836 return FalseResult; 06837 } 06838 return TrueResult; 06839 } 06840 case Expr::CXXDefaultArgExprClass: 06841 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 06842 case Expr::ChooseExprClass: { 06843 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 06844 } 06845 } 06846 06847 llvm_unreachable("Invalid StmtClass!"); 06848 } 06849 06850 /// Evaluate an expression as a C++11 integral constant expression. 06851 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx, 06852 const Expr *E, 06853 llvm::APSInt *Value, 06854 SourceLocation *Loc) { 06855 if (!E->getType()->isIntegralOrEnumerationType()) { 06856 if (Loc) *Loc = E->getExprLoc(); 06857 return false; 06858 } 06859 06860 APValue Result; 06861 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 06862 return false; 06863 06864 assert(Result.isInt() && "pointer cast to int is not an ICE"); 06865 if (Value) *Value = Result.getInt(); 06866 return true; 06867 } 06868 06869 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const { 06870 if (Ctx.getLangOpts().CPlusPlus0x) 06871 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc); 06872 06873 ICEDiag d = CheckICE(this, Ctx); 06874 if (d.Val != 0) { 06875 if (Loc) *Loc = d.Loc; 06876 return false; 06877 } 06878 return true; 06879 } 06880 06881 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx, 06882 SourceLocation *Loc, bool isEvaluated) const { 06883 if (Ctx.getLangOpts().CPlusPlus0x) 06884 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 06885 06886 if (!isIntegerConstantExpr(Ctx, Loc)) 06887 return false; 06888 if (!EvaluateAsInt(Value, Ctx)) 06889 llvm_unreachable("ICE cannot be evaluated!"); 06890 return true; 06891 } 06892 06893 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const { 06894 return CheckICE(this, Ctx).Val == 0; 06895 } 06896 06897 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result, 06898 SourceLocation *Loc) const { 06899 // We support this checking in C++98 mode in order to diagnose compatibility 06900 // issues. 06901 assert(Ctx.getLangOpts().CPlusPlus); 06902 06903 // Build evaluation settings. 06904 Expr::EvalStatus Status; 06905 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 06906 Status.Diag = &Diags; 06907 EvalInfo Info(Ctx, Status); 06908 06909 APValue Scratch; 06910 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 06911 06912 if (!Diags.empty()) { 06913 IsConstExpr = false; 06914 if (Loc) *Loc = Diags[0].first; 06915 } else if (!IsConstExpr) { 06916 // FIXME: This shouldn't happen. 06917 if (Loc) *Loc = getExprLoc(); 06918 } 06919 06920 return IsConstExpr; 06921 } 06922 06923 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 06924 llvm::SmallVectorImpl< 06925 PartialDiagnosticAt> &Diags) { 06926 // FIXME: It would be useful to check constexpr function templates, but at the 06927 // moment the constant expression evaluator cannot cope with the non-rigorous 06928 // ASTs which we build for dependent expressions. 06929 if (FD->isDependentContext()) 06930 return true; 06931 06932 Expr::EvalStatus Status; 06933 Status.Diag = &Diags; 06934 06935 EvalInfo Info(FD->getASTContext(), Status); 06936 Info.CheckingPotentialConstantExpression = true; 06937 06938 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 06939 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0; 06940 06941 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it 06942 // is a temporary being used as the 'this' pointer. 06943 LValue This; 06944 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 06945 This.set(&VIE, Info.CurrentCall->Index); 06946 06947 ArrayRef<const Expr*> Args; 06948 06949 SourceLocation Loc = FD->getLocation(); 06950 06951 APValue Scratch; 06952 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 06953 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch); 06954 else 06955 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0, 06956 Args, FD->getBody(), Info, Scratch); 06957 06958 return Diags.empty(); 06959 }