diff --git a/clang/include/clang/AST/ExprCXX.h b/clang/include/clang/AST/ExprCXX.h index d78c7b6363b5d..b7fd4de80b3fd 100644 --- a/clang/include/clang/AST/ExprCXX.h +++ b/clang/include/clang/AST/ExprCXX.h @@ -495,12 +495,10 @@ class CXXDynamicCastExpr final friend class CastExpr; friend TrailingObjects; - static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T, - ExprValueKind VK, CastKind Kind, Expr *Op, - const CXXCastPath *Path, - TypeSourceInfo *Written, SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets); + static CXXDynamicCastExpr * + Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, + Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets); static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context, unsigned pathSize); @@ -540,12 +538,10 @@ class CXXReinterpretCastExpr final friend class CastExpr; friend TrailingObjects; - static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T, - ExprValueKind VK, CastKind Kind, - Expr *Op, const CXXCastPath *Path, - TypeSourceInfo *WrittenTy, SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets); + static CXXReinterpretCastExpr * + Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, + Expr *Op, const CXXCastPath *Path, TypeSourceInfo *WrittenTy, + SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets); static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context, unsigned pathSize); @@ -694,7 +690,7 @@ class UserDefinedLiteral final : public CallExpr { /// removed). Expr *getCookedLiteral(); const Expr *getCookedLiteral() const { - return const_cast(this)->getCookedLiteral(); + return const_cast(this)->getCookedLiteral(); } SourceLocation getBeginLoc() const { @@ -813,8 +809,8 @@ class CXXStdInitializerListExpr : public Expr { setDependence(computeDependence(this)); } - Expr *getSubExpr() { return static_cast(SubExpr); } - const Expr *getSubExpr() const { return static_cast(SubExpr); } + Expr *getSubExpr() { return static_cast(SubExpr); } + const Expr *getSubExpr() const { return static_cast(SubExpr); } SourceLocation getBeginLoc() const LLVM_READONLY { return SubExpr->getBeginLoc(); @@ -868,9 +864,9 @@ class CXXTypeidExpr : public Expr { CXXTypeidExpr(EmptyShell Empty, bool isExpr) : Expr(CXXTypeidExprClass, Empty) { if (isExpr) - Operand = (Expr*)nullptr; + Operand = (Expr *)nullptr; else - Operand = (TypeSourceInfo*)nullptr; + Operand = (TypeSourceInfo *)nullptr; } /// Determine whether this typeid has a type operand which is potentially @@ -968,13 +964,13 @@ class MSPropertyRefExpr : public Expr { else if (QualifierLoc) return QualifierLoc.getBeginLoc(); else - return MemberLoc; + return MemberLoc; } SourceLocation getEndLoc() const { return getMemberLoc(); } child_range children() { - return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1); + return child_range((Stmt **)&BaseExpr, (Stmt **)&BaseExpr + 1); } const_child_range children() const { @@ -1089,11 +1085,11 @@ class CXXUuidofExpr : public Expr { } CXXUuidofExpr(EmptyShell Empty, bool isExpr) - : Expr(CXXUuidofExprClass, Empty) { + : Expr(CXXUuidofExprClass, Empty) { if (isExpr) - Operand = (Expr*)nullptr; + Operand = (Expr *)nullptr; else - Operand = (TypeSourceInfo*)nullptr; + Operand = (TypeSourceInfo *)nullptr; } bool isTypeOperand() const { return isa(Operand); } @@ -1470,9 +1466,7 @@ class CXXTemporary { const CXXDestructorDecl *getDestructor() const { return Destructor; } - void setDestructor(const CXXDestructorDecl *Dtor) { - Destructor = Dtor; - } + void setDestructor(const CXXDestructorDecl *Dtor) { Destructor = Dtor; } }; /// Represents binding an expression to a temporary. @@ -1507,7 +1501,7 @@ class CXXBindTemporaryExpr : public Expr { : Expr(CXXBindTemporaryExprClass, Empty) {} static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp, - Expr* SubExpr); + Expr *SubExpr); CXXTemporary *getTemporary() { return Temp; } const CXXTemporary *getTemporary() const { return Temp; } @@ -2214,9 +2208,7 @@ class CXXScalarValueInitExpr : public Expr { explicit CXXScalarValueInitExpr(EmptyShell Shell) : Expr(CXXScalarValueInitExprClass, Shell) {} - TypeSourceInfo *getTypeSourceInfo() const { - return TypeInfo; - } + TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; } SourceLocation getRParenLoc() const { return CXXScalarValueInitExprBits.RParenLoc; @@ -2777,12 +2769,11 @@ class CXXPseudoDestructorExpr : public Expr { PseudoDestructorTypeStorage DestroyedType; public: - CXXPseudoDestructorExpr(const ASTContext &Context, - Expr *Base, bool isArrow, SourceLocation OperatorLoc, + CXXPseudoDestructorExpr(const ASTContext &Context, Expr *Base, bool isArrow, + SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, - SourceLocation ColonColonLoc, - SourceLocation TildeLoc, + SourceLocation ColonColonLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); explicit CXXPseudoDestructorExpr(EmptyShell Shell) @@ -2925,8 +2916,7 @@ class TypeTraitExpr final static TypeTraitExpr *Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef Args, - SourceLocation RParenLoc, - bool Value); + SourceLocation RParenLoc, bool Value); static TypeTraitExpr *Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, @@ -3043,7 +3033,10 @@ class ArrayTypeTraitExpr : public Expr { TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; } - uint64_t getValue() const { assert(!isTypeDependent()); return Value; } + uint64_t getValue() const { + assert(!isTypeDependent()); + return Value; + } Expr *getDimensionExpression() const { return Dimension; } @@ -3076,7 +3069,7 @@ class ExpressionTraitExpr : public Expr { SourceLocation RParen; /// The expression being queried. - Expr* QueriedExpression = nullptr; + Expr *QueriedExpression = nullptr; public: friend class ASTStmtReader; @@ -3810,7 +3803,7 @@ class CXXUnresolvedConstructExpr final arg_iterator arg_end() { return arg_begin() + getNumArgs(); } arg_range arguments() { return arg_range(arg_begin(), arg_end()); } - using const_arg_iterator = const Expr* const *; + using const_arg_iterator = const Expr *const *; using const_arg_range = llvm::iterator_range; const_arg_iterator arg_begin() const { return getTrailingObjects(); } @@ -4420,9 +4413,7 @@ class PackExpansionExpr : public Expr { } // Iterators - child_range children() { - return child_range(&Pattern, &Pattern + 1); - } + child_range children() { return child_range(&Pattern, &Pattern + 1); } const_child_range children() const { return const_child_range(&Pattern, &Pattern + 1); @@ -4525,9 +4516,7 @@ class SizeOfPackExpr final /// /// template using X = int[sizeof...(Ts)]; /// template void f(X); - bool isPartiallySubstituted() const { - return isValueDependent() && Length; - } + bool isPartiallySubstituted() const { return isValueDependent() && Length; } /// Get ArrayRef getPartialArguments() const { @@ -5056,8 +5045,8 @@ class CXXFoldExpr : public Expr { UnresolvedLookupExpr *getCallee() const { return static_cast(SubExprs[SubExpr::Callee]); } - Expr *getLHS() const { return static_cast(SubExprs[SubExpr::LHS]); } - Expr *getRHS() const { return static_cast(SubExprs[SubExpr::RHS]); } + Expr *getLHS() const { return static_cast(SubExprs[SubExpr::LHS]); } + Expr *getRHS() const { return static_cast(SubExprs[SubExpr::RHS]); } /// Does this produce a right-associated sequence of operators? bool isRightFold() const { @@ -5304,22 +5293,22 @@ class CoroutineSuspendExpr : public Expr { } Expr *getCommonExpr() const { - return static_cast(SubExprs[SubExpr::Common]); + return static_cast(SubExprs[SubExpr::Common]); } /// getOpaqueValue - Return the opaque value placeholder. OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } Expr *getReadyExpr() const { - return static_cast(SubExprs[SubExpr::Ready]); + return static_cast(SubExprs[SubExpr::Ready]); } Expr *getSuspendExpr() const { - return static_cast(SubExprs[SubExpr::Suspend]); + return static_cast(SubExprs[SubExpr::Suspend]); } Expr *getResumeExpr() const { - return static_cast(SubExprs[SubExpr::Resume]); + return static_cast(SubExprs[SubExpr::Resume]); } // The syntactic operand written in the code @@ -5501,6 +5490,55 @@ class BuiltinBitCastExpr final } }; +/// Represents a C++2c reflect expression (P2996). +class CXXReflectExpr : public Expr { + + // Source locations. + SourceLocation OperatorLoc; + SourceRange OperandRange; + + CXXReflectExpr(const ASTContext &C, QualType T, QualType Ty); + CXXReflectExpr(const ASTContext &C, QualType T, Decl *Arg, bool IsNamespace); + CXXReflectExpr(EmptyShell Empty); + +public: + static CXXReflectExpr *Create(ASTContext &C, SourceLocation OperatorLoc, + SourceLocation ArgLoc, QualType Operand); + + static CXXReflectExpr *Create(ASTContext &C, SourceLocation OperatorLoc, + SourceLocation OperandLoc, Decl *Operand); + + static CXXReflectExpr *CreateEmpty(ASTContext &C); + + SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; } + SourceLocation getEndLoc() const LLVM_READONLY { + return OperandRange.getEnd(); + } + SourceRange getSourceRange() const { + return SourceRange(getBeginLoc(), getEndLoc()); + } + + /// Returns location of the '^^'-operator. + SourceLocation getOperatorLoc() const { return OperatorLoc; } + SourceRange getOperandRange() const { return OperandRange; } + + /// Sets the location of the '^^'-operator. + void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } + void setOperandRange(SourceRange R) { OperandRange = R; } + + child_range children() { + return child_range(child_iterator(), child_iterator()); + } + + const_child_range children() const { + return const_child_range(const_child_iterator(), const_child_iterator()); + } + + static bool classof(const Stmt *T) { + return T->getStmtClass() == CXXReflectExprClass; + } +}; + } // namespace clang #endif // LLVM_CLANG_AST_EXPRCXX_H diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h b/clang/include/clang/AST/RecursiveASTVisitor.h index 32b2b6bdb989c..126d5284a23e2 100644 --- a/clang/include/clang/AST/RecursiveASTVisitor.h +++ b/clang/include/clang/AST/RecursiveASTVisitor.h @@ -78,8 +78,7 @@ struct has_same_member_pointer_type template LLVM_ATTRIBUTE_ALWAYS_INLINE LLVM_ATTRIBUTE_NODEBUG auto isSameMethod([[maybe_unused]] FirstMethodPtrTy FirstMethodPtr, - [[maybe_unused]] SecondMethodPtrTy SecondMethodPtr) - -> bool { + [[maybe_unused]] SecondMethodPtrTy SecondMethodPtr) -> bool { if constexpr (has_same_member_pointer_type::value) return FirstMethodPtr == SecondMethodPtr; @@ -161,7 +160,7 @@ template class RecursiveASTVisitor { /// typically not be explicitly specified by derived classes. /// The bool bit indicates whether the statement has been traversed or not. typedef SmallVectorImpl> - DataRecursionQueue; + DataRecursionQueue; /// Return a reference to the derived class. Derived &getDerived() { return *static_cast(this); } @@ -333,7 +332,7 @@ template class RecursiveASTVisitor { #include "clang/AST/AttrVisitor.inc" #undef ATTR_VISITOR_DECLS_ONLY -// ---- Methods on Stmts ---- + // ---- Methods on Stmts ---- Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); } @@ -367,7 +366,7 @@ template class RecursiveASTVisitor { public: // Declare Traverse*() for all concrete Stmt classes. #define ABSTRACT_STMT(STMT) -#define STMT(CLASS, PARENT) \ +#define STMT(CLASS, PARENT) \ bool Traverse##CLASS(CLASS *S, DataRecursionQueue *Queue = nullptr); #include "clang/AST/StmtNodes.inc" // The above header #undefs ABSTRACT_STMT and STMT upon exit. @@ -484,8 +483,7 @@ template class RecursiveASTVisitor { bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL); // Traverses template parameter lists of either a DeclaratorDecl or TagDecl. - template - bool TraverseDeclTemplateParameterLists(T *D); + template bool TraverseDeclTemplateParameterLists(T *D); bool TraverseTemplateTypeParamDeclConstraints(const TemplateTypeParmDecl *D); @@ -966,10 +964,9 @@ bool RecursiveASTVisitor::TraverseConstructorInitializer( } template -bool -RecursiveASTVisitor::TraverseLambdaCapture(LambdaExpr *LE, - const LambdaCapture *C, - Expr *Init) { +bool RecursiveASTVisitor::TraverseLambdaCapture(LambdaExpr *LE, + const LambdaCapture *C, + Expr *Init) { if (LE->isInitCapture(C)) TRY_TO(TraverseDecl(C->getCapturedVar())); else @@ -986,9 +983,7 @@ RecursiveASTVisitor::TraverseLambdaCapture(LambdaExpr *LE, bool TraverseQualifier) { \ if (!getDerived().shouldTraversePostOrder()) \ TRY_TO(WalkUpFrom##TYPE(T)); \ - { \ - CODE; \ - } \ + { CODE; } \ if (getDerived().shouldTraversePostOrder()) \ TRY_TO(WalkUpFrom##TYPE(T)); \ return true; \ @@ -1025,7 +1020,7 @@ DEF_TRAVERSE_TYPE(DecayedType, { TRY_TO(TraverseType(T->getOriginalType())); }) DEF_TRAVERSE_TYPE(ConstantArrayType, { TRY_TO(TraverseType(T->getElementType())); if (T->getSizeExpr()) - TRY_TO(TraverseStmt(const_cast(T->getSizeExpr()))); + TRY_TO(TraverseStmt(const_cast(T->getSizeExpr()))); }) DEF_TRAVERSE_TYPE(ArrayParameterType, { @@ -1137,9 +1132,8 @@ DEF_TRAVERSE_TYPE(AutoType, { }) DEF_TRAVERSE_TYPE(TemplateTypeParmType, {}) -DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, { - TRY_TO(TraverseType(T->getReplacementType())); -}) +DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, + { TRY_TO(TraverseType(T->getReplacementType())); }) DEF_TRAVERSE_TYPE(SubstTemplateTypeParmPackType, { TRY_TO(TraverseSubstPackTypeHelper(T)); }) DEF_TRAVERSE_TYPE(SubstBuiltinTemplatePackType, @@ -1261,9 +1255,7 @@ DEF_TRAVERSE_TYPE(PredefinedSugarType, {}) if (getDerived().shouldWalkTypesOfTypeLocs()) \ TRY_TO(WalkUpFrom##TYPE(const_cast(TL.getTypePtr()))); \ } \ - { \ - CODE; \ - } \ + { CODE; } \ if (getDerived().shouldTraversePostOrder()) { \ TRY_TO(WalkUpFrom##TYPE##Loc(TL)); \ if (getDerived().shouldWalkTypesOfTypeLocs()) \ @@ -1622,7 +1614,7 @@ bool RecursiveASTVisitor::canIgnoreChildDeclWhileTraversingDeclContext( if (isa(Child) || isa(Child)) return true; // Lambda classes are traversed through LambdaExprs. - if (const CXXRecordDecl* Cls = dyn_cast(Child)) + if (const CXXRecordDecl *Cls = dyn_cast(Child)) return Cls->isLambda(); return false; } @@ -1691,9 +1683,8 @@ DEF_TRAVERSE_DECL(HLSLBufferDecl, {}) DEF_TRAVERSE_DECL(HLSLRootSignatureDecl, {}) -DEF_TRAVERSE_DECL(LifetimeExtendedTemporaryDecl, { - TRY_TO(TraverseStmt(D->getTemporaryExpr())); -}) +DEF_TRAVERSE_DECL(LifetimeExtendedTemporaryDecl, + { TRY_TO(TraverseStmt(D->getTemporaryExpr())); }) DEF_TRAVERSE_DECL(FileScopeAsmDecl, { TRY_TO(TraverseStmt(D->getAsmStringExpr())); }) @@ -1734,7 +1725,8 @@ DEF_TRAVERSE_DECL(LinkageSpecDecl, {}) DEF_TRAVERSE_DECL(ExportDecl, {}) -DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {// FIXME: implement this +DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, { + // FIXME: implement this }) DEF_TRAVERSE_DECL(StaticAssertDecl, { @@ -1775,17 +1767,19 @@ DEF_TRAVERSE_DECL(NamespaceAliasDecl, { ShouldVisitChildren = false; }) -DEF_TRAVERSE_DECL(LabelDecl, {// There is no code in a LabelDecl. +DEF_TRAVERSE_DECL(LabelDecl, { + // There is no code in a LabelDecl. }) -DEF_TRAVERSE_DECL( - NamespaceDecl, - {// Code in an unnamed namespace shows up automatically in - // decls_begin()/decls_end(). Thus we don't need to recurse on - // D->getAnonymousNamespace(). - }) +DEF_TRAVERSE_DECL(NamespaceDecl, + { + // Code in an unnamed namespace shows up automatically in + // decls_begin()/decls_end(). Thus we don't need to + // recurse on D->getAnonymousNamespace(). + }) -DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {// FIXME: implement +DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, { + // FIXME: implement }) DEF_TRAVERSE_DECL(ObjCCategoryDecl, { @@ -1800,10 +1794,12 @@ DEF_TRAVERSE_DECL(ObjCCategoryDecl, { } }) -DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {// FIXME: implement +DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, { + // FIXME: implement }) -DEF_TRAVERSE_DECL(ObjCImplementationDecl, {// FIXME: implement +DEF_TRAVERSE_DECL(ObjCImplementationDecl, { + // FIXME: implement }) DEF_TRAVERSE_DECL(ObjCInterfaceDecl, { @@ -2039,24 +2035,24 @@ bool RecursiveASTVisitor::TraverseTemplateInstantiations( // This macro unifies the traversal of class, variable and function // template declarations. -#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND) \ - DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, { \ - TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \ - TRY_TO(TraverseDecl(D->getTemplatedDecl())); \ - \ - /* By default, we do not traverse the instantiations of \ - class templates since they do not appear in the user code. The \ - following code optionally traverses them. \ - \ - We only traverse the class instantiations when we see the canonical \ - declaration of the template, to ensure we only visit them once. */ \ - if (getDerived().shouldVisitTemplateInstantiations() && \ - D == D->getCanonicalDecl()) \ - TRY_TO(TraverseTemplateInstantiations(D)); \ - \ - /* Note that getInstantiatedFromMemberTemplate() is just a link \ - from a template instantiation back to the template from which \ - it was instantiated, and thus should not be traversed. */ \ +#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND) \ + DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, { \ + TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \ + TRY_TO(TraverseDecl(D->getTemplatedDecl())); \ + \ + /* By default, we do not traverse the instantiations of \ + class templates since they do not appear in the user code. The \ + following code optionally traverses them. \ + \ \ + We only traverse the class instantiations when we see the canonical \ + declaration of the template, to ensure we only visit them once. */ \ + if (getDerived().shouldVisitTemplateInstantiations() && \ + D == D->getCanonicalDecl()) \ + TRY_TO(TraverseTemplateInstantiations(D)); \ + \ + /* Note that getInstantiatedFromMemberTemplate() is just a link \ + from a template instantiation back to the template from which \ + it was instantiated, and thus should not be traversed. */ \ }) DEF_TRAVERSE_TMPL_DECL(Class) @@ -2529,8 +2525,9 @@ DEF_TRAVERSE_STMT(GCCAsmStmt, { DEF_TRAVERSE_STMT( MSAsmStmt, - {// FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc. Once - // added this needs to be implemented. + { + // FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc. + // Once added this needs to be implemented. }) DEF_TRAVERSE_STMT(CXXCatchStmt, { @@ -2629,11 +2626,11 @@ DEF_TRAVERSE_STMT(MemberExpr, { S->getNumTemplateArgs())); }) -DEF_TRAVERSE_STMT( - ImplicitCastExpr, - {// We don't traverse the cast type, as it's not written in the - // source code. - }) +DEF_TRAVERSE_STMT(ImplicitCastExpr, + { + // We don't traverse the cast type, as it's not written in + // the source code. + }) DEF_TRAVERSE_STMT(CStyleCastExpr, { TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc())); @@ -2823,8 +2820,9 @@ DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, { TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc())); }) -DEF_TRAVERSE_STMT(ExpressionTraitExpr, - { TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getQueriedExpression()); }) +DEF_TRAVERSE_STMT(ExpressionTraitExpr, { + TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getQueriedExpression()); +}) DEF_TRAVERSE_STMT(VAArgExpr, { // The child-iterator will pick up the expression argument. @@ -2883,6 +2881,10 @@ DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, { TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc())); }) +DEF_TRAVERSE_STMT(CXXReflectExpr, { + // TODO + }) + // These expressions all might take explicit template arguments. // We traverse those if so. FIXME: implement these. DEF_TRAVERSE_STMT(CXXConstructExpr, {}) @@ -3037,8 +3039,8 @@ DEF_TRAVERSE_STMT(CXXRewrittenBinaryOperator, { if (!getDerived().shouldVisitImplicitCode()) { CXXRewrittenBinaryOperator::DecomposedForm Decomposed = S->getDecomposedForm(); - TRY_TO(TraverseStmt(const_cast(Decomposed.LHS))); - TRY_TO(TraverseStmt(const_cast(Decomposed.RHS))); + TRY_TO(TraverseStmt(const_cast(Decomposed.LHS))); + TRY_TO(TraverseStmt(const_cast(Decomposed.RHS))); ShouldVisitChildren = false; } }) @@ -3151,8 +3153,8 @@ DEF_TRAVERSE_STMT(OMPCanonicalLoop, { }) template -bool -RecursiveASTVisitor::TraverseOMPLoopDirective(OMPLoopDirective *S) { +bool RecursiveASTVisitor::TraverseOMPLoopDirective( + OMPLoopDirective *S) { return TraverseOMPExecutableDirective(S); } @@ -3431,7 +3433,8 @@ bool RecursiveASTVisitor::VisitOMPAllocatorClause( } template -bool RecursiveASTVisitor::VisitOMPAllocateClause(OMPAllocateClause *C) { +bool RecursiveASTVisitor::VisitOMPAllocateClause( + OMPAllocateClause *C) { TRY_TO(TraverseStmt(C->getAllocator())); TRY_TO(VisitOMPClauseList(C)); return true; @@ -3452,8 +3455,8 @@ bool RecursiveASTVisitor::VisitOMPFinalClause(OMPFinalClause *C) { } template -bool -RecursiveASTVisitor::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { +bool RecursiveASTVisitor::VisitOMPNumThreadsClause( + OMPNumThreadsClause *C) { TRY_TO(VisitOMPClauseWithPreInit(C)); TRY_TO(TraverseStmt(C->getNumThreads())); return true; @@ -3512,8 +3515,8 @@ bool RecursiveASTVisitor::VisitOMPPartialClause(OMPPartialClause *C) { } template -bool -RecursiveASTVisitor::VisitOMPCollapseClause(OMPCollapseClause *C) { +bool RecursiveASTVisitor::VisitOMPCollapseClause( + OMPCollapseClause *C) { TRY_TO(TraverseStmt(C->getNumForLoops())); return true; } @@ -3580,8 +3583,8 @@ bool RecursiveASTVisitor::VisitOMPMessageClause(OMPMessageClause *C) { } template -bool -RecursiveASTVisitor::VisitOMPScheduleClause(OMPScheduleClause *C) { +bool RecursiveASTVisitor::VisitOMPScheduleClause( + OMPScheduleClause *C) { TRY_TO(VisitOMPClauseWithPreInit(C)); TRY_TO(TraverseStmt(C->getChunkSize())); return true; @@ -3605,8 +3608,8 @@ bool RecursiveASTVisitor::VisitOMPUntiedClause(OMPUntiedClause *) { } template -bool -RecursiveASTVisitor::VisitOMPMergeableClause(OMPMergeableClause *) { +bool RecursiveASTVisitor::VisitOMPMergeableClause( + OMPMergeableClause *) { return true; } @@ -3889,8 +3892,8 @@ bool RecursiveASTVisitor::VisitOMPCopyprivateClause( } template -bool -RecursiveASTVisitor::VisitOMPReductionClause(OMPReductionClause *C) { +bool RecursiveASTVisitor::VisitOMPReductionClause( + OMPReductionClause *C) { TRY_TO(TraverseNestedNameSpecifierLoc(C->getQualifierLoc())); TRY_TO(TraverseDeclarationNameInfo(C->getNameInfo())); TRY_TO(VisitOMPClauseList(C)); @@ -4053,8 +4056,8 @@ bool RecursiveASTVisitor::VisitOMPDistScheduleClause( } template -bool -RecursiveASTVisitor::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { +bool RecursiveASTVisitor::VisitOMPDefaultmapClause( + OMPDefaultmapClause *C) { return true; } diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index e5e071f43fa75..cf82c1a7f21c1 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -1848,6 +1848,11 @@ def err_placeholder_expected_auto_or_decltype_auto : Error< "expected 'auto' or 'decltype(auto)' after concept name">; } +let CategoryName = "Reflection Issue" in { +def err_cannot_reflect_operand : Error< + "cannot reflect the provided operand">; +} + def warn_max_tokens : Warning< "the number of preprocessor source tokens (%0) exceeds this token limit (%1)">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Basic/Features.def b/clang/include/clang/Basic/Features.def index 0e91b42a132c1..c9d24430326ff 100644 --- a/clang/include/clang/Basic/Features.def +++ b/clang/include/clang/Basic/Features.def @@ -380,6 +380,8 @@ FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && LangOpts.RelativeCXXABIVT FEATURE(clang_atomic_attributes, true) +FEATURE(reflection, LangOpts.Reflection) + // CUDA/HIP Features FEATURE(cuda_noinline_keyword, LangOpts.CUDA) EXTENSION(cuda_implicit_host_device_templates, LangOpts.CUDA && LangOpts.OffloadImplicitHostDeviceTemplates) diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 8d6b8a14740ce..ef97b0867321c 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -499,6 +499,7 @@ LANGOPT(BoundsSafety, 1, 0, NotCompatible, "Bounds safety extension for C") LANGOPT(EnableLifetimeSafety, 1, 0, NotCompatible, "Experimental lifetime safety analysis for C++") LANGOPT(PreserveVec3Type, 1, 0, NotCompatible, "Preserve 3-component vector type") +LANGOPT(Reflection , 1, 0, NotCompatible, "C++26 Reflection") #undef LANGOPT #undef ENUM_LANGOPT diff --git a/clang/include/clang/Basic/StmtNodes.td b/clang/include/clang/Basic/StmtNodes.td index bf3686bb372d5..987e1d1408e06 100644 --- a/clang/include/clang/Basic/StmtNodes.td +++ b/clang/include/clang/Basic/StmtNodes.td @@ -177,6 +177,9 @@ def CoyieldExpr : StmtNode; def ConceptSpecializationExpr : StmtNode; def RequiresExpr : StmtNode; +// c++ 26 reflection +def CXXReflectExpr : StmtNode; + // Obj-C Expressions. def ObjCStringLiteral : StmtNode; def ObjCBoxedExpr : StmtNode; diff --git a/clang/include/clang/Basic/TokenKinds.def b/clang/include/clang/Basic/TokenKinds.def index 564d6010181cc..b7fef8b2de739 100644 --- a/clang/include/clang/Basic/TokenKinds.def +++ b/clang/include/clang/Basic/TokenKinds.def @@ -233,6 +233,7 @@ PUNCTUATOR(greatergreater, ">>") PUNCTUATOR(greaterequal, ">=") PUNCTUATOR(greatergreaterequal, ">>=") PUNCTUATOR(caret, "^") +PUNCTUATOR(caretcaret, "^^") PUNCTUATOR(caretequal, "^=") PUNCTUATOR(pipe, "|") PUNCTUATOR(pipepipe, "||") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 0c9584f1b479f..1ac0c15c102b5 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3689,6 +3689,11 @@ defm application_extension : BoolFOption<"application-extension", PosFlag, NegFlag>; +defm reflection : BoolFOption<"reflection", + LangOpts<"Reflection">, DefaultFalse, + PosFlag, + NegFlag>; defm sized_deallocation : BoolFOption<"sized-deallocation", LangOpts<"SizedDeallocation">, Default, PosFlag, @@ -7189,7 +7194,7 @@ defm android_pad_segment : BooleanFFlag<"android-pad-segment">, Group; def shared_libflangrt : Flag<["-"], "shared-libflangrt">, HelpText<"Link the flang-rt shared library">, Group, Visibility<[FlangOption]>, Flags<[NoArgumentUnused]>; -def static_libflangrt : Flag<["-"], "static-libflangrt">, +def static_libflangrt : Flag<["-"], "static-libflangrt">, HelpText<"Link the flang-rt static library">, Group, Visibility<[FlangOption]>, Flags<[NoArgumentUnused]>; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index 0d2316f73fb62..6ead732a51f69 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -150,6 +150,7 @@ enum class TentativeCXXTypeIdContext { AsTemplateArgument, InTrailingReturnType, AsGenericSelectionArgument, + AsReflectionOperand }; /// The kind of attribute specifier we have found. @@ -231,7 +232,8 @@ class Parser : public CodeCompletionHandler { /// [C] translation-unit external-declaration /// [C++] top-level-declaration-seq[opt] /// [C++20] global-module-fragment[opt] module-declaration - /// top-level-declaration-seq[opt] private-module-fragment[opt] + /// top-level-declaration-seq[opt] + /// private-module-fragment[opt] /// \endverbatim /// /// Note that in C, it is an error if there is no first declaration. @@ -923,15 +925,16 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// function-definition: [C99 6.9.1] - /// decl-specs declarator declaration-list[opt] compound-statement + /// decl-specs declarator declaration-list[opt] + /// compound-statement /// [C90] function-definition: [C99 6.7.1] - implicit int result - /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement + /// [C90] decl-specs[opt] declarator declaration-list[opt] + /// compound-statement /// /// declaration: [C99 6.7] /// declaration-specifiers init-declarator-list[opt] ';' - /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] - /// [OMP] threadprivate-directive - /// [OMP] allocate-directive [TODO] + /// [!C99] init-declarator-list ';' [TODO: warn in c99 + /// mode] [OMP] threadprivate-directive [OMP] allocate-directive [TODO] /// \endverbatim /// DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributes &Attrs, @@ -950,10 +953,11 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// function-definition: [C99 6.9.1] - /// decl-specs declarator declaration-list[opt] compound-statement + /// decl-specs declarator declaration-list[opt] + /// compound-statement /// [C90] function-definition: [C99 6.7.1] - implicit int result - /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement - /// [C++] function-definition: [C++ 8.4] + /// [C90] decl-specs[opt] declarator declaration-list[opt] + /// compound-statement [C++] function-definition: [C++ 8.4] /// decl-specifier-seq[opt] declarator ctor-initializer[opt] /// function-body /// [C++] function-definition: [C++ 8.4] @@ -1794,9 +1798,7 @@ class Parser : public CodeCompletionHandler { /// [C++] initializer: /// [C++] '=' initializer-clause /// [C++] '(' expression-list ')' - /// [C++0x] '=' 'default' [TODO] - /// [C++0x] '=' 'delete' - /// [C++0x] braced-init-list + /// [C++0x] '=' 'default' [TODO] [C++0x] '=' 'delete' [C++0x] braced-init-list /// \endverbatim /// /// According to the standard grammar, =default and =delete are function @@ -1913,9 +1915,11 @@ class Parser : public CodeCompletionHandler { /// enum-specifier: [C99 6.7.2.2] /// 'enum' identifier[opt] '{' enumerator-list '}' ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' - /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] + /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' + /// [opt] /// '}' attributes[opt] - /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] + /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' + /// [opt] /// '}' /// 'enum' identifier /// [GNU] 'enum' attributes[opt] identifier @@ -1924,8 +1928,9 @@ class Parser : public CodeCompletionHandler { /// [C++11] enum-head '{' enumerator-list ',' '}' /// /// enum-head: [C++11] - /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] - /// enum-key attribute-specifier-seq[opt] nested-name-specifier + /// enum-key attribute-specifier-seq[opt] identifier[opt] + /// enum-base[opt] enum-key attribute-specifier-seq[opt] + /// nested-name-specifier /// identifier enum-base[opt] /// /// enum-key: [C++11] @@ -2402,8 +2407,8 @@ class Parser : public CodeCompletionHandler { /// Parse the contents of the "objc_bridge_related" attribute. /// \verbatim - /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')' - /// related_class: + /// objc_bridge_related '(' related_class ',' opt-class_method ',' + /// opt-instance_method ')' related_class: /// Identifier /// /// opt-class_method: @@ -3358,8 +3363,10 @@ class Parser : public CodeCompletionHandler { /// struct-or-union-specifier: [C99 6.7.2.1] /// struct-or-union identifier[opt] '{' struct-contents '}' /// struct-or-union identifier - /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents - /// '}' attributes[opt] + /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' + /// struct-contents + /// '}' + /// attributes[opt] /// [GNU] struct-or-union attributes[opt] identifier /// struct-or-union: /// 'struct' @@ -3431,8 +3438,8 @@ class Parser : public CodeCompletionHandler { /// decl-specifier-seq[opt] member-declarator-list[opt] ';' /// function-definition ';'[opt] /// [C++26] friend-type-declaration - /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] - /// using-declaration [TODO] + /// ::[opt] nested-name-specifier template[opt] unqualified-id + /// ';'[TODO] using-declaration [TODO] /// [C++0x] static_assert-declaration /// template-declaration /// [GNU] '__extension__' member-declaration @@ -3903,8 +3910,9 @@ class Parser : public CodeCompletionHandler { /// [GNU] '__PRETTY_FUNCTION__' /// [GNU] '(' compound-statement ')' /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' - /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' - /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' + /// [GNU] '__builtin_offsetof' '(' type-name ',' + /// offsetof-member-designator')' [GNU] '__builtin_choose_expr' '(' + /// assign-expr ',' assign-expr ',' /// assign-expr ')' /// [GNU] '__builtin_FILE' '(' ')' /// [CLANG] '__builtin_FILE_NAME' '(' ')' @@ -3920,21 +3928,19 @@ class Parser : public CodeCompletionHandler { /// [OBJC] '\@protocol' '(' identifier ')' /// [OBJC] '\@encode' '(' type-name ')' /// [OBJC] objc-string-literal - /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] - /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3] - /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] - /// [C++11] typename-specifier braced-init-list [C++11 5.2.3] - /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] - /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] - /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] - /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] - /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] - /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] - /// [C++] 'this' [C++ 9.3.2] - /// [G++] unary-type-trait '(' type-id ')' - /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] - /// [EMBT] array-type-trait '(' type-id ',' integer ')' - /// [clang] '^' block-literal + /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] + /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3] [C++] + /// typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] + /// [C++11] typename-specifier braced-init-list [C++11 5.2.3] [C++] + /// 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] [C++] + /// 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] [C++] + /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] [C++] + /// 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] [C++] + /// 'typeid' '(' expression ')' [C++ 5.2p1] [C++] + /// 'typeid' '(' type-id ')' [C++ 5.2p1] [C++] + /// 'this' [C++ 9.3.2] [G++] unary-type-trait '(' type-id ')' [G++] + /// binary-type-trait '(' type-id ',' type-id ')' [TODO] [EMBT] + /// array-type-trait '(' type-id ',' integer ')' [clang] '^' block-literal /// /// constant: [C99 6.4.4] /// integer-constant @@ -4100,8 +4106,9 @@ class Parser : public CodeCompletionHandler { /// \verbatim /// primary-expression: [C99 6.5.1] /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' - /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' - /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' + /// [GNU] '__builtin_offsetof' '(' type-name ',' + /// offsetof-member-designator')' [GNU] '__builtin_choose_expr' '(' + /// assign-expr ',' assign-expr ',' /// assign-expr ')' /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' /// [GNU] '__builtin_FILE' '(' ')' @@ -4809,16 +4816,8 @@ class Parser : public CodeCompletionHandler { /// \verbatim /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name - /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] - /// char - /// wchar_t - /// bool - /// short - /// int - /// long - /// signed - /// unsigned - /// float + /// '::'[opt] nested-name-specifier 'template' simple-template-id + /// [TODO] char wchar_t bool short int long signed unsigned float /// double /// void /// [GNU] typeof-specifier @@ -5167,6 +5166,10 @@ class Parser : public CodeCompletionHandler { /// Implementations are in ParseHLSL.cpp ///@{ + //===--------------------------------------------------------------------===// + // C++2c: Reflection [P2996] + ExprResult ParseCXXReflectExpression(SourceLocation OpLoc); + private: bool MaybeParseHLSLAnnotations(Declarator &D, SourceLocation *EndLoc = nullptr, @@ -5477,7 +5480,8 @@ class Parser : public CodeCompletionHandler { /// '<' objc-type-parameter (',' objc-type-parameter)* '>' /// /// objc-type-parameter: - /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt] + /// objc-type-parameter-variance? identifier + /// objc-type-parameter-bound[opt] /// /// objc-type-parameter-bound: /// ':' type-name @@ -5748,8 +5752,8 @@ class Parser : public CodeCompletionHandler { /// objc-keyword-selector objc-keyword-decl /// /// objc-keyword-decl: - /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier - /// objc-selector ':' objc-keyword-attributes[opt] identifier + /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] + /// identifier objc-selector ':' objc-keyword-attributes[opt] identifier /// ':' objc-type-name objc-keyword-attributes[opt] identifier /// ':' objc-keyword-attributes[opt] identifier /// @@ -5823,7 +5827,8 @@ class Parser : public CodeCompletionHandler { /// \verbatim /// objc-scalar-literal : '@' scalar-literal /// ; - /// scalar-literal : | numeric-constant /* any numeric constant. */ + /// scalar-literal : | numeric-constant /* any numeric + /// constant. */ /// ; /// \endverbatim ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); @@ -5967,11 +5972,13 @@ class Parser : public CodeCompletionHandler { /// \verbatim /// objc-try-catch-statement: /// @try compound-statement objc-catch-list[opt] - /// @try compound-statement objc-catch-list[opt] @finally compound-statement + /// @try compound-statement objc-catch-list[opt] @finally + /// compound-statement /// /// objc-catch-list: /// @catch ( parameter-declaration ) compound-statement - /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement + /// objc-catch-list @catch ( catch-parameter-declaration ) + /// compound-statement /// catch-parameter-declaration: /// parameter-declaration /// '...' [OBJC2] @@ -6368,8 +6375,8 @@ class Parser : public CodeCompletionHandler { /// Parses an OpenMP context selector set. /// /// \verbatim - /// '=' '{' [, ]* '}' - /// \endverbatim + /// '=' '{' [, ]* + /// '}' \endverbatim void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap &SeenSets); @@ -6473,8 +6480,8 @@ class Parser : public CodeCompletionHandler { /// annot_pragma_openmp_end /// /// declare-mapper-directive: - /// annot_pragma_openmp 'declare' 'mapper' '(' [ ':'] - /// ')' [[[,] ] ... ] + /// annot_pragma_openmp 'declare' 'mapper' '(' [ + /// ':'] ')' [[[,] ] ... ] /// annot_pragma_openmp_end /// /// declare-simd-directive: @@ -6506,8 +6513,8 @@ class Parser : public CodeCompletionHandler { /// declare-reduction-directive: /// annot_pragma_openmp 'declare' 'reduction' /// '(' ':' {',' } ':' ')' - /// ['initializer' '(' ('omp_priv' '=' )| ')'] - /// annot_pragma_openmp_end + /// ['initializer' '(' ('omp_priv' '=' )| + /// ')'] annot_pragma_openmp_end /// \endverbatim /// is either a base language identifier or one of the /// following operators: '+', '-', '*', '&', '|', '^', '&&' and '||'. @@ -6522,8 +6529,8 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// declare-mapper-directive: - /// annot_pragma_openmp 'declare' 'mapper' '(' [ ':'] - /// ')' [[[,] ] ... ] + /// annot_pragma_openmp 'declare' 'mapper' '(' [ + /// ':'] ')' [[[,] ] ... ] /// annot_pragma_openmp_end /// \endverbatim /// and are base language identifiers. @@ -6571,8 +6578,8 @@ class Parser : public CodeCompletionHandler { /// annot_pragma_openmp_end /// /// declare-mapper-directive: - /// annot_pragma_openmp 'declare' 'mapper' '(' [ ':'] - /// ')' [[[,] ] ... ] + /// annot_pragma_openmp 'declare' 'mapper' '(' [ + /// ':'] ')' [[[,] ] ... ] /// annot_pragma_openmp_end /// /// executable-directive: @@ -6745,7 +6752,8 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// schedule-clause: - /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ] + /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression + /// ] /// ')' /// /// if-clause: @@ -6920,7 +6928,8 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// init-clause: - /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var) + /// init([interop-modifier, ]interop-type[[, interop-type] ... + /// ]:interop-var) /// /// destroy-clause: /// destroy(interop-var) @@ -6974,10 +6983,10 @@ class Parser : public CodeCompletionHandler { bool parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data); /// Parse map-type-modifiers in map clause. - /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list) - /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) | - /// present - /// where, map-type ::= alloc | delete | from | release | to | tofrom + /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] + /// list) where, map-type-modifier ::= always | close | + /// mapper(mapper-identifier) | present where, map-type ::= alloc | delete | + /// from | release | to | tofrom bool parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data); /// Parses 'omp begin declare variant' directive. @@ -7192,8 +7201,7 @@ class Parser : public CodeCompletionHandler { /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; - private: - +private: /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations @@ -7436,9 +7444,8 @@ class Parser : public CodeCompletionHandler { /// for-statement: [C99 6.8.5.3] /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement - /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')' - /// [C++] statement - /// [C++0x] 'for' + /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] + /// ')' [C++] statement [C++0x] 'for' /// 'co_await'[opt] [Coroutines] /// '(' for-range-declaration ':' for-range-initializer ')' /// statement @@ -7552,7 +7559,8 @@ class Parser : public CodeCompletionHandler { /// /// exception-declaration: /// attribute-specifier-seq[opt] type-specifier-seq declarator - /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt] + /// attribute-specifier-seq[opt] type-specifier-seq + /// abstract-declarator[opt] /// '...' /// \endverbatim /// @@ -7677,7 +7685,7 @@ class Parser : public CodeCompletionHandler { /// [GNU] asm-clobbers: /// asm-string-literal /// asm-clobbers ',' asm-string-literal - /// \endverbatim + /// \endverbatim /// StmtResult ParseAsmStatement(bool &msAsm); @@ -8023,7 +8031,8 @@ class Parser : public CodeCompletionHandler { /// /// \verbatim /// template-declaration: [C++ temp] - /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration + /// 'export'[opt] 'template' '<' template-parameter-list '>' + /// declaration /// /// template-declaration: [C++2a] /// template-head declaration @@ -8820,7 +8829,7 @@ class Parser : public CodeCompletionHandler { /// ptr-operator: /// '*' cv-qualifier-seq[opt] /// '&' - /// [C++0x] '&&' [TODO] + /// [C++0x] '&&' [TODO] /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] /// /// cv-qualifier-seq: @@ -8835,16 +8844,15 @@ class Parser : public CodeCompletionHandler { /// /// id-expression: /// unqualified-id - /// qualified-id [TODO] + /// qualified-id [TODO] /// /// unqualified-id: /// identifier /// operator-function-id /// conversion-function-id /// literal-operator-id - /// '~' class-name [TODO] - /// '~' decltype-specifier [TODO] - /// template-id [TODO] + /// '~' class-name [TODO] + /// '~' decltype-specifier [TODO] template-id [TODO] /// \endverbatim /// TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, @@ -8861,8 +8869,9 @@ class Parser : public CodeCompletionHandler { /// parameter-declaration-list ',' parameter-declaration /// /// parameter-declaration: - /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] - /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] + /// attribute-specifier-seq[opt] decl-specifier-seq declarator + /// attributes[opt] attribute-specifier-seq[opt] decl-specifier-seq + /// declarator attributes[opt] /// '=' assignment-expression /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] /// attributes[opt] diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 189798f71dbad..ae9f72351f61b 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -14752,6 +14752,16 @@ class Sema final : public SemaBase { /// Implementations are in SemaConcept.cpp ///@{ +public: + ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *T); + ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, SourceLocation ArgLoc, + Decl *D); + + ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, + SourceLocation OperandLoc, QualType T); + ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, + SourceLocation OperandLoc, Decl *D); + public: void PushSatisfactionStackEntry(const NamedDecl *D, const llvm::FoldingSetNodeID &ID) { diff --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h index 5d09d5536e5ab..b950c444d9aa2 100644 --- a/clang/include/clang/Serialization/ASTBitCodes.h +++ b/clang/include/clang/Serialization/ASTBitCodes.h @@ -1925,6 +1925,9 @@ enum StmtCode { EXPR_CONCEPT_SPECIALIZATION, // ConceptSpecializationExpr EXPR_REQUIRES, // RequiresExpr + // Reflection + EXPR_REFLECT, + // CUDA EXPR_CUDA_KERNEL_CALL, // CUDAKernelCallExpr diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp index c7f0ff040194d..94f22af6363ff 100644 --- a/clang/lib/AST/ExprCXX.cpp +++ b/clang/lib/AST/ExprCXX.cpp @@ -54,7 +54,8 @@ bool CXXOperatorCallExpr::isInfixBinaryOp() const { return false; switch (getOperator()) { - case OO_Call: case OO_Subscript: + case OO_Call: + case OO_Subscript: return false; default: return true; @@ -85,13 +86,26 @@ CXXRewrittenBinaryOperator::getDecomposedForm() const { assert(!SkippedNot || BO->getOperator() == OO_EqualEqual); assert(BO->isInfixBinaryOp()); switch (BO->getOperator()) { - case OO_Less: Result.Opcode = BO_LT; break; - case OO_LessEqual: Result.Opcode = BO_LE; break; - case OO_Greater: Result.Opcode = BO_GT; break; - case OO_GreaterEqual: Result.Opcode = BO_GE; break; - case OO_Spaceship: Result.Opcode = BO_Cmp; break; - case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break; - default: llvm_unreachable("unexpected binop in rewritten operator expr"); + case OO_Less: + Result.Opcode = BO_LT; + break; + case OO_LessEqual: + Result.Opcode = BO_LE; + break; + case OO_Greater: + Result.Opcode = BO_GT; + break; + case OO_GreaterEqual: + Result.Opcode = BO_GE; + break; + case OO_Spaceship: + Result.Opcode = BO_Cmp; + break; + case OO_EqualEqual: + Result.Opcode = SkippedNot ? BO_NE : BO_EQ; + break; + default: + llvm_unreachable("unexpected binop in rewritten operator expr"); } Result.LHS = BO->getArg(0); Result.RHS = BO->getArg(1); @@ -490,7 +504,7 @@ OverloadExpr::OverloadExpr(StmtClass SC, const ASTContext &Context, unsigned NumResults = End - Begin; OverloadExprBits.NumResults = NumResults; OverloadExprBits.HasTemplateKWAndArgsInfo = - (TemplateArgs != nullptr ) || TemplateKWLoc.isValid(); + (TemplateArgs != nullptr) || TemplateKWLoc.isValid(); if (NumResults) { // Copy the results to the trailing array past UnresolvedLookupExpr @@ -587,7 +601,7 @@ SourceLocation CXXConstructExpr::getEndLoc() const { SourceLocation End = getLocation(); for (unsigned I = getNumArgs(); I > 0; --I) { - const Expr *Arg = getArg(I-1); + const Expr *Arg = getArg(I - 1); if (!Arg->isDefaultArgument()) { SourceLocation NewEnd = Arg->getEndLoc(); if (NewEnd.isValid()) { @@ -748,7 +762,7 @@ CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const { } CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const { - Expr* ThisArg = getImplicitObjectArgument(); + Expr *ThisArg = getImplicitObjectArgument(); if (!ThisArg) return nullptr; @@ -767,12 +781,18 @@ CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const { /// "const_cast". The returned pointer must not be freed. const char *CXXNamedCastExpr::getCastName() const { switch (getStmtClass()) { - case CXXStaticCastExprClass: return "static_cast"; - case CXXDynamicCastExprClass: return "dynamic_cast"; - case CXXReinterpretCastExprClass: return "reinterpret_cast"; - case CXXConstCastExprClass: return "const_cast"; - case CXXAddrspaceCastExprClass: return "addrspace_cast"; - default: return ""; + case CXXStaticCastExprClass: + return "static_cast"; + case CXXDynamicCastExprClass: + return "dynamic_cast"; + case CXXReinterpretCastExprClass: + return "reinterpret_cast"; + case CXXConstCastExprClass: + return "const_cast"; + case CXXAddrspaceCastExprClass: + return "addrspace_cast"; + default: + return ""; } } @@ -803,19 +823,14 @@ CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C, return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize, HasFPFeatures); } -CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, - CastKind K, Expr *Op, - const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, - SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { +CXXDynamicCastExpr *CXXDynamicCastExpr::Create( + const ASTContext &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, + const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); - auto *E = - new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, - RParenLoc, AngleBrackets); + auto *E = new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, + L, RParenLoc, AngleBrackets); if (PathSize) llvm::uninitialized_copy(*BasePath, E->getTrailingObjects()); return E; @@ -866,36 +881,31 @@ bool CXXDynamicCastExpr::isAlwaysNull() const { return false; } -CXXReinterpretCastExpr * -CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, CastKind K, Expr *Op, - const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { +CXXReinterpretCastExpr *CXXReinterpretCastExpr::Create( + const ASTContext &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, + const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); - auto *E = - new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, - RParenLoc, AngleBrackets); + auto *E = new (Buffer) CXXReinterpretCastExpr( + T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); if (PathSize) llvm::uninitialized_copy(*BasePath, E->getTrailingObjects()); return E; } -CXXReinterpretCastExpr * -CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { +CXXReinterpretCastExpr *CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, + unsigned PathSize) { void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize); } -CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, Expr *Op, - TypeSourceInfo *WrittenTy, - SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { - return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); +CXXConstCastExpr * +CXXConstCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, + Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { + return new (C) + CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); } CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) { @@ -1004,7 +1014,7 @@ UserDefinedLiteral::getLiteralOperatorKind() const { assert(getNumArgs() == 1 && "unexpected #args in literal operator call"); QualType ParamTy = - cast(getCalleeDecl())->getParamDecl(0)->getType(); + cast(getCalleeDecl())->getParamDecl(0)->getType(); if (ParamTy->isPointerType()) return LOK_Raw; if (ParamTy->isAnyCharacterType()) @@ -1117,7 +1127,7 @@ CXXTemporary *CXXTemporary::Create(const ASTContext &C, CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C, CXXTemporary *Temp, - Expr* SubExpr) { + Expr *SubExpr) { assert((SubExpr->getType()->isRecordType() || SubExpr->getType()->isArrayType()) && "Expression bound to a temporary must have record or array type!"); @@ -1438,8 +1448,7 @@ LambdaExpr::const_child_range LambdaExpr::children() const { getStoredStmts() + capture_size() + 1); } -ExprWithCleanups::ExprWithCleanups(Expr *subexpr, - bool CleanupsHaveSideEffects, +ExprWithCleanups::ExprWithCleanups(Expr *subexpr, bool CleanupsHaveSideEffects, ArrayRef objects) : FullExpr(ExprWithCleanupsClass, subexpr) { ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects; @@ -1912,11 +1921,9 @@ TypeTraitExpr::TypeTraitExpr(EmptyShell Empty, bool IsStoredAsBool) } TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T, - SourceLocation Loc, - TypeTrait Kind, + SourceLocation Loc, TypeTrait Kind, ArrayRef Args, - SourceLocation RParenLoc, - bool Value) { + SourceLocation RParenLoc, bool Value) { void *Mem = C.Allocate(totalSizeToAlloc(0, Args.size())); return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value); @@ -1939,6 +1946,43 @@ TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C, return new (Mem) TypeTraitExpr(EmptyShell(), IsStoredAsBool); } +CXXReflectExpr::CXXReflectExpr(const ASTContext &C, QualType T, QualType Ty) + : Expr(CXXReflectExprClass, T, VK_PRValue, OK_Ordinary) {} + +CXXReflectExpr::CXXReflectExpr(const ASTContext &C, QualType T, Decl *Arg, + bool IsNamespace) + : Expr(CXXReflectExprClass, T, VK_PRValue, OK_Ordinary) {} + +CXXReflectExpr::CXXReflectExpr(EmptyShell Empty) + : Expr(CXXReflectExprClass, Empty) {} + +CXXReflectExpr *CXXReflectExpr::Create(ASTContext &C, + SourceLocation OperatorLoc, + SourceLocation OperandLoc, + QualType Operand) { + CXXReflectExpr *E = new (C) CXXReflectExpr(C, C.DependentTy, Operand); + E->setOperatorLoc(OperatorLoc); + E->setOperandRange(OperandLoc); + return E; +} + +CXXReflectExpr *CXXReflectExpr::Create(ASTContext &C, + SourceLocation OperatorLoc, + SourceLocation OperandLoc, + Decl *Operand) { + bool IsNamespace = isa(Operand); + + CXXReflectExpr *E = + new (C) CXXReflectExpr(C, C.DependentTy, Operand, IsNamespace); + E->setOperatorLoc(OperatorLoc); + E->setOperandRange(OperandLoc); + return E; +} + +CXXReflectExpr *CXXReflectExpr::CreateEmpty(ASTContext &C) { + return new (C) CXXReflectExpr(EmptyShell()); +} + CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation RP, diff --git a/clang/lib/AST/ExprClassification.cpp b/clang/lib/AST/ExprClassification.cpp index aeacd0dc765ef..4c53c316e989a 100644 --- a/clang/lib/AST/ExprClassification.cpp +++ b/clang/lib/AST/ExprClassification.cpp @@ -216,6 +216,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { case Expr::SourceLocExprClass: case Expr::ConceptSpecializationExprClass: case Expr::RequiresExprClass: + case Expr::CXXReflectExprClass: return Cl::CL_PRValue; case Expr::EmbedExprClass: diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index 00aaaab957591..cd5cfc5091e06 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -19072,6 +19072,7 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { case Expr::ArrayTypeTraitExprClass: case Expr::ExpressionTraitExprClass: case Expr::CXXNoexceptExprClass: + case Expr::CXXReflectExprClass: return NoDiag(); case Expr::CallExprClass: case Expr::CXXOperatorCallExprClass: { diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp index 5572e0a7ae59c..67f566297b177 100644 --- a/clang/lib/AST/ItaniumMangle.cpp +++ b/clang/lib/AST/ItaniumMangle.cpp @@ -4946,6 +4946,12 @@ void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, E = cast(E)->getSubExpr(); goto recurse; + case Expr::CXXReflectExprClass: { + // TODO: implement this after introducing std::meta::info + // and add info in APValue + break; + } + // FIXME: invent manglings for all these. case Expr::BlockExprClass: case Expr::ChooseExprClass: diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index ff8ca01ec5477..37c2dd40c93e4 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -64,92 +64,93 @@ using namespace clang; namespace { - class StmtPrinter : public StmtVisitor { - raw_ostream &OS; - unsigned IndentLevel; - PrinterHelper* Helper; - PrintingPolicy Policy; - std::string NL; - const ASTContext *Context; - - public: - StmtPrinter(raw_ostream &os, PrinterHelper *helper, - const PrintingPolicy &Policy, unsigned Indentation = 0, - StringRef NL = "\n", const ASTContext *Context = nullptr) - : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy), - NL(NL), Context(Context) {} - - void PrintStmt(Stmt *S) { PrintStmt(S, Policy.Indentation); } - - void PrintStmt(Stmt *S, int SubIndent) { - IndentLevel += SubIndent; - if (isa_and_nonnull(S)) { - // If this is an expr used in a stmt context, indent and newline it. - Indent(); - Visit(S); - OS << ";" << NL; - } else if (S) { - Visit(S); - } else { - Indent() << "<<>>" << NL; - } - IndentLevel -= SubIndent; +class StmtPrinter : public StmtVisitor { + raw_ostream &OS; + unsigned IndentLevel; + PrinterHelper *Helper; + PrintingPolicy Policy; + std::string NL; + const ASTContext *Context; + +public: + StmtPrinter(raw_ostream &os, PrinterHelper *helper, + const PrintingPolicy &Policy, unsigned Indentation = 0, + StringRef NL = "\n", const ASTContext *Context = nullptr) + : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy), + NL(NL), Context(Context) {} + + void PrintStmt(Stmt *S) { PrintStmt(S, Policy.Indentation); } + + void PrintStmt(Stmt *S, int SubIndent) { + IndentLevel += SubIndent; + if (isa_and_nonnull(S)) { + // If this is an expr used in a stmt context, indent and newline it. + Indent(); + Visit(S); + OS << ";" << NL; + } else if (S) { + Visit(S); + } else { + Indent() << "<<>>" << NL; } + IndentLevel -= SubIndent; + } - void PrintInitStmt(Stmt *S, unsigned PrefixWidth) { - // FIXME: Cope better with odd prefix widths. - IndentLevel += (PrefixWidth + 1) / 2; - if (auto *DS = dyn_cast(S)) - PrintRawDeclStmt(DS); - else - PrintExpr(cast(S)); - OS << "; "; - IndentLevel -= (PrefixWidth + 1) / 2; - } + void PrintInitStmt(Stmt *S, unsigned PrefixWidth) { + // FIXME: Cope better with odd prefix widths. + IndentLevel += (PrefixWidth + 1) / 2; + if (auto *DS = dyn_cast(S)) + PrintRawDeclStmt(DS); + else + PrintExpr(cast(S)); + OS << "; "; + IndentLevel -= (PrefixWidth + 1) / 2; + } - void PrintControlledStmt(Stmt *S) { - if (auto *CS = dyn_cast(S)) { - OS << " "; - PrintRawCompoundStmt(CS); - OS << NL; - } else { - OS << NL; - PrintStmt(S); - } + void PrintControlledStmt(Stmt *S) { + if (auto *CS = dyn_cast(S)) { + OS << " "; + PrintRawCompoundStmt(CS); + OS << NL; + } else { + OS << NL; + PrintStmt(S); } + } - void PrintRawCompoundStmt(CompoundStmt *S); - void PrintRawDecl(Decl *D); - void PrintRawDeclStmt(const DeclStmt *S); - void PrintRawIfStmt(IfStmt *If); - void PrintRawCXXCatchStmt(CXXCatchStmt *Catch); - void PrintCallArgs(CallExpr *E); - void PrintRawSEHExceptHandler(SEHExceptStmt *S); - void PrintRawSEHFinallyStmt(SEHFinallyStmt *S); - void PrintOMPExecutableDirective(OMPExecutableDirective *S, - bool ForceNoStmt = false); - void PrintFPPragmas(CompoundStmt *S); - void PrintOpenACCClauseList(OpenACCConstructStmt *S); - void PrintOpenACCConstruct(OpenACCConstructStmt *S); - - void PrintExpr(Expr *E) { - if (E) - Visit(E); - else - OS << ""; - } + void PrintRawCompoundStmt(CompoundStmt *S); + void PrintRawDecl(Decl *D); + void PrintRawDeclStmt(const DeclStmt *S); + void PrintRawIfStmt(IfStmt *If); + void PrintRawCXXCatchStmt(CXXCatchStmt *Catch); + void PrintCallArgs(CallExpr *E); + void PrintRawSEHExceptHandler(SEHExceptStmt *S); + void PrintRawSEHFinallyStmt(SEHFinallyStmt *S); + void PrintOMPExecutableDirective(OMPExecutableDirective *S, + bool ForceNoStmt = false); + void PrintFPPragmas(CompoundStmt *S); + void PrintOpenACCClauseList(OpenACCConstructStmt *S); + void PrintOpenACCConstruct(OpenACCConstructStmt *S); + + void PrintExpr(Expr *E) { + if (E) + Visit(E); + else + OS << ""; + } - raw_ostream &Indent(int Delta = 0) { - for (int i = 0, e = IndentLevel+Delta; i < e; ++i) - OS << " "; - return OS; - } + raw_ostream &Indent(int Delta = 0) { + for (int i = 0, e = IndentLevel + Delta; i < e; ++i) + OS << " "; + return OS; + } - void Visit(Stmt* S) { - if (Helper && Helper->handledStmt(S,OS)) - return; - else StmtVisitor::Visit(S); - } + void Visit(Stmt *S) { + if (Helper && Helper->handledStmt(S, OS)) + return; + else + StmtVisitor::Visit(S); + } [[maybe_unused]] void VisitStmt(Stmt *Node) { Indent() << "<>" << NL; @@ -159,13 +160,12 @@ namespace { OS << "<>"; } - void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node); + void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node); #define ABSTRACT_STMT(CLASS) -#define STMT(CLASS, PARENT) \ - void Visit##CLASS(CLASS *Node); +#define STMT(CLASS, PARENT) void Visit##CLASS(CLASS *Node); #include "clang/AST/StmtNodes.inc" - }; +}; } // namespace @@ -245,18 +245,14 @@ void StmtPrinter::PrintFPPragmas(CompoundStmt *S) { } } -void StmtPrinter::PrintRawDecl(Decl *D) { - D->print(OS, Policy, IndentLevel); -} +void StmtPrinter::PrintRawDecl(Decl *D) { D->print(OS, Policy, IndentLevel); } void StmtPrinter::PrintRawDeclStmt(const DeclStmt *S) { SmallVector Decls(S->decls()); Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel); } -void StmtPrinter::VisitNullStmt(NullStmt *Node) { - Indent() << ";" << NL; -} +void StmtPrinter::VisitNullStmt(NullStmt *Node) { Indent() << ";" << NL; } void StmtPrinter::VisitDeclStmt(DeclStmt *Node) { Indent(); @@ -340,7 +336,8 @@ void StmtPrinter::PrintRawIfStmt(IfStmt *If) { } else { OS << NL; PrintStmt(If->getThen()); - if (If->getElse()) Indent(); + if (If->getElse()) + Indent(); } if (Stmt *Else = If->getElse()) { @@ -462,14 +459,16 @@ void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) { void StmtPrinter::VisitGotoStmt(GotoStmt *Node) { Indent() << "goto " << Node->getLabel()->getName() << ";"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) { Indent() << "goto *"; PrintExpr(Node->getTarget()); OS << ";"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) { @@ -479,7 +478,8 @@ void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) { << ';'; else OS << "continue;"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitBreakStmt(BreakStmt *Node) { @@ -488,7 +488,8 @@ void StmtPrinter::VisitBreakStmt(BreakStmt *Node) { OS << "break " << Node->getLabelDecl()->getIdentifier()->getName() << ';'; else OS << "break;"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) { @@ -498,7 +499,8 @@ void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) { PrintExpr(Node->getRetValue()); } OS << ";"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) { @@ -577,7 +579,8 @@ void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) { } OS << ");"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) { @@ -625,10 +628,9 @@ void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) { } } -void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) { -} +void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {} -void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) { +void StmtPrinter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *Node) { Indent() << "@catch (...) { /* todo */ } " << NL; } @@ -691,7 +693,7 @@ void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) { PrintRawCompoundStmt(Node->getTryBlock()); SEHExceptStmt *E = Node->getExceptHandler(); SEHFinallyStmt *F = Node->getFinallyHandler(); - if(E) + if (E) PrintRawSEHExceptHandler(E); else { assert(F && "Must have a finally block..."); @@ -728,7 +730,8 @@ void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) { void StmtPrinter::VisitSEHLeaveStmt(SEHLeaveStmt *Node) { Indent() << "__leave;"; - if (Policy.IncludeNewlines) OS << NL; + if (Policy.IncludeNewlines) + OS << NL; } //===----------------------------------------------------------------------===// @@ -1368,7 +1371,7 @@ void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) { } void StmtPrinter::VisitDependentScopeDeclRefExpr( - DependentScopeDeclRefExpr *Node) { + DependentScopeDeclRefExpr *Node) { Node->getQualifier().print(OS, Policy); if (Node->hasTemplateKeyword()) OS << "template "; @@ -1484,19 +1487,41 @@ void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) { // Emit suffixes. Integer literals are always a builtin integer type. switch (Node->getType()->castAs()->getKind()) { - default: llvm_unreachable("Unexpected type for integer literal!"); + default: + llvm_unreachable("Unexpected type for integer literal!"); case BuiltinType::Char_S: - case BuiltinType::Char_U: OS << "i8"; break; - case BuiltinType::UChar: OS << "Ui8"; break; - case BuiltinType::SChar: OS << "i8"; break; - case BuiltinType::Short: OS << "i16"; break; - case BuiltinType::UShort: OS << "Ui16"; break; - case BuiltinType::Int: break; // no suffix. - case BuiltinType::UInt: OS << 'U'; break; - case BuiltinType::Long: OS << 'L'; break; - case BuiltinType::ULong: OS << "UL"; break; - case BuiltinType::LongLong: OS << "LL"; break; - case BuiltinType::ULongLong: OS << "ULL"; break; + case BuiltinType::Char_U: + OS << "i8"; + break; + case BuiltinType::UChar: + OS << "Ui8"; + break; + case BuiltinType::SChar: + OS << "i8"; + break; + case BuiltinType::Short: + OS << "i16"; + break; + case BuiltinType::UShort: + OS << "Ui16"; + break; + case BuiltinType::Int: + break; // no suffix. + case BuiltinType::UInt: + OS << 'U'; + break; + case BuiltinType::Long: + OS << 'L'; + break; + case BuiltinType::ULong: + OS << "UL"; + break; + case BuiltinType::LongLong: + OS << "LL"; + break; + case BuiltinType::ULongLong: + OS << "ULL"; + break; case BuiltinType::Int128: break; // no suffix. case BuiltinType::UInt128: @@ -1513,19 +1538,44 @@ void StmtPrinter::VisitFixedPointLiteral(FixedPointLiteral *Node) { OS << Node->getValueAsString(/*Radix=*/10); switch (Node->getType()->castAs()->getKind()) { - default: llvm_unreachable("Unexpected type for fixed point literal!"); - case BuiltinType::ShortFract: OS << "hr"; break; - case BuiltinType::ShortAccum: OS << "hk"; break; - case BuiltinType::UShortFract: OS << "uhr"; break; - case BuiltinType::UShortAccum: OS << "uhk"; break; - case BuiltinType::Fract: OS << "r"; break; - case BuiltinType::Accum: OS << "k"; break; - case BuiltinType::UFract: OS << "ur"; break; - case BuiltinType::UAccum: OS << "uk"; break; - case BuiltinType::LongFract: OS << "lr"; break; - case BuiltinType::LongAccum: OS << "lk"; break; - case BuiltinType::ULongFract: OS << "ulr"; break; - case BuiltinType::ULongAccum: OS << "ulk"; break; + default: + llvm_unreachable("Unexpected type for fixed point literal!"); + case BuiltinType::ShortFract: + OS << "hr"; + break; + case BuiltinType::ShortAccum: + OS << "hk"; + break; + case BuiltinType::UShortFract: + OS << "uhr"; + break; + case BuiltinType::UShortAccum: + OS << "uhk"; + break; + case BuiltinType::Fract: + OS << "r"; + break; + case BuiltinType::Accum: + OS << "k"; + break; + case BuiltinType::UFract: + OS << "ur"; + break; + case BuiltinType::UAccum: + OS << "uk"; + break; + case BuiltinType::LongFract: + OS << "lr"; + break; + case BuiltinType::LongAccum: + OS << "lk"; + break; + case BuiltinType::ULongFract: + OS << "ulr"; + break; + case BuiltinType::ULongAccum: + OS << "ulk"; + break; } } @@ -1542,14 +1592,26 @@ static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node, // Emit suffixes. Float literals are always a builtin float type. switch (Node->getType()->castAs()->getKind()) { - default: llvm_unreachable("Unexpected type for float literal!"); - case BuiltinType::Half: break; // FIXME: suffix? - case BuiltinType::Ibm128: break; // FIXME: No suffix for ibm128 literal - case BuiltinType::Double: break; // no suffix. - case BuiltinType::Float16: OS << "F16"; break; - case BuiltinType::Float: OS << 'F'; break; - case BuiltinType::LongDouble: OS << 'L'; break; - case BuiltinType::Float128: OS << 'Q'; break; + default: + llvm_unreachable("Unexpected type for float literal!"); + case BuiltinType::Half: + break; // FIXME: suffix? + case BuiltinType::Ibm128: + break; // FIXME: No suffix for ibm128 literal + case BuiltinType::Double: + break; // no suffix. + case BuiltinType::Float16: + OS << "F16"; + break; + case BuiltinType::Float: + OS << 'F'; + break; + case BuiltinType::LongDouble: + OS << 'L'; + break; + case BuiltinType::Float128: + OS << 'Q'; + break; } } @@ -1581,7 +1643,8 @@ void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) { // Print a space if this is an "identifier operator" like __real, or if // it might be concatenated incorrectly like '+'. switch (Node->getOpcode()) { - default: break; + default: + break; case UO_Real: case UO_Imag: case UO_Extension: @@ -1751,7 +1814,8 @@ void StmtPrinter::PrintCallArgs(CallExpr *Call) { break; } - if (i) OS << ", "; + if (i) + OS << ", "; PrintExpr(Call->getArg(i)); } } @@ -1854,8 +1918,8 @@ void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) { // GNU extensions. -void -StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) { +void StmtPrinter::VisitBinaryConditionalOperator( + BinaryConditionalOperator *Node) { PrintExpr(Node->getCommon()); OS << " ?: "; PrintExpr(Node->getFalseExpr()); @@ -1881,14 +1945,13 @@ void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) { OS << ")"; } -void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) { - OS << "__null"; -} +void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) { OS << "__null"; } void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) { OS << "__builtin_shufflevector("; for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) { - if (i) OS << ", "; + if (i) + OS << ", "; PrintExpr(Node->getExpr(i)); } OS << ")"; @@ -1902,7 +1965,7 @@ void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) { OS << ")"; } -void StmtPrinter::VisitInitListExpr(InitListExpr* Node) { +void StmtPrinter::VisitInitListExpr(InitListExpr *Node) { if (Node->getSyntacticForm()) { Visit(Node->getSyntacticForm()); return; @@ -1910,7 +1973,8 @@ void StmtPrinter::VisitInitListExpr(InitListExpr* Node) { OS << "{"; for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) { - if (i) OS << ", "; + if (i) + OS << ", "; if (Node->getInit(i)) PrintExpr(Node->getInit(i)); else @@ -1931,10 +1995,11 @@ void StmtPrinter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *Node) { OS << "*"; } -void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) { +void StmtPrinter::VisitParenListExpr(ParenListExpr *Node) { OS << "("; for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) { - if (i) OS << ", "; + if (i) + OS << ", "; PrintExpr(Node->getExpr(i)); } OS << ")"; @@ -1984,9 +2049,7 @@ void StmtPrinter::VisitDesignatedInitUpdateExpr( OS << "}"; } -void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) { - OS << "/*no init*/"; -} +void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) { OS << "/*no init*/"; } void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) { if (Node->getType()->getAsCXXRecordDecl()) { @@ -2019,9 +2082,9 @@ void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) { void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) { const char *Name = nullptr; switch (Node->getOp()) { -#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ - case AtomicExpr::AO ## ID: \ - Name = #ID "("; \ +#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ + case AtomicExpr::AO##ID: \ + Name = #ID "("; \ break; #include "clang/Basic/Builtins.inc" } @@ -2033,8 +2096,7 @@ void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) { OS << ", "; PrintExpr(Node->getVal1()); } - if (Node->getOp() == AtomicExpr::AO__atomic_exchange || - Node->isCmpXChg()) { + if (Node->getOp() == AtomicExpr::AO__atomic_exchange || Node->isCmpXChg()) { OS << ", "; PrintExpr(Node->getVal2()); } @@ -2113,9 +2175,9 @@ void StmtPrinter::VisitCXXRewrittenBinaryOperator( CXXRewrittenBinaryOperator *Node) { CXXRewrittenBinaryOperator::DecomposedForm Decomposed = Node->getDecomposedForm(); - PrintExpr(const_cast(Decomposed.LHS)); + PrintExpr(const_cast(Decomposed.LHS)); OS << ' ' << BinaryOperator::getOpcodeStr(Decomposed.Opcode) << ' '; - PrintExpr(const_cast(Decomposed.RHS)); + PrintExpr(const_cast(Decomposed.RHS)); } void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) { @@ -2199,7 +2261,7 @@ void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) { case UserDefinedLiteral::LOK_Template: { const auto *DRE = cast(Node->getCallee()->IgnoreImpCasts()); const TemplateArgumentList *Args = - cast(DRE->getDecl())->getTemplateSpecializationArgs(); + cast(DRE->getDecl())->getTemplateSpecializationArgs(); assert(Args); if (Args->size() != 1 || Args->get(0).getKind() != TemplateArgument::Pack) { @@ -2223,7 +2285,7 @@ void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) { case UserDefinedLiteral::LOK_Integer: { // Print integer literal without suffix. const auto *Int = cast(Node->getCookedLiteral()); - OS << toString(Int->getValue(), 10, /*isSigned*/false); + OS << toString(Int->getValue(), 10, /*isSigned*/ false); break; } case UserDefinedLiteral::LOK_Floating: { @@ -2248,9 +2310,7 @@ void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) { OS << "nullptr"; } -void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) { - OS << "this"; -} +void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) { OS << "this"; } void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) { if (!Node->getSubExpr()) @@ -2302,7 +2362,7 @@ void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) { else OS << "("; for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(), - ArgEnd = Node->arg_end(); + ArgEnd = Node->arg_end(); Arg != ArgEnd; ++Arg) { if ((*Arg)->isDefaultArgument()) break; @@ -2336,9 +2396,8 @@ void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) { break; } for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(), - CEnd = Node->explicit_capture_end(); - C != CEnd; - ++C) { + CEnd = Node->explicit_capture_end(); + C != CEnd; ++C) { if (C->capturesVLAType()) continue; @@ -2396,7 +2455,7 @@ void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) { if (!Node->getExplicitTemplateParameters().empty()) { Node->getTemplateParameterList()->print( OS, Node->getLambdaClass()->getASTContext(), - /*OmitTemplateKW*/true); + /*OmitTemplateKW*/ true); } if (Node->hasExplicitParameters()) { @@ -2529,7 +2588,8 @@ void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) { break; } - if (i) OS << ", "; + if (i) + OS << ", "; PrintExpr(E->getArg(i)); } @@ -2566,8 +2626,13 @@ void StmtPrinter::VisitCXXUnresolvedConstructExpr( OS << ')'; } +void StmtPrinter::VisitCXXReflectExpr(CXXReflectExpr *S) { + // TODO: Make this better. + OS << "^(...)"; +} + void StmtPrinter::VisitCXXDependentScopeMemberExpr( - CXXDependentScopeMemberExpr *Node) { + CXXDependentScopeMemberExpr *Node) { if (!Node->isImplicitAccess()) { PrintExpr(Node->getBase()); OS << (Node->isArrow() ? "->" : "."); @@ -2638,12 +2703,12 @@ void StmtPrinter::VisitPackIndexingExpr(PackIndexingExpr *E) { } void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr( - SubstNonTypeTemplateParmPackExpr *Node) { + SubstNonTypeTemplateParmPackExpr *Node) { OS << *Node->getParameterPack(); } void StmtPrinter::VisitSubstNonTypeTemplateParmExpr( - SubstNonTypeTemplateParmExpr *Node) { + SubstNonTypeTemplateParmExpr *Node) { Visit(Node->getReplacement()); } @@ -2651,7 +2716,8 @@ void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) { OS << *E->getParameterPack(); } -void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){ +void StmtPrinter::VisitMaterializeTemporaryExpr( + MaterializeTemporaryExpr *Node) { PrintExpr(Node->getSubExpr()); } @@ -2848,13 +2914,14 @@ void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) { } else { for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) { if (i < selector.getNumArgs()) { - if (i > 0) OS << ' '; + if (i > 0) + OS << ' '; if (selector.getIdentifierInfoForSlot(i)) OS << selector.getIdentifierInfoForSlot(i)->getName() << ':'; else - OS << ":"; - } - else OS << ", "; // Handle variadic methods. + OS << ":"; + } else + OS << ", "; // Handle variadic methods. PrintExpr(Mess->getArg(i)); } @@ -2866,13 +2933,12 @@ void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) { OS << (Node->getValue() ? "__objc_yes" : "__objc_no"); } -void -StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) { +void StmtPrinter::VisitObjCIndirectCopyRestoreExpr( + ObjCIndirectCopyRestoreExpr *E) { PrintExpr(E->getSubExpr()); } -void -StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) { +void StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) { OS << '(' << E->getBridgeKindName(); E->getType().print(OS, Policy); OS << ')'; @@ -2889,16 +2955,18 @@ void StmtPrinter::VisitBlockExpr(BlockExpr *Node) { OS << "()"; } else if (!BD->param_empty() || cast(AFT)->isVariadic()) { OS << '('; - for (BlockDecl::param_iterator AI = BD->param_begin(), - E = BD->param_end(); AI != E; ++AI) { - if (AI != BD->param_begin()) OS << ", "; + for (BlockDecl::param_iterator AI = BD->param_begin(), E = BD->param_end(); + AI != E; ++AI) { + if (AI != BD->param_begin()) + OS << ", "; std::string ParamStr = (*AI)->getNameAsString(); (*AI)->getType().print(OS, Policy, ParamStr); } const auto *FT = cast(AFT); if (FT->isVariadic()) { - if (!BD->param_empty()) OS << ", "; + if (!BD->param_empty()) + OS << ", "; OS << "..."; } OS << ')'; diff --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp index 05b64ccda0d01..bc6af1fe72cb9 100644 --- a/clang/lib/AST/StmtProfile.cpp +++ b/clang/lib/AST/StmtProfile.cpp @@ -25,214 +25,210 @@ using namespace clang; namespace { - class StmtProfiler : public ConstStmtVisitor { - protected: - llvm::FoldingSetNodeID &ID; - bool Canonical; - bool ProfileLambdaExpr; +class StmtProfiler : public ConstStmtVisitor { +protected: + llvm::FoldingSetNodeID &ID; + bool Canonical; + bool ProfileLambdaExpr; - public: - StmtProfiler(llvm::FoldingSetNodeID &ID, bool Canonical, - bool ProfileLambdaExpr) - : ID(ID), Canonical(Canonical), ProfileLambdaExpr(ProfileLambdaExpr) {} +public: + StmtProfiler(llvm::FoldingSetNodeID &ID, bool Canonical, + bool ProfileLambdaExpr) + : ID(ID), Canonical(Canonical), ProfileLambdaExpr(ProfileLambdaExpr) {} - virtual ~StmtProfiler() {} + virtual ~StmtProfiler() {} - void VisitStmt(const Stmt *S); + void VisitStmt(const Stmt *S); - void VisitStmtNoChildren(const Stmt *S) { - HandleStmtClass(S->getStmtClass()); - } + void VisitStmtNoChildren(const Stmt *S) { + HandleStmtClass(S->getStmtClass()); + } - virtual void HandleStmtClass(Stmt::StmtClass SC) = 0; + virtual void HandleStmtClass(Stmt::StmtClass SC) = 0; #define STMT(Node, Base) void Visit##Node(const Node *S); #include "clang/AST/StmtNodes.inc" - /// Visit a declaration that is referenced within an expression - /// or statement. - virtual void VisitDecl(const Decl *D) = 0; + /// Visit a declaration that is referenced within an expression + /// or statement. + virtual void VisitDecl(const Decl *D) = 0; - /// Visit a type that is referenced within an expression or - /// statement. - virtual void VisitType(QualType T) = 0; + /// Visit a type that is referenced within an expression or + /// statement. + virtual void VisitType(QualType T) = 0; - /// Visit a name that occurs within an expression or statement. - virtual void VisitName(DeclarationName Name, bool TreatAsDecl = false) = 0; + /// Visit a name that occurs within an expression or statement. + virtual void VisitName(DeclarationName Name, bool TreatAsDecl = false) = 0; - /// Visit identifiers that are not in Decl's or Type's. - virtual void VisitIdentifierInfo(const IdentifierInfo *II) = 0; + /// Visit identifiers that are not in Decl's or Type's. + virtual void VisitIdentifierInfo(const IdentifierInfo *II) = 0; - /// Visit a nested-name-specifier that occurs within an expression - /// or statement. - virtual void VisitNestedNameSpecifier(NestedNameSpecifier NNS) = 0; + /// Visit a nested-name-specifier that occurs within an expression + /// or statement. + virtual void VisitNestedNameSpecifier(NestedNameSpecifier NNS) = 0; - /// Visit a template name that occurs within an expression or - /// statement. - virtual void VisitTemplateName(TemplateName Name) = 0; + /// Visit a template name that occurs within an expression or + /// statement. + virtual void VisitTemplateName(TemplateName Name) = 0; - /// Visit template arguments that occur within an expression or - /// statement. - void VisitTemplateArguments(const TemplateArgumentLoc *Args, - unsigned NumArgs); + /// Visit template arguments that occur within an expression or + /// statement. + void VisitTemplateArguments(const TemplateArgumentLoc *Args, + unsigned NumArgs); - /// Visit a single template argument. - void VisitTemplateArgument(const TemplateArgument &Arg); - }; + /// Visit a single template argument. + void VisitTemplateArgument(const TemplateArgument &Arg); +}; - class StmtProfilerWithPointers : public StmtProfiler { - const ASTContext &Context; +class StmtProfilerWithPointers : public StmtProfiler { + const ASTContext &Context; - public: - StmtProfilerWithPointers(llvm::FoldingSetNodeID &ID, - const ASTContext &Context, bool Canonical, - bool ProfileLambdaExpr) - : StmtProfiler(ID, Canonical, ProfileLambdaExpr), Context(Context) {} +public: + StmtProfilerWithPointers(llvm::FoldingSetNodeID &ID, + const ASTContext &Context, bool Canonical, + bool ProfileLambdaExpr) + : StmtProfiler(ID, Canonical, ProfileLambdaExpr), Context(Context) {} + +private: + void HandleStmtClass(Stmt::StmtClass SC) override { ID.AddInteger(SC); } + + void VisitDecl(const Decl *D) override { + ID.AddInteger(D ? D->getKind() : 0); + + if (Canonical && D) { + if (const NonTypeTemplateParmDecl *NTTP = + dyn_cast(D)) { + ID.AddInteger(NTTP->getDepth()); + ID.AddInteger(NTTP->getIndex()); + ID.AddBoolean(NTTP->isParameterPack()); + // C++20 [temp.over.link]p6: + // Two template-parameters are equivalent under the following + // conditions: [...] if they declare non-type template parameters, + // they have equivalent types ignoring the use of type-constraints + // for placeholder types + // + // TODO: Why do we need to include the type in the profile? It's not + // part of the mangling. + VisitType(Context.getUnconstrainedType(NTTP->getType())); + return; + } - private: - void HandleStmtClass(Stmt::StmtClass SC) override { - ID.AddInteger(SC); - } + if (const ParmVarDecl *Parm = dyn_cast(D)) { + // The Itanium C++ ABI uses the type, scope depth, and scope + // index of a parameter when mangling expressions that involve + // function parameters, so we will use the parameter's type for + // establishing function parameter identity. That way, our + // definition of "equivalent" (per C++ [temp.over.link]) is at + // least as strong as the definition of "equivalent" used for + // name mangling. + // + // TODO: The Itanium C++ ABI only uses the top-level cv-qualifiers, + // not the entirety of the type. + VisitType(Parm->getType()); + ID.AddInteger(Parm->getFunctionScopeDepth()); + ID.AddInteger(Parm->getFunctionScopeIndex()); + return; + } - void VisitDecl(const Decl *D) override { - ID.AddInteger(D ? D->getKind() : 0); - - if (Canonical && D) { - if (const NonTypeTemplateParmDecl *NTTP = - dyn_cast(D)) { - ID.AddInteger(NTTP->getDepth()); - ID.AddInteger(NTTP->getIndex()); - ID.AddBoolean(NTTP->isParameterPack()); - // C++20 [temp.over.link]p6: - // Two template-parameters are equivalent under the following - // conditions: [...] if they declare non-type template parameters, - // they have equivalent types ignoring the use of type-constraints - // for placeholder types - // - // TODO: Why do we need to include the type in the profile? It's not - // part of the mangling. - VisitType(Context.getUnconstrainedType(NTTP->getType())); - return; - } - - if (const ParmVarDecl *Parm = dyn_cast(D)) { - // The Itanium C++ ABI uses the type, scope depth, and scope - // index of a parameter when mangling expressions that involve - // function parameters, so we will use the parameter's type for - // establishing function parameter identity. That way, our - // definition of "equivalent" (per C++ [temp.over.link]) is at - // least as strong as the definition of "equivalent" used for - // name mangling. - // - // TODO: The Itanium C++ ABI only uses the top-level cv-qualifiers, - // not the entirety of the type. - VisitType(Parm->getType()); - ID.AddInteger(Parm->getFunctionScopeDepth()); - ID.AddInteger(Parm->getFunctionScopeIndex()); - return; - } - - if (const TemplateTypeParmDecl *TTP = - dyn_cast(D)) { - ID.AddInteger(TTP->getDepth()); - ID.AddInteger(TTP->getIndex()); - ID.AddBoolean(TTP->isParameterPack()); - return; - } - - if (const TemplateTemplateParmDecl *TTP = - dyn_cast(D)) { - ID.AddInteger(TTP->getDepth()); - ID.AddInteger(TTP->getIndex()); - ID.AddBoolean(TTP->isParameterPack()); - return; - } + if (const TemplateTypeParmDecl *TTP = dyn_cast(D)) { + ID.AddInteger(TTP->getDepth()); + ID.AddInteger(TTP->getIndex()); + ID.AddBoolean(TTP->isParameterPack()); + return; } - ID.AddPointer(D ? D->getCanonicalDecl() : nullptr); + if (const TemplateTemplateParmDecl *TTP = + dyn_cast(D)) { + ID.AddInteger(TTP->getDepth()); + ID.AddInteger(TTP->getIndex()); + ID.AddBoolean(TTP->isParameterPack()); + return; + } } - void VisitType(QualType T) override { - if (Canonical && !T.isNull()) - T = Context.getCanonicalType(T); + ID.AddPointer(D ? D->getCanonicalDecl() : nullptr); + } - ID.AddPointer(T.getAsOpaquePtr()); - } + void VisitType(QualType T) override { + if (Canonical && !T.isNull()) + T = Context.getCanonicalType(T); - void VisitName(DeclarationName Name, bool /*TreatAsDecl*/) override { - ID.AddPointer(Name.getAsOpaquePtr()); - } + ID.AddPointer(T.getAsOpaquePtr()); + } - void VisitIdentifierInfo(const IdentifierInfo *II) override { - ID.AddPointer(II); - } + void VisitName(DeclarationName Name, bool /*TreatAsDecl*/) override { + ID.AddPointer(Name.getAsOpaquePtr()); + } - void VisitNestedNameSpecifier(NestedNameSpecifier NNS) override { - if (Canonical) - NNS = NNS.getCanonical(); - NNS.Profile(ID); - } + void VisitIdentifierInfo(const IdentifierInfo *II) override { + ID.AddPointer(II); + } - void VisitTemplateName(TemplateName Name) override { - if (Canonical) - Name = Context.getCanonicalTemplateName(Name); + void VisitNestedNameSpecifier(NestedNameSpecifier NNS) override { + if (Canonical) + NNS = NNS.getCanonical(); + NNS.Profile(ID); + } - Name.Profile(ID); - } - }; - - class StmtProfilerWithoutPointers : public StmtProfiler { - ODRHash &Hash; - public: - StmtProfilerWithoutPointers(llvm::FoldingSetNodeID &ID, ODRHash &Hash) - : StmtProfiler(ID, /*Canonical=*/false, /*ProfileLambdaExpr=*/false), - Hash(Hash) {} - - private: - void HandleStmtClass(Stmt::StmtClass SC) override { - if (SC == Stmt::UnresolvedLookupExprClass) { - // Pretend that the name looked up is a Decl due to how templates - // handle some Decl lookups. - ID.AddInteger(Stmt::DeclRefExprClass); - } else { - ID.AddInteger(SC); - } - } + void VisitTemplateName(TemplateName Name) override { + if (Canonical) + Name = Context.getCanonicalTemplateName(Name); - void VisitType(QualType T) override { - Hash.AddQualType(T); - } + Name.Profile(ID); + } +}; - void VisitName(DeclarationName Name, bool TreatAsDecl) override { - if (TreatAsDecl) { - // A Decl can be null, so each Decl is preceded by a boolean to - // store its nullness. Add a boolean here to match. - ID.AddBoolean(true); - } - Hash.AddDeclarationName(Name, TreatAsDecl); - } - void VisitIdentifierInfo(const IdentifierInfo *II) override { - ID.AddBoolean(II); - if (II) { - Hash.AddIdentifierInfo(II); - } +class StmtProfilerWithoutPointers : public StmtProfiler { + ODRHash &Hash; + +public: + StmtProfilerWithoutPointers(llvm::FoldingSetNodeID &ID, ODRHash &Hash) + : StmtProfiler(ID, /*Canonical=*/false, /*ProfileLambdaExpr=*/false), + Hash(Hash) {} + +private: + void HandleStmtClass(Stmt::StmtClass SC) override { + if (SC == Stmt::UnresolvedLookupExprClass) { + // Pretend that the name looked up is a Decl due to how templates + // handle some Decl lookups. + ID.AddInteger(Stmt::DeclRefExprClass); + } else { + ID.AddInteger(SC); } - void VisitDecl(const Decl *D) override { - ID.AddBoolean(D); - if (D) { - Hash.AddDecl(D); - } + } + + void VisitType(QualType T) override { Hash.AddQualType(T); } + + void VisitName(DeclarationName Name, bool TreatAsDecl) override { + if (TreatAsDecl) { + // A Decl can be null, so each Decl is preceded by a boolean to + // store its nullness. Add a boolean here to match. + ID.AddBoolean(true); } - void VisitTemplateName(TemplateName Name) override { - Hash.AddTemplateName(Name); + Hash.AddDeclarationName(Name, TreatAsDecl); + } + void VisitIdentifierInfo(const IdentifierInfo *II) override { + ID.AddBoolean(II); + if (II) { + Hash.AddIdentifierInfo(II); } - void VisitNestedNameSpecifier(NestedNameSpecifier NNS) override { - ID.AddBoolean(bool(NNS)); - if (NNS) - Hash.AddNestedNameSpecifier(NNS); + } + void VisitDecl(const Decl *D) override { + ID.AddBoolean(D); + if (D) { + Hash.AddDecl(D); } - }; -} + } + void VisitTemplateName(TemplateName Name) override { + Hash.AddTemplateName(Name); + } + void VisitNestedNameSpecifier(NestedNameSpecifier NNS) override { + ID.AddBoolean(bool(NNS)); + if (NNS) + Hash.AddNestedNameSpecifier(NNS); + } +}; +} // namespace void StmtProfiler::VisitStmt(const Stmt *S) { assert(S && "Requires non-null Stmt pointer"); @@ -253,21 +249,13 @@ void StmtProfiler::VisitDeclStmt(const DeclStmt *S) { VisitDecl(D); } -void StmtProfiler::VisitNullStmt(const NullStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitNullStmt(const NullStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitCompoundStmt(const CompoundStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitCompoundStmt(const CompoundStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitCaseStmt(const CaseStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitCaseStmt(const CaseStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitDefaultStmt(const DefaultStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitDefaultStmt(const DefaultStmt *S) { VisitStmt(S); } void StmtProfiler::VisitLabelStmt(const LabelStmt *S) { VisitStmt(S); @@ -294,13 +282,9 @@ void StmtProfiler::VisitWhileStmt(const WhileStmt *S) { VisitDecl(S->getConditionVariable()); } -void StmtProfiler::VisitDoStmt(const DoStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitDoStmt(const DoStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitForStmt(const ForStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitForStmt(const ForStmt *S) { VisitStmt(S); } void StmtProfiler::VisitGotoStmt(const GotoStmt *S) { VisitStmt(S); @@ -311,17 +295,11 @@ void StmtProfiler::VisitIndirectGotoStmt(const IndirectGotoStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitContinueStmt(const ContinueStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitContinueStmt(const ContinueStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitBreakStmt(const BreakStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitBreakStmt(const BreakStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitReturnStmt(const ReturnStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitReturnStmt(const ReturnStmt *S) { VisitStmt(S); } void StmtProfiler::VisitGCCAsmStmt(const GCCAsmStmt *S) { VisitStmt(S); @@ -356,9 +334,7 @@ void StmtProfiler::VisitCXXCatchStmt(const CXXCatchStmt *S) { VisitType(S->getCaughtType()); } -void StmtProfiler::VisitCXXTryStmt(const CXXTryStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitCXXTryStmt(const CXXTryStmt *S) { VisitStmt(S); } void StmtProfiler::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { VisitStmt(S); @@ -371,25 +347,17 @@ void StmtProfiler::VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) { VisitName(S->getNameInfo().getName()); } -void StmtProfiler::VisitSEHTryStmt(const SEHTryStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitSEHTryStmt(const SEHTryStmt *S) { VisitStmt(S); } void StmtProfiler::VisitSEHFinallyStmt(const SEHFinallyStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitSEHExceptStmt(const SEHExceptStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitSEHExceptStmt(const SEHExceptStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitSEHLeaveStmt(const SEHLeaveStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitSEHLeaveStmt(const SEHLeaveStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitCapturedStmt(const CapturedStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitCapturedStmt(const CapturedStmt *S) { VisitStmt(S); } void StmtProfiler::VisitSYCLKernelCallStmt(const SYCLKernelCallStmt *S) { VisitStmt(S); @@ -410,12 +378,10 @@ void StmtProfiler::VisitObjCAtFinallyStmt(const ObjCAtFinallyStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitObjCAtTryStmt(const ObjCAtTryStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitObjCAtTryStmt(const ObjCAtTryStmt *S) { VisitStmt(S); } -void -StmtProfiler::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S) { +void StmtProfiler::VisitObjCAtSynchronizedStmt( + const ObjCAtSynchronizedStmt *S) { VisitStmt(S); } @@ -423,8 +389,8 @@ void StmtProfiler::VisitObjCAtThrowStmt(const ObjCAtThrowStmt *S) { VisitStmt(S); } -void -StmtProfiler::VisitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt *S) { +void StmtProfiler::VisitObjCAutoreleasePoolStmt( + const ObjCAutoreleasePoolStmt *S) { VisitStmt(S); } @@ -432,11 +398,10 @@ namespace { class OMPClauseProfiler : public ConstOMPClauseVisitor { StmtProfiler *Profiler; /// Process clauses with list of variables. - template - void VisitOMPClauseList(T *Node); + template void VisitOMPClauseList(T *Node); public: - OMPClauseProfiler(StmtProfiler *P) : Profiler(P) { } + OMPClauseProfiler(StmtProfiler *P) : Profiler(P) {} #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C); #include "llvm/Frontend/OpenMP/OMP.inc" @@ -544,9 +509,9 @@ void OMPClauseProfiler::VisitOMPNocontextClause(const OMPNocontextClause *C) { Profiler->VisitStmt(C->getCondition()); } -void OMPClauseProfiler::VisitOMPDefaultClause(const OMPDefaultClause *C) { } +void OMPClauseProfiler::VisitOMPDefaultClause(const OMPDefaultClause *C) {} -void OMPClauseProfiler::VisitOMPProcBindClause(const OMPProcBindClause *C) { } +void OMPClauseProfiler::VisitOMPProcBindClause(const OMPProcBindClause *C) {} void OMPClauseProfiler::VisitOMPUnifiedAddressClause( const OMPUnifiedAddressClause *C) {} @@ -661,8 +626,7 @@ void OMPClauseProfiler::VisitOMPFilterClause(const OMPFilterClause *C) { Profiler->VisitStmt(C->getThreadID()); } -template -void OMPClauseProfiler::VisitOMPClauseList(T *Node) { +template void OMPClauseProfiler::VisitOMPClauseList(T *Node) { for (auto *E : Node->varlist()) { if (E) Profiler->VisitStmt(E); @@ -676,8 +640,8 @@ void OMPClauseProfiler::VisitOMPPrivateClause(const OMPPrivateClause *C) { Profiler->VisitStmt(E); } } -void -OMPClauseProfiler::VisitOMPFirstprivateClause(const OMPFirstprivateClause *C) { +void OMPClauseProfiler::VisitOMPFirstprivateClause( + const OMPFirstprivateClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPreInit(C); for (auto *E : C->private_copies()) { @@ -689,8 +653,8 @@ OMPClauseProfiler::VisitOMPFirstprivateClause(const OMPFirstprivateClause *C) { Profiler->VisitStmt(E); } } -void -OMPClauseProfiler::VisitOMPLastprivateClause(const OMPLastprivateClause *C) { +void OMPClauseProfiler::VisitOMPLastprivateClause( + const OMPLastprivateClause *C) { VisitOMPClauseList(C); VisitOMPClauseWithPostUpdate(C); for (auto *E : C->source_exprs()) { @@ -709,8 +673,7 @@ OMPClauseProfiler::VisitOMPLastprivateClause(const OMPLastprivateClause *C) { void OMPClauseProfiler::VisitOMPSharedClause(const OMPSharedClause *C) { VisitOMPClauseList(C); } -void OMPClauseProfiler::VisitOMPReductionClause( - const OMPReductionClause *C) { +void OMPClauseProfiler::VisitOMPReductionClause(const OMPReductionClause *C) { Profiler->VisitNestedNameSpecifier( C->getQualifierLoc().getNestedNameSpecifier()); Profiler->VisitName(C->getNameInfo().getName()); @@ -843,8 +806,8 @@ void OMPClauseProfiler::VisitOMPCopyinClause(const OMPCopyinClause *C) { Profiler->VisitStmt(E); } } -void -OMPClauseProfiler::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) { +void OMPClauseProfiler::VisitOMPCopyprivateClause( + const OMPCopyprivateClause *C) { VisitOMPClauseList(C); for (auto *E : C->source_exprs()) { if (E) @@ -974,8 +937,8 @@ void OMPClauseProfiler::VisitOMPXAttributeClause(const OMPXAttributeClause *C) { void OMPClauseProfiler::VisitOMPXBareClause(const OMPXBareClause *C) {} } // namespace -void -StmtProfiler::VisitOMPExecutableDirective(const OMPExecutableDirective *S) { +void StmtProfiler::VisitOMPExecutableDirective( + const OMPExecutableDirective *S) { VisitStmt(S); OMPClauseProfiler P(this); ArrayRef Clauses = S->clauses(); @@ -1077,8 +1040,8 @@ void StmtProfiler::VisitOMPCriticalDirective(const OMPCriticalDirective *S) { VisitName(S->getDirectiveName().getName()); } -void -StmtProfiler::VisitOMPParallelForDirective(const OMPParallelForDirective *S) { +void StmtProfiler::VisitOMPParallelForDirective( + const OMPParallelForDirective *S) { VisitOMPLoopDirective(S); } @@ -1155,7 +1118,8 @@ void StmtProfiler::VisitOMPTargetDirective(const OMPTargetDirective *S) { VisitOMPExecutableDirective(S); } -void StmtProfiler::VisitOMPTargetDataDirective(const OMPTargetDataDirective *S) { +void StmtProfiler::VisitOMPTargetDataDirective( + const OMPTargetDataDirective *S) { VisitOMPExecutableDirective(S); } @@ -1367,9 +1331,7 @@ void StmtProfiler::VisitOMPTargetParallelGenericLoopDirective( VisitOMPLoopDirective(S); } -void StmtProfiler::VisitExpr(const Expr *S) { - VisitStmt(S); -} +void StmtProfiler::VisitExpr(const Expr *S) { VisitStmt(S); } void StmtProfiler::VisitConstantExpr(const ConstantExpr *S) { // Profile exactly as the sub-expression. @@ -1447,13 +1409,9 @@ void StmtProfiler::VisitStringLiteral(const StringLiteral *S) { ID.AddInteger(llvm::to_underlying(S->getKind())); } -void StmtProfiler::VisitParenExpr(const ParenExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitParenExpr(const ParenExpr *S) { VisitExpr(S); } -void StmtProfiler::VisitParenListExpr(const ParenListExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitParenListExpr(const ParenListExpr *S) { VisitExpr(S); } void StmtProfiler::VisitUnaryOperator(const UnaryOperator *S) { VisitExpr(S); @@ -1488,8 +1446,8 @@ void StmtProfiler::VisitOffsetOfExpr(const OffsetOfExpr *S) { VisitExpr(S); } -void -StmtProfiler::VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *S) { +void StmtProfiler::VisitUnaryExprOrTypeTraitExpr( + const UnaryExprOrTypeTraitExpr *S) { VisitExpr(S); ID.AddInteger(S->getKind()); if (S->isArgumentType()) @@ -1518,9 +1476,7 @@ void StmtProfiler::VisitOMPIteratorExpr(const OMPIteratorExpr *S) { VisitDecl(S->getIteratorDecl(I)); } -void StmtProfiler::VisitCallExpr(const CallExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitCallExpr(const CallExpr *S) { VisitExpr(S); } void StmtProfiler::VisitMemberExpr(const MemberExpr *S) { VisitExpr(S); @@ -1535,9 +1491,7 @@ void StmtProfiler::VisitCompoundLiteralExpr(const CompoundLiteralExpr *S) { ID.AddBoolean(S->isFileScope()); } -void StmtProfiler::VisitCastExpr(const CastExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitCastExpr(const CastExpr *S) { VisitExpr(S); } void StmtProfiler::VisitImplicitCastExpr(const ImplicitCastExpr *S) { VisitCastExpr(S); @@ -1558,8 +1512,8 @@ void StmtProfiler::VisitBinaryOperator(const BinaryOperator *S) { ID.AddInteger(S->getOpcode()); } -void -StmtProfiler::VisitCompoundAssignOperator(const CompoundAssignOperator *S) { +void StmtProfiler::VisitCompoundAssignOperator( + const CompoundAssignOperator *S) { VisitBinaryOperator(S); } @@ -1577,9 +1531,7 @@ void StmtProfiler::VisitAddrLabelExpr(const AddrLabelExpr *S) { VisitDecl(S->getLabel()); } -void StmtProfiler::VisitStmtExpr(const StmtExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitStmtExpr(const StmtExpr *S) { VisitExpr(S); } void StmtProfiler::VisitShuffleVectorExpr(const ShuffleVectorExpr *S) { VisitExpr(S); @@ -1589,17 +1541,11 @@ void StmtProfiler::VisitConvertVectorExpr(const ConvertVectorExpr *S) { VisitExpr(S); } -void StmtProfiler::VisitChooseExpr(const ChooseExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitChooseExpr(const ChooseExpr *S) { VisitExpr(S); } -void StmtProfiler::VisitGNUNullExpr(const GNUNullExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitGNUNullExpr(const GNUNullExpr *S) { VisitExpr(S); } -void StmtProfiler::VisitVAArgExpr(const VAArgExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitVAArgExpr(const VAArgExpr *S) { VisitExpr(S); } void StmtProfiler::VisitInitListExpr(const InitListExpr *S) { if (S->getSyntacticForm()) { @@ -1666,8 +1612,7 @@ void StmtProfiler::VisitBlockExpr(const BlockExpr *S) { void StmtProfiler::VisitGenericSelectionExpr(const GenericSelectionExpr *S) { VisitExpr(S); - for (const GenericSelectionExpr::ConstAssociation Assoc : - S->associations()) { + for (const GenericSelectionExpr::ConstAssociation Assoc : S->associations()) { QualType T = Assoc.getType(); if (T.isNull()) ID.AddPointer(nullptr); @@ -1679,8 +1624,9 @@ void StmtProfiler::VisitGenericSelectionExpr(const GenericSelectionExpr *S) { void StmtProfiler::VisitPseudoObjectExpr(const PseudoObjectExpr *S) { VisitExpr(S); - for (PseudoObjectExpr::const_semantics_iterator - i = S->semantics_begin(), e = S->semantics_end(); i != e; ++i) + for (PseudoObjectExpr::const_semantics_iterator i = S->semantics_begin(), + e = S->semantics_end(); + i != e; ++i) // Normally, we would not profile the source expressions of OVEs. if (const OpaqueValueExpr *OVE = dyn_cast(*i)) Visit(OVE->getSourceExpr()); @@ -1692,7 +1638,7 @@ void StmtProfiler::VisitAtomicExpr(const AtomicExpr *S) { } void StmtProfiler::VisitConceptSpecializationExpr( - const ConceptSpecializationExpr *S) { + const ConceptSpecializationExpr *S) { VisitExpr(S); VisitDecl(S->getNamedConcept()); for (const TemplateArgument &Arg : S->getTemplateArguments()) @@ -1939,7 +1885,8 @@ static Stmt::StmtClass DecodeOperatorCall(const CXXOperatorCallExpr *S, #if defined(_MSC_VER) && !defined(__clang__) #if _MSC_VER == 1911 -// Work around https://developercommunity.visualstudio.com/content/problem/84002/clang-cl-when-built-with-vc-2017-crashes-cause-vc.html +// Work around +// https://developercommunity.visualstudio.com/content/problem/84002/clang-cl-when-built-with-vc-2017-crashes-cause-vc.html // MSVC 2017 update 3 miscompiles this function, and a clang built with it // will crash in stage 2 of a bootstrap build. #pragma optimize("", off) @@ -2003,9 +1950,7 @@ void StmtProfiler::VisitCUDAKernelCallExpr(const CUDAKernelCallExpr *S) { VisitCallExpr(S); } -void StmtProfiler::VisitAsTypeExpr(const AsTypeExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitAsTypeExpr(const AsTypeExpr *S) { VisitExpr(S); } void StmtProfiler::VisitCXXNamedCastExpr(const CXXNamedCastExpr *S) { VisitExplicitCastExpr(S); @@ -2019,8 +1964,8 @@ void StmtProfiler::VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *S) { VisitCXXNamedCastExpr(S); } -void -StmtProfiler::VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *S) { +void StmtProfiler::VisitCXXReinterpretCastExpr( + const CXXReinterpretCastExpr *S) { VisitCXXNamedCastExpr(S); } @@ -2083,9 +2028,7 @@ void StmtProfiler::VisitCXXThisExpr(const CXXThisExpr *S) { ID.AddBoolean(S->isCapturedByCopyInLambdaWithExplicitObjectParameter()); } -void StmtProfiler::VisitCXXThrowExpr(const CXXThrowExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitCXXThrowExpr(const CXXThrowExpr *S) { VisitExpr(S); } void StmtProfiler::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *S) { VisitExpr(S); @@ -2100,7 +2043,7 @@ void StmtProfiler::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *S) { void StmtProfiler::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *S) { VisitExpr(S); VisitDecl( - const_cast(S->getTemporary()->getDestructor())); + const_cast(S->getTemporary()->getDestructor())); } void StmtProfiler::VisitCXXConstructExpr(const CXXConstructExpr *S) { @@ -2119,13 +2062,12 @@ void StmtProfiler::VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *S) { VisitExplicitCastExpr(S); } -void -StmtProfiler::VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *S) { +void StmtProfiler::VisitCXXTemporaryObjectExpr( + const CXXTemporaryObjectExpr *S) { VisitCXXConstructExpr(S); } -void -StmtProfiler::VisitLambdaExpr(const LambdaExpr *S) { +void StmtProfiler::VisitLambdaExpr(const LambdaExpr *S) { if (!ProfileLambdaExpr) { // Do not recursively visit the children of this expression. Profiling the // body would result in unnecessary work, and is not safe to do during @@ -2167,8 +2109,13 @@ StmtProfiler::VisitLambdaExpr(const LambdaExpr *S) { ID.AddInteger(Hasher.CalculateHash()); } -void -StmtProfiler::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *S) { +void StmtProfiler::VisitCXXReflectExpr(const CXXReflectExpr *E) { + VisitExpr(E); + // TODO: +} + +void StmtProfiler::VisitCXXScalarValueInitExpr( + const CXXScalarValueInitExpr *S) { VisitExpr(S); } @@ -2191,8 +2138,8 @@ void StmtProfiler::VisitCXXNewExpr(const CXXNewExpr *S) { ID.AddInteger(llvm::to_underlying(S->getInitializationStyle())); } -void -StmtProfiler::VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *S) { +void StmtProfiler::VisitCXXPseudoDestructorExpr( + const CXXPseudoDestructorExpr *S) { VisitExpr(S); ID.AddBoolean(S->isArrow()); VisitNestedNameSpecifier(S->getQualifier()); @@ -2221,8 +2168,7 @@ void StmtProfiler::VisitOverloadExpr(const OverloadExpr *S) { VisitTemplateArguments(S->getTemplateArgs(), S->getNumTemplateArgs()); } -void -StmtProfiler::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *S) { +void StmtProfiler::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *S) { VisitOverloadExpr(S); } @@ -2349,7 +2295,7 @@ void StmtProfiler::VisitFunctionParmPackExpr(const FunctionParmPackExpr *S) { } void StmtProfiler::VisitMaterializeTemporaryExpr( - const MaterializeTemporaryExpr *S) { + const MaterializeTemporaryExpr *S) { VisitExpr(S); } @@ -2366,29 +2312,21 @@ void StmtProfiler::VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitCoreturnStmt(const CoreturnStmt *S) { - VisitStmt(S); -} +void StmtProfiler::VisitCoreturnStmt(const CoreturnStmt *S) { VisitStmt(S); } -void StmtProfiler::VisitCoawaitExpr(const CoawaitExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitCoawaitExpr(const CoawaitExpr *S) { VisitExpr(S); } void StmtProfiler::VisitDependentCoawaitExpr(const DependentCoawaitExpr *S) { VisitExpr(S); } -void StmtProfiler::VisitCoyieldExpr(const CoyieldExpr *S) { - VisitExpr(S); -} +void StmtProfiler::VisitCoyieldExpr(const CoyieldExpr *S) { VisitExpr(S); } void StmtProfiler::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { VisitExpr(E); } -void StmtProfiler::VisitSourceLocExpr(const SourceLocExpr *E) { - VisitExpr(E); -} +void StmtProfiler::VisitSourceLocExpr(const SourceLocExpr *E) { VisitExpr(E); } void StmtProfiler::VisitEmbedExpr(const EmbedExpr *E) { VisitExpr(E); } @@ -2398,9 +2336,7 @@ void StmtProfiler::VisitObjCStringLiteral(const ObjCStringLiteral *S) { VisitExpr(S); } -void StmtProfiler::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { - VisitExpr(E); -} +void StmtProfiler::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { VisitExpr(E); } void StmtProfiler::VisitObjCArrayLiteral(const ObjCArrayLiteral *E) { VisitExpr(E); diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index b282a600c0e56..5df36d041d0c1 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -4348,6 +4348,9 @@ bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) { if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::caretequal; + } else if (LangOpts.Reflection && Char == '^') { + CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); + Kind = tok::caretcaret; } else { if (LangOpts.OpenCL && Char == '^') Diag(CurPtr, diag::err_opencl_logical_exclusive_or); diff --git a/clang/lib/Parse/CMakeLists.txt b/clang/lib/Parse/CMakeLists.txt index e6cbf3b868b7d..8dd120f529b13 100644 --- a/clang/lib/Parse/CMakeLists.txt +++ b/clang/lib/Parse/CMakeLists.txt @@ -26,6 +26,7 @@ add_clang_library(clangParse ParseTentative.cpp Parser.cpp ParseOpenACC.cpp + ParseReflect.cpp LINK_LIBS clangAST diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index 3515343202de1..22963d985b01b 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -1208,6 +1208,13 @@ Parser::ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, AllowSuffix = false; Res = ParseUnaryExprOrTypeTraitExpression(); break; + case tok::caretcaret: { + if (getLangOpts().Reflection) { + SourceLocation FirstCaret = ConsumeToken(); // eat first '^' + Res = ParseCXXReflectExpression(/*OpLoc=*/FirstCaret); + } + break; + } case tok::ampamp: { // unary-expression: '&&' identifier if (NotPrimaryExpression) *NotPrimaryExpression = true; @@ -2249,6 +2256,9 @@ ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { else if (getLangOpts().C2y && OpTok.is(tok::kw__Countof)) Diag(OpTok, diag::warn_c2y_compat_keyword) << OpTok.getName(); + if (OpTok.is(tok::caretcaret)) + return ParseCXXReflectExpression(OpTok.getLocation()); + EnterExpressionEvaluationContext Unevaluated( Actions, Sema::ExpressionEvaluationContext::Unevaluated, Sema::ReuseLambdaContextDecl); diff --git a/clang/lib/Parse/ParseReflect.cpp b/clang/lib/Parse/ParseReflect.cpp new file mode 100644 index 0000000000000..541cbd90261ea --- /dev/null +++ b/clang/lib/Parse/ParseReflect.cpp @@ -0,0 +1,61 @@ +//===--- ParseReflect.cpp - C++2c Reflection Parsing ---------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements parsing for reflection facilities. +// +//===----------------------------------------------------------------------===// + +#include "clang/AST/LocInfoType.h" +#include "clang/Basic/DiagnosticParse.h" +#include "clang/Parse/Parser.h" +#include "clang/Sema/EnterExpressionEvaluationContext.h" +using namespace clang; + +ExprResult Parser::ParseCXXReflectExpression(SourceLocation OpLoc) { + assert(Tok.is(tok::caretcaret) && "expected '^^'"); + EnterExpressionEvaluationContext Unevaluated( + Actions, Sema::ExpressionEvaluationContext::Unevaluated); + + SourceLocation OperandLoc = Tok.getLocation(); + + // Parse a leading nested-name-specifier + CXXScopeSpec SS; + if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, + /*ObjectHasErrors=*/false, + /*EnteringContext=*/false)) { + SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); + return ExprError(); + } + + { + TentativeParsingAction TPA(*this); + + if (SS.isValid() && + SS.getScopeRep().getKind() == NestedNameSpecifier::Kind::Global) { + // Check for global namespace '^^::' + TPA.Commit(); + Decl *TUDecl = Actions.getASTContext().getTranslationUnitDecl(); + return Actions.ActOnCXXReflectExpr(OpLoc, SourceLocation(), TUDecl); + } + TPA.Revert(); + } + + if (isCXXTypeId(TentativeCXXTypeIdContext::AsReflectionOperand)) { + TypeResult TR = ParseTypeName(/*TypeOf=*/nullptr); + if (TR.isInvalid()) + return ExprError(); + + TypeSourceInfo *TSI = nullptr; + QualType QT = Actions.GetTypeFromParser(TR.get(), &TSI); + + return Actions.ActOnCXXReflectExpr(OpLoc, TSI); + } + + Diag(OperandLoc, diag::err_cannot_reflect_operand); + return ExprError(); +} diff --git a/clang/lib/Parse/ParseTentative.cpp b/clang/lib/Parse/ParseTentative.cpp index 82f2294ff5bb7..8a3ae2232767e 100644 --- a/clang/lib/Parse/ParseTentative.cpp +++ b/clang/lib/Parse/ParseTentative.cpp @@ -574,6 +574,9 @@ bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) { } else if (Context == TentativeCXXTypeIdContext::InTrailingReturnType) { TPR = TPResult::True; isAmbiguous = true; + } else if (Context == TentativeCXXTypeIdContext::AsReflectionOperand) { + TPR = TPResult::True; + isAmbiguous = true; } else TPR = TPResult::False; } diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp b/clang/lib/Sema/SemaExceptionSpec.cpp index a0483c3027199..ff8d2139289a3 100644 --- a/clang/lib/Sema/SemaExceptionSpec.cpp +++ b/clang/lib/Sema/SemaExceptionSpec.cpp @@ -1379,6 +1379,7 @@ CanThrowResult Sema::canThrow(const Stmt *S) { case Expr::CXXNoexceptExprClass: case Expr::CXXNullPtrLiteralExprClass: case Expr::CXXPseudoDestructorExprClass: + case Expr::CXXReflectExprClass: case Expr::CXXScalarValueInitExprClass: case Expr::CXXThisExprClass: case Expr::CXXUuidofExprClass: diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index a50c27610dc96..57238f63f0132 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -139,7 +139,7 @@ void Sema::NoteDeletedFunction(FunctionDecl *Decl) { return NoteDeletedInheritingConstructor(Ctor); Diag(Decl->getLocation(), diag::note_availability_specified_here) - << Decl << 1; + << Decl << 1; } /// Determine whether a FunctionDecl was ever declared with an @@ -217,7 +217,7 @@ void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { if (!hasAnyExplicitStorageClass(First)) { SourceLocation DeclBegin = First->getSourceRange().getBegin(); Diag(DeclBegin, diag::note_convert_inline_to_static) - << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); + << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); } } @@ -256,7 +256,7 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs, if (ParsingInitForAutoVars.count(D)) { if (isa(D)) { Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) - << D->getDeclName(); + << D->getDeclName(); } else { Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) << diag::ParsingInitFor::Var << D->getDeclName() @@ -298,8 +298,7 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs, // constraint expression, for example) return true; if (!Satisfaction.IsSatisfied) { - Diag(Loc, - diag::err_reference_to_function_with_unsatisfied_constraints) + Diag(Loc, diag::err_reference_to_function_with_unsatisfied_constraints) << D; DiagnoseUnsatisfiedConstraint(Satisfaction); return true; @@ -314,7 +313,6 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs, if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD)) return true; - } if (auto *Concept = dyn_cast(D); @@ -328,12 +326,12 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs, cast(MD)->isDefaultConstructor()) || MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) - << !isa(MD); + << !isa(MD); } } - auto getReferencedObjCProp = [](const NamedDecl *D) -> - const ObjCPropertyDecl * { + auto getReferencedObjCProp = + [](const NamedDecl *D) -> const ObjCPropertyDecl * { if (const auto *MD = dyn_cast(D)) return MD->findPropertyDecl(); return nullptr; @@ -342,7 +340,7 @@ bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs, if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) return true; } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { - return true; + return true; } // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions @@ -516,7 +514,8 @@ ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { // Handle any placeholder expressions which made it here. if (E->hasPlaceholderType()) { ExprResult result = CheckPlaceholderExpr(E); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); E = result.get(); } @@ -530,7 +529,8 @@ ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { return ExprError(); E = ImpCastExprToType(E, Context.getPointerType(Ty), - CK_FunctionToPointerDecay).get(); + CK_FunctionToPointerDecay) + .get(); } else if (Ty->isArrayType()) { // In C90 mode, arrays only promote to pointers if the array expression is // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has @@ -580,8 +580,7 @@ static void CheckForNullPointerDereference(Sema &S, Expr *E) { } static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, - SourceLocation AssignLoc, - const Expr* RHS) { + SourceLocation AssignLoc, const Expr *RHS) { const ObjCIvarDecl *IV = OIRE->getDecl(); if (!IV) return; @@ -599,13 +598,12 @@ static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { ObjCInterfaceDecl *ClassDeclared = nullptr; ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); - if (!ClassDeclared->getSuperClass() - && (*ClassDeclared->ivar_begin()) == IV) { + if (!ClassDeclared->getSuperClass() && + (*ClassDeclared->ivar_begin()) == IV) { if (RHS) { - NamedDecl *ObjectSetClass = - S.LookupSingleName(S.TUScope, - &S.Context.Idents.get("object_setClass"), - SourceLocation(), S.LookupOrdinaryName); + NamedDecl *ObjectSetClass = S.LookupSingleName( + S.TUScope, &S.Context.Idents.get("object_setClass"), + SourceLocation(), S.LookupOrdinaryName); if (ObjectSetClass) { SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) @@ -614,14 +612,12 @@ static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, << FixItHint::CreateReplacement( SourceRange(OIRE->getOpLoc(), AssignLoc), ",") << FixItHint::CreateInsertion(RHSLocEnd, ")"); - } - else + } else S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); } else { - NamedDecl *ObjectGetClass = - S.LookupSingleName(S.TUScope, - &S.Context.Idents.get("object_getClass"), - SourceLocation(), S.LookupOrdinaryName); + NamedDecl *ObjectGetClass = S.LookupSingleName( + S.TUScope, &S.Context.Idents.get("object_getClass"), + SourceLocation(), S.LookupOrdinaryName); if (ObjectGetClass) S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << FixItHint::CreateInsertion(OIRE->getBeginLoc(), @@ -640,14 +636,16 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { // Handle any placeholder expressions which made it here. if (E->hasPlaceholderType()) { ExprResult result = CheckPlaceholderExpr(E); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); E = result.get(); } // C++ [conv.lval]p1: // A glvalue of a non-function, non-array type T can be // converted to a prvalue. - if (!E->isGLValue()) return E; + if (!E->isGLValue()) + return E; QualType T = E->getType(); assert(!T.isNull() && "r-value conversion on typeless expression?"); @@ -678,16 +676,15 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && T->isHalfType()) { - Diag(E->getExprLoc(), diag::err_opencl_half_load_store) - << 0 << T; + Diag(E->getExprLoc(), diag::err_opencl_half_load_store) << 0 << T; return ExprError(); } CheckForNullPointerDereference(*this, E); if (const ObjCIsaExpr *OISA = dyn_cast(E->IgnoreParenCasts())) { - NamedDecl *ObjectGetClass = LookupSingleName(TUScope, - &Context.Idents.get("object_getClass"), - SourceLocation(), LookupOrdinaryName); + NamedDecl *ObjectGetClass = + LookupSingleName(TUScope, &Context.Idents.get("object_getClass"), + SourceLocation(), LookupOrdinaryName); if (ObjectGetClass) Diag(E->getExprLoc(), diag::warn_objc_isa_use) << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") @@ -695,10 +692,9 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); else Diag(E->getExprLoc(), diag::warn_objc_isa_use); - } - else if (const ObjCIvarRefExpr *OIRE = - dyn_cast(E->IgnoreParenCasts())) - DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); + } else if (const ObjCIvarRefExpr *OIRE = + dyn_cast(E->IgnoreParenCasts())) + DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/ nullptr); // C++ [conv.lval]p1: // [...] If T is a non-class type, the type of the prvalue is the @@ -722,8 +718,8 @@ ExprResult Sema::DefaultLvalueConversion(Expr *E) { return Res; E = Res.get(); - // Loading a __weak object implicitly retains the value, so we need a cleanup to - // balance that. + // Loading a __weak object implicitly retains the value, so we need a cleanup + // to balance that. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) Cleanup.setExprNeedsCleanups(true); @@ -932,8 +928,8 @@ ExprResult Sema::DefaultArgumentPromotion(Expr *E) { // potentially potentially evaluated contexts. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { ExprResult Temp = PerformCopyInitialization( - InitializedEntity::InitializeTemporary(E->getType()), - E->getExprLoc(), E); + InitializedEntity::InitializeTemporary(E->getType()), E->getExprLoc(), + E); if (Temp.isInvalid()) return ExprError(); E = Temp.get(); @@ -1129,8 +1125,10 @@ static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, QualType IntTy, QualType ComplexTy, bool SkipCast) { - if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; - if (SkipCast) return false; + if (IntTy->isComplexType() || IntTy->isRealFloatingType()) + return true; + if (SkipCast) + return false; if (IntTy->isIntegerType()) { QualType fpTy = ComplexTy->castAs()->getElementType(); IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); @@ -1206,8 +1204,8 @@ static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, if (IntTy->isIntegerType()) { if (ConvertInt) // Convert intExpr to the lhs floating point type. - IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, - CK_IntegralToFloating); + IntExpr = + S.ImpCastExprToType(IntExpr.get(), FloatTy, CK_IntegralToFloating); return FloatTy; } @@ -1222,17 +1220,17 @@ static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, // float -> _Complex float if (ConvertFloat) - FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, - CK_FloatingRealToComplex); + FloatExpr = + S.ImpCastExprToType(FloatExpr.get(), result, CK_FloatingRealToComplex); return result; } /// Handle arithmethic conversion with floating point types. Helper /// function of UsualArithmeticConversions() -static QualType handleFloatConversion(Sema &S, ExprResult &LHS, - ExprResult &RHS, QualType LHSType, - QualType RHSType, bool IsCompAssign) { +static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, + QualType LHSType, QualType RHSType, + bool IsCompAssign) { bool LHSFloat = LHSType->isRealFloatingType(); bool RHSFloat = RHSType->isRealFloatingType(); @@ -1269,11 +1267,11 @@ static QualType handleFloatConversion(Sema &S, ExprResult &LHS, return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, /*ConvertFloat=*/!IsCompAssign, - /*ConvertInt=*/ true); + /*ConvertInt=*/true); } assert(RHSFloat); return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, - /*ConvertFloat=*/ true, + /*ConvertFloat=*/true, /*ConvertInt=*/!IsCompAssign); } @@ -1318,7 +1316,7 @@ ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { return S.ImpCastExprToType(op, S.Context.getComplexType(toType), CK_IntegralComplexCast); } -} +} // namespace /// Handle integer arithmetic conversions. Helper function of /// UsualArithmeticConversions() @@ -1363,7 +1361,7 @@ static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, // on most 32-bit systems). Use the unsigned type corresponding // to the signed type. QualType result = - S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); + S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); RHS = (*doRHSCast)(S, RHS.get(), result); if (!IsCompAssign) LHS = (*doLHSCast)(S, LHS.get(), result); @@ -1384,8 +1382,8 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, QualType LHSEltType = LHSComplexInt->getElementType(); QualType RHSEltType = RHSComplexInt->getElementType(); QualType ScalarType = - handleIntegerConversion - (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); + handleIntegerConversion( + S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); return S.Context.getComplexType(ScalarType); } @@ -1393,11 +1391,10 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, if (LHSComplexInt) { QualType LHSEltType = LHSComplexInt->getElementType(); QualType ScalarType = - handleIntegerConversion - (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); + handleIntegerConversion( + S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); QualType ComplexType = S.Context.getComplexType(ScalarType); - RHS = S.ImpCastExprToType(RHS.get(), ComplexType, - CK_IntegralRealToComplex); + RHS = S.ImpCastExprToType(RHS.get(), ComplexType, CK_IntegralRealToComplex); return ComplexType; } @@ -1406,13 +1403,12 @@ static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, QualType RHSEltType = RHSComplexInt->getElementType(); QualType ScalarType = - handleIntegerConversion - (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); + handleIntegerConversion( + S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); QualType ComplexType = S.Context.getComplexType(ScalarType); if (!IsCompAssign) - LHS = S.ImpCastExprToType(LHS.get(), ComplexType, - CK_IntegralRealToComplex); + LHS = S.ImpCastExprToType(LHS.get(), ComplexType, CK_IntegralRealToComplex); return ComplexType; } @@ -1725,7 +1721,6 @@ QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, // Semantic Analysis for various Expression Types //===----------------------------------------------------------------------===// - ExprResult Sema::ActOnGenericSelectionExpr( SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, @@ -1733,10 +1728,10 @@ ExprResult Sema::ActOnGenericSelectionExpr( unsigned NumAssocs = ArgTypes.size(); assert(NumAssocs == ArgExprs.size()); - TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; + TypeSourceInfo **Types = new TypeSourceInfo *[NumAssocs]; for (unsigned i = 0; i < NumAssocs; ++i) { if (ArgTypes[i]) - (void) GetTypeFromParser(ArgTypes[i], &Types[i]); + (void)GetTypeFromParser(ArgTypes[i], &Types[i]); else Types[i] = nullptr; } @@ -1754,7 +1749,7 @@ ExprResult Sema::ActOnGenericSelectionExpr( ExprResult ER = CreateGenericSelectionExpr( KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType, llvm::ArrayRef(Types, NumAssocs), ArgExprs); - delete [] Types; + delete[] Types; return ER; } @@ -1880,19 +1875,17 @@ ExprResult Sema::CreateGenericSelectionExpr( // C11 6.5.1.1p2 "No two generic associations in the same generic // selection shall specify compatible types." - for (unsigned j = i+1; j < NumAssocs; ++j) + for (unsigned j = i + 1; j < NumAssocs; ++j) if (Types[j] && !Types[j]->getType()->isDependentType() && Context.typesAreCompatible(Types[i]->getType(), Types[j]->getType())) { Diag(Types[j]->getTypeLoc().getBeginLoc(), diag::err_assoc_compatible_types) - << Types[j]->getTypeLoc().getSourceRange() - << Types[j]->getType() - << Types[i]->getType(); - Diag(Types[i]->getTypeLoc().getBeginLoc(), - diag::note_compat_assoc) - << Types[i]->getTypeLoc().getSourceRange() - << Types[i]->getType(); + << Types[j]->getTypeLoc().getSourceRange() + << Types[j]->getType() << Types[i]->getType(); + Diag(Types[i]->getTypeLoc().getBeginLoc(), diag::note_compat_assoc) + << Types[i]->getTypeLoc().getSourceRange() + << Types[i]->getType(); TypeErrorFound = true; } } @@ -1958,10 +1951,8 @@ ExprResult Sema::CreateGenericSelectionExpr( Diag(SR.getBegin(), diag::err_generic_sel_multi_match) << SR << P.second << (unsigned)CompatIndices.size(); for (unsigned I : CompatIndices) { - Diag(Types[I]->getTypeLoc().getBeginLoc(), - diag::note_compat_assoc) - << Types[I]->getTypeLoc().getSourceRange() - << Types[I]->getType(); + Diag(Types[I]->getTypeLoc().getBeginLoc(), diag::note_compat_assoc) + << Types[I]->getTypeLoc().getSourceRange() << Types[I]->getType(); } return ExprError(); } @@ -1982,8 +1973,7 @@ ExprResult Sema::CreateGenericSelectionExpr( // then the result expression of the generic selection is the expression // in that generic association. Otherwise, the result expression of the // generic selection is the expression in the default generic association." - unsigned ResultIndex = - CompatIndices.size() ? CompatIndices[0] : DefaultIndex; + unsigned ResultIndex = CompatIndices.size() ? CompatIndices[0] : DefaultIndex; if (ControllingExpr) { return GenericSelectionExpr::Create( @@ -2038,7 +2028,7 @@ static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, - ArrayRef Args, + ArrayRef Args, SourceLocation LitEndLoc) { assert(Args.size() <= 2 && "too many arguments for literal operator"); @@ -2050,7 +2040,7 @@ static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, } DeclarationName OpName = - S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); + S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); @@ -2142,8 +2132,8 @@ Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef Toks) { return ExpandedToks; } -ExprResult -Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { +ExprResult Sema::ActOnStringLiteral(ArrayRef StringToks, + Scope *UDLScope) { assert(!StringToks.empty() && "Must have at least one string!"); // StringToks needs backing storage as it doesn't hold array elements itself @@ -2223,8 +2213,8 @@ Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { // We're building a user-defined literal. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); SourceLocation UDSuffixLoc = - getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], - Literal.getUDSuffixOffset()); + getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], + Literal.getUDSuffixOffset()); // Make sure we're allowed user-defined literals here. if (!UDLScope) @@ -2235,13 +2225,11 @@ Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { QualType SizeType = Context.getSizeType(); DeclarationName OpName = - Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); + Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); - QualType ArgTy[] = { - Context.getArrayDecayedType(StrTy), SizeType - }; + QualType ArgTy[] = {Context.getArrayDecayedType(StrTy), SizeType}; LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); switch (LookupLiteralOperator(UDLScope, R, ArgTy, @@ -2251,9 +2239,9 @@ Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { case LOLR_Cooked: { llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); - IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, - StringTokLocs[0]); - Expr *Args[] = { Lit, LenArg }; + IntegerLiteral *LenArg = + IntegerLiteral::Create(Context, Len, SizeType, StringTokLocs[0]); + Expr *Args[] = {Lit, LenArg}; return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); } @@ -2275,7 +2263,8 @@ Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { llvm::APSInt Value(CharBits, CharIsUnsigned); TemplateArgument TypeArg(CharTy); - TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); + TemplateArgumentLocInfo TypeArgInfo( + Context.getTrivialTypeSourceInfo(CharTy)); ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { @@ -2296,10 +2285,9 @@ Sema::ActOnStringLiteral(ArrayRef StringToks, Scope *UDLScope) { llvm_unreachable("unexpected literal operator lookup result"); } -DeclRefExpr * -Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, - SourceLocation Loc, - const CXXScopeSpec *SS) { +DeclRefExpr *Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, + SourceLocation Loc, + const CXXScopeSpec *SS) { DeclarationNameInfo NameInfo(D->getDeclName(), Loc); return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); } @@ -2430,11 +2418,10 @@ Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, return E; } -void -Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, - TemplateArgumentListInfo &Buffer, - DeclarationNameInfo &NameInfo, - const TemplateArgumentListInfo *&TemplateArgs) { +void Sema::DecomposeUnqualifiedId( + const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, + DeclarationNameInfo &NameInfo, + const TemplateArgumentListInfo *&TemplateArgs) { if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); @@ -2591,15 +2578,14 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CSK_Normal); OverloadCandidateSet::iterator Best; for (NamedDecl *CD : Corrected) { - if (FunctionTemplateDecl *FTD = - dyn_cast(CD)) - AddTemplateOverloadCandidate( - FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, - Args, OCS); + if (FunctionTemplateDecl *FTD = dyn_cast(CD)) + AddTemplateOverloadCandidate(FTD, + DeclAccessPair::make(FTD, AS_none), + ExplicitTemplateArgs, Args, OCS); else if (FunctionDecl *FD = dyn_cast(CD)) if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) - AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), - Args, OCS); + AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, + OCS); } switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { case OR_Success: @@ -2617,8 +2603,8 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CXXRecordDecl *Record = Corrected.getCorrectionSpecifier().getAsRecordDecl(); if (!Record) - Record = cast( - ND->getDeclContext()->getRedeclContext()); + Record = + cast(ND->getDeclContext()->getRedeclContext()); R.setNamingClass(Record); } @@ -2718,12 +2704,13 @@ recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, TemplateArgs); } -ExprResult -Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, - SourceLocation TemplateKWLoc, UnqualifiedId &Id, - bool HasTrailingLParen, bool IsAddressOfOperand, - CorrectionCandidateCallback *CCC, - bool IsInlineAsmIdentifier, Token *KeywordReplacement) { +ExprResult Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, + SourceLocation TemplateKWLoc, + UnqualifiedId &Id, bool HasTrailingLParen, + bool IsAddressOfOperand, + CorrectionCandidateCallback *CCC, + bool IsInlineAsmIdentifier, + Token *KeywordReplacement) { assert(!(IsAddressOfOperand && HasTrailingLParen) && "cannot be direct & operand and have a trailing lparen"); if (SS.isInvalid()) @@ -2814,7 +2801,8 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, if (R.empty() && HasTrailingLParen && II && getLangOpts().implicitFunctionsAllowed()) { NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); - if (D) R.addDecl(D); + if (D) + R.addDecl(D); } // Determine whether this name might be a candidate for @@ -2940,7 +2928,7 @@ ExprResult Sema::BuildQualifiedDeclarationNameExpr( if (CD->isInvalidDecl()) return ExprError(); Diag(NameInfo.getLoc(), diag::err_no_member) - << NameInfo.getName() << DC << SS.getRange(); + << NameInfo.getName() << DC << SS.getRange(); return ExprError(); } @@ -3105,14 +3093,15 @@ ExprResult Sema::PerformObjectMemberConversion(Expr *From, // Otherwise build the appropriate casts. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { CXXCastPath BasePath; - if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, - FromLoc, FromRange, &BasePath)) + if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, FromLoc, + FromRange, &BasePath)) return ExprError(); if (PointerConversions) QType = Context.getPointerType(QType); - From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, - VK, &BasePath).get(); + From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, VK, + &BasePath) + .get(); FromType = QType; FromRecordType = QRecordType; @@ -3125,8 +3114,8 @@ ExprResult Sema::PerformObjectMemberConversion(Expr *From, } CXXCastPath BasePath; - if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, - FromLoc, FromRange, &BasePath, + if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, FromLoc, + FromRange, &BasePath, /*IgnoreAccess=*/true)) return ExprError(); @@ -3192,7 +3181,6 @@ bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, return true; } - /// Diagnoses obvious problems with the use of the given declaration /// as an expression. This is only actually called for lookups that /// were not overloaded, and it doesn't promise that the declaration @@ -3598,7 +3586,7 @@ ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { else if (Literal.isUTF32()) Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) - Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. + Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. else Ty = Context.CharTy; // 'x' -> char in C++; // u8'x' -> char in C11-C17 and in C++ without char8_t. @@ -3613,8 +3601,8 @@ ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { else if (Literal.isUTF8()) Kind = CharacterLiteralKind::UTF8; - Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, - Tok.getLocation()); + Expr *Lit = new (Context) + CharacterLiteral(Literal.getValue(), Kind, Ty, Tok.getLocation()); if (Literal.getUDSuffix().empty()) return Lit; @@ -3622,7 +3610,7 @@ ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { // We're building a user-defined literal. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); SourceLocation UDSuffixLoc = - getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); + getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); // Make sure we're allowed user-defined literals here. if (!UDLScope) @@ -3739,7 +3727,7 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // We're building a user-defined literal. const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); SourceLocation UDSuffixLoc = - getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); + getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); // Make sure we're allowed user-defined literals here. if (!UDLScope) @@ -3759,7 +3747,7 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { } DeclarationName OpName = - Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); + Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); @@ -3853,7 +3841,8 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { } } - if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); + if (Literal.isUnsigned) + Ty = Context.getCorrespondingUnsignedType(Ty); bool isSigned = !Literal.isUnsigned; unsigned scale = Context.getFixedPointScale(Ty); @@ -3877,7 +3866,7 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { Tok.getLocation(), scale); } else if (Literal.isFloatingLiteral()) { QualType Ty; - if (Literal.isHalf){ + if (Literal.isHalf) { if (getLangOpts().HLSL || getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) Ty = Context.HalfTy; @@ -4049,7 +4038,7 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // Does it fit in a unsigned int? if (ResultVal.isIntN(IntSize)) { // Does it fit in a signed int? - if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) + if (!Literal.isUnsigned && ResultVal[IntSize - 1] == 0) Ty = Context.IntTy; else if (AllowUnsigned) Ty = Context.UnsignedIntTy; @@ -4064,7 +4053,7 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // Does it fit in a unsigned long? if (ResultVal.isIntN(LongSize)) { // Does it fit in a signed long? - if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) + if (!Literal.isUnsigned && ResultVal[LongSize - 1] == 0) Ty = Context.LongTy; else if (AllowUnsigned) Ty = Context.UnsignedLongTy; @@ -4097,8 +4086,9 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // Does it fit in a signed long long? // To be compatible with MSVC, hex integer literals ending with the // LL or i64 suffix are always signed in Microsoft mode. - if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || - (getLangOpts().MSVCCompat && Literal.isLongLong))) + if (!Literal.isUnsigned && + (ResultVal[LongLongSize - 1] == 0 || + (getLangOpts().MSVCCompat && Literal.isLongLong))) Ty = Context.LongLongTy; else if (AllowUnsigned) Ty = Context.UnsignedLongLongTy; @@ -4137,8 +4127,8 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { // If this is an imaginary literal, create the ImaginaryLiteral wrapper. if (Literal.isImaginary) { - Res = new (Context) ImaginaryLiteral(Res, - Context.getComplexType(Res->getType())); + Res = new (Context) + ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); // In C++, this is a GNU extension. In C, it's a C2y extension. unsigned DiagId; @@ -4170,8 +4160,7 @@ static bool CheckVecStepTraitOperandType(Sema &S, QualType T, // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic // type (C99 6.2.5p18) or void. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { - S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) - << T << ArgRange; + S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) << T << ArgRange; return true; } @@ -4186,8 +4175,7 @@ static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, // builtin_vectorelements supports both fixed-sized and scalable vectors. if (!T->isVectorType() && !T->isSizelessVectorType()) return S.Diag(Loc, diag::err_builtin_non_vector_type) - << "" - << "__builtin_vectorelements" << T << ArgRange; + << "" << "__builtin_vectorelements" << T << ArgRange; return false; } @@ -4245,8 +4233,7 @@ static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, // runtime doesn't allow it. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { S.Diag(Loc, diag::err_sizeof_nonfragile_interface) - << T << (TraitKind == UETT_SizeOf) - << ArgRange; + << T << (TraitKind == UETT_SizeOf) << ArgRange; return true; } @@ -4266,9 +4253,9 @@ static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) return; - S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() - << ICE->getType() - << ICE->getSubExpr()->getType(); + S.Diag(Loc, diag::warn_sizeof_array_decay) + << ICE->getSourceRange() << ICE->getType() + << ICE->getSubExpr()->getType(); } bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, @@ -4293,8 +4280,7 @@ bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, // used to build SFINAE gadgets. // FIXME: Should we consider instantiation-dependent operands to 'alignof'? if (IsUnevaluatedOperand && !inTemplateInstantiation() && - !E->isInstantiationDependent() && - !E->getType()->isVariableArrayType() && + !E->isInstantiationDependent() && !E->getType()->isVariableArrayType() && E->HasSideEffects(Context, false)) Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); @@ -4372,8 +4358,7 @@ bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, QualType OType = PVD->getOriginalType(); QualType Type = PVD->getType(); if (Type->isPointerType() && OType->isArrayType()) { - Diag(E->getExprLoc(), diag::warn_sizeof_array_param) - << Type << OType; + Diag(E->getExprLoc(), diag::warn_sizeof_array_param) << Type << OType; Diag(PVD->getLocation(), diag::note_declared_at); } } @@ -4400,7 +4385,7 @@ static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { if (E->getObjectKind() == OK_BitField) { S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) - << 1 << E->getSourceRange(); + << 1 << E->getSourceRange(); return true; } @@ -4434,7 +4419,7 @@ static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { // definition if we can find a member of it. if (!FD->getParent()->isCompleteDefinition()) { S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) - << E->getSourceRange(); + << E->getSourceRange(); return true; } @@ -4717,9 +4702,8 @@ ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); } -ExprResult -Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, - UnaryExprOrTypeTrait ExprKind) { +ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, + UnaryExprOrTypeTrait ExprKind) { ExprResult PE = CheckPlaceholderExpr(E); if (PE.isInvalid()) return ExprError(); @@ -4735,9 +4719,9 @@ Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, } else if (ExprKind == UETT_VecStep) { isInvalid = CheckVecStepExpr(E); } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { - Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); - isInvalid = true; - } else if (E->refersToBitField()) { // C99 6.5.3.4p1. + Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); + isInvalid = true; + } else if (E->refersToBitField()) { // C99 6.5.3.4p1. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; isInvalid = true; } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf || @@ -4751,7 +4735,8 @@ Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) && E->getType()->isVariableArrayType()) { PE = TransformToPotentiallyEvaluated(E); - if (PE.isInvalid()) return ExprError(); + if (PE.isInvalid()) + return ExprError(); E = PE.get(); } @@ -4760,16 +4745,17 @@ Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); } -ExprResult -Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, - UnaryExprOrTypeTrait ExprKind, bool IsType, - void *TyOrEx, SourceRange ArgRange) { +ExprResult Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, + UnaryExprOrTypeTrait ExprKind, + bool IsType, void *TyOrEx, + SourceRange ArgRange) { // If error parsing type, ignore. - if (!TyOrEx) return ExprError(); + if (!TyOrEx) + return ExprError(); if (IsType) { TypeSourceInfo *TInfo; - (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); + (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); } @@ -4816,33 +4802,37 @@ static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, // Test for placeholders. ExprResult PR = S.CheckPlaceholderExpr(V.get()); - if (PR.isInvalid()) return QualType(); + if (PR.isInvalid()) + return QualType(); if (PR.get() != V.get()) { V = PR; return CheckRealImagOperand(S, V, Loc, IsReal); } // Reject anything else. - S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() - << (IsReal ? "__real" : "__imag"); + S.Diag(Loc, diag::err_realimag_invalid_type) + << V.get()->getType() << (IsReal ? "__real" : "__imag"); return QualType(); } - - -ExprResult -Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, - tok::TokenKind Kind, Expr *Input) { +ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, + tok::TokenKind Kind, Expr *Input) { UnaryOperatorKind Opc; switch (Kind) { - default: llvm_unreachable("Unknown unary op!"); - case tok::plusplus: Opc = UO_PostInc; break; - case tok::minusminus: Opc = UO_PostDec; break; + default: + llvm_unreachable("Unknown unary op!"); + case tok::plusplus: + Opc = UO_PostInc; + break; + case tok::minusminus: + Opc = UO_PostDec; + break; } // Since this might is a postfix expression, get rid of ParenListExprs. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); Input = Result.get(); return BuildUnaryOp(S, OpLoc, Opc, Input); @@ -4851,8 +4841,7 @@ Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, /// Diagnose if arithmetic on the given ObjC pointer is illegal. /// /// \return true on error -static bool checkArithmeticOnObjCPointer(Sema &S, - SourceLocation opLoc, +static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op) { assert(op->getType()->isObjCObjectPointerType()); if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && @@ -4860,8 +4849,8 @@ static bool checkArithmeticOnObjCPointer(Sema &S, return false; S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) - << op->getType()->castAs()->getPointeeType() - << op->getSourceRange(); + << op->getType()->castAs()->getPointeeType() + << op->getSourceRange(); return true; } @@ -5195,9 +5184,9 @@ void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { } } -ExprResult -Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, - Expr *Idx, SourceLocation RLoc) { +ExprResult Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, + SourceLocation LLoc, Expr *Idx, + SourceLocation RLoc) { Expr *LHSExp = Base; Expr *RHSExp = Idx; @@ -5244,7 +5233,7 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, IndexExpr = RHSExp; ResultType = PTy->getPointeeType(); } else if (const ObjCObjectPointerType *PTy = - LHSTy->getAs()) { + LHSTy->getAs()) { BaseExpr = LHSExp; IndexExpr = RHSExp; @@ -5256,19 +5245,19 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, ResultType = PTy->getPointeeType(); } else if (const PointerType *PTy = RHSTy->getAs()) { - // Handle the uncommon case of "123[Ptr]". + // Handle the uncommon case of "123[Ptr]". BaseExpr = RHSExp; IndexExpr = LHSExp; ResultType = PTy->getPointeeType(); } else if (const ObjCObjectPointerType *PTy = - RHSTy->getAs()) { - // Handle the uncommon case of "123[Ptr]". + RHSTy->getAs()) { + // Handle the uncommon case of "123[Ptr]". BaseExpr = RHSExp; IndexExpr = LHSExp; ResultType = PTy->getPointeeType(); if (!LangOpts.isSubscriptPointerArithmetic()) { Diag(LLoc, diag::err_subscript_nonfragile_interface) - << ResultType << BaseExpr->getSourceRange(); + << ResultType << BaseExpr->getSourceRange(); return ExprError(); } } else if (LHSTy->isSubscriptableVectorType()) { @@ -5312,7 +5301,8 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) << LHSExp->getSourceRange(); LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), - CK_ArrayToPointerDecay).get(); + CK_ArrayToPointerDecay) + .get(); LHSTy = LHSExp->getType(); BaseExpr = LHSExp; @@ -5323,7 +5313,8 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) << RHSExp->getSourceRange(); RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), - CK_ArrayToPointerDecay).get(); + CK_ArrayToPointerDecay) + .get(); RHSTy = RHSExp->getType(); BaseExpr = RHSExp; @@ -5331,7 +5322,7 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, ResultType = RHSTy->castAs()->getPointeeType(); } else { return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) - << LHSExp->getSourceRange() << RHSExp->getSourceRange()); + << LHSExp->getSourceRange() << RHSExp->getSourceRange()); } // C99 6.5.2.1p1 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) @@ -5360,8 +5351,7 @@ Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { // GNU extension: subscripting on pointer to void - Diag(LLoc, diag::ext_gnu_subscript_void_type) - << BaseExpr->getSourceRange(); + Diag(LLoc, diag::ext_gnu_subscript_void_type) << BaseExpr->getSourceRange(); // C forbids expressions of unqualified void type from being l-values. // See IsCForbiddenLValueType. @@ -5828,7 +5818,7 @@ class FunctionCallCCC final : public FunctionCallFilterCCC { private: const IdentifierInfo *const FunctionName; }; -} +} // namespace static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, @@ -5888,13 +5878,12 @@ static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) { return false; } -bool -Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, - FunctionDecl *FDecl, - const FunctionProtoType *Proto, - ArrayRef Args, - SourceLocation RParenLoc, - bool IsExecConfig) { +bool Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, + FunctionDecl *FDecl, + const FunctionProtoType *Proto, + ArrayRef Args, + SourceLocation RParenLoc, + bool IsExecConfig) { // Bail out early if calling a builtin with custom typechecking. if (FDecl) if (unsigned ID = FDecl->getBuiltinID()) @@ -5912,9 +5901,9 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, bool Invalid = false; unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; unsigned FnKind = Fn->getType()->isBlockPointerType() - ? 1 /* block */ - : (IsExecConfig ? 3 /* kernel function (exec config) */ - : 0 /* function */); + ? 1 /* block */ + : (IsExecConfig ? 3 /* kernel function (exec config) */ + : 0 /* function */); // If too few arguments are available (and we don't have default // arguments for the remaining parameters), don't make the call. @@ -6053,12 +6042,12 @@ bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, // Strip the unbridged-cast placeholder expression off, if applicable. bool CFAudited = false; - if (Arg->getType() == Context.ARCUnbridgedCastTy && - FDecl && FDecl->hasAttr() && + if (Arg->getType() == Context.ARCUnbridgedCastTy && FDecl && + FDecl->hasAttr() && (!Param || !Param->hasAttr())) Arg = ObjC().stripARCUnbridgedCast(Arg); - else if (getLangOpts().ObjCAutoRefCount && - FDecl && FDecl->hasAttr() && + else if (getLangOpts().ObjCAutoRefCount && FDecl && + FDecl->hasAttr() && (!Param || !Param->hasAttr())) CFAudited = true; @@ -6124,7 +6113,7 @@ bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, AllArgs.push_back(arg.get()); } - // Otherwise do argument promotion, (C99 6.5.2.2p7). + // Otherwise do argument promotion, (C99 6.5.2.2p7). } else { for (Expr *A : Args.slice(ArgIx)) { ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); @@ -6146,13 +6135,11 @@ static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { TL = DTL.getOriginalLoc(); if (ArrayTypeLoc ATL = TL.getAs()) S.Diag(PVD->getLocation(), diag::note_callee_static_array) - << ATL.getLocalSourceRange(); + << ATL.getLocalSourceRange(); } -void -Sema::CheckStaticArrayArgument(SourceLocation CallLoc, - ParmVarDecl *Param, - const Expr *ArgExpr) { +void Sema::CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, + const Expr *ArgExpr) { // Static array parameters are not supported in C++. if (!Param || getLangOpts().CPlusPlus) return; @@ -6163,8 +6150,7 @@ Sema::CheckStaticArrayArgument(SourceLocation CallLoc, if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static) return; - if (ArgExpr->isNullPointerConstant(Context, - Expr::NPC_NeverValueDependent)) { + if (ArgExpr->isNullPointerConstant(Context, Expr::NPC_NeverValueDependent)) { Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); DiagnoseCalleeStaticArrayParam(*this, Param); return; @@ -6175,7 +6161,7 @@ Sema::CheckStaticArrayArgument(SourceLocation CallLoc, return; const ConstantArrayType *ArgCAT = - Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); + Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); if (!ArgCAT) return; @@ -6211,23 +6197,21 @@ static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); static bool isPlaceholderToRemoveAsArg(QualType type) { // Placeholders are never sugared. const BuiltinType *placeholder = dyn_cast(type); - if (!placeholder) return false; + if (!placeholder) + return false; switch (placeholder->getKind()) { - // Ignore all the non-placeholder types. -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + // Ignore all the non-placeholder types. +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - case BuiltinType::Id: +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" - // In practice we'll never use this, since all SVE types are sugared - // via TypedefTypes rather than exposed directly as BuiltinTypes. -#define SVE_TYPE(Name, Id, SingletonId) \ - case BuiltinType::Id: + // In practice we'll never use this, since all SVE types are sugared + // via TypedefTypes rather than exposed directly as BuiltinTypes. +#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/AArch64ACLETypes.def" -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: #include "clang/Basic/PPCTypes.def" #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" @@ -6270,7 +6254,6 @@ static bool isPlaceholderToRemoveAsArg(QualType type) { case BuiltinType::OMPArrayShaping: case BuiltinType::OMPIterator: return true; - } llvm_unreachable("bad builtin type kind"); } @@ -6282,8 +6265,10 @@ bool Sema::CheckArgsForPlaceholders(MultiExprArg args) { for (size_t i = 0, e = args.size(); i != e; i++) { if (isPlaceholderToRemoveAsArg(args[i]->getType())) { ExprResult result = CheckPlaceholderExpr(args[i]); - if (result.isInvalid()) hasInvalid = true; - else args[i] = result.get(); + if (result.isInvalid()) + hasInvalid = true; + else + args[i] = result.get(); } } return hasInvalid; @@ -6354,8 +6339,8 @@ static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionProtoType::ExtProtoInfo EPI; EPI.Variadic = FT->isVariadic(); - QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), - OverloadParams, EPI); + QualType OverloadTy = + Context.getFunctionType(FT->getReturnType(), OverloadParams, EPI); DeclContext *Parent = FDecl->getParent(); FunctionDecl *OverloadDecl = FunctionDecl::Create( Context, Parent, FDecl->getLocation(), FDecl->getLocation(), @@ -6363,14 +6348,14 @@ static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), false, /*hasPrototype=*/true); - SmallVector Params; + SmallVector Params; FT = cast(OverloadTy); for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { QualType ParamType = FT->getParamType(i); ParmVarDecl *Parm = ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), - SourceLocation(), nullptr, ParamType, - /*TInfo=*/nullptr, SC_None, nullptr); + SourceLocation(), nullptr, ParamType, + /*TInfo=*/nullptr, SC_None, nullptr); Parm->setScopeInfo(0, i); Params.push_back(Parm); } @@ -6476,7 +6461,6 @@ tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) return; - DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); // If the enclosing function is not dependent, then this lambda is // capture ready, so if we can capture this, do so. @@ -6585,7 +6569,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, bool AllowRecovery) { // Since this might be a postfix expression, get rid of ParenListExprs. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); Fn = Result.get(); if (CheckArgsForPlaceholders(ArgExprs)) @@ -6614,7 +6599,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, } if (Fn->getType() == Context.PseudoObjectTy) { ExprResult result = CheckPlaceholderExpr(Fn); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); Fn = result.get(); } @@ -6652,7 +6638,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, if (Fn->getType() == Context.UnknownAnyTy) { ExprResult result = rebuildUnknownAnyFunction(*this, Fn); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); Fn = result.get(); } @@ -6686,7 +6673,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, // If we're directly calling a function, get the appropriate declaration. if (Fn->getType() == Context.UnknownAnyTy) { ExprResult result = rebuildUnknownAnyFunction(*this, Fn); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); Fn = result.get(); } @@ -6737,7 +6725,7 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && FD->getBuiltinID()) { for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size(); - ++Idx) { + ++Idx) { ParmVarDecl *Param = FD->getParamDecl(Idx); if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || !ArgExprs[Idx]->getType()->isPointerType()) @@ -6750,10 +6738,14 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, // Add address space cast if target address spaces are different bool NeedImplicitASC = - ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. - ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS - // or from specific AS which has target AS matching that of Param. - getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); + ParamAS != LangAS::Default && // Pointer params in generic AS don't + // need special handling. + (ArgAS == + LangAS::Default || // We do allow implicit conversion from + // generic AS or from specific AS which has + // target AS matching that of Param. + getASTContext().getTargetAddressSpace(ArgAS) == + getASTContext().getTargetAddressSpace(ParamAS)); if (!NeedImplicitASC) continue; @@ -6769,9 +6761,8 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, ArgPtQuals.setAddressSpace(ParamAS); auto NewArgPtTy = Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); - auto NewArgTy = - Context.getQualifiedType(Context.getPointerType(NewArgPtTy), - ArgTy.getQualifiers()); + auto NewArgTy = Context.getQualifiedType( + Context.getPointerType(NewArgPtTy), ArgTy.getQualifiers()); // Finally perform an implicit address space cast ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, @@ -6968,7 +6959,8 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, if (Config) { // CUDA: Kernel calls must be to global functions if (FDecl && !FDecl->hasAttr()) - return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) + return ExprError( + Diag(LParenLoc, diag::err_kern_call_not_global_function) << FDecl << Fn->getSourceRange()); // CUDA: Kernel function must have 'void' return type @@ -6976,12 +6968,12 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, !FuncT->getReturnType()->getAs() && !FuncT->getReturnType()->isInstantiationDependentType()) return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) - << Fn->getType() << Fn->getSourceRange()); + << Fn->getType() << Fn->getSourceRange()); } else { // CUDA: Calls to global functions must be configured if (FDecl && FDecl->hasAttr()) return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) - << FDecl << Fn->getSourceRange()); + << FDecl << Fn->getSourceRange()); } } @@ -7017,9 +7009,11 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, const FunctionDecl *Def = nullptr; if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { Proto = Def->getType()->getAs(); - if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) + if (!Proto || + !(Proto->isVariadic() && Args.size() >= Def->param_size())) Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) - << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); + << (Args.size() > Def->param_size()) << FDecl + << Fn->getSourceRange(); } // If the function we're calling isn't a function prototype, but we have @@ -7118,9 +7112,9 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); } -ExprResult -Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, - SourceLocation RParenLoc, Expr *InitExpr) { +ExprResult Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, + SourceLocation RParenLoc, + Expr *InitExpr) { assert(Ty && "ActOnCompoundLiteral(): missing type"); assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); @@ -7132,9 +7126,10 @@ Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); } -ExprResult -Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, - SourceLocation RParenLoc, Expr *LiteralExpr) { +ExprResult Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, + TypeSourceInfo *TInfo, + SourceLocation RParenLoc, + Expr *LiteralExpr) { QualType literalType = TInfo->getType(); if (literalType->isArrayType()) { @@ -7170,20 +7165,21 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, return ExprError(); } } else if (!literalType->isDependentType() && - RequireCompleteType(LParenLoc, literalType, - diag::err_typecheck_decl_incomplete_type, - SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) + RequireCompleteType( + LParenLoc, literalType, + diag::err_typecheck_decl_incomplete_type, + SourceRange(LParenLoc, + LiteralExpr->getSourceRange().getEnd()))) return ExprError(); - InitializedEntity Entity - = InitializedEntity::InitializeCompoundLiteralInit(TInfo); - InitializationKind Kind - = InitializationKind::CreateCStyleCast(LParenLoc, - SourceRange(LParenLoc, RParenLoc), - /*InitList=*/true); + InitializedEntity Entity = + InitializedEntity::InitializeCompoundLiteralInit(TInfo); + InitializationKind Kind = InitializationKind::CreateCStyleCast( + LParenLoc, SourceRange(LParenLoc, RParenLoc), + /*InitList=*/true); InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); - ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, - &literalType); + ExprResult Result = + InitSeq.Perform(*this, Entity, Kind, LiteralExpr, &literalType); if (Result.isInvalid()) return ExprError(); LiteralExpr = Result.get(); @@ -7240,8 +7236,7 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK, LiteralExpr, IsFileScope); if (IsFileScope) { - if (!LiteralExpr->isTypeDependent() && - !LiteralExpr->isValueDependent() && + if (!LiteralExpr->isTypeDependent() && !LiteralExpr->isValueDependent() && !literalType->isDependentType()) // C99 6.5.2.5p3 if (CheckForConstantInitializer(LiteralExpr)) return ExprError(); @@ -7251,7 +7246,7 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, // "If the compound literal occurs inside the body of a function, the // type name shall not be qualified by an address-space qualifier." Diag(LParenLoc, diag::err_compound_literal_with_address_space) - << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); + << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); return ExprError(); } @@ -7282,9 +7277,9 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, return MaybeBindToTemporary(E); } -ExprResult -Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, - SourceLocation RBraceLoc) { +ExprResult Sema::ActOnInitList(SourceLocation LBraceLoc, + MultiExprArg InitArgList, + SourceLocation RBraceLoc) { // Only produce each kind of designated initialization diagnostic once. SourceLocation FirstDesignator; bool DiagnosedArrayDesignator = false; @@ -7304,14 +7299,14 @@ Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, if (!DiagnosedNestedDesignator && DIE->size() > 1) { DiagnosedNestedDesignator = true; Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) - << DIE->getDesignatorsSourceRange(); + << DIE->getDesignatorsSourceRange(); } for (auto &Desig : DIE->designators()) { if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { DiagnosedArrayDesignator = true; Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) - << Desig.getSourceRange(); + << Desig.getSourceRange(); } } @@ -7319,18 +7314,18 @@ Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, !isa(InitArgList[0])) { DiagnosedMixedDesignator = true; Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) - << DIE->getSourceRange(); + << DIE->getSourceRange(); Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) - << InitArgList[0]->getSourceRange(); + << InitArgList[0]->getSourceRange(); } } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && isa(InitArgList[0])) { DiagnosedMixedDesignator = true; auto *DIE = cast(InitArgList[0]); Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) - << DIE->getSourceRange(); + << DIE->getSourceRange(); Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) - << InitArgList[I]->getSourceRange(); + << InitArgList[I]->getSourceRange(); } } @@ -7350,9 +7345,9 @@ Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); } -ExprResult -Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, - SourceLocation RBraceLoc) { +ExprResult Sema::BuildInitList(SourceLocation LBraceLoc, + MultiExprArg InitArgList, + SourceLocation RBraceLoc) { // Semantic analysis for initializers is done by ActOnDeclarator() and // CheckInitializer() - it requires knowledge of the object being initialized. @@ -7364,7 +7359,8 @@ Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, // Ignore failures; dropping the entire initializer list because // of one failure would be terrible for indexing/etc. - if (result.isInvalid()) continue; + if (result.isInvalid()) + continue; InitArgList[I] = result.get(); } @@ -7381,7 +7377,8 @@ void Sema::maybeExtendBlockObject(ExprResult &E) { assert(E.get()->isPRValue()); // Only do this in an r-value context. - if (!getLangOpts().ObjCAutoRefCount) return; + if (!getLangOpts().ObjCAutoRefCount) + return; E = ImplicitCastExpr::Create( Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), @@ -7417,7 +7414,8 @@ CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { } case Type::STK_BlockPointer: return (SrcKind == Type::STK_BlockPointer - ? CK_BitCast : CK_AnyPointerToBlockPointerCast); + ? CK_BitCast + : CK_AnyPointerToBlockPointerCast); case Type::STK_ObjCObjectPointer: if (SrcKind == Type::STK_ObjCObjectPointer) return CK_BitCast; @@ -7480,13 +7478,13 @@ CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { return CK_IntegralToFloating; case Type::STK_IntegralComplex: Src = ImpCastExprToType(Src.get(), - DestTy->castAs()->getElementType(), - CK_IntegralCast); + DestTy->castAs()->getElementType(), + CK_IntegralCast); return CK_IntegralRealToComplex; case Type::STK_FloatingComplex: Src = ImpCastExprToType(Src.get(), - DestTy->castAs()->getElementType(), - CK_IntegralToFloating); + DestTy->castAs()->getElementType(), + CK_IntegralToFloating); return CK_FloatingRealToComplex; case Type::STK_MemberPointer: llvm_unreachable("member pointer type in C"); @@ -7608,7 +7606,8 @@ static bool breakDownVectorType(QualType type, uint64_t &len, // We allow lax conversion to and from non-vector types, but only if // they're real types (i.e. non-complex, non-pointer scalar types). - if (!type->isRealType()) return false; + if (!type->isRealType()) + return false; len = 1; eltType = type; @@ -7691,8 +7690,10 @@ bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { // depend on them). Most scalar OP ExtVector cases are handled by the // splat path anyway, which does what we want (convert, not bitcast). // What this rules out for ExtVectors is crazy things like char4*float. - if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; - if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; + if (srcTy->isScalarType() && destTy->isExtVectorType()) + return false; + if (destTy->isScalarType() && srcTy->isExtVectorType()) + return false; return areVectorTypesSameSize(srcTy, destTy); } @@ -7718,7 +7719,7 @@ bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { // OK, integer (vector) -> integer (vector) bitcast. break; - case LangOptions::LaxVectorConversionKind::All: + case LangOptions::LaxVectorConversionKind::All: break; } @@ -7753,14 +7754,14 @@ bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, if (Ty->isVectorType() || Ty->isIntegralType(Context)) { if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) return Diag(R.getBegin(), - Ty->isVectorType() ? - diag::err_invalid_conversion_between_vectors : - diag::err_invalid_conversion_between_vector_and_integer) - << VectorTy << Ty << R; + Ty->isVectorType() + ? diag::err_invalid_conversion_between_vectors + : diag::err_invalid_conversion_between_vector_and_integer) + << VectorTy << Ty << R; } else return Diag(R.getBegin(), diag::err_invalid_conversion_between_vector_and_scalar) - << VectorTy << Ty << R; + << VectorTy << Ty << R; Kind = CK_BitCast; return false; @@ -7813,8 +7814,8 @@ ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || (getLangOpts().OpenCL && !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { - Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) - << DestTy << SrcTy << R; + Diag(R.getBegin(), diag::err_invalid_conversion_between_ext_vectors) + << DestTy << SrcTy << R; return ExprError(); } Kind = CK_BitCast; @@ -7827,7 +7828,7 @@ ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, if (SrcTy->isPointerType()) return Diag(R.getBegin(), diag::err_invalid_conversion_between_vector_and_scalar) - << DestTy << SrcTy << R; + << DestTy << SrcTy << R; Kind = CK_VectorSplat; return prepareVectorSplat(DestTy, CastExpr); @@ -7868,10 +7869,9 @@ static void CheckSufficientAllocSize(Sema &S, QualType DestType, << Size.getQuantity() << TargetType << LhsSize->getQuantity(); } -ExprResult -Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, - Declarator &D, ParsedType &Ty, - SourceLocation RParenLoc, Expr *CastExpr) { +ExprResult Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, + Declarator &D, ParsedType &Ty, + SourceLocation RParenLoc, Expr *CastExpr) { assert(!D.isInvalidType() && (CastExpr != nullptr) && "ActOnCastExpr(): missing type or expr"); @@ -7895,8 +7895,9 @@ Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, // i.e. all the elements are integer constants. ParenExpr *PE = dyn_cast(CastExpr); ParenListExpr *PLE = dyn_cast(CastExpr); - if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) - && castType->isVectorType() && (PE || PLE)) { + if ((getLangOpts().AltiVec || getLangOpts().ZVector || + getLangOpts().OpenCL) && + castType->isVectorType() && (PE || PLE)) { if (PLE && PLE->getNumExprs() == 0) { Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); return ExprError(); @@ -7905,8 +7906,7 @@ Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); if (!E->isTypeDependent() && !E->getType()->isVectorType()) isVectorLiteral = true; - } - else + } else isVectorLiteral = true; } @@ -7920,7 +7920,8 @@ Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, // sequence of BinOp comma operators. if (isa(CastExpr)) { ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); CastExpr = Result.get(); } @@ -7987,16 +7988,12 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, Literal = ImpCastExprToType(Literal.get(), ElemTy, PrepareScalarCast(Literal, ElemTy)); return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); - } - else if (numExprs < numElems) { - Diag(E->getExprLoc(), - diag::err_incorrect_number_of_vector_initializers); + } else if (numExprs < numElems) { + Diag(E->getExprLoc(), diag::err_incorrect_number_of_vector_initializers); return ExprError(); - } - else + } else initExprs.append(exprs, exprs + numExprs); - } - else { + } else { // For OpenCL, when the number of initializers is a single value, // it will be replicated to all components of the vector. if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic && @@ -8014,14 +8011,14 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, } // FIXME: This means that pretty-printing the final AST will produce curly // braces instead of the original commas. - InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, - initExprs, LiteralRParenLoc); + InitListExpr *initE = new (Context) + InitListExpr(Context, LiteralLParenLoc, initExprs, LiteralRParenLoc); initE->setType(Ty); return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); } -ExprResult -Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { +ExprResult Sema::MaybeConvertParenListExprToParenExpr(Scope *S, + Expr *OrigExpr) { ParenListExpr *E = dyn_cast(OrigExpr); if (!E) return OrigExpr; @@ -8029,16 +8026,16 @@ Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { ExprResult Result(E->getExpr(0)); for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) - Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), - E->getExpr(i)); + Result = + ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), E->getExpr(i)); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); } -ExprResult Sema::ActOnParenListExpr(SourceLocation L, - SourceLocation R, +ExprResult Sema::ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val) { return ParenListExpr::Create(Context, L, Val, R); } @@ -8056,16 +8053,14 @@ bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc) { const Expr *NullExpr = LHSExpr; const Expr *NonPointerExpr = RHSExpr; - Expr::NullPointerConstantKind NullKind = - NullExpr->isNullPointerConstant(Context, - Expr::NPC_ValueDependentIsNotNull); + Expr::NullPointerConstantKind NullKind = NullExpr->isNullPointerConstant( + Context, Expr::NPC_ValueDependentIsNotNull); if (NullKind == Expr::NPCK_NotNull) { NullExpr = RHSExpr; NonPointerExpr = LHSExpr; - NullKind = - NullExpr->isNullPointerConstant(Context, - Expr::NPC_ValueDependentIsNotNull); + NullKind = NullExpr->isNullPointerConstant( + Context, Expr::NPC_ValueDependentIsNotNull); } if (NullKind == Expr::NPCK_NotNull) @@ -8098,15 +8093,16 @@ static bool checkCondition(Sema &S, const Expr *Cond, // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) - << CondTy << Cond->getSourceRange(); + << CondTy << Cond->getSourceRange(); return true; } // C99 6.5.15p2 - if (CondTy->isScalarType()) return false; + if (CondTy->isScalarType()) + return false; S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) - << CondTy << Cond->getSourceRange(); + << CondTy << Cond->getSourceRange(); return true; } @@ -8116,7 +8112,7 @@ static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy) { if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || !NullExpr.get()->isNullPointerConstant(S.Context, - Expr::NPC_ValueDependentIsNull)) + Expr::NPC_ValueDependentIsNull)) return true; NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); @@ -8178,7 +8174,8 @@ static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, return QualType(); } - unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); + unsigned MergedCVRQual = + lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; lhQual.removeCVRQualifiers(); rhQual.removeCVRQualifiers(); @@ -8278,8 +8275,8 @@ static QualType checkConditionalBlockPointerCompatibility(Sema &S, return destType; } S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) - << LHSTy << RHSTy << LHS.get()->getSourceRange() - << RHS.get()->getSourceRange(); + << LHSTy << RHSTy << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return QualType(); } @@ -8288,10 +8285,8 @@ static QualType checkConditionalBlockPointerCompatibility(Sema &S, } /// Return the resulting type when the operands are both pointers. -static QualType -checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, - ExprResult &RHS, - SourceLocation Loc) { +static QualType checkConditionalObjectPointersCompatibility( + Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc) { // get the pointer types QualType LHSTy = LHS.get()->getType(); QualType RHSTy = RHS.get()->getType(); @@ -8303,8 +8298,8 @@ checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, // ignore qualifiers on void (C99 6.5.15p3, clause 6) if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { // Figure out necessary qualifiers (C99 6.5.15p6) - QualType destPointee - = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); + QualType destPointee = + S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); QualType destType = S.Context.getPointerType(destPointee); // Add qualifiers if necessary. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); @@ -8313,8 +8308,8 @@ checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, return destType; } if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { - QualType destPointee - = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); + QualType destPointee = + S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); QualType destType = S.Context.getPointerType(destPointee); // Add qualifiers if necessary. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); @@ -8329,7 +8324,7 @@ checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, /// Return false if the first expression is not an integer and the second /// expression is not a pointer, true otherwise. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, - Expr* PointerExpr, SourceLocation Loc, + Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr) { if (!PointerExpr->getType()->isPointerType() || !Int.get()->getType()->isIntegerType()) @@ -8339,8 +8334,8 @@ static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) - << Expr1->getType() << Expr2->getType() - << Expr1->getSourceRange() << Expr2->getSourceRange(); + << Expr1->getType() << Expr2->getType() << Expr1->getSourceRange() + << Expr2->getSourceRange(); Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), CK_IntegralToPointer); return true; @@ -8371,19 +8366,19 @@ static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, // For conversion purposes, we ignore any qualifiers. // For example, "const float" and "float" are equivalent. QualType LHSType = - S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); + S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); QualType RHSType = - S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); + S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) - << LHSType << LHS.get()->getSourceRange(); + << LHSType << LHS.get()->getSourceRange(); return QualType(); } if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) - << RHSType << RHS.get()->getSourceRange(); + << RHSType << RHS.get()->getSourceRange(); return QualType(); } @@ -8397,8 +8392,8 @@ static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, /*IsCompAssign = */ false); // Finally, we have two differing integer types. - return handleIntegerConversion - (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); + return handleIntegerConversion( + S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); } /// Convert scalar operands to a vector that matches the @@ -8412,11 +8407,12 @@ static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, /// into a vector of that type where the length matches the condition /// vector type. s6.11.6 requires that the element types of the result /// and the condition must have the same number of bits. -static QualType -OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, - QualType CondTy, SourceLocation QuestionLoc) { +static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, + ExprResult &RHS, QualType CondTy, + SourceLocation QuestionLoc) { QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); - if (ResTy.isNull()) return QualType(); + if (ResTy.isNull()) + return QualType(); const VectorType *CV = CondTy->getAs(); assert(CV); @@ -8426,8 +8422,8 @@ OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); // Ensure that all types have the same number of bits - if (S.Context.getTypeSize(CV->getElementType()) - != S.Context.getTypeSize(ResTy)) { + if (S.Context.getTypeSize(CV->getElementType()) != + S.Context.getTypeSize(ResTy)) { // Since VectorTy is created internally, it does not pretty print // with an OpenCL name. Instead, we just print a description. std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); @@ -8435,7 +8431,7 @@ OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, llvm::raw_svector_ostream OS(Str); OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) - << CondTy << OS.str(); + << CondTy << OS.str(); return QualType(); } @@ -8454,10 +8450,11 @@ static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, const VectorType *CondTy = Cond->getType()->getAs(); assert(CondTy); QualType EleTy = CondTy->getElementType(); - if (EleTy->isIntegerType()) return false; + if (EleTy->isIntegerType()) + return false; S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) - << Cond->getType() << Cond->getSourceRange(); + << Cond->getType() << Cond->getSourceRange(); return true; } @@ -8475,7 +8472,7 @@ static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, if (CV->getNumElements() != RV->getNumElements()) { S.Diag(QuestionLoc, diag::err_conditional_vector_size) - << CondTy << VecResTy; + << CondTy << VecResTy; return true; } @@ -8496,10 +8493,9 @@ static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, /// Return the resulting type for the conditional operator in /// OpenCL (aka "ternary selection operator", OpenCL v1.1 /// s6.3.i) when the condition is a vector type. -static QualType -OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, - ExprResult &LHS, ExprResult &RHS, - SourceLocation QuestionLoc) { +static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, + ExprResult &LHS, ExprResult &RHS, + SourceLocation QuestionLoc) { Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); if (Cond.isInvalid()) return QualType(); @@ -8560,11 +8556,13 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, SourceLocation QuestionLoc) { ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); - if (!LHSResult.isUsable()) return QualType(); + if (!LHSResult.isUsable()) + return QualType(); LHS = LHSResult; ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); - if (!RHSResult.isUsable()) return QualType(); + if (!RHSResult.isUsable()) + return QualType(); RHS = RHSResult; // C++ is sufficiently different to merit its own checker. @@ -8623,16 +8621,16 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, // Diagnose attempts to convert between __ibm128, __float128 and long double // where such conversions currently can't be handled. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { - Diag(QuestionLoc, - diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) + << LHSTy << RHSTy << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return QualType(); } // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary // selection operator (?:). - if (getLangOpts().OpenCL && - ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { + if (getLangOpts().OpenCL && ((int)checkBlockType(*this, LHS.get()) | + (int)checkBlockType(*this, RHS.get()))) { return QualType(); } @@ -8691,8 +8689,10 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has // the type of the other operand." - if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; - if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; + if (!checkConditionalNullPointer(*this, RHS, LHSTy)) + return LHSTy; + if (!checkConditionalNullPointer(*this, LHS, RHSTy)) + return RHSTy; // All objective-c pointer type analysis is done here. QualType compositeType = @@ -8702,7 +8702,6 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, if (!compositeType.isNull()) return compositeType; - // Handle block pointer types. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, @@ -8716,10 +8715,10 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, // GCC compatibility: soften pointer/integer mismatch. Note that // null pointers have been filtered out by this point. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, - /*IsIntFirstExpr=*/true)) + /*IsIntFirstExpr=*/true)) return RHSTy; if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, - /*IsIntFirstExpr=*/false)) + /*IsIntFirstExpr=*/false)) return LHSTy; // Emit a better diagnostic if one of the expressions is a null pointer @@ -8735,8 +8734,8 @@ QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, // Otherwise, the operands are not compatible. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) - << LHSTy << RHSTy << LHS.get()->getSourceRange() - << RHS.get()->getSourceRange(); + << LHSTy << RHSTy << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return QualType(); } @@ -8748,9 +8747,9 @@ static void SuggestParentheses(Sema &Self, SourceLocation Loc, SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && EndLoc.isValid()) { - Self.Diag(Loc, Note) - << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") - << FixItHint::CreateInsertion(EndLoc, ")"); + Self.Diag(Loc, Note) << FixItHint::CreateInsertion(ParenRange.getBegin(), + "(") + << FixItHint::CreateInsertion(EndLoc, ")"); } else { // We can't display the parentheses, so just show the bare note. Self.Diag(Loc, Note) << ParenRange; @@ -8799,8 +8798,8 @@ static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, // Make sure this is really a binary operator that is safe to pass into // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. OverloadedOperatorKind OO = Call->getOperator(); - if (OO < OO_Plus || OO > OO_Arrow || - OO == OO_PlusPlus || OO == OO_MinusMinus) + if (OO < OO_Plus || OO > OO_Arrow || OO == OO_PlusPlus || + OO == OO_MinusMinus) return false; BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); @@ -8856,9 +8855,8 @@ static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, ? diag::warn_precedence_bitwise_conditional : diag::warn_precedence_conditional; - Self.Diag(OpLoc, DiagID) - << Condition->getSourceRange() - << BinaryOperator::getOpcodeStr(CondOpcode); + Self.Diag(OpLoc, DiagID) << Condition->getSourceRange() + << BinaryOperator::getOpcodeStr(CondOpcode); SuggestParentheses( Self, OpLoc, @@ -8898,7 +8896,7 @@ static QualType computeConditionalNullability(QualType ResTy, bool IsBin, MergedKind = NullabilityKind::NonNull; else MergedKind = RHSKind; - // Compute nullability of a normal conditional expression. + // Compute nullability of a normal conditional expression. } else { if (LHSKind == NullabilityKind::Nullable || RHSKind == NullabilityKind::Nullable) @@ -8924,9 +8922,8 @@ static QualType computeConditionalNullability(QualType ResTy, bool IsBin, } ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, - SourceLocation ColonLoc, - Expr *CondExpr, Expr *LHSExpr, - Expr *RHSExpr) { + SourceLocation ColonLoc, Expr *CondExpr, + Expr *LHSExpr, Expr *RHSExpr) { // If this is the gnu "x ?: y" extension, analyze the types as though the LHS // was the condition. OpaqueValueExpr *opaqueValue = nullptr; @@ -8938,18 +8935,17 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, // as Objective-C++'s dictionary subscripting syntax. if (commonExpr->hasPlaceholderType()) { ExprResult result = CheckPlaceholderExpr(commonExpr); - if (!result.isUsable()) return ExprError(); + if (!result.isUsable()) + return ExprError(); commonExpr = result.get(); } // We usually want to apply unary conversions *before* saving, except // in the special case of a C++ l-value conditional. - if (!(getLangOpts().CPlusPlus - && !commonExpr->isTypeDependent() - && commonExpr->getValueKind() == RHSExpr->getValueKind() - && commonExpr->isGLValue() - && commonExpr->isOrdinaryOrBitFieldObject() - && RHSExpr->isOrdinaryOrBitFieldObject() - && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { + if (!(getLangOpts().CPlusPlus && !commonExpr->isTypeDependent() && + commonExpr->getValueKind() == RHSExpr->getValueKind() && + commonExpr->isGLValue() && commonExpr->isOrdinaryOrBitFieldObject() && + RHSExpr->isOrdinaryOrBitFieldObject() && + Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { ExprResult commonRes = UsualUnaryConversions(commonExpr); if (commonRes.isInvalid()) return ExprError(); @@ -8966,11 +8962,9 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, commonExpr = MatExpr.get(); } - opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), - commonExpr->getType(), - commonExpr->getValueKind(), - commonExpr->getObjectKind(), - commonExpr); + opaqueValue = new (Context) OpaqueValueExpr( + commonExpr->getExprLoc(), commonExpr->getType(), + commonExpr->getValueKind(), commonExpr->getObjectKind(), commonExpr); LHSExpr = CondExpr = opaqueValue; } @@ -8978,10 +8972,9 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, ExprValueKind VK = VK_PRValue; ExprObjectKind OK = OK_Ordinary; ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; - QualType result = CheckConditionalOperands(Cond, LHS, RHS, - VK, OK, QuestionLoc); - if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || - RHS.isInvalid()) + QualType result = + CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); + if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) return ExprError(); DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), @@ -8989,8 +8982,8 @@ ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, CheckBoolLikeConversion(Cond.get(), QuestionLoc); - result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, - Context); + result = + computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, Context); if (!commonExpr) return new (Context) @@ -9144,9 +9137,9 @@ static AssignConvertType checkPointerTypesForAssignment(Sema &S, if (isa(lhptee) && isa(rhptee)) { do { std::tie(lhptee, lhq) = - cast(lhptee)->getPointeeType().split().asPair(); + cast(lhptee)->getPointeeType().split().asPair(); std::tie(rhptee, rhq) = - cast(rhptee)->getPointeeType().split().asPair(); + cast(rhptee)->getPointeeType().split().asPair(); // Inconsistent address spaces at this point is invalid, even if the // address spaces would be compatible. @@ -9721,8 +9714,8 @@ static void ConstructTransparentUnion(Sema &S, ASTContext &C, // Build an initializer list that designates the appropriate member // of the transparent union. Expr *E = EResult.get(); - InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), - E, SourceLocation()); + InitListExpr *Initializer = + new (C) InitListExpr(C, SourceLocation(), E, SourceLocation()); Initializer->setType(UnionType); Initializer->setInitializedFieldInUnion(Field); @@ -9765,8 +9758,7 @@ Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, if (RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { - RHS = ImpCastExprToType(RHS.get(), it->getType(), - CK_NullToPointer); + RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_NullToPointer); InitField = it; break; } @@ -9824,13 +9816,12 @@ AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType, RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), AssignmentAction::Assigning); } else { - ImplicitConversionSequence ICS = - TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), - /*SuppressUserConversions=*/false, - AllowedExplicit::None, - /*InOverloadResolution=*/false, - /*CStyle=*/false, - /*AllowObjCWritebackConversion=*/false); + ImplicitConversionSequence ICS = TryImplicitConversion( + RHS.get(), LHSType.getUnqualifiedType(), + /*SuppressUserConversions=*/false, AllowedExplicit::None, + /*InOverloadResolution=*/false, + /*CStyle=*/false, + /*AllowObjCWritebackConversion=*/false); if (ICS.isFailure()) return AssignConvertType::Incompatible; RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), @@ -10024,27 +10015,27 @@ struct OriginalOperand { Expr *Orig; NamedDecl *Conversion; }; -} +} // namespace QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS) { OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); Diag(Loc, diag::err_typecheck_invalid_operands) - << OrigLHS.getType() << OrigRHS.getType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << OrigLHS.getType() << OrigRHS.getType() << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); // If a user-defined conversion was applied to either of the operands prior // to applying the built-in operator rules, tell the user about it. if (OrigLHS.Conversion) { Diag(OrigLHS.Conversion->getLocation(), diag::note_typecheck_invalid_operands_converted) - << 0 << LHS.get()->getType(); + << 0 << LHS.get()->getType(); } if (OrigRHS.Conversion) { Diag(OrigRHS.Conversion->getLocation(), diag::note_typecheck_invalid_operands_converted) - << 1 << RHS.get()->getType(); + << 1 << RHS.get()->getType(); } return QualType(); @@ -10087,10 +10078,8 @@ QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, /// \param scalar - if non-null, actually perform the conversions /// \return true if the operation fails (but without diagnosing the failure) static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, - QualType scalarTy, - QualType vectorEltTy, - QualType vectorTy, - unsigned &DiagID) { + QualType scalarTy, QualType vectorEltTy, + QualType vectorTy, unsigned &DiagID) { // The conversion to apply to the scalar before splatting it, // if necessary. CastKind scalarCast = CK_NoOp; @@ -10098,9 +10087,10 @@ static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) { scalarCast = CK_IntegralToBoolean; } else if (vectorEltTy->isIntegralType(S.Context)) { - if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || - (scalarTy->isIntegerType() && - S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { + if (S.getLangOpts().OpenCL && + (scalarTy->isRealFloatingType() || + (scalarTy->isIntegerType() && + S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; return true; } @@ -10115,8 +10105,7 @@ static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, return true; } scalarCast = CK_FloatingCast; - } - else if (scalarTy->isIntegralType(S.Context)) + } else if (scalarTy->isIntegralType(S.Context)) scalarCast = CK_IntegralToFloating; else return true; @@ -10545,11 +10534,11 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, if (!IsCompAssign) { *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); return VecType; - // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding - // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' - // type. Note that this is already done by non-compound assignments in - // CheckAssignmentConstraints. If it's a scalar type, only bitcast for - // <1 x T> -> T. The result is also a vector type. + // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding + // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' + // type. Note that this is already done by non-compound assignments in + // CheckAssignmentConstraints. If it's a scalar type, only bitcast for + // <1 x T> -> T. The result is also a vector type. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || (OtherType->isScalarType() && VT->getNumElements() == 1)) { ExprResult *RHSExpr = &RHS; @@ -10564,8 +10553,8 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, if ((!RHSVecType && !RHSType->isRealType()) || (!LHSVecType && !LHSType->isRealType())) { Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) - << LHSType << RHSType - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return QualType(); } @@ -10573,15 +10562,13 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, // If the operands are of more than one vector type, then an error shall // occur. Implicit conversions between vector types are not permitted, per // section 6.2.1. - if (getLangOpts().OpenCL && - RHSVecType && isa(RHSVecType) && + if (getLangOpts().OpenCL && RHSVecType && isa(RHSVecType) && LHSVecType && isa(LHSVecType)) { - Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType - << RHSType; + Diag(Loc, diag::err_opencl_implicit_vector_conversion) + << LHSType << RHSType; return QualType(); } - // If there is a vector type that is not a ExtVector and a scalar, we reach // this point if scalar could not be converted to the vector's element type // without truncation. @@ -10590,17 +10577,15 @@ QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, QualType Scalar = LHSVecType ? RHSType : LHSType; QualType Vector = LHSVecType ? LHSType : RHSType; unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; - Diag(Loc, - diag::err_typecheck_vector_not_convertable_implict_truncation) + Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) << ScalarOrVector << Scalar << Vector; return QualType(); } // Otherwise, use the generic diagnostic. - Diag(Loc, DiagID) - << LHSType << RHSType - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return QualType(); } @@ -10714,8 +10699,8 @@ static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, return; S.Diag(Loc, diag::warn_null_in_comparison_operation) - << LHSNull /* LHS is NULL */ << NonNullType - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << LHSNull /* LHS is NULL */ << NonNullType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); } static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, @@ -10758,7 +10743,7 @@ static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, } static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, - SourceLocation Loc) { + SourceLocation Loc) { const auto *LUE = dyn_cast(LHS); const auto *RUE = dyn_cast(RHS); if (!LUE || !RUE) @@ -10805,7 +10790,7 @@ static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, } } -static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, +static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv) { // Check for division/remainder by zero. @@ -10815,7 +10800,7 @@ static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, RHSValue.Val.getInt() == 0) S.DiagRuntimeBehavior(Loc, RHS.get(), S.PDiag(diag::warn_remainder_division_by_zero) - << IsDiv << RHS.get()->getSourceRange()); + << IsDiv << RHS.get()->getSourceRange()); } static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, @@ -10902,8 +10887,8 @@ QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, return compType; } -QualType Sema::CheckRemainderOperands( - ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { +QualType Sema::CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, + SourceLocation Loc, bool IsCompAssign) { checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); // Note: This check is here to simplify the double exclusions of @@ -10970,19 +10955,19 @@ QualType Sema::CheckRemainderOperands( static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr) { S.Diag(Loc, S.getLangOpts().CPlusPlus - ? diag::err_typecheck_pointer_arith_void_type - : diag::ext_gnu_void_ptr) - << 1 /* two pointers */ << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + ? diag::err_typecheck_pointer_arith_void_type + : diag::ext_gnu_void_ptr) + << 1 /* two pointers */ << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); } /// Diagnose invalid arithmetic on a void pointer. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer) { S.Diag(Loc, S.getLangOpts().CPlusPlus - ? diag::err_typecheck_pointer_arith_void_type - : diag::ext_gnu_void_ptr) - << 0 /* one pointer */ << Pointer->getSourceRange(); + ? diag::err_typecheck_pointer_arith_void_type + : diag::ext_gnu_void_ptr) + << 0 /* one pointer */ << Pointer->getSourceRange(); } /// Diagnose invalid arithmetic on a null pointer. @@ -10993,11 +10978,10 @@ static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom) { if (IsGNUIdiom) - S.Diag(Loc, diag::warn_gnu_null_ptr_arith) - << Pointer->getSourceRange(); + S.Diag(Loc, diag::warn_gnu_null_ptr_arith) << Pointer->getSourceRange(); else S.Diag(Loc, diag::warn_pointer_arith_null_ptr) - << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); + << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); } /// Diagnose invalid subraction on a null pointer. @@ -11024,14 +11008,15 @@ static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, assert(LHS->getType()->isAnyPointerType()); assert(RHS->getType()->isAnyPointerType()); S.Diag(Loc, S.getLangOpts().CPlusPlus - ? diag::err_typecheck_pointer_arith_function_type - : diag::ext_gnu_ptr_func_arith) - << 1 /* two pointers */ << LHS->getType()->getPointeeType() - // We only show the second type if it differs from the first. - << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), - RHS->getType()) - << RHS->getType()->getPointeeType() - << LHS->getSourceRange() << RHS->getSourceRange(); + ? diag::err_typecheck_pointer_arith_function_type + : diag::ext_gnu_ptr_func_arith) + << 1 /* two pointers */ + << LHS->getType()->getPointeeType() + // We only show the second type if it differs from the first. + << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), + RHS->getType()) + << RHS->getType()->getPointeeType() << LHS->getSourceRange() + << RHS->getSourceRange(); } /// Diagnose invalid arithmetic on a function pointer. @@ -11039,11 +11024,11 @@ static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer) { assert(Pointer->getType()->isAnyPointerType()); S.Diag(Loc, S.getLangOpts().CPlusPlus - ? diag::err_typecheck_pointer_arith_function_type - : diag::ext_gnu_ptr_func_arith) - << 0 /* one pointer */ << Pointer->getType()->getPointeeType() - << 0 /* one pointer, so only one type */ - << Pointer->getSourceRange(); + ? diag::err_typecheck_pointer_arith_function_type + : diag::ext_gnu_ptr_func_arith) + << 0 /* one pointer */ << Pointer->getType()->getPointeeType() + << 0 /* one pointer, so only one type */ + << Pointer->getSourceRange(); } /// Emit error if Operand is incomplete pointer type @@ -11077,7 +11062,8 @@ static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, if (const AtomicType *ResAtomicType = ResType->getAs()) ResType = ResAtomicType->getValueType(); - if (!ResType->isAnyPointerType()) return true; + if (!ResType->isAnyPointerType()) + return true; QualType PointeeTy = ResType->getPointeeType(); if (PointeeTy->isVoidType()) { @@ -11089,7 +11075,8 @@ static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, return !S.getLangOpts().CPlusPlus; } - if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; + if (checkArithmeticIncompletePointerType(S, Loc, Operand)) + return false; return true; } @@ -11107,11 +11094,14 @@ static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr) { bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); - if (!isLHSPointer && !isRHSPointer) return true; + if (!isLHSPointer && !isRHSPointer) + return true; QualType LHSPointeeTy, RHSPointeeTy; - if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); - if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); + if (isLHSPointer) + LHSPointeeTy = LHSExpr->getType()->getPointeeType(); + if (isRHSPointer) + RHSPointeeTy = RHSExpr->getType()->getPointeeType(); // if both are pointers check if operation is valid wrt address spaces if (isLHSPointer && isRHSPointer) { @@ -11129,9 +11119,12 @@ static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); if (isLHSVoidPtr || isRHSVoidPtr) { - if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); - else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); - else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); + if (!isRHSVoidPtr) + diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); + else if (!isLHSVoidPtr) + diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); + else + diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); return !S.getLangOpts().CPlusPlus; } @@ -11139,10 +11132,12 @@ static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); if (isLHSFuncPtr || isRHSFuncPtr) { - if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); - else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, - RHSExpr); - else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); + if (!isRHSFuncPtr) + diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); + else if (!isLHSFuncPtr) + diagnoseArithmeticOnFunctionPointer(S, Loc, RHSExpr); + else + diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); return !S.getLangOpts().CPlusPlus; } @@ -11159,15 +11154,15 @@ static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, /// literal. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr) { - StringLiteral* StrExpr = dyn_cast(LHSExpr->IgnoreImpCasts()); - Expr* IndexExpr = RHSExpr; + StringLiteral *StrExpr = dyn_cast(LHSExpr->IgnoreImpCasts()); + Expr *IndexExpr = RHSExpr; if (!StrExpr) { StrExpr = dyn_cast(RHSExpr->IgnoreImpCasts()); IndexExpr = LHSExpr; } - bool IsStringPlusInt = StrExpr && - IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); + bool IsStringPlusInt = + StrExpr && IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); if (!IsStringPlusInt || IndexExpr->isValueDependent()) return; @@ -11215,11 +11210,9 @@ static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); const QualType CharType = CharExpr->getType(); - if (!CharType->isAnyCharacterType() && - CharType->isIntegerType() && + if (!CharType->isAnyCharacterType() && CharType->isIntegerType() && llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { - Self.Diag(OpLoc, diag::warn_string_plus_char) - << DiagRange << Ctx.CharTy; + Self.Diag(OpLoc, diag::warn_string_plus_char) << DiagRange << Ctx.CharTy; } else { Self.Diag(OpLoc, diag::warn_string_plus_char) << DiagRange << CharExpr->getType(); @@ -11243,14 +11236,14 @@ static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, assert(LHSExpr->getType()->isAnyPointerType()); assert(RHSExpr->getType()->isAnyPointerType()); S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) - << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() - << RHSExpr->getSourceRange(); + << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() + << RHSExpr->getSourceRange(); } // C99 6.5.6 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, - QualType* CompLHSTy) { + QualType *CompLHSTy) { checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); if (LHS.get()->getType()->isVectorType() || @@ -11261,7 +11254,8 @@ QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, /*AllowBoolConversions*/ getLangOpts().ZVector, /*AllowBooleanOperation*/ false, /*ReportInvalid*/ true); - if (CompLHSTy) *CompLHSTy = compType; + if (CompLHSTy) + *CompLHSTy = compType; return compType; } @@ -11297,7 +11291,8 @@ QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, // handle the common case first (both operands are arithmetic). if (!compType.isNull() && compType->isArithmeticType()) { - if (CompLHSTy) *CompLHSTy = compType; + if (CompLHSTy) + *CompLHSTy = compType; return compType; } @@ -11332,10 +11327,9 @@ QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, Context, Expr::NPC_ValueDependentIsNotNull)) { // In C++ adding zero to a null pointer is defined. Expr::EvalResult KnownVal; - if (!getLangOpts().CPlusPlus || - (!IExp->isValueDependent() && - (!IExp->EvaluateAsInt(KnownVal, Context) || - KnownVal.Val.getInt() != 0))) { + if (!getLangOpts().CPlusPlus || (!IExp->isValueDependent() && + (!IExp->EvaluateAsInt(KnownVal, Context) || + KnownVal.Val.getInt() != 0))) { // Check the conditions to see if this is the 'p = nullptr + n' idiom. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( Context, BO_Add, PExp, IExp); @@ -11388,7 +11382,8 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, /*AllowBoolConversions*/ getLangOpts().ZVector, /*AllowBooleanOperation*/ false, /*ReportInvalid*/ true); - if (CompLHSTy) *CompLHSTy = compType; + if (CompLHSTy) + *CompLHSTy = compType; return compType; } @@ -11420,7 +11415,8 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, // Handle the common case first (both operands are arithmetic). if (!compType.isNull() && compType->isArithmeticType()) { - if (CompLHSTy) *CompLHSTy = compType; + if (CompLHSTy) + *CompLHSTy = compType; return compType; } @@ -11447,8 +11443,8 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, // Subtracting from a null pointer should produce a warning. // The last argument to the diagnose call says this doesn't match the // GNU int-to-pointer idiom. - if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, - Expr::NPC_ValueDependentIsNotNull)) { + if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant( + Context, Expr::NPC_ValueDependentIsNotNull)) { // In C++ adding zero to a null pointer is defined. Expr::EvalResult KnownVal; if (!getLangOpts().CPlusPlus || @@ -11463,16 +11459,17 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, return QualType(); // Check array bounds for pointer arithemtic - CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, - /*AllowOnePastEnd*/true, /*IndexNegated*/true); + CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/ nullptr, + /*AllowOnePastEnd*/ true, /*IndexNegated*/ true); - if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); + if (CompLHSTy) + *CompLHSTy = LHS.get()->getType(); return LHS.get()->getType(); } // Handle pointer-pointer subtractions. - if (const PointerType *RHSPTy - = RHS.get()->getType()->getAs()) { + if (const PointerType *RHSPTy = + RHS.get()->getType()->getAs()) { QualType rpointee = RHSPTy->getPointeeType(); if (getLangOpts().CPlusPlus) { @@ -11490,8 +11487,8 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, } } - if (!checkArithmeticBinOpPointerOperands(*this, Loc, - LHS.get(), RHS.get())) + if (!checkArithmeticBinOpPointerOperands(*this, Loc, LHS.get(), + RHS.get())) return QualType(); bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( @@ -11511,13 +11508,14 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); if (ElementSize.isZero()) { - Diag(Loc,diag::warn_sub_ptr_zero_size_types) - << rpointee.getUnqualifiedType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + Diag(Loc, diag::warn_sub_ptr_zero_size_types) + << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); } } - if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); + if (CompLHSTy) + *CompLHSTy = LHS.get()->getType(); return Context.getPointerDiffType(); } } @@ -11533,11 +11531,12 @@ static bool isScopedEnumerationType(QualType T) { return false; } -static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, +static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType) { - // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), - // so skip remaining warnings as we don't want to modify values within Sema. + // OpenCL 6.3j: shift values are effectively % word size of LHS (more + // defined), so skip remaining warnings as we don't want to modify values + // within Sema. if (S.getLangOpts().OpenCL) return; @@ -11625,8 +11624,8 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, // turned off separately if needed. if (ResultBits - 1 == LeftSize) { S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) - << HexResult << LHSType - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << HexResult << LHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); return; } @@ -11644,18 +11643,20 @@ static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && !LHS.get()->getType()->isVectorType()) { S.Diag(Loc, diag::err_shift_rhs_only_vector) - << RHS.get()->getType() << LHS.get()->getType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << RHS.get()->getType() << LHS.get()->getType() + << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); return QualType(); } if (!IsCompAssign) { LHS = S.UsualUnaryConversions(LHS.get()); - if (LHS.isInvalid()) return QualType(); + if (LHS.isInvalid()) + return QualType(); } RHS = S.UsualUnaryConversions(RHS.get()); - if (RHS.isInvalid()) return QualType(); + if (RHS.isInvalid()) + return QualType(); QualType LHSType = LHS.get()->getType(); // Note that LHS might be a scalar because the routine calls not only in @@ -11680,13 +11681,13 @@ static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, // The operands need to be integers. if (!LHSEleType->isIntegerType()) { S.Diag(Loc, diag::err_typecheck_expect_int) - << LHS.get()->getType() << LHS.get()->getSourceRange(); + << LHS.get()->getType() << LHS.get()->getSourceRange(); return QualType(); } if (!RHSEleType->isIntegerType()) { S.Diag(Loc, diag::err_typecheck_expect_int) - << RHS.get()->getType() << RHS.get()->getSourceRange(); + << RHS.get()->getType() << RHS.get()->getSourceRange(); return QualType(); } @@ -11695,7 +11696,7 @@ static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, if (IsCompAssign) return RHSType; if (LHSEleType != RHSEleType) { - LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); + LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, CK_IntegralCast); LHSEleType = RHSEleType; } QualType VecTy = @@ -11708,8 +11709,8 @@ static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, // that the number of elements is the same as LHS... if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) - << LHS.get()->getType() << RHS.get()->getType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << LHS.get()->getType() << RHS.get()->getType() + << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); return QualType(); } if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { @@ -11725,7 +11726,7 @@ static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, } else { // ...else expand RHS to match the number of elements in LHS. QualType VecTy = - S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); + S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); } @@ -11860,7 +11861,8 @@ QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, if (LHS.isInvalid()) return QualType(); QualType LHSType = LHS.get()->getType(); - if (IsCompAssign) LHS = OldLHS; + if (IsCompAssign) + LHS = OldLHS; // The RHS is simpler. RHS = UsualUnaryConversions(RHS.get()); @@ -11890,8 +11892,8 @@ static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, bool IsError) { S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers : diag::ext_typecheck_comparison_of_distinct_pointers) - << LHS.get()->getType() << RHS.get()->getType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << LHS.get()->getType() << RHS.get()->getType() + << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); } /// Returns false if the pointers are converted to a composite type, @@ -11916,7 +11918,7 @@ static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, if (T.isNull()) { if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) - diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); + diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/ true); else S.InvalidOperands(Loc, LHS, RHS); return true; @@ -11931,8 +11933,8 @@ static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, bool IsError) { S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void : diag::ext_typecheck_comparison_of_fptr_to_void) - << LHS.get()->getType() << RHS.get()->getType() - << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + << LHS.get()->getType() << RHS.get()->getType() + << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); } static bool isObjCObjectLiteral(ExprResult &E) { @@ -11950,7 +11952,7 @@ static bool isObjCObjectLiteral(ExprResult &E) { static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { const ObjCObjectPointerType *Type = - LHS->getType()->getAs(); + LHS->getType()->getAs(); // If this is not actually an Objective-C object, bail out. if (!Type) @@ -11997,7 +11999,7 @@ static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, - BinaryOperator::Opcode Opc){ + BinaryOperator::Opcode Opc) { Expr *Literal; Expr *Other; if (isObjCObjectLiteral(LHS)) { @@ -12025,22 +12027,22 @@ static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, if (LiteralKind == SemaObjC::LK_String) S.Diag(Loc, diag::warn_objc_string_literal_comparison) - << Literal->getSourceRange(); + << Literal->getSourceRange(); else S.Diag(Loc, diag::warn_objc_literal_comparison) - << LiteralKind << Literal->getSourceRange(); + << LiteralKind << Literal->getSourceRange(); if (BinaryOperator::isEqualityOp(Opc) && hasIsEqualMethod(S, LHS.get(), RHS.get())) { SourceLocation Start = LHS.get()->getBeginLoc(); SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); CharSourceRange OpRange = - CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); + CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); S.Diag(Loc, diag::note_objc_literal_comparison_isequal) - << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") - << FixItHint::CreateReplacement(OpRange, " isEqual:") - << FixItHint::CreateInsertion(End, "]"); + << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") + << FixItHint::CreateReplacement(OpRange, " isEqual:") + << FixItHint::CreateInsertion(End, "]"); } } @@ -12050,14 +12052,17 @@ static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, BinaryOperatorKind Opc) { // Check that left hand side is !something. UnaryOperator *UO = dyn_cast(LHS.get()->IgnoreImpCasts()); - if (!UO || UO->getOpcode() != UO_LNot) return; + if (!UO || UO->getOpcode() != UO_LNot) + return; // Only check if the right hand side is non-bool arithmetic type. - if (RHS.get()->isKnownToHaveBooleanValue()) return; + if (RHS.get()->isKnownToHaveBooleanValue()) + return; // Make sure that the something in !something is not bool. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); - if (SubExpr->isKnownToHaveBooleanValue()) return; + if (SubExpr->isKnownToHaveBooleanValue()) + return; // Emit warning. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; @@ -12071,8 +12076,7 @@ static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, if (FirstClose.isInvalid()) FirstOpen = SourceLocation(); S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) - << IsBitwiseOp - << FixItHint::CreateInsertion(FirstOpen, "(") + << IsBitwiseOp << FixItHint::CreateInsertion(FirstOpen, "(") << FixItHint::CreateInsertion(FirstClose, ")"); // Second note suggests (!x) < y @@ -12279,8 +12283,8 @@ static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, LiteralStringStripped = LHSStripped; } else if ((isa(RHSStripped) || isa(RHSStripped)) && - !LHSStripped->isNullPointerConstant(S.Context, - Expr::NPC_ValueDependentIsNull)) { + !LHSStripped->isNullPointerConstant( + S.Context, Expr::NPC_ValueDependentIsNull)) { LiteralString = RHS; LiteralStringStripped = RHSStripped; } @@ -12496,7 +12500,7 @@ void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { if (!E.get()->getType()->isAnyPointerType() && E.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == - Expr::NPCK_ZeroExpression) { + Expr::NPCK_ZeroExpression) { if (const auto *CL = dyn_cast(E.get())) { if (CL->getValue() == 0) Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) @@ -12504,14 +12508,14 @@ void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { << FixItHint::CreateReplacement(E.get()->getExprLoc(), NullValue ? "NULL" : "(void *)0"); } else if (const auto *CE = dyn_cast(E.get())) { - TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); - QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); - if (T == Context.CharTy) - Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) - << NullValue - << FixItHint::CreateReplacement(E.get()->getExprLoc(), - NullValue ? "NULL" : "(void *)0"); - } + TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); + QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); + if (T == Context.CharTy) + Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) + << NullValue + << FixItHint::CreateReplacement(E.get()->getExprLoc(), + NullValue ? "NULL" : "(void *)0"); + } } } @@ -12688,9 +12692,9 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, // All of the following pointer-related warnings are GCC extensions, except // when handling null pointer constants. QualType LCanPointeeTy = - LHSType->castAs()->getPointeeType().getCanonicalType(); + LHSType->castAs()->getPointeeType().getCanonicalType(); QualType RCanPointeeTy = - RHSType->castAs()->getPointeeType().getCanonicalType(); + RHSType->castAs()->getPointeeType().getCanonicalType(); // C99 6.5.9p2 and C99 6.5.8p2 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), @@ -12709,13 +12713,15 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, } else if (!IsRelational && (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { // Valid unless comparison between non-null pointer and function pointer - if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) - && !LHSIsNull && !RHSIsNull) + if ((LCanPointeeTy->isFunctionType() || + RCanPointeeTy->isFunctionType()) && + !LHSIsNull && !RHSIsNull) diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, - /*isError*/false); + /*isError*/ false); } else { // Invalid - diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); + diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, + /*isError*/ false); } if (LCanPointeeTy != RCanPointeeTy) { // Treat NULL constant as a special case in OpenCL. @@ -12730,8 +12736,8 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, } LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); - CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion - : CK_BitCast; + CastKind Kind = + AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; const FunctionType *LFn = LCanPointeeTy->getAs(); const FunctionType *RFn = RCanPointeeTy->getAs(); @@ -12748,7 +12754,6 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, return computeResultTy(); } - // C++ [expr.eq]p4: // Two operands of type std::nullptr_t or one operand of type // std::nullptr_t and the other a null pointer constant compare @@ -12843,34 +12848,36 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (!LHSIsNull && !RHSIsNull && !Context.typesAreCompatible(lpointee, rpointee)) { Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) - << LHSType << RHSType << LHS.get()->getSourceRange() - << RHS.get()->getSourceRange(); + << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); } RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); return computeResultTy(); } // Allow block pointers to be compared with null pointer constants. - if (!IsOrdered - && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) - || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { + if (!IsOrdered && + ((LHSType->isBlockPointerType() && RHSType->isPointerType()) || + (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { if (!LHSIsNull && !RHSIsNull) { - if (!((RHSType->isPointerType() && RHSType->castAs() - ->getPointeeType()->isVoidType()) - || (LHSType->isPointerType() && LHSType->castAs() - ->getPointeeType()->isVoidType()))) + if (!((RHSType->isPointerType() && + RHSType->castAs()->getPointeeType()->isVoidType()) || + (LHSType->isPointerType() && + LHSType->castAs()->getPointeeType()->isVoidType()))) Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) - << LHSType << RHSType << LHS.get()->getSourceRange() - << RHS.get()->getSourceRange(); + << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); } if (LHSIsNull && !RHSIsNull) LHS = ImpCastExprToType(LHS.get(), RHSType, - RHSType->isPointerType() ? CK_BitCast - : CK_AnyPointerToBlockPointerCast); + RHSType->isPointerType() + ? CK_BitCast + : CK_AnyPointerToBlockPointerCast); else RHS = ImpCastExprToType(RHS.get(), LHSType, - LHSType->isPointerType() ? CK_BitCast - : CK_AnyPointerToBlockPointerCast); + LHSType->isPointerType() + ? CK_BitCast + : CK_AnyPointerToBlockPointerCast); return computeResultTy(); } @@ -12885,7 +12892,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (!LPtrToVoid && !RPtrToVoid && !Context.typesAreCompatible(LHSType, RHSType)) { diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, - /*isError*/false); + /*isError*/ false); } // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than // the RHS, but we have test coverage for this behavior. @@ -12895,18 +12902,17 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (getLangOpts().ObjCAutoRefCount) ObjC().CheckObjCConversion(SourceRange(), RHSType, E, CheckedConversionKind::Implicit); - LHS = ImpCastExprToType(E, RHSType, - RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); - } - else { + LHS = ImpCastExprToType( + E, RHSType, RPT ? CK_BitCast : CK_CPointerToObjCPointerCast); + } else { Expr *E = RHS.get(); if (getLangOpts().ObjCAutoRefCount) ObjC().CheckObjCConversion(SourceRange(), LHSType, E, CheckedConversionKind::Implicit, /*Diagnose=*/true, /*DiagnoseCFAudited=*/false, Opc); - RHS = ImpCastExprToType(E, LHSType, - LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); + RHS = ImpCastExprToType( + E, LHSType, LPT ? CK_BitCast : CK_CPointerToObjCPointerCast); } return computeResultTy(); } @@ -12914,7 +12920,7 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, RHSType->isObjCObjectPointerType()) { if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, - /*isError*/false); + /*isError*/ false); if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); @@ -12950,8 +12956,9 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, if (IsOrdered) { isError = getLangOpts().CPlusPlus; DiagID = - isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero - : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; + isError + ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero + : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; } } else if (getLangOpts().CPlusPlus) { DiagID = diag::err_typecheck_comparison_of_pointer_integer; @@ -12962,30 +12969,31 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, DiagID = diag::ext_typecheck_comparison_of_pointer_integer; if (DiagID) { - Diag(Loc, DiagID) - << LHSType << RHSType << LHS.get()->getSourceRange() - << RHS.get()->getSourceRange(); + Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() + << RHS.get()->getSourceRange(); if (isError) return QualType(); } if (LHSType->isIntegerType()) LHS = ImpCastExprToType(LHS.get(), RHSType, - LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); + LHSIsNull ? CK_NullToPointer + : CK_IntegralToPointer); else RHS = ImpCastExprToType(RHS.get(), LHSType, - RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); + RHSIsNull ? CK_NullToPointer + : CK_IntegralToPointer); return computeResultTy(); } // Handle block pointers. - if (!IsOrdered && RHSIsNull - && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { + if (!IsOrdered && RHSIsNull && LHSType->isBlockPointerType() && + RHSType->isIntegerType()) { RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); return computeResultTy(); } - if (!IsOrdered && LHSIsNull - && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { + if (!IsOrdered && LHSIsNull && LHSType->isIntegerType() && + RHSType->isBlockPointerType()) { LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); return computeResultTy(); } @@ -13612,11 +13620,14 @@ inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, static bool IsReadonlyMessage(Expr *E, Sema &S) { const MemberExpr *ME = dyn_cast(E); - if (!ME) return false; - if (!isa(ME->getMemberDecl())) return false; + if (!ME) + return false; + if (!isa(ME->getMemberDecl())) + return false; ObjCMessageExpr *Base = dyn_cast( ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); - if (!Base) return false; + if (!Base) + return false; return Base->getMethodDecl() != nullptr; } @@ -13630,8 +13641,10 @@ static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { // Must be a reference to a declaration from an enclosing scope. DeclRefExpr *DRE = dyn_cast(E); - if (!DRE) return NCCK_None; - if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; + if (!DRE) + return NCCK_None; + if (!DRE->refersToEnclosingVariableOrCapture()) + return NCCK_None; ValueDecl *Value = dyn_cast(DRE->getDecl()); @@ -13690,7 +13703,7 @@ enum { ConstMember, ConstMethod, NestedConstMember, - ConstUnknown, // Keep as last element + ConstUnknown, // Keep as last element }; /// Emit the "read-only variable not assignable" error and print notes to give @@ -13771,8 +13784,8 @@ static void DiagnoseConstAssignment(Sema &S, const Expr *E, const FunctionDecl *FD = CE->getDirectCallee(); if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { if (!DiagnosticEmitted) { - S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange - << ConstFunction << FD; + S.Diag(Loc, diag::err_typecheck_assign_const) + << ExprRange << ConstFunction << FD; DiagnosticEmitted = true; } S.Diag(FD->getReturnTypeSourceRange().getBegin(), @@ -13798,8 +13811,8 @@ static void DiagnoseConstAssignment(Sema &S, const Expr *E, if (const CXXMethodDecl *MD = dyn_cast(DC)) { if (MD->isConst()) { if (!DiagnosticEmitted) { - S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange - << ConstMethod << MD; + S.Diag(Loc, diag::err_typecheck_assign_const) + << ExprRange << ConstMethod << MD; DiagnosticEmitted = true; } S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) @@ -13816,11 +13829,7 @@ static void DiagnoseConstAssignment(Sema &S, const Expr *E, S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; } -enum OriginalExprKind { - OEK_Variable, - OEK_Member, - OEK_LValue -}; +enum OriginalExprKind { OEK_Variable, OEK_Member, OEK_LValue }; static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, @@ -13843,13 +13852,12 @@ static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, if (FieldTy.isConstQualified()) { if (!DiagnosticEmitted) { S.Diag(Loc, diag::err_typecheck_assign_const) - << Range << NestedConstMember << OEK << VD - << IsNested << Field; + << Range << NestedConstMember << OEK << VD << IsNested << Field; DiagnosticEmitted = true; } S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) - << NestedConstMember << IsNested << Field - << FieldTy << Field->getSourceRange(); + << NestedConstMember << IsNested << Field << FieldTy + << Field->getSourceRange(); } // Then we append it to the list to check next in order. @@ -13874,14 +13882,14 @@ static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, bool DiagEmitted = false; if (const MemberExpr *ME = dyn_cast(E)) - DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, - Range, OEK_Member, DiagEmitted); + DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, Range, + OEK_Member, DiagEmitted); else if (const DeclRefExpr *DRE = dyn_cast(E)) - DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, - Range, OEK_Variable, DiagEmitted); + DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, Range, + OEK_Variable, DiagEmitted); else - DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, - Range, OEK_LValue, DiagEmitted); + DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, Range, OEK_LValue, + DiagEmitted); if (!DiagEmitted) DiagnoseConstAssignment(S, E, Loc); } @@ -13894,8 +13902,7 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { S.CheckShadowingDeclModification(E, Loc); SourceLocation OrigLoc = Loc; - Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, - &Loc); + Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, &Loc); if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) IsLV = Expr::MLV_InvalidMessageExpression; if (IsLV == Expr::MLV_Valid) @@ -13932,15 +13939,15 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { ObjCMethodDecl *method = S.getCurMethodDecl(); if (method && var == method->getSelfDecl()) { DiagID = method->isClassMethod() - ? diag::err_typecheck_arc_assign_self_class_method - : diag::err_typecheck_arc_assign_self; + ? diag::err_typecheck_arc_assign_self_class_method + : diag::err_typecheck_arc_assign_self; - // - Objective-C externally_retained attribute. + // - Objective-C externally_retained attribute. } else if (var->hasAttr() || isa(var)) { DiagID = diag::err_typecheck_arc_assign_externally_retained; - // - fast enumeration variables + // - fast enumeration variables } else { DiagID = diag::err_typecheck_arr_assign_enumeration; } @@ -13991,8 +13998,9 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { break; case Expr::MLV_IncompleteType: case Expr::MLV_IncompleteVoidType: - return S.RequireCompleteType(Loc, E->getType(), - diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); + return S.RequireCompleteType( + Loc, E->getType(), + diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); case Expr::MLV_DuplicateVectorComponents: DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; break; @@ -14017,8 +14025,7 @@ static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { } static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, - SourceLocation Loc, - Sema &Sema) { + SourceLocation Loc, Sema &Sema) { if (Sema.inTemplateInstantiation()) return; if (Sema.isUnevaluatedContext()) @@ -14072,8 +14079,8 @@ QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, return QualType(); QualType LHSType = LHSExpr->getType(); - QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : - CompoundType; + QualType RHSType = + CompoundType.isNull() ? RHS.get()->getType() : CompoundType; if (RHS.isUsable()) { // Even if this check fails don't return early to allow the best @@ -14100,8 +14107,8 @@ QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && LHSType->isHalfType()) { - Diag(Loc, diag::err_opencl_half_load_store) << 1 - << LHSType.getUnqualifiedType(); + Diag(Loc, diag::err_opencl_half_load_store) + << 1 << LHSType.getUnqualifiedType(); return QualType(); } @@ -14147,8 +14154,8 @@ QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && UO->getSubExpr()->getBeginLoc().isFileID()) { Diag(Loc, diag::warn_not_compound_assign) - << (UO->getOpcode() == UO_Plus ? "+" : "-") - << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); + << (UO->getOpcode() == UO_Plus ? "+" : "-") + << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); } } @@ -14348,7 +14355,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, // Increment of bool sets it to true, but is deprecated. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool : diag::warn_increment_bool) - << Op->getSourceRange(); + << Op->getSourceRange(); } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { // Error on enum increments and decrements in C++ mode S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; @@ -14372,9 +14379,10 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, << IsInc << Op->getSourceRange(); } else if (ResType->isPlaceholderType()) { ExprResult PR = S.CheckPlaceholderExpr(Op); - if (PR.isInvalid()) return QualType(); - return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, - IsInc, IsPrefix); + if (PR.isInvalid()) + return QualType(); + return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, IsInc, + IsPrefix); } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) } else if (S.getLangOpts().ZVector && ResType->isVectorType() && @@ -14386,7 +14394,7 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. } else { S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) - << ResType << int(IsInc) << Op->getSourceRange(); + << ResType << int(IsInc) << Op->getSourceRange(); return QualType(); } // At this point, we know we have a real, complex or pointer type. @@ -14442,8 +14450,8 @@ static ValueDecl *getPrimaryDecl(Expr *E) { case Stmt::ArraySubscriptExprClass: { // FIXME: This code shouldn't be necessary! We should catch the implicit // promotion of register arrays earlier. - Expr* Base = cast(E)->getBase(); - if (ImplicitCastExpr* ICE = dyn_cast(Base)) { + Expr *Base = cast(E)->getBase(); + if (ImplicitCastExpr *ICE = dyn_cast(Base)) { if (ICE->getSubExpr()->getType()->isArrayType()) return getPrimaryDecl(ICE->getSubExpr()); } @@ -14452,7 +14460,7 @@ static ValueDecl *getPrimaryDecl(Expr *E) { case Stmt::UnaryOperatorClass: { UnaryOperator *UO = cast(E); - switch(UO->getOpcode()) { + switch (UO->getOpcode()) { case UO_Real: case UO_Imag: case UO_Extension: @@ -14487,8 +14495,8 @@ enum { /// Diagnose invalid operand for address of operations. /// /// \param Type The type of operand which cannot have its address taken. -static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, - Expr *E, unsigned Type) { +static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, + unsigned Type) { S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); } @@ -14521,13 +14529,14 @@ bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, } QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { - if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ + if (const BuiltinType *PTy = + OrigOp.get()->getType()->getAsPlaceholderType()) { if (PTy->getKind() == BuiltinType::Overload) { Expr *E = OrigOp.get()->IgnoreParens(); if (!isa(E)) { assert(cast(E)->getOpcode() == UO_AddrOf); Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) - << OrigOp.get()->getSourceRange(); + << OrigOp.get()->getSourceRange(); return QualType(); } @@ -14535,7 +14544,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { if (isa(Ovl)) if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { Diag(OpLoc, diag::err_invalid_form_pointer_member_function) - << OrigOp.get()->getSourceRange(); + << OrigOp.get()->getSourceRange(); return QualType(); } @@ -14547,12 +14556,13 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { if (PTy->getKind() == BuiltinType::BoundMember) { Diag(OpLoc, diag::err_invalid_form_pointer_member_function) - << OrigOp.get()->getSourceRange(); + << OrigOp.get()->getSourceRange(); return QualType(); } OrigOp = CheckPlaceholderExpr(OrigOp.get()); - if (OrigOp.isInvalid()) return QualType(); + if (OrigOp.isInvalid()) + return QualType(); } if (OrigOp.get()->isTypeDependent()) @@ -14569,7 +14579,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { // depending on a vendor implementation. Thus preventing // taking an address of the capture to avoid invalid AS casts. if (LangOpts.OpenCL) { - auto* VarRef = dyn_cast(op); + auto *VarRef = dyn_cast(op); if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); return QualType(); @@ -14578,7 +14588,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { if (getLangOpts().C99) { // Implement C99-only parts of addressof rules. - if (UnaryOperator* uOp = dyn_cast(op)) { + if (UnaryOperator *uOp = dyn_cast(op)) { if (uOp->getOpcode() == UO_Deref) // Per C99 6.5.3.2, the address of a deref always returns a valid result // (assuming the deref expression is valid). @@ -14601,7 +14611,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { bool sfinae = (bool)isSFINAEContext(); Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary : diag::ext_typecheck_addrof_temporary) - << op->getType() << op->getSourceRange(); + << op->getType() << op->getSourceRange(); if (sfinae) return QualType(); // Materialize the temporary as an lvalue so that we can take its address. @@ -14616,7 +14626,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { // If the underlying expression isn't a decl ref, give up. if (!isa(op)) { Diag(OpLoc, diag::err_invalid_form_pointer_member_function) - << OrigOp.get()->getSourceRange(); + << OrigOp.get()->getSourceRange(); return QualType(); } DeclRefExpr *DRE = cast(op); @@ -14671,7 +14681,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { AddressOfError = AO_Property_Expansion; } else { Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) - << op->getType() << op->getSourceRange(); + << op->getType() << op->getSourceRange(); return QualType(); } } else if (const auto *DRE = dyn_cast(op)) { @@ -14694,8 +14704,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { if (const VarDecl *vd = dyn_cast(dcl)) { // in C++ it is not error to take address of a register // variable (c++03 7.1.1P3) - if (vd->getStorageClass() == SC_Register && - !getLangOpts().CPlusPlus) { + if (vd->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus) { AddressOfError = AO_Register_Variable; } } else if (isa(dcl)) { @@ -14719,7 +14728,7 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { if (dcl->getType()->isReferenceType()) { Diag(OpLoc, diag::err_cannot_form_pointer_to_member_of_reference_type) - << dcl->getDeclName() << dcl->getType(); + << dcl->getDeclName() << dcl->getType(); return QualType(); } @@ -14786,7 +14795,7 @@ static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { const ParmVarDecl *Param = dyn_cast(D); if (!Param) return; - if (const FunctionDecl* FD = dyn_cast(Param->getDeclContext())) + if (const FunctionDecl *FD = dyn_cast(Param->getDeclContext())) if (!FD->hasAttr() && !Param->hasAttr()) return; if (FunctionScopeInfo *FD = S.getCurFunction()) @@ -14806,27 +14815,26 @@ static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, if (isa(Op->IgnoreParens())) { QualType OpOrigType = Op->IgnoreParenCasts()->getType(); - S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, + S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/ true, Op->getSourceRange()); } - if (const PointerType *PT = OpTy->getAs()) - { + if (const PointerType *PT = OpTy->getAs()) { Result = PT->getPointeeType(); - } - else if (const ObjCObjectPointerType *OPT = - OpTy->getAs()) + } else if (const ObjCObjectPointerType *OPT = + OpTy->getAs()) Result = OPT->getPointeeType(); else { ExprResult PR = S.CheckPlaceholderExpr(Op); - if (PR.isInvalid()) return QualType(); + if (PR.isInvalid()) + return QualType(); if (PR.get() != Op) return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); } if (Result.isNull()) { S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) - << OpTy << Op->getSourceRange(); + << OpTy << Op->getSourceRange(); return QualType(); } @@ -14856,60 +14864,150 @@ static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { BinaryOperatorKind Opc; switch (Kind) { - default: llvm_unreachable("Unknown binop!"); - case tok::periodstar: Opc = BO_PtrMemD; break; - case tok::arrowstar: Opc = BO_PtrMemI; break; - case tok::star: Opc = BO_Mul; break; - case tok::slash: Opc = BO_Div; break; - case tok::percent: Opc = BO_Rem; break; - case tok::plus: Opc = BO_Add; break; - case tok::minus: Opc = BO_Sub; break; - case tok::lessless: Opc = BO_Shl; break; - case tok::greatergreater: Opc = BO_Shr; break; - case tok::lessequal: Opc = BO_LE; break; - case tok::less: Opc = BO_LT; break; - case tok::greaterequal: Opc = BO_GE; break; - case tok::greater: Opc = BO_GT; break; - case tok::exclaimequal: Opc = BO_NE; break; - case tok::equalequal: Opc = BO_EQ; break; - case tok::spaceship: Opc = BO_Cmp; break; - case tok::amp: Opc = BO_And; break; - case tok::caret: Opc = BO_Xor; break; - case tok::pipe: Opc = BO_Or; break; - case tok::ampamp: Opc = BO_LAnd; break; - case tok::pipepipe: Opc = BO_LOr; break; - case tok::equal: Opc = BO_Assign; break; - case tok::starequal: Opc = BO_MulAssign; break; - case tok::slashequal: Opc = BO_DivAssign; break; - case tok::percentequal: Opc = BO_RemAssign; break; - case tok::plusequal: Opc = BO_AddAssign; break; - case tok::minusequal: Opc = BO_SubAssign; break; - case tok::lesslessequal: Opc = BO_ShlAssign; break; - case tok::greatergreaterequal: Opc = BO_ShrAssign; break; - case tok::ampequal: Opc = BO_AndAssign; break; - case tok::caretequal: Opc = BO_XorAssign; break; - case tok::pipeequal: Opc = BO_OrAssign; break; - case tok::comma: Opc = BO_Comma; break; + default: + llvm_unreachable("Unknown binop!"); + case tok::periodstar: + Opc = BO_PtrMemD; + break; + case tok::arrowstar: + Opc = BO_PtrMemI; + break; + case tok::star: + Opc = BO_Mul; + break; + case tok::slash: + Opc = BO_Div; + break; + case tok::percent: + Opc = BO_Rem; + break; + case tok::plus: + Opc = BO_Add; + break; + case tok::minus: + Opc = BO_Sub; + break; + case tok::lessless: + Opc = BO_Shl; + break; + case tok::greatergreater: + Opc = BO_Shr; + break; + case tok::lessequal: + Opc = BO_LE; + break; + case tok::less: + Opc = BO_LT; + break; + case tok::greaterequal: + Opc = BO_GE; + break; + case tok::greater: + Opc = BO_GT; + break; + case tok::exclaimequal: + Opc = BO_NE; + break; + case tok::equalequal: + Opc = BO_EQ; + break; + case tok::spaceship: + Opc = BO_Cmp; + break; + case tok::amp: + Opc = BO_And; + break; + case tok::caret: + Opc = BO_Xor; + break; + case tok::pipe: + Opc = BO_Or; + break; + case tok::ampamp: + Opc = BO_LAnd; + break; + case tok::pipepipe: + Opc = BO_LOr; + break; + case tok::equal: + Opc = BO_Assign; + break; + case tok::starequal: + Opc = BO_MulAssign; + break; + case tok::slashequal: + Opc = BO_DivAssign; + break; + case tok::percentequal: + Opc = BO_RemAssign; + break; + case tok::plusequal: + Opc = BO_AddAssign; + break; + case tok::minusequal: + Opc = BO_SubAssign; + break; + case tok::lesslessequal: + Opc = BO_ShlAssign; + break; + case tok::greatergreaterequal: + Opc = BO_ShrAssign; + break; + case tok::ampequal: + Opc = BO_AndAssign; + break; + case tok::caretequal: + Opc = BO_XorAssign; + break; + case tok::pipeequal: + Opc = BO_OrAssign; + break; + case tok::comma: + Opc = BO_Comma; + break; } return Opc; } -static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( - tok::TokenKind Kind) { +static inline UnaryOperatorKind +ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind) { UnaryOperatorKind Opc; switch (Kind) { - default: llvm_unreachable("Unknown unary op!"); - case tok::plusplus: Opc = UO_PreInc; break; - case tok::minusminus: Opc = UO_PreDec; break; - case tok::amp: Opc = UO_AddrOf; break; - case tok::star: Opc = UO_Deref; break; - case tok::plus: Opc = UO_Plus; break; - case tok::minus: Opc = UO_Minus; break; - case tok::tilde: Opc = UO_Not; break; - case tok::exclaim: Opc = UO_LNot; break; - case tok::kw___real: Opc = UO_Real; break; - case tok::kw___imag: Opc = UO_Imag; break; - case tok::kw___extension__: Opc = UO_Extension; break; + default: + llvm_unreachable("Unknown unary op!"); + case tok::plusplus: + Opc = UO_PreInc; + break; + case tok::minusminus: + Opc = UO_PreDec; + break; + case tok::amp: + Opc = UO_AddrOf; + break; + case tok::star: + Opc = UO_Deref; + break; + case tok::plus: + Opc = UO_Plus; + break; + case tok::minus: + Opc = UO_Minus; + break; + case tok::tilde: + Opc = UO_Not; + break; + case tok::exclaim: + Opc = UO_LNot; + break; + case tok::kw___real: + Opc = UO_Real; + break; + case tok::kw___imag: + Opc = UO_Imag; + break; + case tok::kw___extension__: + Opc = UO_Extension; + break; } return Opc; } @@ -14962,14 +15060,13 @@ static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, RHSExpr = RHSExpr->IgnoreParenImpCasts(); const DeclRefExpr *LHSDeclRef = dyn_cast(LHSExpr); const DeclRefExpr *RHSDeclRef = dyn_cast(RHSExpr); - if (!LHSDeclRef || !RHSDeclRef || - LHSDeclRef->getLocation().isMacroID() || + if (!LHSDeclRef || !RHSDeclRef || LHSDeclRef->getLocation().isMacroID() || RHSDeclRef->getLocation().isMacroID()) return; const ValueDecl *LHSDecl = - cast(LHSDeclRef->getDecl()->getCanonicalDecl()); + cast(LHSDeclRef->getDecl()->getCanonicalDecl()); const ValueDecl *RHSDecl = - cast(RHSDeclRef->getDecl()->getCanonicalDecl()); + cast(RHSDeclRef->getDecl()->getCanonicalDecl()); if (LHSDecl != RHSDecl) return; if (LHSDecl->getType().isVolatileQualified()) @@ -15004,8 +15101,7 @@ static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { ObjCPointerExpr = LHS; OtherExpr = RHS; - } - else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { + } else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { ObjCPointerExpr = RHS; OtherExpr = LHS; } @@ -15028,8 +15124,7 @@ static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, Diag = diag::warn_objc_pointer_masking_performSelector; } - S.Diag(OpLoc, Diag) - << ObjCPointerExpr->getSourceRange(); + S.Diag(OpLoc, Diag) << ObjCPointerExpr->getSourceRange(); } } @@ -15116,7 +15211,7 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, } ExprResult LHS = LHSExpr, RHS = RHSExpr; - QualType ResultTy; // Result type of the binary operator. + QualType ResultTy; // Result type of the binary operator. // The following two variables are used for compound assignment operators QualType CompLHSTy; // Type of LHS after promotions for computation QualType CompResultTy; // Type of computation result @@ -15143,9 +15238,8 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, // OpenCL special types - image, sampler, pipe, and blocks are to be used // only with a builtin functions and therefore should be disallowed here. - if (LHSTy->isImageType() || RHSTy->isImageType() || - LHSTy->isSamplerT() || RHSTy->isSamplerT() || - LHSTy->isPipeType() || RHSTy->isPipeType() || + if (LHSTy->isImageType() || RHSTy->isImageType() || LHSTy->isSamplerT() || + RHSTy->isSamplerT() || LHSTy->isPipeType() || RHSTy->isPipeType() || LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { ResultTy = InvalidOperands(OpLoc, LHS, RHS); return ExprError(); @@ -15194,8 +15288,8 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, break; case BO_PtrMemD: case BO_PtrMemI: - ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, - Opc == BO_PtrMemI); + ResultTy = + CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, Opc == BO_PtrMemI); break; case BO_Mul: case BO_Div: @@ -15327,10 +15421,11 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, CheckArrayAccess(LHS.get()); CheckArrayAccess(RHS.get()); - if (const ObjCIsaExpr *OISA = dyn_cast(LHS.get()->IgnoreParenCasts())) { - NamedDecl *ObjectSetClass = LookupSingleName(TUScope, - &Context.Idents.get("object_setClass"), - SourceLocation(), LookupOrdinaryName); + if (const ObjCIsaExpr *OISA = + dyn_cast(LHS.get()->IgnoreParenCasts())) { + NamedDecl *ObjectSetClass = + LookupSingleName(TUScope, &Context.Idents.get("object_setClass"), + SourceLocation(), LookupOrdinaryName); if (ObjectSetClass && isa(LHS.get())) { SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) @@ -15339,12 +15434,10 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << FixItHint::CreateInsertion(RHSLocEnd, ")"); - } - else + } else Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); - } - else if (const ObjCIvarRefExpr *OIRE = - dyn_cast(LHS.get()->IgnoreParenCasts())) + } else if (const ObjCIvarRefExpr *OIRE = + dyn_cast(LHS.get()->IgnoreParenCasts())) DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); // Opc is not a compound assignment if CompResultTy is null. @@ -15357,8 +15450,8 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, } // Handle compound assignments. - if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != - OK_ObjCProperty) { + if (getLangOpts().CPlusPlus && + LHS.get()->getObjectKind() != OK_ObjCProperty) { VK = VK_LValue; OK = LHS.get()->getObjectKind(); } @@ -15411,29 +15504,29 @@ static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) - << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; + << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; SuggestParentheses(Self, OpLoc, - Self.PDiag(diag::note_precedence_silence) << OpStr, - (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); + Self.PDiag(diag::note_precedence_silence) << OpStr, + (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); SuggestParentheses(Self, OpLoc, - Self.PDiag(diag::note_precedence_bitwise_first) - << BinaryOperator::getOpcodeStr(Opc), - ParensRange); + Self.PDiag(diag::note_precedence_bitwise_first) + << BinaryOperator::getOpcodeStr(Opc), + ParensRange); } /// It accepts a '&&' expr that is inside a '||' one. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression /// in parentheses. -static void -EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, - BinaryOperator *Bop) { +static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, + SourceLocation OpLoc, + BinaryOperator *Bop) { assert(Bop->getOpcode() == BO_LAnd); Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) << Bop->getSourceRange() << OpLoc; SuggestParentheses(Self, Bop->getOperatorLoc(), - Self.PDiag(diag::note_precedence_silence) - << Bop->getOpcodeStr(), - Bop->getSourceRange()); + Self.PDiag(diag::note_precedence_silence) + << Bop->getOpcodeStr(), + Bop->getSourceRange()); } /// Look for '&&' in the left hand of a '||' expr. @@ -15478,12 +15571,12 @@ static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, if (BinaryOperator *Bop = dyn_cast(SubExpr)) { if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) - << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) - << Bop->getSourceRange() << OpLoc; + << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) + << Bop->getSourceRange() << OpLoc; SuggestParentheses(S, Bop->getOperatorLoc(), - S.PDiag(diag::note_precedence_silence) - << Bop->getOpcodeStr(), - Bop->getSourceRange()); + S.PDiag(diag::note_precedence_silence) + << Bop->getOpcodeStr(), + Bop->getSourceRange()); } } } @@ -15496,14 +15589,14 @@ static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) << Bop->getSourceRange() << OpLoc << Shift << Op; SuggestParentheses(S, Bop->getOperatorLoc(), - S.PDiag(diag::note_precedence_silence) << Op, - Bop->getSourceRange()); + S.PDiag(diag::note_precedence_silence) << Op, + Bop->getSourceRange()); } } } -static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, - Expr *LHSExpr, Expr *RHSExpr) { +static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, + Expr *RHSExpr) { CXXOperatorCallExpr *OCE = dyn_cast(LHSExpr); if (!OCE) return; @@ -15532,27 +15625,28 @@ static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, /// precedence. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, - Expr *RHSExpr){ + Expr *RHSExpr) { // Diagnose "arg1 'bitwise' arg2 'eq' arg3". if (BinaryOperator::isBitwiseOp(Opc)) DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); // Diagnose "arg1 & arg2 | arg3" if ((Opc == BO_Or || Opc == BO_Xor) && - !OpLoc.isMacroID()/* Don't warn in macros. */) { + !OpLoc.isMacroID() /* Don't warn in macros. */) { DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); } // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. // We don't warn for 'assert(a || b && "bad")' since this is safe. - if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { + if (Opc == BO_LOr && !OpLoc.isMacroID() /* Don't warn in macros. */) { DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); } - if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) - || Opc == BO_Shr) { + if ((Opc == BO_Shl && + LHSExpr->getType()->isIntegralType(Self.getASTContext())) || + Opc == BO_Shr) { StringRef Shift = BinaryOperator::getOpcodeStr(Opc); DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); @@ -15565,8 +15659,7 @@ static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, } ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, - tok::TokenKind Kind, - Expr *LHSExpr, Expr *RHSExpr) { + tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr) { BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); assert(LHSExpr && "ActOnBinOp(): missing left expression"); assert(RHSExpr && "ActOnBinOp(): missing right expression"); @@ -15599,8 +15692,8 @@ void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, /// Build an overloaded binary operator expression in the given scope. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, - BinaryOperatorKind Opc, - Expr *LHS, Expr *RHS) { + BinaryOperatorKind Opc, Expr *LHS, + Expr *RHS) { switch (Opc) { case BO_Assign: // In the non-overloaded case, we warn about self-assignment (x = x) for @@ -15661,7 +15754,8 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, // that an overload set can be dependently-typed, but it never // instantiates to having an overloadable type. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); - if (resolvedRHS.isInvalid()) return ExprError(); + if (resolvedRHS.isInvalid()) + return ExprError(); RHSExpr = resolvedRHS.get(); if (RHSExpr->isTypeDependent() || @@ -15692,7 +15786,8 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, } ExprResult LHS = CheckPlaceholderExpr(LHSExpr); - if (LHS.isInvalid()) return ExprError(); + if (LHS.isInvalid()) + return ExprError(); LHSExpr = LHS.get(); } @@ -15716,7 +15811,8 @@ ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); - if (!resolvedRHS.isUsable()) return ExprError(); + if (!resolvedRHS.isUsable()) + return ExprError(); RHSExpr = resolvedRHS.get(); } @@ -15804,10 +15900,11 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, QualType Ty = InputExpr->getType(); // The only legal unary operation for atomics is '&'. if ((Opc != UO_AddrOf && Ty->isAtomicType()) || - // OpenCL special types - image, sampler, pipe, and blocks are to be used - // only with a builtin functions and therefore should be disallowed here. - (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() - || Ty->isBlockPointerType())) { + // OpenCL special types - image, sampler, pipe, and blocks are to be + // used only with a builtin functions and therefore should be disallowed + // here. + (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() || + Ty->isBlockPointerType())) { return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) << InputExpr->getType() << Input.get()->getSourceRange()); @@ -16100,15 +16197,15 @@ ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, // & gets special logic for several kinds of placeholder. // The builtin code knows what to do. - if (Opc == UO_AddrOf && - (pty->getKind() == BuiltinType::Overload || - pty->getKind() == BuiltinType::UnknownAny || - pty->getKind() == BuiltinType::BoundMember)) + if (Opc == UO_AddrOf && (pty->getKind() == BuiltinType::Overload || + pty->getKind() == BuiltinType::UnknownAny || + pty->getKind() == BuiltinType::BoundMember)) return CreateBuiltinUnaryOp(OpLoc, Opc, Input); // Anything else needs to be handled now. ExprResult Result = CheckPlaceholderExpr(Input); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); Input = Result.get(); } @@ -16248,32 +16345,32 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, // a struct/union/class. if (!Dependent && !ArgTy->isRecordType()) return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) - << ArgTy << TypeRange); + << ArgTy << TypeRange); // Type must be complete per C99 7.17p3 because a declaring a variable // with an incomplete type would be ill-formed. - if (!Dependent - && RequireCompleteType(BuiltinLoc, ArgTy, - diag::err_offsetof_incomplete_type, TypeRange)) + if (!Dependent && + RequireCompleteType(BuiltinLoc, ArgTy, diag::err_offsetof_incomplete_type, + TypeRange)) return ExprError(); bool DidWarnAboutNonPOD = false; QualType CurrentType = ArgTy; SmallVector Comps; - SmallVector Exprs; + SmallVector Exprs; for (const OffsetOfComponent &OC : Components) { if (OC.isBrackets) { // Offset of an array sub-field. TODO: Should we allow vector elements? if (!CurrentType->isDependentType()) { const ArrayType *AT = Context.getAsArrayType(CurrentType); - if(!AT) + if (!AT) return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) << CurrentType); CurrentType = AT->getElementType(); } else CurrentType = Context.DependentTy; - ExprResult IdxRval = DefaultLvalueConversion(static_cast(OC.U.E)); + ExprResult IdxRval = DefaultLvalueConversion(static_cast(OC.U.E)); if (IdxRval.isInvalid()) return ExprError(); Expr *Idx = IdxRval.get(); @@ -16320,9 +16417,10 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, // If type is not a standard-layout class (Clause 9), the results are // undefined. if (CXXRecordDecl *CRD = dyn_cast(RD)) { - bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); - unsigned DiagID = - LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type + bool IsSafe = + LangOpts.CPlusPlus11 ? CRD->isStandardLayout() : CRD->isPOD(); + unsigned DiagID = LangOpts.CPlusPlus11 + ? diag::ext_offsetof_non_standardlayout_type : diag::ext_offsetof_non_pod_type; if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) { @@ -16358,8 +16456,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, // We diagnose this as an error. if (MemberDecl->isBitField()) { Diag(OC.LocEnd, diag::err_offsetof_bitfield) - << MemberDecl->getDeclName() - << SourceRange(BuiltinLoc, RParenLoc); + << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc); Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); return ExprError(); } @@ -16375,8 +16472,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, Context.getCanonicalTagType(Parent), Paths)) { if (Paths.getDetectedVirtual()) { Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) - << MemberDecl->getDeclName() - << SourceRange(BuiltinLoc, RParenLoc); + << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc); return ExprError(); } @@ -16388,8 +16484,8 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, if (IndirectMemberDecl) { for (auto *FI : IndirectMemberDecl->chain()) { assert(isa(FI)); - Comps.push_back(OffsetOfNode(OC.LocStart, - cast(FI), OC.LocEnd)); + Comps.push_back( + OffsetOfNode(OC.LocStart, cast(FI), OC.LocEnd)); } } else Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); @@ -16401,8 +16497,7 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, Comps, Exprs, RParenLoc); } -ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, - SourceLocation BuiltinLoc, +ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef Components, @@ -16419,9 +16514,7 @@ ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); } - -ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, - Expr *CondExpr, +ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc) { assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); @@ -16507,8 +16600,8 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, // Look for an explicit signature in that function type. FunctionProtoTypeLoc ExplicitSignature; - if ((ExplicitSignature = Sig->getTypeLoc() - .getAsAdjusted())) { + if ((ExplicitSignature = + Sig->getTypeLoc().getAsAdjusted())) { // Check whether that explicit signature was synthesized by // GetTypeForDeclarator. If so, don't save that as part of the @@ -16547,7 +16640,7 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, } // Push block parameters from the declarator if we had them. - SmallVector Params; + SmallVector Params; if (ExplicitSignature) { for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { ParmVarDecl *Param = ExplicitSignature.getParam(I); @@ -16560,8 +16653,8 @@ void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Params.push_back(Param); } - // Fake up parameter variables if we have a typedef, like - // ^ fntype { ... } + // Fake up parameter variables if we have a typedef, like + // ^ fntype { ... } } else if (const FunctionProtoType *Fn = T->getAs()) { for (const auto &I : Fn->param_types()) { ParmVarDecl *Param = BuildParmVarDeclForTypedef( @@ -16606,8 +16699,8 @@ void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { PopFunctionScopeInfo(); } -ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, - Stmt *Body, Scope *CurScope) { +ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, + Scope *CurScope) { // If blocks are disabled, emit an error. if (!LangOpts.Blocks) Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; @@ -16639,7 +16732,8 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, const FunctionType *FTy = BSI->FunctionType->castAs(); FunctionType::ExtInfo Ext = FTy->getExtInfo(); - if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); + if (NoReturn && !Ext.getNoReturn()) + Ext = Ext.withNoReturn(true); // Turn protoless block types into nullary block types. if (isa(FTy)) { @@ -16653,7 +16747,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, (!NoReturn || FTy->getNoReturnAttr())) { BlockTy = BSI->FunctionType; - // Otherwise, make the minimal modifications to the function type. + // Otherwise, make the minimal modifications to the function type. } else { const FunctionProtoType *FPT = cast(FTy); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); @@ -16662,7 +16756,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); } - // If we don't have a function type, just build one from nothing. + // If we don't have a function type, just build one from nothing. } else { FunctionProtoType::ExtProtoInfo EPI; EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); @@ -16673,8 +16767,7 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, BlockTy = Context.getBlockPointerType(BlockTy); // If needed, diagnose invalid gotos and switches in the block. - if (getCurFunction()->NeedsScopeChecking() && - !PP.isCodeCompletionEnabled()) + if (getCurFunction()->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) DiagnoseInvalidJumps(cast(Body)); BD->setBody(cast(Body)); @@ -16749,9 +16842,9 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, // Build a full-expression copy expression if initialization // succeeded and used a non-trivial constructor. Recover from // errors by pretending that the copy isn't necessary. - if (!Result.isInvalid() && - !cast(Result.get())->getConstructor() - ->isTrivial()) { + if (!Result.isInvalid() && !cast(Result.get()) + ->getConstructor() + ->isTrivial()) { Result = MaybeCreateExprWithCleanups(Result); CopyExpr = Result.get(); } @@ -16808,9 +16901,8 @@ ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); } -ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, - Expr *E, TypeSourceInfo *TInfo, - SourceLocation RPLoc) { +ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, + TypeSourceInfo *TInfo, SourceLocation RPLoc) { Expr *OrigExpr = E; bool IsMS = false; @@ -16832,7 +16924,8 @@ ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, // as Microsoft ABI on an actual Microsoft platform, where // __builtin_ms_va_list and __builtin_va_list are the same.) if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && - Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { + Context.getTargetInfo().getBuiltinVaListKind() != + TargetInfo::CharPtrBuiltinVaList) { QualType MSVaListType = Context.getBuiltinMSVaListType(); if (Context.hasSameType(MSVaListType, E->getType())) { if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) @@ -16885,19 +16978,17 @@ ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, TInfo->getTypeLoc())) return ExprError(); - if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), - TInfo->getType(), - diag::err_second_parameter_to_va_arg_abstract, - TInfo->getTypeLoc())) + if (RequireNonAbstractType( + TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), + diag::err_second_parameter_to_va_arg_abstract, TInfo->getTypeLoc())) return ExprError(); if (!TInfo->getType().isPODType(Context)) { Diag(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType()->isObjCLifetimeType() - ? diag::warn_second_parameter_to_va_arg_ownership_qualified - : diag::warn_second_parameter_to_va_arg_not_pod) - << TInfo->getType() - << TInfo->getTypeLoc().getSourceRange(); + ? diag::warn_second_parameter_to_va_arg_ownership_qualified + : diag::warn_second_parameter_to_va_arg_not_pod) + << TInfo->getType() << TInfo->getTypeLoc().getSourceRange(); } if (TInfo->getType()->isArrayType()) { @@ -16959,11 +17050,11 @@ ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) PromoteType = Context.DoubleTy; if (!PromoteType.isNull()) - DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, - PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) - << TInfo->getType() - << PromoteType - << TInfo->getTypeLoc().getSourceRange()); + DiagRuntimeBehavior( + TInfo->getTypeLoc().getBeginLoc(), E, + PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) + << TInfo->getType() << PromoteType + << TInfo->getTypeLoc().getSourceRange()); } QualType T = TInfo->getType().getNonLValueExprType(Context); @@ -17126,10 +17217,9 @@ static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, } bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, - SourceLocation Loc, - QualType DstType, QualType SrcType, - Expr *SrcExpr, AssignmentAction Action, - bool *Complained) { + SourceLocation Loc, QualType DstType, + QualType SrcType, Expr *SrcExpr, + AssignmentAction Action, bool *Complained) { if (Complained) *Complained = false; @@ -17198,7 +17288,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, DiagKind = diag::ext_typecheck_convert_incompatible_pointer; } CheckInferredResultType = DstType->isObjCObjectPointerType() && - SrcType->isObjCObjectPointerType(); + SrcType->isObjCObjectPointerType(); if (CheckInferredResultType) { SrcType = SrcType.getUnqualifiedType(); DstType = DstType.getUnqualifiedType(); @@ -17225,7 +17315,8 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, break; case AssignConvertType::IncompatiblePointerDiscardsQualifiers: { // Perform array-to-pointer decay if necessary. - if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); + if (SrcType->isArrayType()) + SrcType = Context.getArrayDecayedType(SrcType); isInvalid = true; @@ -17259,10 +17350,10 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) return false; if (getLangOpts().CPlusPlus) { - DiagKind = diag::err_typecheck_convert_discards_qualifiers; + DiagKind = diag::err_typecheck_convert_discards_qualifiers; isInvalid = true; } else { - DiagKind = diag::ext_typecheck_convert_discards_qualifiers; + DiagKind = diag::ext_typecheck_convert_discards_qualifiers; } break; @@ -17289,24 +17380,23 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, case AssignConvertType::IncompatibleObjCQualifiedId: { if (SrcType->isObjCQualifiedIdType()) { const ObjCObjectPointerType *srcOPT = - SrcType->castAs(); + SrcType->castAs(); for (auto *srcProto : srcOPT->quals()) { PDecl = srcProto; break; } if (const ObjCInterfaceType *IFaceT = - DstType->castAs()->getInterfaceType()) + DstType->castAs()->getInterfaceType()) IFace = IFaceT->getDecl(); - } - else if (DstType->isObjCQualifiedIdType()) { + } else if (DstType->isObjCQualifiedIdType()) { const ObjCObjectPointerType *dstOPT = - DstType->castAs(); + DstType->castAs(); for (auto *dstProto : dstOPT->quals()) { PDecl = dstProto; break; } if (const ObjCInterfaceType *IFaceT = - SrcType->castAs()->getInterfaceType()) + SrcType->castAs()->getInterfaceType()) IFace = IFaceT->getDecl(); } if (getLangOpts().CPlusPlus) { @@ -17389,7 +17479,9 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, FDiag << H; } - if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } + if (MayHaveConvFixit) { + FDiag << (unsigned)(ConvHints.Kind); + } if (MayHaveFunctionDiff) HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); @@ -17402,8 +17494,8 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, << IFace << PDecl; if (SecondType == Context.OverloadTy) - NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, - FirstType, /*TakingAddress=*/true); + NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, FirstType, + /*TakingAddress=*/true); if (CheckInferredResultType) ObjC().EmitRelatedResultTypeNote(SrcExpr); @@ -17417,8 +17509,7 @@ bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, return isInvalid; } -ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, - llvm::APSInt *Result, +ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, AllowFoldKind CanFold) { class SimpleICEDiagnoser : public VerifyICEDiagnoser { public: @@ -17435,8 +17526,7 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); } -ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, - llvm::APSInt *Result, +ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold) { class IDDiagnoser : public VerifyICEDiagnoser { @@ -17444,7 +17534,7 @@ ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, public: IDDiagnoser(unsigned DiagID) - : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } + : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) {} SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { return S.Diag(Loc, DiagID); @@ -17465,10 +17555,9 @@ Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; } -ExprResult -Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, - VerifyICEDiagnoser &Diagnoser, - AllowFoldKind CanFold) { +ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, + VerifyICEDiagnoser &Diagnoser, + AllowFoldKind CanFold) { SourceLocation DiagLoc = E->getBeginLoc(); if (getLangOpts().CPlusPlus11) { @@ -17480,6 +17569,7 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, ExprResult Converted; class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { VerifyICEDiagnoser &BaseDiagnoser; + public: CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, @@ -17491,41 +17581,43 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); } - SemaDiagnosticBuilder diagnoseIncomplete( - Sema &S, SourceLocation Loc, QualType T) override { + SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, + QualType T) override { return S.Diag(Loc, diag::err_ice_incomplete_type) << T; } - SemaDiagnosticBuilder diagnoseExplicitConv( - Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { + SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, + QualType T, + QualType ConvTy) override { return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; } - SemaDiagnosticBuilder noteExplicitConv( - Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { + SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, + QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) - << ConvTy->isEnumeralType() << ConvTy; + << ConvTy->isEnumeralType() << ConvTy; } - SemaDiagnosticBuilder diagnoseAmbiguous( - Sema &S, SourceLocation Loc, QualType T) override { + SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, + QualType T) override { return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; } - SemaDiagnosticBuilder noteAmbiguous( - Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { + SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, + QualType ConvTy) override { return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) - << ConvTy->isEnumeralType() << ConvTy; + << ConvTy->isEnumeralType() << ConvTy; } - SemaDiagnosticBuilder diagnoseConversion( - Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { + SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, + QualType T, + QualType ConvTy) override { llvm_unreachable("conversion functions are permitted"); } } ConvertDiagnoser(Diagnoser); - Converted = PerformContextualImplicitConversion(DiagLoc, E, - ConvertDiagnoser); + Converted = + PerformContextualImplicitConversion(DiagLoc, E, ConvertDiagnoser); if (Converted.isInvalid()) return Converted; E = Converted.get(); @@ -17568,7 +17660,7 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, // the caret at its location rather than producing an essentially // redundant note. if (Notes.size() == 1 && Notes[0].second.getDiagID() == - diag::note_invalid_subexpr_in_const_expr) { + diag::note_invalid_subexpr_in_const_expr) { DiagLoc = Notes[0].first; Notes.clear(); } @@ -17615,8 +17707,8 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, // If our only note is the usual "invalid subexpression" note, just point // the caret at its location rather than producing an essentially // redundant note. - if (Notes.size() == 1 && Notes[0].second.getDiagID() == - diag::note_invalid_subexpr_in_const_expr) { + if (Notes.size() == 1 && + Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { DiagLoc = Notes[0].first; Notes.clear(); } @@ -17641,58 +17733,57 @@ Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, } namespace { - // Handle the case where we conclude a expression which we speculatively - // considered to be unevaluated is actually evaluated. - class TransformToPE : public TreeTransform { - typedef TreeTransform BaseTransform; +// Handle the case where we conclude a expression which we speculatively +// considered to be unevaluated is actually evaluated. +class TransformToPE : public TreeTransform { + typedef TreeTransform BaseTransform; - public: - TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } +public: + TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) {} - // Make sure we redo semantic analysis - bool AlwaysRebuild() { return true; } - bool ReplacingOriginal() { return true; } + // Make sure we redo semantic analysis + bool AlwaysRebuild() { return true; } + bool ReplacingOriginal() { return true; } - // We need to special-case DeclRefExprs referring to FieldDecls which - // are not part of a member pointer formation; normal TreeTransforming - // doesn't catch this case because of the way we represent them in the AST. - // FIXME: This is a bit ugly; is it really the best way to handle this - // case? - // - // Error on DeclRefExprs referring to FieldDecls. - ExprResult TransformDeclRefExpr(DeclRefExpr *E) { - if (isa(E->getDecl()) && - !SemaRef.isUnevaluatedContext()) - return SemaRef.Diag(E->getLocation(), - diag::err_invalid_non_static_member_use) - << E->getDecl() << E->getSourceRange(); + // We need to special-case DeclRefExprs referring to FieldDecls which + // are not part of a member pointer formation; normal TreeTransforming + // doesn't catch this case because of the way we represent them in the AST. + // FIXME: This is a bit ugly; is it really the best way to handle this + // case? + // + // Error on DeclRefExprs referring to FieldDecls. + ExprResult TransformDeclRefExpr(DeclRefExpr *E) { + if (isa(E->getDecl()) && !SemaRef.isUnevaluatedContext()) + return SemaRef.Diag(E->getLocation(), + diag::err_invalid_non_static_member_use) + << E->getDecl() << E->getSourceRange(); - return BaseTransform::TransformDeclRefExpr(E); - } + return BaseTransform::TransformDeclRefExpr(E); + } - // Exception: filter out member pointer formation - ExprResult TransformUnaryOperator(UnaryOperator *E) { - if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) - return E; + // Exception: filter out member pointer formation + ExprResult TransformUnaryOperator(UnaryOperator *E) { + if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) + return E; - return BaseTransform::TransformUnaryOperator(E); - } + return BaseTransform::TransformUnaryOperator(E); + } - // The body of a lambda-expression is in a separate expression evaluation - // context so never needs to be transformed. - // FIXME: Ideally we wouldn't transform the closure type either, and would - // just recreate the capture expressions and lambda expression. - StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { - return SkipLambdaBody(E, Body); - } - }; -} + // The body of a lambda-expression is in a separate expression evaluation + // context so never needs to be transformed. + // FIXME: Ideally we wouldn't transform the closure type either, and would + // just recreate the capture expressions and lambda expression. + StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { + return SkipLambdaBody(E, Body); + } +}; +} // namespace ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { assert(isUnevaluatedContext() && "Should only transform unevaluated expressions"); ExprEvalContexts.back().Context = - ExprEvalContexts[ExprEvalContexts.size()-2].Context; + ExprEvalContexts[ExprEvalContexts.size() - 2].Context; if (isUnevaluatedContext()) return E; return TransformToPE(*this).TransformExpr(E); @@ -17707,8 +17798,7 @@ TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { return TransformToPE(*this).TransformType(TInfo); } -void -Sema::PushExpressionEvaluationContext( +void Sema::PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, @@ -17736,8 +17826,7 @@ Sema::PushExpressionEvaluationContext( std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); } -void -Sema::PushExpressionEvaluationContext( +void Sema::PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; @@ -17783,6 +17872,27 @@ void Sema::PushExpressionEvaluationContextForFunction( } } +ExprResult Sema::ActOnCXXReflectExpr(SourceLocation OpLoc, + TypeSourceInfo *TSI) { + return BuildCXXReflectExpr(OpLoc, TSI->getTypeLoc().getBeginLoc(), + TSI->getType()); +} + +ExprResult Sema::ActOnCXXReflectExpr(SourceLocation OpLoc, + SourceLocation ArgLoc, Decl *D) { + return BuildCXXReflectExpr(OpLoc, ArgLoc, D); +} + +ExprResult Sema::BuildCXXReflectExpr(SourceLocation OperatorLoc, + SourceLocation OperandLoc, QualType T) { + return CXXReflectExpr::Create(Context, OperatorLoc, OperandLoc, T); +} + +ExprResult Sema::BuildCXXReflectExpr(SourceLocation OperatorLoc, + SourceLocation OperandLoc, Decl *D) { + return CXXReflectExpr::Create(Context, OperatorLoc, OperandLoc, D); +} + namespace { const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { @@ -17996,7 +18106,7 @@ static void RemoveNestedImmediateInvocation( SmallVector::reverse_iterator Current) : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} - void RemoveImmediateInvocation(ConstantExpr* E) { + void RemoveImmediateInvocation(ConstantExpr *E) { auto It = std::find_if(CurrentII, IISet.rend(), [E](Sema::ImmediateInvocationCandidate Elem) { return Elem.getPointer() == E; @@ -18200,7 +18310,7 @@ HandleImmediateInvocations(Sema &SemaRef, } void Sema::PopExpressionEvaluationContext() { - ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); + ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back(); if (!Rec.Lambdas.empty()) { using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; if (!getLangOpts().CPlusPlus20 && @@ -18260,7 +18370,7 @@ void Sema::PopExpressionEvaluationContext() { Cleanup = Rec.ParentCleanup; CleanupVarDeclMarking(); std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); - // Otherwise, merge the contexts together. + // Otherwise, merge the contexts together. } else { Cleanup.mergeFrom(Rec.ParentCleanup); MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs); @@ -18273,9 +18383,9 @@ void Sema::PopExpressionEvaluationContext() { } void Sema::DiscardCleanupsInEvaluationContext() { - ExprCleanupObjects.erase( - ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, - ExprCleanupObjects.end()); + ExprCleanupObjects.erase(ExprCleanupObjects.begin() + + ExprEvalContexts.back().NumCleanupObjects, + ExprCleanupObjects.end()); Cleanup.reset(); MaybeODRUseExprs.clear(); } @@ -18296,27 +18406,27 @@ static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { /// C++2a [expr.const]p12: // An expression or conversion is potentially constant evaluated if it is switch (SemaRef.ExprEvalContexts.back().Context) { - case Sema::ExpressionEvaluationContext::ConstantEvaluated: - case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: - - // -- a manifestly constant-evaluated expression, - case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: - case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: - case Sema::ExpressionEvaluationContext::DiscardedStatement: - // -- a potentially-evaluated expression, - case Sema::ExpressionEvaluationContext::UnevaluatedList: - // -- an immediate subexpression of a braced-init-list, - - // -- [FIXME] an expression of the form & cast-expression that occurs - // within a templated entity - // -- a subexpression of one of the above that is not a subexpression of - // a nested unevaluated operand. - return true; + case Sema::ExpressionEvaluationContext::ConstantEvaluated: + case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: + + // -- a manifestly constant-evaluated expression, + case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: + case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: + case Sema::ExpressionEvaluationContext::DiscardedStatement: + // -- a potentially-evaluated expression, + case Sema::ExpressionEvaluationContext::UnevaluatedList: + // -- an immediate subexpression of a braced-init-list, + + // -- [FIXME] an expression of the form & cast-expression that occurs + // within a templated entity + // -- a subexpression of one of the above that is not a subexpression of + // a nested unevaluated operand. + return true; - case Sema::ExpressionEvaluationContext::Unevaluated: - case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: - // Expressions in this context are never evaluated. - return false; + case Sema::ExpressionEvaluationContext::Unevaluated: + case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: + // Expressions in this context are never evaluated. + return false; } llvm_unreachable("Invalid context"); } @@ -18594,7 +18704,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, PointOfInstantiation = Loc; if (auto *MSI = Func->getMemberSpecializationInfo()) MSI->setPointOfInstantiation(Loc); - // FIXME: Notify listener. + // FIXME: Notify listener. else Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); } else if (TSK != TSK_ImplicitInstantiation) { @@ -18687,8 +18797,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) { if (mightHaveNonExternalLinkage(Func)) UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); - else if (Func->getMostRecentDecl()->isInlined() && - !LangOpts.GNUInline && + else if (Func->getMostRecentDecl()->isInlined() && !LangOpts.GNUInline && !Func->getMostRecentDecl()->hasAttr()) UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); else if (isExternalWithNoLinkageType(Func)) @@ -18810,8 +18919,7 @@ static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, // If the parameter still belongs to the translation unit, then // we're actually just using one parameter in the declaration of // the next. - if (isa(var) && - isa(VarDC)) + if (isa(var) && isa(VarDC)) return; // For C code, don't diagnose about capture if we're not actually in code @@ -18836,9 +18944,8 @@ static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, } S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) - << var << ValueKind << ContextKind << VarDC; - S.Diag(var->getLocation(), diag::note_entity_declared_at) - << var; + << var << ValueKind << ContextKind << VarDC; + S.Diag(var->getLocation(), diag::note_entity_declared_at) << var; // FIXME: Add additional diagnostic info about class etc. which prevents // capture. @@ -19002,8 +19109,7 @@ static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, if (!Invalid && CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { if (BuildAndDiagnose) { - S.Diag(Loc, diag::err_arc_autoreleasing_capture) - << /*block*/ 0; + S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*block*/ 0; S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; Invalid = true; } else { @@ -19134,7 +19240,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, // captured entity is a reference to a function, the // corresponding data member is also a reference to a // function. - end note ] - if (const ReferenceType *RefType = CaptureType->getAs()){ + if (const ReferenceType *RefType = CaptureType->getAs()) { if (!RefType->getPointeeType()->isFunctionType()) CaptureType = RefType->getPointeeType(); } @@ -19145,7 +19251,7 @@ static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, if (BuildAndDiagnose) { S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; S.Diag(Var->getLocation(), diag::note_previous_decl) - << Var->getDeclName(); + << Var->getDeclName(); Invalid = true; } else { return false; @@ -19332,7 +19438,8 @@ bool Sema::tryCaptureVariable( assert(VD && "Cannot capture a null variable"); const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt - ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; + ? *FunctionScopeIndexToStopAt + : FunctionScopes.size() - 1; // We need to sync up the Declaration Context with the // FunctionScopeIndexToStopAt if (FunctionScopeIndexToStopAt) { @@ -19417,7 +19524,7 @@ bool Sema::tryCaptureVariable( return true; } - FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; + FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; CapturingScopeInfo *CSI = cast(FSI); // Check whether we've already captured it. @@ -19565,13 +19672,13 @@ bool Sema::tryCaptureVariable( // If the variable had already been captured previously, we start capturing // at the lambda nested within that one. bool Invalid = false; - for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; - ++I) { + for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; + I != N; ++I) { CapturingScopeInfo *CSI = cast(FunctionScopes[I]); - // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture - // certain types of variables (unnamed, variably modified types etc.) - // so check for eligibility. + // Certain capturing entities (lambdas, blocks etc.) are not allowed to + // capture certain types of variables (unnamed, variably modified types + // etc.) so check for eligibility. if (!Invalid) Invalid = !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); @@ -19582,10 +19689,12 @@ bool Sema::tryCaptureVariable( return true; if (BlockScopeInfo *BSI = dyn_cast(CSI)) { - Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, - DeclRefType, Nested, *this, Invalid); + Invalid = + !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, + DeclRefType, Nested, *this, Invalid); Nested = true; - } else if (CapturedRegionScopeInfo *RSI = dyn_cast(CSI)) { + } else if (CapturedRegionScopeInfo *RSI = + dyn_cast(CSI)) { Invalid = !captureInCapturedRegion( RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); @@ -19610,8 +19719,8 @@ bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, QualType CaptureType; QualType DeclRefType; return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, - /*BuildAndDiagnose=*/true, CaptureType, - DeclRefType, nullptr); + /*BuildAndDiagnose=*/true, CaptureType, DeclRefType, + nullptr); } bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { @@ -19645,23 +19754,24 @@ namespace { class CopiedTemplateArgs { bool HasArgs; TemplateArgumentListInfo TemplateArgStorage; + public: - template + template CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { if (HasArgs) E->copyTemplateArgumentsInto(TemplateArgStorage); } - operator TemplateArgumentListInfo*() + operator TemplateArgumentListInfo *() #ifdef __has_cpp_attribute #if __has_cpp_attribute(clang::lifetimebound) - [[clang::lifetimebound]] + [[clang::lifetimebound]] #endif #endif { return HasArgs ? &TemplateArgStorage : nullptr; } }; -} +} // namespace /// Walk the set of potential results of an expression and mark them all as /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. @@ -19853,7 +19963,7 @@ static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, if (!Sub.isUsable()) return Sub; BO->setLHS(Sub.get()); - // -- If e is a comma expression, ... + // -- If e is a comma expression, ... } else if (BO->getOpcode() == BO_Comma) { ExprResult Sub = Rebuild(RHS); if (!Sub.isUsable()) @@ -20050,8 +20160,8 @@ void Sema::CleanupVarDeclMarking() { for (Expr *E : LocalMaybeODRUseExprs) { if (auto *DRE = dyn_cast(E)) { - MarkVarDeclODRUsed(cast(DRE->getDecl()), - DRE->getLocation(), *this); + MarkVarDeclODRUsed(cast(DRE->getDecl()), DRE->getLocation(), + *this); } else if (auto *ME = dyn_cast(E)) { MarkVarDeclODRUsed(cast(ME->getMemberDecl()), ME->getMemberLoc(), *this); @@ -20165,7 +20275,7 @@ static void DoMarkVarDeclReferenced( PointOfInstantiation = Loc; if (MSI) MSI->setPointOfInstantiation(PointOfInstantiation); - // FIXME: Notify listener. + // FIXME: Notify listener. else Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); } @@ -20191,8 +20301,8 @@ static void DoMarkVarDeclReferenced( else if (auto *ME = dyn_cast_or_null(E)) ME->setMemberDecl(ME->getMemberDecl()); } else if (FirstInstantiation) { - SemaRef.PendingInstantiations - .push_back(std::make_pair(Var, PointOfInstantiation)); + SemaRef.PendingInstantiations.push_back( + std::make_pair(Var, PointOfInstantiation)); } else { bool Inserted = false; for (auto &I : SemaRef.SavedPendingInstantiations) { @@ -20214,8 +20324,8 @@ static void DoMarkVarDeclReferenced( // no direct way to avoid enqueueing the pending instantiation // multiple times. if (isa(Var) && !Inserted) - SemaRef.PendingInstantiations - .push_back(std::make_pair(Var, PointOfInstantiation)); + SemaRef.PendingInstantiations.push_back( + std::make_pair(Var, PointOfInstantiation)); } } } @@ -20389,8 +20499,8 @@ MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, if (!MD) return; // Only attempt to devirtualize if this is truly a virtual call. - bool IsVirtualCall = MD->isVirtual() && - ME->performsVirtualDispatch(SemaRef.getLangOpts()); + bool IsVirtualCall = + MD->isVirtual() && ME->performsVirtualDispatch(SemaRef.getLangOpts()); if (!IsVirtualCall) return; @@ -20471,13 +20581,13 @@ void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, } namespace { - // Mark all of the declarations used by a type as referenced. - // FIXME: Not fully implemented yet! We need to have a better understanding - // of when we're entering a context we should not recurse into. - // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to - // TreeTransforms rebuilding the type in a new context. Rather than - // duplicating the TreeTransform logic, we should consider reusing it here. - // Currently that causes problems when rebuilding LambdaExprs. +// Mark all of the declarations used by a type as referenced. +// FIXME: Not fully implemented yet! We need to have a better understanding +// of when we're entering a context we should not recurse into. +// FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to +// TreeTransforms rebuilding the type in a new context. Rather than +// duplicating the TreeTransform logic, we should consider reusing it here. +// Currently that causes problems when rebuilding LambdaExprs. class MarkReferencedDecls : public DynamicRecursiveASTVisitor { Sema &S; SourceLocation Loc; @@ -20487,7 +20597,7 @@ class MarkReferencedDecls : public DynamicRecursiveASTVisitor { bool TraverseTemplateArgument(const TemplateArgument &Arg) override; }; -} +} // namespace bool MarkReferencedDecls::TraverseTemplateArgument( const TemplateArgument &Arg) { @@ -20560,9 +20670,8 @@ class EvaluatedExprMarker : public UsedDeclVisitor { }; } // namespace -void Sema::MarkDeclarationsReferencedInExpr(Expr *E, - bool SkipLocalVariables, - ArrayRef StopAt) { +void Sema::MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables, + ArrayRef StopAt) { EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); } @@ -20614,7 +20723,7 @@ bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef Stmts, /// behavior of a program, such as passing a non-POD value through an ellipsis. /// Failure to do so will likely result in spurious diagnostics or failures /// during overload resolution or within sizeof/alignof/typeof/typeid. -bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef Stmts, +bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef Stmts, const PartialDiagnostic &PD) { if (ExprEvalContexts.back().isDiscardedStatementContext()) @@ -20667,12 +20776,12 @@ bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, public: CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) - : FD(FD), CE(CE) { } + : FD(FD), CE(CE) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { if (!FD) { S.Diag(Loc, diag::err_call_incomplete_return) - << T << CE->getSourceRange(); + << T << CE->getSourceRange(); return; } @@ -20704,8 +20813,8 @@ void Sema::DiagnoseAssignmentAsCondition(Expr *E) { IsOrAssign = Op->getOpcode() == BO_OrAssign; // Greylist some idioms by putting them into a warning subcategory. - if (ObjCMessageExpr *ME - = dyn_cast(Op->getRHS()->IgnoreParenCasts())) { + if (ObjCMessageExpr *ME = + dyn_cast(Op->getRHS()->IgnoreParenCasts())) { Selector Sel = ME->getSelector(); // self = [ init...] @@ -20736,15 +20845,15 @@ void Sema::DiagnoseAssignmentAsCondition(Expr *E) { SourceLocation Open = E->getBeginLoc(); SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); Diag(Loc, diag::note_condition_assign_silence) - << FixItHint::CreateInsertion(Open, "(") - << FixItHint::CreateInsertion(Close, ")"); + << FixItHint::CreateInsertion(Open, "(") + << FixItHint::CreateInsertion(Close, ")"); if (IsOrAssign) Diag(Loc, diag::note_condition_or_assign_to_comparison) - << FixItHint::CreateReplacement(Loc, "!="); + << FixItHint::CreateReplacement(Loc, "!="); else Diag(Loc, diag::note_condition_assign_to_comparison) - << FixItHint::CreateReplacement(Loc, "=="); + << FixItHint::CreateReplacement(Loc, "=="); } void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { @@ -20762,17 +20871,17 @@ void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { if (BinaryOperator *opE = dyn_cast(E)) if (opE->getOpcode() == BO_EQ && - opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) - == Expr::MLV_Valid) { + opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) == + Expr::MLV_Valid) { SourceLocation Loc = opE->getOperatorLoc(); Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); SourceRange ParenERange = ParenE->getSourceRange(); Diag(Loc, diag::note_equality_comparison_silence) - << FixItHint::CreateRemoval(ParenERange.getBegin()) - << FixItHint::CreateRemoval(ParenERange.getEnd()); + << FixItHint::CreateRemoval(ParenERange.getBegin()) + << FixItHint::CreateRemoval(ParenERange.getEnd()); Diag(Loc, diag::note_equality_comparison_to_assign) - << FixItHint::CreateReplacement(Loc, "="); + << FixItHint::CreateReplacement(Loc, "="); } } @@ -20783,7 +20892,8 @@ ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, DiagnoseEqualityWithExtraParens(parenE); ExprResult result = CheckPlaceholderExpr(E); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); E = result.get(); if (!E->isTypeDependent()) { @@ -20798,7 +20908,7 @@ ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, QualType T = E->getType(); if (!T->isScalarType()) { // C99 6.8.4.1p1 Diag(Loc, diag::err_typecheck_statement_requires_scalar) - << T << E->getSourceRange(); + << T << E->getSourceRange(); return ExprError(); } CheckBoolLikeConversion(E, Loc); @@ -20846,190 +20956,182 @@ Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, } namespace { - /// A visitor for rebuilding a call to an __unknown_any expression - /// to have an appropriate type. - struct RebuildUnknownAnyFunction +/// A visitor for rebuilding a call to an __unknown_any expression +/// to have an appropriate type. +struct RebuildUnknownAnyFunction : StmtVisitor { - Sema &S; + Sema &S; - RebuildUnknownAnyFunction(Sema &S) : S(S) {} + RebuildUnknownAnyFunction(Sema &S) : S(S) {} - ExprResult VisitStmt(Stmt *S) { - llvm_unreachable("unexpected statement!"); - } + ExprResult VisitStmt(Stmt *S) { llvm_unreachable("unexpected statement!"); } - ExprResult VisitExpr(Expr *E) { - S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) + ExprResult VisitExpr(Expr *E) { + S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) << E->getSourceRange(); - return ExprError(); - } + return ExprError(); + } - /// Rebuild an expression which simply semantically wraps another - /// expression which it shares the type and value kind of. - template ExprResult rebuildSugarExpr(T *E) { - ExprResult SubResult = Visit(E->getSubExpr()); - if (SubResult.isInvalid()) return ExprError(); + /// Rebuild an expression which simply semantically wraps another + /// expression which it shares the type and value kind of. + template ExprResult rebuildSugarExpr(T *E) { + ExprResult SubResult = Visit(E->getSubExpr()); + if (SubResult.isInvalid()) + return ExprError(); - Expr *SubExpr = SubResult.get(); - E->setSubExpr(SubExpr); - E->setType(SubExpr->getType()); - E->setValueKind(SubExpr->getValueKind()); - assert(E->getObjectKind() == OK_Ordinary); - return E; - } + Expr *SubExpr = SubResult.get(); + E->setSubExpr(SubExpr); + E->setType(SubExpr->getType()); + E->setValueKind(SubExpr->getValueKind()); + assert(E->getObjectKind() == OK_Ordinary); + return E; + } - ExprResult VisitParenExpr(ParenExpr *E) { - return rebuildSugarExpr(E); - } + ExprResult VisitParenExpr(ParenExpr *E) { return rebuildSugarExpr(E); } - ExprResult VisitUnaryExtension(UnaryOperator *E) { - return rebuildSugarExpr(E); - } + ExprResult VisitUnaryExtension(UnaryOperator *E) { + return rebuildSugarExpr(E); + } - ExprResult VisitUnaryAddrOf(UnaryOperator *E) { - ExprResult SubResult = Visit(E->getSubExpr()); - if (SubResult.isInvalid()) return ExprError(); + ExprResult VisitUnaryAddrOf(UnaryOperator *E) { + ExprResult SubResult = Visit(E->getSubExpr()); + if (SubResult.isInvalid()) + return ExprError(); - Expr *SubExpr = SubResult.get(); - E->setSubExpr(SubExpr); - E->setType(S.Context.getPointerType(SubExpr->getType())); - assert(E->isPRValue()); - assert(E->getObjectKind() == OK_Ordinary); - return E; - } + Expr *SubExpr = SubResult.get(); + E->setSubExpr(SubExpr); + E->setType(S.Context.getPointerType(SubExpr->getType())); + assert(E->isPRValue()); + assert(E->getObjectKind() == OK_Ordinary); + return E; + } - ExprResult resolveDecl(Expr *E, ValueDecl *VD) { - if (!isa(VD)) return VisitExpr(E); + ExprResult resolveDecl(Expr *E, ValueDecl *VD) { + if (!isa(VD)) + return VisitExpr(E); - E->setType(VD->getType()); + E->setType(VD->getType()); - assert(E->isPRValue()); - if (S.getLangOpts().CPlusPlus && - !(isa(VD) && - cast(VD)->isInstance())) - E->setValueKind(VK_LValue); + assert(E->isPRValue()); + if (S.getLangOpts().CPlusPlus && + !(isa(VD) && cast(VD)->isInstance())) + E->setValueKind(VK_LValue); - return E; - } + return E; + } - ExprResult VisitMemberExpr(MemberExpr *E) { - return resolveDecl(E, E->getMemberDecl()); - } + ExprResult VisitMemberExpr(MemberExpr *E) { + return resolveDecl(E, E->getMemberDecl()); + } - ExprResult VisitDeclRefExpr(DeclRefExpr *E) { - return resolveDecl(E, E->getDecl()); - } - }; -} + ExprResult VisitDeclRefExpr(DeclRefExpr *E) { + return resolveDecl(E, E->getDecl()); + } +}; +} // namespace /// Given a function expression of unknown-any type, try to rebuild it /// to have a function type. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); return S.DefaultFunctionArrayConversion(Result.get()); } namespace { - /// A visitor for rebuilding an expression of type __unknown_anytype - /// into one which resolves the type directly on the referring - /// expression. Strict preservation of the original source - /// structure is not a goal. - struct RebuildUnknownAnyExpr - : StmtVisitor { +/// A visitor for rebuilding an expression of type __unknown_anytype +/// into one which resolves the type directly on the referring +/// expression. Strict preservation of the original source +/// structure is not a goal. +struct RebuildUnknownAnyExpr : StmtVisitor { - Sema &S; + Sema &S; - /// The current destination type. - QualType DestType; + /// The current destination type. + QualType DestType; - RebuildUnknownAnyExpr(Sema &S, QualType CastType) + RebuildUnknownAnyExpr(Sema &S, QualType CastType) : S(S), DestType(CastType) {} - ExprResult VisitStmt(Stmt *S) { - llvm_unreachable("unexpected statement!"); - } + ExprResult VisitStmt(Stmt *S) { llvm_unreachable("unexpected statement!"); } - ExprResult VisitExpr(Expr *E) { - S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) + ExprResult VisitExpr(Expr *E) { + S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) << E->getSourceRange(); - return ExprError(); - } + return ExprError(); + } - ExprResult VisitCallExpr(CallExpr *E); - ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); + ExprResult VisitCallExpr(CallExpr *E); + ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); - /// Rebuild an expression which simply semantically wraps another - /// expression which it shares the type and value kind of. - template ExprResult rebuildSugarExpr(T *E) { - ExprResult SubResult = Visit(E->getSubExpr()); - if (SubResult.isInvalid()) return ExprError(); - Expr *SubExpr = SubResult.get(); - E->setSubExpr(SubExpr); - E->setType(SubExpr->getType()); - E->setValueKind(SubExpr->getValueKind()); - assert(E->getObjectKind() == OK_Ordinary); - return E; - } + /// Rebuild an expression which simply semantically wraps another + /// expression which it shares the type and value kind of. + template ExprResult rebuildSugarExpr(T *E) { + ExprResult SubResult = Visit(E->getSubExpr()); + if (SubResult.isInvalid()) + return ExprError(); + Expr *SubExpr = SubResult.get(); + E->setSubExpr(SubExpr); + E->setType(SubExpr->getType()); + E->setValueKind(SubExpr->getValueKind()); + assert(E->getObjectKind() == OK_Ordinary); + return E; + } - ExprResult VisitParenExpr(ParenExpr *E) { - return rebuildSugarExpr(E); - } + ExprResult VisitParenExpr(ParenExpr *E) { return rebuildSugarExpr(E); } - ExprResult VisitUnaryExtension(UnaryOperator *E) { - return rebuildSugarExpr(E); - } + ExprResult VisitUnaryExtension(UnaryOperator *E) { + return rebuildSugarExpr(E); + } - ExprResult VisitUnaryAddrOf(UnaryOperator *E) { - const PointerType *Ptr = DestType->getAs(); - if (!Ptr) { - S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) + ExprResult VisitUnaryAddrOf(UnaryOperator *E) { + const PointerType *Ptr = DestType->getAs(); + if (!Ptr) { + S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) << E->getSourceRange(); - return ExprError(); - } + return ExprError(); + } - if (isa(E->getSubExpr())) { - S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) + if (isa(E->getSubExpr())) { + S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) << E->getSourceRange(); - return ExprError(); - } + return ExprError(); + } - assert(E->isPRValue()); - assert(E->getObjectKind() == OK_Ordinary); - E->setType(DestType); + assert(E->isPRValue()); + assert(E->getObjectKind() == OK_Ordinary); + E->setType(DestType); - // Build the sub-expression as if it were an object of the pointee type. - DestType = Ptr->getPointeeType(); - ExprResult SubResult = Visit(E->getSubExpr()); - if (SubResult.isInvalid()) return ExprError(); - E->setSubExpr(SubResult.get()); - return E; - } + // Build the sub-expression as if it were an object of the pointee type. + DestType = Ptr->getPointeeType(); + ExprResult SubResult = Visit(E->getSubExpr()); + if (SubResult.isInvalid()) + return ExprError(); + E->setSubExpr(SubResult.get()); + return E; + } - ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); + ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); - ExprResult resolveDecl(Expr *E, ValueDecl *VD); + ExprResult resolveDecl(Expr *E, ValueDecl *VD); - ExprResult VisitMemberExpr(MemberExpr *E) { - return resolveDecl(E, E->getMemberDecl()); - } + ExprResult VisitMemberExpr(MemberExpr *E) { + return resolveDecl(E, E->getMemberDecl()); + } - ExprResult VisitDeclRefExpr(DeclRefExpr *E) { - return resolveDecl(E, E->getDecl()); - } - }; -} + ExprResult VisitDeclRefExpr(DeclRefExpr *E) { + return resolveDecl(E, E->getDecl()); + } +}; +} // namespace /// Rebuilds a call expression which yielded __unknown_anytype. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { Expr *CalleeExpr = E->getCallee(); - enum FnKind { - FK_MemberFunction, - FK_FunctionPointer, - FK_BlockPointer - }; + enum FnKind { FK_MemberFunction, FK_FunctionPointer, FK_BlockPointer }; FnKind Kind; QualType CalleeType = CalleeExpr->getType(); @@ -21053,8 +21155,7 @@ ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { if (Kind == FK_BlockPointer) diagID = diag::err_block_returning_array_function; - S.Diag(E->getExprLoc(), diagID) - << DestType->isFunctionType() << DestType; + S.Diag(E->getExprLoc(), diagID) << DestType->isFunctionType() << DestType; return ExprError(); } @@ -21097,8 +21198,7 @@ ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { DestType = S.Context.getFunctionType(DestType, ParamTypes, Proto->getExtProtoInfo()); } else { - DestType = S.Context.getFunctionNoProtoType(DestType, - FnType->getExtInfo()); + DestType = S.Context.getFunctionNoProtoType(DestType, FnType->getExtInfo()); } // Rebuild the appropriate pointer-to-function type. @@ -21118,7 +21218,8 @@ ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { // Finally, we can recurse. ExprResult CalleeResult = Visit(CalleeExpr); - if (!CalleeResult.isUsable()) return ExprError(); + if (!CalleeResult.isUsable()) + return ExprError(); E->setCallee(CalleeResult.get()); // Bind a temporary if necessary. @@ -21129,7 +21230,7 @@ ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { // Verify that this is a legal result type of a call. if (DestType->isArrayType() || DestType->isFunctionType()) { S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) - << DestType->isFunctionType() << DestType; + << DestType->isFunctionType() << DestType; return ExprError(); } @@ -21158,7 +21259,8 @@ ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { DestType = DestType->castAs()->getPointeeType(); ExprResult Result = Visit(E->getSubExpr()); - if (!Result.isUsable()) return ExprError(); + if (!Result.isUsable()) + return ExprError(); E->setSubExpr(Result.get()); return E; @@ -21174,7 +21276,8 @@ ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { DestType = S.Context.getLValueReferenceType(DestType); ExprResult Result = Visit(E->getSubExpr()); - if (!Result.isUsable()) return ExprError(); + if (!Result.isUsable()) + return ExprError(); E->setSubExpr(Result.get()); return E; @@ -21194,14 +21297,15 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { if (const PointerType *Ptr = Type->getAs()) { DestType = Ptr->getPointeeType(); ExprResult Result = resolveDecl(E, VD); - if (Result.isInvalid()) return ExprError(); + if (Result.isInvalid()) + return ExprError(); return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, VK_PRValue); } if (!Type->isFunctionType()) { S.Diag(E->getExprLoc(), diag::err_unknown_any_function) - << VD << E->getSourceRange(); + << VD << E->getSourceRange(); return ExprError(); } if (const FunctionProtoType *FT = Type->getAs()) { @@ -21210,9 +21314,11 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { // type. See the lengthy commentary in that routine. QualType FDT = FD->getType(); const FunctionType *FnType = FDT->castAs(); - const FunctionProtoType *Proto = dyn_cast_or_null(FnType); + const FunctionProtoType *Proto = + dyn_cast_or_null(FnType); DeclRefExpr *DRE = dyn_cast(E); - if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { + if (DRE && Proto && Proto->getParamTypes().empty() && + Proto->isVariadic()) { SourceLocation Loc = FD->getLocation(); FunctionDecl *NewFD = FunctionDecl::Create( S.Context, FD->getDeclContext(), Loc, Loc, @@ -21224,10 +21330,9 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { if (FD->getQualifier()) NewFD->setQualifierInfo(FD->getQualifierLoc()); - SmallVector Params; + SmallVector Params; for (const auto &AI : FT->param_types()) { - ParmVarDecl *Param = - S.BuildParmVarDeclForTypedef(FD, Loc, AI); + ParmVarDecl *Param = S.BuildParmVarDeclForTypedef(FD, Loc, AI); Param->setScopeInfo(0, Params.size()); Params.push_back(Param); } @@ -21247,20 +21352,20 @@ ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { if (!S.getLangOpts().CPlusPlus) ValueKind = VK_PRValue; - // - variables + // - variables } else if (isa(VD)) { if (const ReferenceType *RefTy = Type->getAs()) { Type = RefTy->getPointeeType(); } else if (Type->isFunctionType()) { S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) - << VD << E->getSourceRange(); + << VD << E->getSourceRange(); return ExprError(); } - // - nothing else + // - nothing else } else { S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) - << VD << E->getSourceRange(); + << VD << E->getSourceRange(); return ExprError(); } @@ -21283,7 +21388,8 @@ ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, // Rewrite the casted expression from scratch. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); - if (!result.isUsable()) return ExprError(); + if (!result.isUsable()) + return ExprError(); CastExpr = result.get(); VK = CastExpr->getValueKind(); @@ -21296,14 +21402,15 @@ ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { return RebuildUnknownAnyExpr(*this, ToType).Visit(E); } -ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, - Expr *arg, QualType ¶mType) { +ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, Expr *arg, + QualType ¶mType) { // If the syntactic form of the argument is not an explicit cast of // any sort, just do default argument promotion. ExplicitCastExpr *castArg = dyn_cast(arg->IgnoreParens()); if (!castArg) { ExprResult result = DefaultArgumentPromotion(arg); - if (result.isInvalid()) return ExprError(); + if (result.isInvalid()) + return ExprError(); paramType = result.get()->getType(); return result; } @@ -21314,8 +21421,8 @@ ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, // Copy-initialize a parameter of that type. InitializedEntity entity = - InitializedEntity::InitializeParameter(Context, paramType, - /*consumed*/ false); + InitializedEntity::InitializeParameter(Context, paramType, + /*consumed*/ false); return PerformCopyInitialization(entity, callLoc, arg); } @@ -21346,13 +21453,13 @@ static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { d = msg->getMethodDecl(); if (!d) { S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) - << static_cast(msg->isClassMessage()) << msg->getSelector() - << orig->getSourceRange(); + << static_cast(msg->isClassMessage()) << msg->getSelector() + << orig->getSourceRange(); return ExprError(); } } else { S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) - << E->getSourceRange(); + << E->getSourceRange(); return ExprError(); } @@ -21364,7 +21471,8 @@ static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { ExprResult Sema::CheckPlaceholderExpr(Expr *E) { const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); - if (!placeholderType) return E; + if (!placeholderType) + return E; switch (placeholderType->getKind()) { case BuiltinType::UnresolvedTemplate: { @@ -21540,18 +21648,15 @@ ExprResult Sema::CheckPlaceholderExpr(Expr *E) { case BuiltinType::OMPIterator: return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); - // Everything else should be impossible. -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + // Everything else should be impossible. +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - case BuiltinType::Id: +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" -#define SVE_TYPE(Name, Id, SingletonId) \ - case BuiltinType::Id: +#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/AArch64ACLETypes.def" -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: #include "clang/Basic/PPCTypes.def" #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 0c8c1d18d317e..d47078cae8a84 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -12938,6 +12938,12 @@ ExprResult TreeTransform::TransformSYCLUniqueStableNameExpr( E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT); } +template +ExprResult TreeTransform::TransformCXXReflectExpr(CXXReflectExpr *E) { + // No subexpressions to recurse over in PR1. + return E; +} + template ExprResult TreeTransform::TransformPredefinedExpr(PredefinedExpr *E) { diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index eef97a8588f0b..1b60f1096069f 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -65,62 +65,48 @@ using namespace serialization; namespace clang { - class ASTStmtReader : public StmtVisitor { - ASTRecordReader &Record; - llvm::BitstreamCursor &DeclsCursor; +class ASTStmtReader : public StmtVisitor { + ASTRecordReader &Record; + llvm::BitstreamCursor &DeclsCursor; - std::optional CurrentUnpackingBits; + std::optional CurrentUnpackingBits; - SourceLocation readSourceLocation() { - return Record.readSourceLocation(); - } + SourceLocation readSourceLocation() { return Record.readSourceLocation(); } - SourceRange readSourceRange() { - return Record.readSourceRange(); - } + SourceRange readSourceRange() { return Record.readSourceRange(); } - std::string readString() { - return Record.readString(); - } + std::string readString() { return Record.readString(); } - TypeSourceInfo *readTypeSourceInfo() { - return Record.readTypeSourceInfo(); - } + TypeSourceInfo *readTypeSourceInfo() { return Record.readTypeSourceInfo(); } - Decl *readDecl() { - return Record.readDecl(); - } + Decl *readDecl() { return Record.readDecl(); } - template - T *readDeclAs() { - return Record.readDeclAs(); - } + template T *readDeclAs() { return Record.readDeclAs(); } - public: - ASTStmtReader(ASTRecordReader &Record, llvm::BitstreamCursor &Cursor) - : Record(Record), DeclsCursor(Cursor) {} +public: + ASTStmtReader(ASTRecordReader &Record, llvm::BitstreamCursor &Cursor) + : Record(Record), DeclsCursor(Cursor) {} - /// The number of record fields required for the Stmt class - /// itself. - static const unsigned NumStmtFields = 0; + /// The number of record fields required for the Stmt class + /// itself. + static const unsigned NumStmtFields = 0; - /// The number of record fields required for the Expr class - /// itself. - static const unsigned NumExprFields = NumStmtFields + 2; + /// The number of record fields required for the Expr class + /// itself. + static const unsigned NumExprFields = NumStmtFields + 2; - /// The number of bits required for the packing bits for the Expr class. - static const unsigned NumExprBits = 10; + /// The number of bits required for the packing bits for the Expr class. + static const unsigned NumExprBits = 10; - /// Read and initialize a ExplicitTemplateArgumentList structure. - void ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args, - TemplateArgumentLoc *ArgsLocArray, - unsigned NumTemplateArgs); + /// Read and initialize a ExplicitTemplateArgumentList structure. + void ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args, + TemplateArgumentLoc *ArgsLocArray, + unsigned NumTemplateArgs); - void VisitStmt(Stmt *S); -#define STMT(Type, Base) \ - void Visit##Type(Type *); + void VisitStmt(Stmt *S); +#define STMT(Type, Base) void Visit##Type(Type *); #include "clang/AST/StmtNodes.inc" - }; +}; } // namespace clang @@ -259,7 +245,7 @@ void ASTStmtReader::VisitSwitchStmt(SwitchStmt *S) { S->setRParenLoc(readSourceLocation()); SwitchCase *PrevSC = nullptr; - for (auto E = Record.size(); Record.getIdx() != E; ) { + for (auto E = Record.size(); Record.getIdx() != E;) { SwitchCase *SC = Record.getSwitchCaseWithID(Record.readInt()); if (PrevSC) PrevSC->setNextSwitchCase(SC); @@ -361,9 +347,8 @@ void ASTStmtReader::VisitDeclStmt(DeclStmt *S) { Decls.reserve(N); for (int I = 0; I < N; ++I) Decls.push_back(readDecl()); - S->setDeclGroup(DeclGroupRef(DeclGroup::Create(Record.getContext(), - Decls.data(), - Decls.size()))); + S->setDeclGroup(DeclGroupRef( + DeclGroup::Create(Record.getContext(), Decls.data(), Decls.size()))); } } @@ -391,7 +376,7 @@ void ASTStmtReader::VisitGCCAsmStmt(GCCAsmStmt *S) { // Outputs and inputs SmallVector Names; SmallVector Constraints; - SmallVector Exprs; + SmallVector Exprs; for (unsigned I = 0, N = NumOutputs + NumInputs; I != N; ++I) { Names.push_back(Record.readIdentifier()); Constraints.push_back(cast_or_null(Record.readSubStmt())); @@ -409,11 +394,9 @@ void ASTStmtReader::VisitGCCAsmStmt(GCCAsmStmt *S) { Exprs.push_back(Record.readSubStmt()); } - S->setOutputsAndInputsAndClobbers(Record.getContext(), - Names.data(), Constraints.data(), - Exprs.data(), NumOutputs, NumInputs, - NumLabels, - Clobbers.data(), NumClobbers); + S->setOutputsAndInputsAndClobbers( + Record.getContext(), Names.data(), Constraints.data(), Exprs.data(), + NumOutputs, NumInputs, NumLabels, Clobbers.data(), NumClobbers); } void ASTStmtReader::VisitMSAsmStmt(MSAsmStmt *S) { @@ -445,7 +428,7 @@ void ASTStmtReader::VisitMSAsmStmt(MSAsmStmt *S) { // Read the operands. unsigned NumOperands = S->NumOutputs + S->NumInputs; - SmallVector Exprs; + SmallVector Exprs; SmallVector ConstraintsData; SmallVector Constraints; Exprs.reserve(NumOperands); @@ -457,8 +440,8 @@ void ASTStmtReader::VisitMSAsmStmt(MSAsmStmt *S) { Constraints.push_back(ConstraintsData.back()); } - S->initialize(Record.getContext(), AsmStr, AsmToks, - Constraints, Exprs, Clobbers); + S->initialize(Record.getContext(), AsmStr, AsmToks, Constraints, Exprs, + Clobbers); } void ASTStmtReader::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) { @@ -474,7 +457,7 @@ void ASTStmtReader::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) { void ASTStmtReader::VisitCoreturnStmt(CoreturnStmt *S) { VisitStmt(S); S->CoreturnLoc = Record.readSourceLocation(); - for (auto &SubStmt: S->SubStmts) + for (auto &SubStmt : S->SubStmts) SubStmt = Record.readSubStmt(); S->IsImplicit = Record.readInt() != 0; } @@ -482,7 +465,7 @@ void ASTStmtReader::VisitCoreturnStmt(CoreturnStmt *S) { void ASTStmtReader::VisitCoawaitExpr(CoawaitExpr *E) { VisitExpr(E); E->KeywordLoc = readSourceLocation(); - for (auto &SubExpr: E->SubExprs) + for (auto &SubExpr : E->SubExprs) SubExpr = Record.readSubStmt(); E->OpaqueValue = cast_or_null(Record.readSubStmt()); E->setIsImplicit(Record.readInt() != 0); @@ -491,7 +474,7 @@ void ASTStmtReader::VisitCoawaitExpr(CoawaitExpr *E) { void ASTStmtReader::VisitCoyieldExpr(CoyieldExpr *E) { VisitExpr(E); E->KeywordLoc = readSourceLocation(); - for (auto &SubExpr: E->SubExprs) + for (auto &SubExpr : E->SubExprs) SubExpr = Record.readSubStmt(); E->OpaqueValue = cast_or_null(Record.readSubStmt()); } @@ -499,7 +482,7 @@ void ASTStmtReader::VisitCoyieldExpr(CoyieldExpr *E) { void ASTStmtReader::VisitDependentCoawaitExpr(DependentCoawaitExpr *E) { VisitExpr(E); E->KeywordLoc = readSourceLocation(); - for (auto &SubExpr: E->SubExprs) + for (auto &SubExpr : E->SubExprs) SubExpr = Record.readSubStmt(); } @@ -529,6 +512,10 @@ void ASTStmtReader::VisitCapturedStmt(CapturedStmt *S) { } } +void ASTStmtReader::VisitCXXReflectExpr(CXXReflectExpr *E) { + llvm_unreachable("unimplemented"); +} + void ASTStmtReader::VisitSYCLKernelCallStmt(SYCLKernelCallStmt *S) { VisitStmt(S); S->setOriginalStmt(cast(Record.readSubStmt())); @@ -762,14 +749,11 @@ void ASTStmtReader::VisitOffsetOfExpr(OffsetOfExpr *E) { break; case OffsetOfNode::Field: - E->setComponent( - I, OffsetOfNode(Start, readDeclAs(), End)); + E->setComponent(I, OffsetOfNode(Start, readDeclAs(), End)); break; case OffsetOfNode::Identifier: - E->setComponent( - I, - OffsetOfNode(Start, Record.readIdentifier(), End)); + E->setComponent(I, OffsetOfNode(Start, Record.readIdentifier(), End)); break; case OffsetOfNode::Base: { @@ -826,14 +810,16 @@ readConstraintSatisfaction(ASTRecordReader &Record) { } void ASTStmtReader::VisitConceptSpecializationExpr( - ConceptSpecializationExpr *E) { + ConceptSpecializationExpr *E) { VisitExpr(E); E->SpecDecl = Record.readDeclAs(); if (Record.readBool()) E->ConceptRef = Record.readConceptReference(); - E->Satisfaction = E->isValueDependent() ? nullptr : - ASTConstraintSatisfaction::Create(Record.getContext(), - readConstraintSatisfaction(Record)); + E->Satisfaction = + E->isValueDependent() + ? nullptr + : ASTConstraintSatisfaction::Create( + Record.getContext(), readConstraintSatisfaction(Record)); } static concepts::Requirement::SubstitutionDiagnostic * @@ -866,83 +852,81 @@ void ASTStmtReader::VisitRequiresExpr(RequiresExpr *E) { static_cast(Record.readInt()); concepts::Requirement *R = nullptr; switch (RK) { - case concepts::Requirement::RK_Type: { - auto Status = - static_cast( - Record.readInt()); - if (Status == concepts::TypeRequirement::SS_SubstitutionFailure) - R = new (Record.getContext()) - concepts::TypeRequirement(readSubstitutionDiagnostic(Record)); - else - R = new (Record.getContext()) - concepts::TypeRequirement(Record.readTypeSourceInfo()); - } break; - case concepts::Requirement::RK_Simple: - case concepts::Requirement::RK_Compound: { - auto Status = - static_cast( - Record.readInt()); - llvm::PointerUnion E; - if (Status == concepts::ExprRequirement::SS_ExprSubstitutionFailure) { - E = readSubstitutionDiagnostic(Record); - } else - E = Record.readExpr(); - - std::optional Req; - ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; - SourceLocation NoexceptLoc; - if (RK == concepts::Requirement::RK_Simple) { + case concepts::Requirement::RK_Type: { + auto Status = static_cast( + Record.readInt()); + if (Status == concepts::TypeRequirement::SS_SubstitutionFailure) + R = new (Record.getContext()) + concepts::TypeRequirement(readSubstitutionDiagnostic(Record)); + else + R = new (Record.getContext()) + concepts::TypeRequirement(Record.readTypeSourceInfo()); + } break; + case concepts::Requirement::RK_Simple: + case concepts::Requirement::RK_Compound: { + auto Status = static_cast( + Record.readInt()); + llvm::PointerUnion + E; + if (Status == concepts::ExprRequirement::SS_ExprSubstitutionFailure) { + E = readSubstitutionDiagnostic(Record); + } else + E = Record.readExpr(); + + std::optional Req; + ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; + SourceLocation NoexceptLoc; + if (RK == concepts::Requirement::RK_Simple) { + Req.emplace(); + } else { + NoexceptLoc = Record.readSourceLocation(); + switch (/* returnTypeRequirementKind */ Record.readInt()) { + case 0: + // No return type requirement. Req.emplace(); - } else { - NoexceptLoc = Record.readSourceLocation(); - switch (/* returnTypeRequirementKind */Record.readInt()) { - case 0: - // No return type requirement. - Req.emplace(); - break; - case 1: { - // type-constraint - TemplateParameterList *TPL = Record.readTemplateParameterList(); - if (Status >= - concepts::ExprRequirement::SS_ConstraintsNotSatisfied) - SubstitutedConstraintExpr = - cast(Record.readExpr()); - Req.emplace(TPL); - } break; - case 2: - // Substitution failure - Req.emplace(readSubstitutionDiagnostic(Record)); - break; - } - } - if (Expr *Ex = E.dyn_cast()) - R = new (Record.getContext()) concepts::ExprRequirement( - Ex, RK == concepts::Requirement::RK_Simple, NoexceptLoc, - std::move(*Req), Status, SubstitutedConstraintExpr); - else - R = new (Record.getContext()) concepts::ExprRequirement( - cast(E), - RK == concepts::Requirement::RK_Simple, NoexceptLoc, - std::move(*Req)); - } break; - case concepts::Requirement::RK_Nested: { - ASTContext &C = Record.getContext(); - bool HasInvalidConstraint = Record.readInt(); - if (HasInvalidConstraint) { - StringRef InvalidConstraint = C.backupStr(Record.readString()); - R = new (C) concepts::NestedRequirement( - Record.getContext(), InvalidConstraint, - readConstraintSatisfaction(Record)); + break; + case 1: { + // type-constraint + TemplateParameterList *TPL = Record.readTemplateParameterList(); + if (Status >= concepts::ExprRequirement::SS_ConstraintsNotSatisfied) + SubstitutedConstraintExpr = + cast(Record.readExpr()); + Req.emplace(TPL); + } break; + case 2: + // Substitution failure + Req.emplace(readSubstitutionDiagnostic(Record)); break; } - Expr *E = Record.readExpr(); - if (E->isInstantiationDependent()) - R = new (C) concepts::NestedRequirement(E); - else - R = new (C) concepts::NestedRequirement( - C, E, readConstraintSatisfaction(Record)); - } break; + } + if (Expr *Ex = E.dyn_cast()) + R = new (Record.getContext()) concepts::ExprRequirement( + Ex, RK == concepts::Requirement::RK_Simple, NoexceptLoc, + std::move(*Req), Status, SubstitutedConstraintExpr); + else + R = new (Record.getContext()) concepts::ExprRequirement( + cast(E), + RK == concepts::Requirement::RK_Simple, NoexceptLoc, + std::move(*Req)); + } break; + case concepts::Requirement::RK_Nested: { + ASTContext &C = Record.getContext(); + bool HasInvalidConstraint = Record.readInt(); + if (HasInvalidConstraint) { + StringRef InvalidConstraint = C.backupStr(Record.readString()); + R = new (C) + concepts::NestedRequirement(Record.getContext(), InvalidConstraint, + readConstraintSatisfaction(Record)); + break; + } + Expr *E = Record.readExpr(); + if (E->isInstantiationDependent()) + R = new (C) concepts::NestedRequirement(E); + else + R = new (C) concepts::NestedRequirement( + C, E, readConstraintSatisfaction(Record)); + } break; } if (!R) continue; @@ -1106,8 +1090,8 @@ void ASTStmtReader::VisitObjCIsaExpr(ObjCIsaExpr *E) { E->setArrow(Record.readInt()); } -void ASTStmtReader:: -VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) { +void ASTStmtReader::VisitObjCIndirectCopyRestoreExpr( + ObjCIndirectCopyRestoreExpr *E) { VisitExpr(E); E->Operand = Record.readSubExpr(); E->setShouldCopy(Record.readInt()); @@ -1174,8 +1158,8 @@ void ASTStmtReader::VisitConditionalOperator(ConditionalOperator *E) { E->ColonLoc = readSourceLocation(); } -void -ASTStmtReader::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { +void ASTStmtReader::VisitBinaryConditionalOperator( + BinaryConditionalOperator *E) { VisitExpr(E); E->OpaqueValue = cast(Record.readSubExpr()); E->SubExprs[BinaryConditionalOperator::COMMON] = Record.readSubExpr(); @@ -1272,8 +1256,8 @@ void ASTStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { const IdentifierInfo *Name = Record.readIdentifier(); SourceLocation DotLoc = readSourceLocation(); SourceLocation FieldLoc = readSourceLocation(); - Designators.push_back(Designator::CreateFieldDesignator(Name, DotLoc, - FieldLoc)); + Designators.push_back( + Designator::CreateFieldDesignator(Name, DotLoc, FieldLoc)); break; } @@ -1281,9 +1265,8 @@ void ASTStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { unsigned Index = Record.readInt(); SourceLocation LBracketLoc = readSourceLocation(); SourceLocation RBracketLoc = readSourceLocation(); - Designators.push_back(Designator::CreateArrayDesignator(Index, - LBracketLoc, - RBracketLoc)); + Designators.push_back( + Designator::CreateArrayDesignator(Index, LBracketLoc, RBracketLoc)); break; } @@ -1298,8 +1281,8 @@ void ASTStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) { } } } - E->setDesignators(Record.getContext(), - Designators.data(), Designators.size()); + E->setDesignators(Record.getContext(), Designators.data(), + Designators.size()); } void ASTStmtReader::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { @@ -1308,9 +1291,7 @@ void ASTStmtReader::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { E->setUpdater(Record.readSubExpr()); } -void ASTStmtReader::VisitNoInitExpr(NoInitExpr *E) { - VisitExpr(E); -} +void ASTStmtReader::VisitNoInitExpr(NoInitExpr *E) { VisitExpr(E); } void ASTStmtReader::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { VisitExpr(E); @@ -1494,7 +1475,8 @@ void ASTStmtReader::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { unsigned NumElements = Record.readInt(); assert(NumElements == E->getNumElements() && "Wrong number of elements"); bool HasPackExpansions = Record.readInt(); - assert(HasPackExpansions == E->HasPackExpansions &&"Pack expansion mismatch"); + assert(HasPackExpansions == E->HasPackExpansions && + "Pack expansion mismatch"); auto *KeyValues = E->getTrailingObjects(); auto *Expansions = @@ -1685,7 +1667,8 @@ void ASTStmtReader::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) { E->setLocation(readSourceLocation()); } -void ASTStmtReader::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { +void ASTStmtReader::VisitObjCAvailabilityCheckExpr( + ObjCAvailabilityCheckExpr *E) { VisitExpr(E); SourceRange R = Record.readSourceRange(); E->AtLoc = R.getBegin(); @@ -1808,8 +1791,8 @@ void ASTStmtReader::VisitLambdaExpr(LambdaExpr *E) { // declaration. } -void -ASTStmtReader::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) { +void ASTStmtReader::VisitCXXStdInitializerListExpr( + CXXStdInitializerListExpr *E) { VisitExpr(E); E->SubExpr = Record.readSubExpr(); } @@ -2057,8 +2040,8 @@ void ASTStmtReader::VisitCXXDependentScopeMemberExpr( E->MemberNameInfo = Record.readDeclarationNameInfo(); } -void -ASTStmtReader::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { +void ASTStmtReader::VisitDependentScopeDeclRefExpr( + DependentScopeDeclRefExpr *E) { VisitExpr(E); if (CurrentUnpackingBits->getNextBit()) // HasTemplateKWAndArgsInfo @@ -2071,8 +2054,8 @@ ASTStmtReader::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { E->NameInfo = Record.readDeclarationNameInfo(); } -void -ASTStmtReader::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E) { +void ASTStmtReader::VisitCXXUnresolvedConstructExpr( + CXXUnresolvedConstructExpr *E) { VisitExpr(E); assert(Record.peekInt() == E->getNumArgs() && "Read wrong record during creation ?"); @@ -2231,7 +2214,7 @@ void ASTStmtReader::VisitPackIndexingExpr(PackIndexingExpr *E) { } void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr( - SubstNonTypeTemplateParmExpr *E) { + SubstNonTypeTemplateParmExpr *E) { VisitExpr(E); E->AssociatedDeclAndRef.setPointer(readDeclAs()); E->AssociatedDeclAndRef.setInt(CurrentUnpackingBits->getNextBit()); @@ -2243,7 +2226,7 @@ void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr( } void ASTStmtReader::VisitSubstNonTypeTemplateParmPackExpr( - SubstNonTypeTemplateParmPackExpr *E) { + SubstNonTypeTemplateParmPackExpr *E) { VisitExpr(E); E->AssociatedDecl = readDeclAs(); E->Final = CurrentUnpackingBits->getNextBit(); @@ -2996,9 +2979,7 @@ Expr *ASTReader::ReadExpr(ModuleFile &F) { return cast_or_null(ReadStmt(F)); } -Expr *ASTReader::ReadSubExpr() { - return cast_or_null(ReadSubStmt()); -} +Expr *ASTReader::ReadSubExpr() { return cast_or_null(ReadSubStmt()); } // Within the bitstream, expressions are stored in Reverse Polish // Notation, with each of the subexpressions preceding the @@ -3096,8 +3077,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case STMT_ATTRIBUTED: S = AttributedStmt::CreateEmpty( - Context, - /*NumAttrs*/Record[ASTStmtReader::NumStmtFields]); + Context, + /*NumAttrs*/ Record[ASTStmtReader::NumStmtFields]); break; case STMT_IF: { @@ -3364,8 +3345,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; case EXPR_DESIGNATED_INIT: - S = DesignatedInitExpr::CreateEmpty(Context, - Record[ASTStmtReader::NumExprFields] - 1); + S = DesignatedInitExpr::CreateEmpty( + Context, Record[ASTStmtReader::NumExprFields] - 1); break; @@ -3453,9 +3434,9 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; case EXPR_OBJC_DICTIONARY_LITERAL: - S = ObjCDictionaryLiteral::CreateEmpty(Context, - Record[ASTStmtReader::NumExprFields], - Record[ASTStmtReader::NumExprFields + 1]); + S = ObjCDictionaryLiteral::CreateEmpty( + Context, Record[ASTStmtReader::NumExprFields], + Record[ASTStmtReader::NumExprFields + 1]); break; case EXPR_OBJC_ENCODE: @@ -3486,9 +3467,9 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { llvm_unreachable("mismatching AST file"); case EXPR_OBJC_MESSAGE_EXPR: - S = ObjCMessageExpr::CreateEmpty(Context, - Record[ASTStmtReader::NumExprFields], - Record[ASTStmtReader::NumExprFields + 1]); + S = ObjCMessageExpr::CreateEmpty( + Context, Record[ASTStmtReader::NumExprFields], + Record[ASTStmtReader::NumExprFields + 1]); break; case EXPR_OBJC_ISA: @@ -3562,8 +3543,9 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; case STMT_CXX_TRY: - S = CXXTryStmt::Create(Context, Empty, - /*numHandlers=*/Record[ASTStmtReader::NumStmtFields]); + S = CXXTryStmt::Create( + Context, Empty, + /*numHandlers=*/Record[ASTStmtReader::NumStmtFields]); break; case STMT_CXX_FOR_RANGE: @@ -3573,8 +3555,7 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case STMT_MS_DEPENDENT_EXISTS: S = new (Context) MSDependentExistsStmt(SourceLocation(), true, NestedNameSpecifierLoc(), - DeclarationNameInfo(), - nullptr); + DeclarationNameInfo(), nullptr); break; case STMT_OMP_CANONICAL_LOOP: @@ -3587,17 +3568,15 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; case STMT_OMP_PARALLEL_DIRECTIVE: - S = - OMPParallelDirective::CreateEmpty(Context, - Record[ASTStmtReader::NumStmtFields], - Empty); + S = OMPParallelDirective::CreateEmpty( + Context, Record[ASTStmtReader::NumStmtFields], Empty); break; case STMT_OMP_SIMD_DIRECTIVE: { unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields]; unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1]; - S = OMPSimdDirective::CreateEmpty(Context, NumClauses, - CollapsedNum, Empty); + S = OMPSimdDirective::CreateEmpty(Context, NumClauses, CollapsedNum, + Empty); break; } @@ -3616,7 +3595,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { } case STMT_OMP_UNROLL_DIRECTIVE: { - assert(Record[ASTStmtReader::NumStmtFields] == 1 && "Unroll directive accepts only a single loop"); + assert(Record[ASTStmtReader::NumStmtFields] == 1 && + "Unroll directive accepts only a single loop"); unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1]; S = OMPUnrollDirective::CreateEmpty(Context, NumClauses); break; @@ -3925,9 +3905,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case STMT_OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE: { unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields]; unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1]; - S = OMPDistributeParallelForSimdDirective::CreateEmpty(Context, NumClauses, - CollapsedNum, - Empty); + S = OMPDistributeParallelForSimdDirective::CreateEmpty( + Context, NumClauses, CollapsedNum, Empty); break; } @@ -3955,12 +3934,12 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; } - case STMT_OMP_TEAMS_DISTRIBUTE_DIRECTIVE: { - unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields]; - unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1]; - S = OMPTeamsDistributeDirective::CreateEmpty(Context, NumClauses, - CollapsedNum, Empty); - break; + case STMT_OMP_TEAMS_DISTRIBUTE_DIRECTIVE: { + unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields]; + unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1]; + S = OMPTeamsDistributeDirective::CreateEmpty(Context, NumClauses, + CollapsedNum, Empty); + break; } case STMT_OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE: { @@ -4295,8 +4274,9 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { } case EXPR_CXX_UNRESOLVED_CONSTRUCT: - S = CXXUnresolvedConstructExpr::CreateEmpty(Context, - /*NumArgs=*/Record[ASTStmtReader::NumExprFields]); + S = CXXUnresolvedConstructExpr::CreateEmpty( + Context, + /*NumArgs=*/Record[ASTStmtReader::NumExprFields]); break; case EXPR_CXX_UNRESOLVED_MEMBER: { @@ -4347,8 +4327,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case EXPR_SIZEOF_PACK: S = SizeOfPackExpr::CreateDeserialized( - Context, - /*NumPartialArgs=*/Record[ASTStmtReader::NumExprFields]); + Context, + /*NumPartialArgs=*/Record[ASTStmtReader::NumExprFields]); break; case EXPR_PACK_INDEXING: @@ -4366,8 +4346,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { break; case EXPR_FUNCTION_PARM_PACK: - S = FunctionParmPackExpr::CreateEmpty(Context, - Record[ASTStmtReader::NumExprFields]); + S = FunctionParmPackExpr::CreateEmpty( + Context, Record[ASTStmtReader::NumExprFields]); break; case EXPR_MATERIALIZE_TEMPORARY: @@ -4524,6 +4504,10 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case EXPR_HLSL_OUT_ARG: S = HLSLOutArgExpr::CreateEmpty(Context); break; + case EXPR_REFLECT: { + S = CXXReflectExpr::CreateEmpty(Context); + break; + } } // We hit a STMT_STOP, so we're done with this expression. diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp index acf345392aa1a..2a1f7139d738c 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -466,6 +466,12 @@ void ASTStmtWriter::VisitCoyieldExpr(CoyieldExpr *E) { Code = serialization::EXPR_COYIELD; } +void ASTStmtWriter::VisitCXXReflectExpr(CXXReflectExpr *E) { + VisitExpr(E); + Record.AddSourceLocation(E->getOperatorLoc()); + Code = serialization::EXPR_REFLECT; +} + void ASTStmtWriter::VisitDependentCoawaitExpr(DependentCoawaitExpr *E) { VisitExpr(E); Record.AddSourceLocation(E->getKeywordLoc()); diff --git a/clang/test/Reflection/parsing-reflection.pass.cpp b/clang/test/Reflection/parsing-reflection.pass.cpp new file mode 100644 index 0000000000000..22101970bd2bd --- /dev/null +++ b/clang/test/Reflection/parsing-reflection.pass.cpp @@ -0,0 +1,21 @@ +// RUN: %clang_cc1 %s -std=c++23 -freflection + + +int main() +{ + (void)(^^::); + (void)(^^void); + (void)(^^bool); + (void)(^^char); + (void)(^^signed char); + (void)(^^unsigned char); + (void)(^^short); + (void)(^^unsigned short); + (void)(^^int); + (void)(^^unsigned int); + (void)(^^long); + (void)(^^unsigned long); + (void)(^^long long); + (void)(^^float); + (void)(^^double); +}