diff --git a/clang/docs/checkedc/3C/CONTRIBUTING.md b/clang/docs/checkedc/3C/CONTRIBUTING.md index ab534c153dd2..326a20fa48ca 100644 --- a/clang/docs/checkedc/3C/CONTRIBUTING.md +++ b/clang/docs/checkedc/3C/CONTRIBUTING.md @@ -50,17 +50,19 @@ problems arising from your 3C pull request and/or we may ask you to make specific changes to your pull request to accommodate 5C's code. At the appropriate time during development of a pull request, please -run the [regression tests](development.md#regression-tests) and +run the [regression tests](development.md#regression-tests) and the +[automated style checks](development.md#code-style-automation) and correct any failures. (For example, it may not make sense to do this on a draft pull request containing an unfinished demonstration of an -idea.) All regression tests must pass (or be disabled if appropriate) -before your pull request can be merged. If you're changing behavior -(as opposed to just cleaning up the code), we'll typically require you -to add or update enough tests to exercise the important behavior -changes (i.e., those tests fail before your code change and pass after -it). If there's a concern that your change might affect other cases -that are not adequately tested yet, we may ask you to add tests for -those cases as well. +idea.) All regression tests and automated style checks must pass (or +be disabled if appropriate) before your pull request can be merged. + +If you're changing behavior (as opposed to just cleaning up the code), +we'll typically require you to add or update enough regression tests +to exercise the important behavior changes (i.e., those tests fail +before your code change and pass after it). If there's a concern that +your change might affect other cases that are not adequately tested +yet, we may ask you to add tests for those cases as well. See the [developer's guide](development.md) for additional information that may be helpful as you work on 3C. diff --git a/clang/docs/checkedc/3C/development.md b/clang/docs/checkedc/3C/development.md index 97f899760910..c6cc7029d8a4 100644 --- a/clang/docs/checkedc/3C/development.md +++ b/clang/docs/checkedc/3C/development.md @@ -135,10 +135,31 @@ in your code. Specifically: * Space before and after `:` in iterators, i.e., `for (auto &k : List)` -Our goal is that all files should be formatted with `clang-format` and -pass `clang-tidy` ([more information](clang-tidy.md)), and nonempty -files should have a final newline (surprisingly, `clang-format` cannot -enforce this). However, until we have better automation, we decided it -isn't reasonable to require contributors to manually run these tools -and fix style nits in each change; instead, we periodically run the -tools on the entire 3C codebase. +* Nonempty files should have a final newline. + +All 3C C++ source files should be formatted with `clang-format` and +pass `clang-tidy` ([more information](clang-tidy.md)) based on the +`.clang-format` and `.clang-tidy` files in the repository (which the +tools will automatically use by default). (We are not using either of +these tools on the 3C regression tests at this time.) Likewise, 3C +Python files should pass `yapf` based on the `.style.yapf` files +(except for `clang/tools/3c/utils/*.py`, which are pretty much +unmaintained at this point). Where appropriate, code may be excluded +from these checks via `// clang-format off`, `NOLINTNEXTLINE(...)`, +and `yapf: disable`. These tools (as currently configured) enforce +some but not all of the specific guidelines above, and they also +enforce many other standards not listed above. + +### Code style automation + +`ninja lint-3c` runs the `clang-format`, `clang-tidy`, and `yapf` +checks described above. We generally want it to pass on the `main` +branch at all times. It requires the relevant tools to be available on +your system; see `clang/tools/3c/utils/code_style/CMakeLists.txt` for +details. `clang/tools/3c/utils/code_style/fix-all.sh` will try to fix +all style violations that can be fixed automatically, but see the +caveats in that script before running it. + +As a convenience for fully validating a change to 3C, `ninja +validate-3c` runs both the regression tests (`check-3c`) and the +automated style checks (`lint-3c`). diff --git a/clang/include/clang/3C/3CInteractiveData.h b/clang/include/clang/3C/3CInteractiveData.h index ec66c5b263ab..b97991a37807 100644 --- a/clang/include/clang/3C/3CInteractiveData.h +++ b/clang/include/clang/3C/3CInteractiveData.h @@ -27,9 +27,7 @@ class RootCauseDiagnostic { const PersistentSourceLoc &getLocation() const { return Main.Location; } - void addReason(const ReasonLoc &Rsn) { - Supplemental.push_back(Rsn); - } + void addReason(const ReasonLoc &Rsn) { Supplemental.push_back(Rsn); } std::vector &additionalNotes() { return Supplemental; } diff --git a/clang/include/clang/3C/CastPlacement.h b/clang/include/clang/3C/CastPlacement.h index 994f700223c5..fb1c0a3cb167 100644 --- a/clang/include/clang/3C/CastPlacement.h +++ b/clang/include/clang/3C/CastPlacement.h @@ -65,8 +65,7 @@ class CastPlacementVisitor : public RecursiveASTVisitor { ConstraintVariable *TypeVar, CastNeeded CastKind); - void surroundByCast(ConstraintVariable *Dst, - ConstraintVariable *TypeVar, + void surroundByCast(ConstraintVariable *Dst, ConstraintVariable *TypeVar, CastNeeded CastKind, Expr *E); void reportCastInsertionFailure(Expr *E, const std::string &CastStr); void updateRewriteStats(CastNeeded CastKind); diff --git a/clang/include/clang/3C/ConstraintResolver.h b/clang/include/clang/3C/ConstraintResolver.h index 8099590cbf80..a44dfeae02d4 100644 --- a/clang/include/clang/3C/ConstraintResolver.h +++ b/clang/include/clang/3C/ConstraintResolver.h @@ -71,8 +71,8 @@ class ConstraintResolver { CVarSet getInvalidCastPVCons(CastExpr *E); - CVarSet addAtomAll(CVarSet CVS, ConstAtom *PtrTyp, - ReasonLoc &Rsn, Constraints &CS); + CVarSet addAtomAll(CVarSet CVS, ConstAtom *PtrTyp, ReasonLoc &Rsn, + Constraints &CS); CVarSet pvConstraintFromType(QualType TypE); CSetBkeyPair getAllSubExprConstraintVars(std::vector &Exprs); @@ -80,9 +80,7 @@ class ConstraintResolver { PVConstraint *getRewritablePVConstraint(Expr *E); - bool isNonPtrType(QualType &TE); - }; #endif // LLVM_CLANG_3C_CONSTRAINTRESOLVER_H diff --git a/clang/include/clang/3C/ConstraintVariables.h b/clang/include/clang/3C/ConstraintVariables.h index 470363066b11..dae4c64c30ae 100644 --- a/clang/include/clang/3C/ConstraintVariables.h +++ b/clang/include/clang/3C/ConstraintVariables.h @@ -104,13 +104,13 @@ class ConstraintVariable { // Only subclasses should call this ConstraintVariable(ConstraintVariableKind K, std::string T, std::string N, std::string TN) - : Kind(K), OriginalType(T), Name(N), OriginalTypeWithName(TN), - HasEqArgumentConstraints(false), ValidBoundsKey(false), - IsForDecl(false) {} + : Kind(K), OriginalType(T), Name(N), OriginalTypeWithName(TN), + HasEqArgumentConstraints(false), ValidBoundsKey(false), + IsForDecl(false) {} ConstraintVariable(ConstraintVariableKind K, QualType QT, std::string N) - : ConstraintVariable(K, qtyToStr(QT), N, - qtyToStr(QT, N == RETVAR ? "" : N)) {} + : ConstraintVariable(K, qtyToStr(QT), N, + qtyToStr(QT, N == RETVAR ? "" : N)) {} public: // Create a "for-rewriting" representation of this ConstraintVariable. @@ -235,16 +235,16 @@ enum ConsAction { Safe_to_Wild, Wild_to_Safe, Same_to_Same }; void constrainConsVarGeq(const std::set &LHS, const std::set &RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey = true); void constrainConsVarGeq(ConstraintVariable *LHS, const CVarSet &RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey = true); void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey = true); // True if [C] is a PVConstraint that contains at least one Atom (i.e., @@ -280,8 +280,8 @@ class PointerVariableConstraint : public ConstraintVariable { // TODO: This method always returns a constraint variable containing one atom. // This causes problems if the variable is later used as a deeper // pointer type. See correctcomputation/checkedc-clang#673. - static PointerVariableConstraint * - getWildPVConstraint(Constraints &CS, const ReasonLoc &Rsn); + static PointerVariableConstraint *getWildPVConstraint(Constraints &CS, + const ReasonLoc &Rsn); // Get constraint variables representing values that are not pointers. If a // meaningful name can be assigned to the value, the second method should be @@ -405,12 +405,12 @@ class PointerVariableConstraint : public ConstraintVariable { // Construct and empty PointerVariableConstraint with only the name set. All // other fields are initialized to default values. This is used to construct // variables for non-pointer expressions. - PointerVariableConstraint(std::string Name) : - ConstraintVariable(PointerVariable, "", Name, ""), FV(nullptr), - SrcHasItype(false), PartOfFuncPrototype(false), Parent(nullptr), - SourceGenericIndex(-1), InferredGenericIndex(-1), - IsZeroWidthArray(false), IsTypedef(false), - TypedefLevelInfo({}), IsVoidPtr(false) {} + PointerVariableConstraint(std::string Name) + : ConstraintVariable(PointerVariable, "", Name, ""), FV(nullptr), + SrcHasItype(false), PartOfFuncPrototype(false), Parent(nullptr), + SourceGenericIndex(-1), InferredGenericIndex(-1), + IsZeroWidthArray(false), IsTypedef(false), TypedefLevelInfo({}), + IsVoidPtr(false) {} public: std::string getTy() const { return BaseType; } @@ -437,7 +437,7 @@ class PointerVariableConstraint : public ConstraintVariable { bool isGeneric() const { return InferredGenericIndex >= 0; } int getGenericIndex() const { return InferredGenericIndex; } - void setGenericIndex(int idx) { InferredGenericIndex = idx; } + void setGenericIndex(int Idx) { InferredGenericIndex = Idx; } bool isGenericChanged() const { return SourceGenericIndex != InferredGenericIndex; } @@ -491,15 +491,12 @@ class PointerVariableConstraint : public ConstraintVariable { // code representation of the type. Allows for more precise rewriting by // preserving the exact syntax used to write types that aren't rewritten // by 3C. If this is null, then the type will be reconstructed from QT. - PointerVariableConstraint(const clang::QualType &QT, clang::DeclaratorDecl *D, - std::string N, ProgramInfo &I, - const clang::ASTContext &C, - std::string *InFunc = nullptr, - int ForceGenericIndex = -1, - bool PotentialGeneric = false, - bool VarAtomForChecked = false, - TypeSourceInfo *TSI = nullptr, - const clang::QualType &ItypeT = QualType()); + PointerVariableConstraint( + const clang::QualType &QT, clang::DeclaratorDecl *D, std::string N, + ProgramInfo &I, const clang::ASTContext &C, std::string *InFunc = nullptr, + int ForceGenericIndex = -1, bool PotentialGeneric = false, + bool VarAtomForChecked = false, TypeSourceInfo *TSI = nullptr, + const clang::QualType &ItypeT = QualType()); const CAtoms &getCvars() const { return Vars; } @@ -526,8 +523,8 @@ class PointerVariableConstraint : public ConstraintVariable { void constrainOuterTo(Constraints &CS, ConstAtom *C, const ReasonLoc &Rsn, bool DoLB = false, bool Soft = false); void constrainIdxTo(Constraints &CS, ConstAtom *C, unsigned int Idx, - const ReasonLoc &Rsn, - bool DoLB = false, bool Soft = false); + const ReasonLoc &Rsn, bool DoLB = false, + bool Soft = false); bool anyChanges(const EnvironmentMap &E) const override; bool anyArgumentIsWild(const EnvironmentMap &E); bool hasWild(const EnvironmentMap &E, int AIdx = -1) const override; @@ -542,8 +539,8 @@ class PointerVariableConstraint : public ConstraintVariable { bool isPartOfFunctionPrototype() const { return PartOfFuncPrototype; } // Add the provided constraint variable as an argument constraint. - bool addArgumentConstraint(ConstraintVariable *DstCons, - ReasonLoc &Rsn, ProgramInfo &Info); + bool addArgumentConstraint(ConstraintVariable *DstCons, ReasonLoc &Rsn, + ProgramInfo &Info); // Get the set of constraint variables corresponding to the arguments. const std::set &getArgumentConstraints() const; @@ -608,9 +605,9 @@ class FVComponentVariable { PVConstraint *getInternal() const { return InternalConstraint; } PVConstraint *getExternal() const { return ExternalConstraint; } - void setGenericIndex(int idx) { - ExternalConstraint->setGenericIndex(idx); - InternalConstraint->setGenericIndex(idx); + void setGenericIndex(int Idx) { + ExternalConstraint->setGenericIndex(Idx); + InternalConstraint->setGenericIndex(Idx); } void equateWithItype(ProgramInfo &CS, @@ -637,7 +634,6 @@ class FunctionVariableConstraint : public ConstraintVariable { bool Hasproto; bool Hasbody; bool IsStatic; - FunctionVariableConstraint *Parent; // Flag to indicate whether this is a function pointer or not. bool IsFunctionPtr; @@ -653,9 +649,9 @@ class FunctionVariableConstraint : public ConstraintVariable { FunctionVariableConstraint(clang::TypedefDecl *D, ProgramInfo &I, const clang::ASTContext &C); - FunctionVariableConstraint(const clang::QualType Ty, - clang::DeclaratorDecl *D, std::string N, - ProgramInfo &I, const clang::ASTContext &C, + FunctionVariableConstraint(const clang::QualType Ty, clang::DeclaratorDecl *D, + std::string N, ProgramInfo &I, + const clang::ASTContext &C, TypeSourceInfo *TSI = nullptr); PVConstraint *getExternalReturn() const { @@ -701,22 +697,18 @@ class FunctionVariableConstraint : public ConstraintVariable { bool srcHasBounds() const override; // The number of type variables - int getGenericParams() const { - return TypeParams; - } + int getGenericParams() const { return TypeParams; } // remove added generics // use when we constrain a potential generic param to wild - void resetGenericParams() { - TypeParams = 0; - } + void resetGenericParams() { TypeParams = 0; } // The type parameter index of the return int getGenericIndex() const { return ReturnVar.ExternalConstraint->getGenericIndex(); } // Change the type parameter index of the return - void setGenericIndex(int idx) { - ReturnVar.ExternalConstraint->setGenericIndex(idx); + void setGenericIndex(int Idx) { + ReturnVar.ExternalConstraint->setGenericIndex(Idx); } bool solutionEqualTo(Constraints &CS, const ConstraintVariable *CV, diff --git a/clang/include/clang/3C/Constraints.h b/clang/include/clang/3C/Constraints.h index 85f8274b0445..e9abd1ae2772 100644 --- a/clang/include/clang/3C/Constraints.h +++ b/clang/include/clang/3C/Constraints.h @@ -314,13 +314,9 @@ class Constraint { } virtual std::vector &additionalReasons() { return ExtraReasons; } // include additional reasons that will appear in output as notes - virtual void addReason(const ReasonLoc &Rsn) { - ExtraReasons.push_back(Rsn); - } + virtual void addReason(const ReasonLoc &Rsn) { ExtraReasons.push_back(Rsn); } - bool isUnwritable(void) const { - return getReasonText() == UNWRITABLE_REASON; - } + bool isUnwritable(void) const { return getReasonText() == UNWRITABLE_REASON; } const PersistentSourceLoc &getLocation() const { return Reason.Location; } }; diff --git a/clang/include/clang/3C/ConstraintsGraph.h b/clang/include/clang/3C/ConstraintsGraph.h index deebf43f40f6..23266e98177a 100644 --- a/clang/include/clang/3C/ConstraintsGraph.h +++ b/clang/include/clang/3C/ConstraintsGraph.h @@ -158,8 +158,9 @@ class DataGraph // This version provides more info by returning graph edges // rather than data items - bool getIncidentEdges(Data D, std::set &EdgeSet, bool Succ, - bool Append = false, bool IgnoreSoftEdges = false) const { + bool getIncidentEdges(Data D, std::set &EdgeSet, bool Succ, + bool Append = false, + bool IgnoreSoftEdges = false) const { NodeType *N = this->findNode(D); if (N == nullptr) return false; @@ -188,23 +189,23 @@ class DataGraph return !DataSet.empty(); } - bool getSuccessorsEdges(Atom *A, std::set &EdgeSet, - bool Append = false) { + bool getSuccessorsEdges(Atom *A, std::set &EdgeSet, + bool Append = false) { return getIncidentEdges(A, EdgeSet, true, Append); } - bool getPredecessorsEdges(Atom *A, std::set &EdgeSet, + bool getPredecessorsEdges(Atom *A, std::set &EdgeSet, bool Append = false) { return getIncidentEdges(A, EdgeSet, false, Append); } - bool - getSuccessors(Data D, std::set &DataSet, bool Append = false) const { + bool getSuccessors(Data D, std::set &DataSet, + bool Append = false) const { return getNeighbors(D, DataSet, true, Append); } - bool - getPredecessors(Data D, std::set &DataSet, bool Append = false) const { + bool getPredecessors(Data D, std::set &DataSet, + bool Append = false) const { return getNeighbors(D, DataSet, false, Append); } @@ -267,7 +268,8 @@ class ConstraintsGraph : public DataGraph { // be able to retrieve them from the graph. std::set &getAllConstAtoms(); - typedef DataEdge EdgeType; + typedef DataEdge EdgeType; + protected: // Add vertex is overridden to save const atoms as they are added to the graph // so that getAllConstAtoms can efficiently retrieve them. diff --git a/clang/include/clang/3C/DeclRewriter.h b/clang/include/clang/3C/DeclRewriter.h index 8ebc9f037f49..b7add5fc8d41 100644 --- a/clang/include/clang/3C/DeclRewriter.h +++ b/clang/include/clang/3C/DeclRewriter.h @@ -34,10 +34,9 @@ class DeclRewriter { // Info parameter are rewritten. static void rewriteDecls(ASTContext &Context, ProgramInfo &Info, Rewriter &R); - static void - buildItypeDecl(PVConstraint *Defn, DeclaratorDecl *Decl, std::string &Type, - std::string &IType, ProgramInfo &Info, - ArrayBoundsRewriter &ABR); + static void buildItypeDecl(PVConstraint *Defn, DeclaratorDecl *Decl, + std::string &Type, std::string &IType, + ProgramInfo &Info, ArrayBoundsRewriter &ABR); private: static RecordDecl *LastRecordDecl; @@ -102,11 +101,11 @@ class FunctionDeclBuilder : public RecursiveASTVisitor { // Get existing itype string from constraint variables. std::string getExistingIType(ConstraintVariable *DeclC); - virtual void buildDeclVar(const FVComponentVariable *CV, - DeclaratorDecl *Decl, std::string &Type, - std::string &IType, std::string UseName, - bool &RewriteGen, bool &RewriteParm, - bool &RewriteRet, bool StaticFunc); + virtual void buildDeclVar(const FVComponentVariable *CV, DeclaratorDecl *Decl, + std::string &Type, std::string &IType, + std::string UseName, bool &RewriteGen, + bool &RewriteParm, bool &RewriteRet, + bool StaticFunc); void buildCheckedDecl(PVConstraint *Defn, DeclaratorDecl *Decl, std::string &Type, std::string &IType, std::string UseName, bool &RewriteParm, diff --git a/clang/include/clang/3C/ProgramInfo.h b/clang/include/clang/3C/ProgramInfo.h index a208458039ab..03a506a24d33 100644 --- a/clang/include/clang/3C/ProgramInfo.h +++ b/clang/include/clang/3C/ProgramInfo.h @@ -50,10 +50,9 @@ typedef std::pair CSetBkeyPair; struct TypeParamConstraint { ConstraintVariable *MainConstraint; ConstraintVariable *GenericAddition; - TypeParamConstraint() : - MainConstraint(nullptr), GenericAddition(nullptr) {} - TypeParamConstraint(ConstraintVariable *M, ConstraintVariable *G) : - MainConstraint(M), GenericAddition(G) {} + TypeParamConstraint() : MainConstraint(nullptr), GenericAddition(nullptr) {} + TypeParamConstraint(ConstraintVariable *M, ConstraintVariable *G) + : MainConstraint(M), GenericAddition(G) {} // Fast. Whether `getConstraint` will return something other than nullptr. bool isConsistent() const { return MainConstraint != nullptr; } // Provides generic information if available and safe. This is somewhat of @@ -64,15 +63,13 @@ struct TypeParamConstraint { if (MainConstraint != nullptr && GenericAddition != nullptr && GenericAddition->isSolutionChecked(E)) { return GenericAddition; - } else { - return MainConstraint; } + return MainConstraint; } }; class ProgramInfo : public ProgramVariableAdder { public: - // This map holds similar information as the type variable map in // ConstraintBuilder.cpp, but it is stored in a form that is usable during // rewriting. @@ -151,8 +148,8 @@ class ProgramInfo : public ProgramVariableAdder { } void setTypeParamBinding(CallExpr *CE, unsigned int TypeVarIdx, - ConstraintVariable *CV, - ConstraintVariable* Ident, ASTContext *C); + ConstraintVariable *CV, ConstraintVariable *Ident, + ASTContext *C); bool hasTypeParamBindings(CallExpr *CE, ASTContext *C) const; const CallTypeParamBindingsT &getTypeParamBindings(CallExpr *CE, ASTContext *C) const; @@ -163,8 +160,8 @@ class ProgramInfo : public ProgramVariableAdder { void ensureNtCorrect(const QualType &QT, const PersistentSourceLoc &PSL, PointerVariableConstraint *PV); - void unifyIfTypedef(const QualType &QT, clang::ASTContext &, - PVConstraint *, ConsAction CA = Same_to_Same); + void unifyIfTypedef(const QualType &QT, clang::ASTContext &, PVConstraint *, + ConsAction CA = Same_to_Same); CVarOption lookupTypedef(PersistentSourceLoc PSL); diff --git a/clang/include/clang/3C/ProgramVar.h b/clang/include/clang/3C/ProgramVar.h index 5742b95c0d75..84f950a2c7d7 100644 --- a/clang/include/clang/3C/ProgramVar.h +++ b/clang/include/clang/3C/ProgramVar.h @@ -413,7 +413,7 @@ class ProgramVar { std::string verboseStr() const; ProgramVar *makeCopy(BoundsKey NK) const; - bool isNumConstant() const {return IsConstant; } + bool isNumConstant() const { return IsConstant; } uint64_t getConstantVal() const { assert("Can't get constant value for non-constant var." && IsConstant); return ConstantVal; @@ -440,8 +440,8 @@ class ProgramVar { ProgramVar(BoundsKey K, const std::string &VarName, const ProgramVarScope *VScope, bool IsConstant, uint32_t ConstantVal) - : K(K), VarName(VarName), VScope(VScope), IsConstant(IsConstant), - ConstantVal(ConstantVal) { + : K(K), VarName(VarName), VScope(VScope), IsConstant(IsConstant), + ConstantVal(ConstantVal) { // Constant variables should be a subclass of ProgramVariable. Until that // change happens this should sanity check how ProgramVars are constructed. assert("Constant value should not be set for non-constant variables." && @@ -450,11 +450,11 @@ class ProgramVar { } ProgramVar(BoundsKey VK, std::string VName, const ProgramVarScope *PVS) - : ProgramVar(VK, VName, PVS, false, 0) {} + : ProgramVar(VK, VName, PVS, false, 0) {} ProgramVar(BoundsKey VK, uint32_t CVal) - : ProgramVar(VK, std::to_string(CVal), GlobalScope::getGlobalScope(), true, - CVal) {} + : ProgramVar(VK, std::to_string(CVal), GlobalScope::getGlobalScope(), + true, CVal) {} }; #endif // LLVM_CLANG_3C_PROGRAMVAR_H diff --git a/clang/include/clang/3C/RewriteUtils.h b/clang/include/clang/3C/RewriteUtils.h index a571ba27e026..35cea61ed9d6 100644 --- a/clang/include/clang/3C/RewriteUtils.h +++ b/clang/include/clang/3C/RewriteUtils.h @@ -31,12 +31,7 @@ class DeclReplacement { virtual SourceRange getSourceRange(SourceManager &SM) const; // Discriminator for LLVM-style RTTI (dyn_cast<> et al.). - enum DRKind { - DRK_VarDecl, - DRK_FunctionDecl, - DRK_FieldDecl, - DRK_TypedefDecl - }; + enum DRKind { DRK_VarDecl, DRK_FunctionDecl, DRK_FieldDecl, DRK_TypedefDecl }; DRKind getKind() const { return Kind; } diff --git a/clang/include/clang/3C/TypeVariableAnalysis.h b/clang/include/clang/3C/TypeVariableAnalysis.h index 416550a6f378..b99e5d47789a 100644 --- a/clang/include/clang/3C/TypeVariableAnalysis.h +++ b/clang/include/clang/3C/TypeVariableAnalysis.h @@ -20,9 +20,9 @@ class TypeVariableEntry { public: // Note: does not initialize TyVarType! TypeVariableEntry() : IsConsistent(false), TypeParamConsVar(nullptr) {} - TypeVariableEntry(QualType Ty, std::set &CVs - , bool ForceInconsistent = false - , ConstraintVariable *IdentCV = nullptr) + TypeVariableEntry(QualType Ty, std::set &CVs, + bool ForceInconsistent = false, + ConstraintVariable *IdentCV = nullptr) : TypeParamConsVar(nullptr) { // We'll need a name to provide the type arguments during rewriting, so no // anonymous types are allowed. @@ -110,8 +110,8 @@ class TypeVarVisitor : public RecursiveASTVisitor, ConstraintResolver CR; TypeVariableMapT TVMap; - void insertBinding(CallExpr *CE, const int TyIdx, QualType Ty, - CVarSet &CVs, ConstraintVariable *IdentCV = nullptr); + void insertBinding(CallExpr *CE, const int TyIdx, QualType Ty, CVarSet &CVs, + ConstraintVariable *IdentCV = nullptr); }; bool typeArgsProvided(CallExpr *Call); diff --git a/clang/include/clang/3C/Utils.h b/clang/include/clang/3C/Utils.h index b14041381605..cd309e55c2c1 100644 --- a/clang/include/clang/3C/Utils.h +++ b/clang/include/clang/3C/Utils.h @@ -240,18 +240,16 @@ clang::SourceLocation getCheckedCAnnotationsEnd(const clang::Decl *D); template inline clang::DiagnosticBuilder reportCustomDiagnostic( - clang::DiagnosticsEngine &DE, - clang::DiagnosticsEngine::Level Level, - const char (&FormatString)[N], - clang::SourceLocation Loc) { + clang::DiagnosticsEngine &DE, clang::DiagnosticsEngine::Level Level, + const char (&FormatString)[N], clang::SourceLocation Loc) { return DE.Report(Loc, DE.getCustomDiagID(Level, FormatString)); } // For whatever reason, Clang provides << equivalents for many other // DiagnosticBuilder::Add* methods but not this one, and we want it in a few // places. -inline const clang::DiagnosticBuilder &operator<<( - const clang::DiagnosticBuilder &DB, clang::NamedDecl *ND) { +inline const clang::DiagnosticBuilder & +operator<<(const clang::DiagnosticBuilder &DB, clang::NamedDecl *ND) { DB.AddTaggedVal(reinterpret_cast(ND), clang::DiagnosticsEngine::ArgumentKind::ak_nameddecl); return DB; diff --git a/clang/lib/3C/3C.cpp b/clang/lib/3C/3C.cpp index f7a1cf38de5c..7f918da041ae 100644 --- a/clang/lib/3C/3C.cpp +++ b/clang/lib/3C/3C.cpp @@ -260,8 +260,7 @@ class _3CASTBuilderAction : public ToolAction { } private: - void handleExtraProgramAction(FrontendOptions &Opts, - ASTContext &C) { + void handleExtraProgramAction(FrontendOptions &Opts, ASTContext &C) { // The Opts.ProgramAction field is normally used only by `clang -cc1` to // select a FrontendAction (see CreateFrontendBaseAction in // ExecuteCompilerInvocation.cpp) and is ignored by LibTooling tools, which @@ -283,11 +282,10 @@ class _3CASTBuilderAction : public ToolAction { // look trivial because ASTPrinter requires ownership of the output // stream, and it probably isn't important for the intended debugging use // case. - std::unique_ptr Dumper = - CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter, - Opts.ASTDumpDecls, Opts.ASTDumpAll, - Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes, - Opts.ASTDumpFormat); + std::unique_ptr Dumper = CreateASTDumper( + nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter, Opts.ASTDumpDecls, + Opts.ASTDumpAll, Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes, + Opts.ASTDumpFormat); // In principle, we should call all the ASTConsumer methods the same way // the normal AST parsing process would, but there isn't an obvious way to // do that when using ASTUnit. Instead, we rely on the assumption @@ -584,7 +582,7 @@ bool _3CInterface::solveConstraints() { // after constraint solving because the bound added depends on whether the // array is NTARR or ARR. GlobalProgramInfo.getABoundsInfo().addConstantArrayBounds( - GlobalProgramInfo); + GlobalProgramInfo); if (DebugArrSolver) GlobalProgramInfo.getABoundsInfo().dumpAVarGraph( diff --git a/clang/lib/3C/3CInteractiveData.cpp b/clang/lib/3C/3CInteractiveData.cpp index 3a9f039f645f..65b54a6e9c07 100644 --- a/clang/lib/3C/3CInteractiveData.cpp +++ b/clang/lib/3C/3CInteractiveData.cpp @@ -131,10 +131,12 @@ void ConstraintsInfo::printConstraintStats(llvm::raw_ostream &O, O << "\"PtrsAffected\":" << PtrsAffected.size() << ","; O << "\"PtrsScore\":" << getPtrAffectedScore(PtrsAffected) << ","; - O << "\"SubReasons\":" << "["; + O << "\"SubReasons\":" + << "["; bool AddComma = false; - for(const ReasonLoc &Rsn : PtrInfo.additionalNotes()) { - if (AddComma) O << ","; + for (const ReasonLoc &Rsn : PtrInfo.additionalNotes()) { + if (AddComma) + O << ","; O << "{"; O << "\"Rsn\":\"" << Rsn.Reason << "\", "; O << "\"Location\":"; diff --git a/clang/lib/3C/AVarBoundsInfo.cpp b/clang/lib/3C/AVarBoundsInfo.cpp index 3bb8bbd90745..7bc411ac7227 100644 --- a/clang/lib/3C/AVarBoundsInfo.cpp +++ b/clang/lib/3C/AVarBoundsInfo.cpp @@ -101,8 +101,8 @@ class ScopeVisitor { ScopeVisitor(const ProgramVarScope *S, const std::map &VM, const std::set &P) - : Scope(S), InScopeKeys(), VisibleKeys(), PVarInfo(VM), - PointerBoundsKey(P) {} + : Scope(S), InScopeKeys(), VisibleKeys(), PVarInfo(VM), + PointerBoundsKey(P) {} void visitBoundsKey(BoundsKey V) { // If the variable is non-pointer? if (PVarInfo.find(V) != PVarInfo.end() && @@ -270,7 +270,7 @@ ABounds *AvarBoundsInference::getPreferredBound(const BndsKindMap &BKindMap) { if (HasBoundKind(ABounds::CountPlusOneBoundKind)) return new CountPlusOneBound( - getOnly(BKindMap.at(ABounds::CountPlusOneBoundKind))); + getOnly(BKindMap.at(ABounds::CountPlusOneBoundKind))); return nullptr; } @@ -536,9 +536,8 @@ bool AvarBoundsInference::inferFromPotentialBounds(BoundsKey BK, bool HasInferredBound = false; if (CurrIterInferBounds.find(BK) != CurrIterInferBounds.end()) { auto &BM = CurrIterInferBounds[BK]; - HasInferredBound = llvm::any_of(BM, [](auto InfB) { - return !InfB.second.empty(); - }); + HasInferredBound = + llvm::any_of(BM, [](auto InfB) { return !InfB.second.empty(); }); } if (!HasInferredBound) { @@ -975,7 +974,7 @@ bool AVarBoundsInfo::addAssignment(BoundsKey L, BoundsKey R) { class CollectDeclsVisitor : public RecursiveASTVisitor { public: explicit CollectDeclsVisitor(ASTContext *Ctx) - : ObservedDecls(), StructAccess(), C(Ctx) {} + : ObservedDecls(), StructAccess(), C(Ctx) {} virtual ~CollectDeclsVisitor() {} @@ -1404,11 +1403,12 @@ void AVarBoundsInfo::printStats(llvm::raw_ostream &O, const CVarSet &SrcCVarSet, std::set NTArraysReqBnds; for (auto NTBK : NtArrPointerBoundsKey) { - ProgVarGraph.visitBreadthFirst(NTBK, [this, NTBK, &NTArraysReqBnds](BoundsKey BK) { - if (NtArrPointerBoundsKey.find(BK) == NtArrPointerBoundsKey.end() && - ArrPointerBoundsKey.find(BK) != ArrPointerBoundsKey.end()) - NTArraysReqBnds.insert(NTBK); - }); + ProgVarGraph.visitBreadthFirst( + NTBK, [this, NTBK, &NTArraysReqBnds](BoundsKey BK) { + if (NtArrPointerBoundsKey.find(BK) == NtArrPointerBoundsKey.end() && + ArrPointerBoundsKey.find(BK) != ArrPointerBoundsKey.end()) + NTArraysReqBnds.insert(NTBK); + }); } std::set NTArrayReqNoBounds; diff --git a/clang/lib/3C/ArrayBoundsInferenceConsumer.cpp b/clang/lib/3C/ArrayBoundsInferenceConsumer.cpp index 5f25bc9af9d9..a644b44617f8 100644 --- a/clang/lib/3C/ArrayBoundsInferenceConsumer.cpp +++ b/clang/lib/3C/ArrayBoundsInferenceConsumer.cpp @@ -118,8 +118,8 @@ static bool needArrayBounds(Expr *E, ProgramInfo &Info, ASTContext *C) { return false; } -static bool -needArrayBounds(ConstraintVariable *CV, ProgramInfo &Info, bool IsNtArr) { +static bool needArrayBounds(ConstraintVariable *CV, ProgramInfo &Info, + bool IsNtArr) { const auto &E = Info.getConstraints().getVariables(); if (IsNtArr) return needNTArrayBounds(CV, E); @@ -181,7 +181,7 @@ bool tryGetValidBoundsKey(Expr *E, BoundsKey &BK, ProgramInfo &I, return Ret; } -bool hasValidBoundsKey(Expr *E, ProgramInfo &I, ASTContext *C) { +bool hasValidBoundsKey(Expr *E, ProgramInfo &I, ASTContext *C) { BoundsKey Unused; return tryGetValidBoundsKey(E, Unused, I, C); } @@ -766,10 +766,10 @@ class ComparisonVisitor : public RecursiveASTVisitor { }; LengthVarInference::LengthVarInference(ProgramInfo &In, ASTContext *AC, - FunctionDecl *F) : - I(In), C(AC), CurBB(nullptr), - Cfg(CFG::buildCFG(nullptr, F->getBody(), AC, CFG::BuildOptions())), - CDG(Cfg.get()) { + FunctionDecl *F) + : I(In), C(AC), CurBB(nullptr), + Cfg(CFG::buildCFG(nullptr, F->getBody(), AC, CFG::BuildOptions())), + CDG(Cfg.get()) { for (auto *CBlock : *(Cfg.get())) { for (auto &CfgElem : *CBlock) { if (CfgElem.getKind() == clang::CFGElement::Statement) { diff --git a/clang/lib/3C/CastPlacement.cpp b/clang/lib/3C/CastPlacement.cpp index b3886eaed7e5..3059ea0fde73 100644 --- a/clang/lib/3C/CastPlacement.cpp +++ b/clang/lib/3C/CastPlacement.cpp @@ -60,7 +60,7 @@ bool CastPlacementVisitor::VisitCallExpr(CallExpr *CE) { // Check if local type vars are available if (TypeVars.find(TyVarIdx) != TypeVars.end()) { TypeVar = TypeVars[TyVarIdx].getConstraint( - Info.getConstraints().getVariables()); + Info.getConstraints().getVariables()); } } if (TypeVar != nullptr) @@ -158,10 +158,8 @@ CastPlacementVisitor::CastNeeded CastPlacementVisitor::needCasting( // Get the string representation of the cast required for the call. The return // is a pair of strings: a prefix and suffix string that form the complete cast // when placed around the expression being cast. -std::pair -CastPlacementVisitor::getCastString(ConstraintVariable *Dst, - ConstraintVariable *TypeVar, - CastNeeded CastKind) { +std::pair CastPlacementVisitor::getCastString( + ConstraintVariable *Dst, ConstraintVariable *TypeVar, CastNeeded CastKind) { switch (CastKind) { case CAST_NT_ARRAY: return std::make_pair("((" + @@ -199,11 +197,13 @@ CastPlacementVisitor::getCastString(ConstraintVariable *Dst, std::string Type; if (TypeVar != nullptr) { Type = "_Ptr<" + - TypeVar->mkString(Info.getConstraints(), - MKSTRING_OPTS(EmitName = false, EmitPointee = true)) + - ">"; + TypeVar->mkString( + Info.getConstraints(), + MKSTRING_OPTS(EmitName = false, EmitPointee = true)) + + ">"; } else { - Type = Dst->mkString(Info.getConstraints(), MKSTRING_OPTS(EmitName = false)); + Type = + Dst->mkString(Info.getConstraints(), MKSTRING_OPTS(EmitName = false)); } return std::make_pair("_Assume_bounds_cast<" + Type + ">(", Suffix); } @@ -222,8 +222,7 @@ void CastPlacementVisitor::surroundByCast(ConstraintVariable *Dst, // warning rather than letting the main "unwritable change" error trigger // later. reportCustomDiagnostic( - Writer.getSourceMgr().getDiagnostics(), - DiagnosticsEngine::Warning, + Writer.getSourceMgr().getDiagnostics(), DiagnosticsEngine::Warning, "3C internal error: tried to insert a cast into an unwritable file " "(https://github.com/correctcomputation/checkedc-clang/issues/454)", E->getBeginLoc()); @@ -283,8 +282,7 @@ void CastPlacementVisitor::reportCastInsertionFailure( // FIXME: This is a warning rather than an error so that a new benchmark // failure is not introduced in Lua. // github.com/correctcomputation/checkedc-clang/issues/439 - reportCustomDiagnostic(Context->getDiagnostics(), - DiagnosticsEngine::Warning, + reportCustomDiagnostic(Context->getDiagnostics(), DiagnosticsEngine::Warning, "Unable to surround expression with cast.\n" "Intended cast: \"%0\"", E->getExprLoc()) diff --git a/clang/lib/3C/CheckedRegions.cpp b/clang/lib/3C/CheckedRegions.cpp index 7c6d36cebb93..95aaefb16bab 100644 --- a/clang/lib/3C/CheckedRegions.cpp +++ b/clang/lib/3C/CheckedRegions.cpp @@ -88,9 +88,8 @@ bool CheckedRegionAdder::VisitCallExpr(CallExpr *C) { typedef std::pair StmtPair; -StmtPair -CheckedRegionAdder::findParentCompound(const DynTypedNode &N, - int Distance = 1) { +StmtPair CheckedRegionAdder::findParentCompound(const DynTypedNode &N, + int Distance = 1) { auto Parents = Context->getParents(N); if (Parents.empty()) return std::make_pair(nullptr, INT_MAX); @@ -440,10 +439,9 @@ void CheckedRegionFinder::emitCauseDiagnostic(PersistentSourceLoc PSL) { SourceLocation SL = SM.translateFileLineCol(*File, PSL.getLineNo(), PSL.getColSNo()); if (SL.isValid()) - reportCustomDiagnostic(Context->getDiagnostics(), - DiagnosticsEngine::Warning, - "Root cause of unchecked region: Variadic Call", - SL); + reportCustomDiagnostic( + Context->getDiagnostics(), DiagnosticsEngine::Warning, + "Root cause of unchecked region: Variadic Call", SL); Emitted.insert(PSL); } } diff --git a/clang/lib/3C/ConstraintBuilder.cpp b/clang/lib/3C/ConstraintBuilder.cpp index 37442ca12546..3cba0713ab14 100644 --- a/clang/lib/3C/ConstraintBuilder.cpp +++ b/clang/lib/3C/ConstraintBuilder.cpp @@ -128,8 +128,7 @@ class InlineStructDetector { class FunctionVisitor : public RecursiveASTVisitor { public: explicit FunctionVisitor(ASTContext *C, ProgramInfo &I, FunctionDecl *FD) - : Context(C), Info(I), Function(FD), CB(Info, Context), - ISD() {} + : Context(C), Info(I), Function(FD), CB(Info, Context), ISD() {} // T x = e bool VisitDeclStmt(DeclStmt *S) { @@ -166,8 +165,8 @@ class FunctionVisitor : public RecursiveASTVisitor { // Is cast compatible with LHS type? QualType SrcT = C->getSubExpr()->getType(); QualType DstT = C->getType(); - if (!CB.isCastofGeneric(C) && !isCastSafe(DstT, SrcT) - && !Info.hasPersistentConstraints(C, Context)) { + if (!CB.isCastofGeneric(C) && !isCastSafe(DstT, SrcT) && + !Info.hasPersistentConstraints(C, Context)) { auto CVs = CB.getExprConstraintVarsSet(C->getSubExpr()); std::string Rsn = "Cast from " + SrcT.getAsString() + " to " + DstT.getAsString(); @@ -214,10 +213,9 @@ class FunctionVisitor : public RecursiveASTVisitor { // Collect type parameters for this function call that are // consistently instantiated as single type in this function call. - auto ConsistentTypeParams = - Info.hasTypeParamBindings(E,Context) ? - Info.getTypeParamBindings(E,Context) : - ProgramInfo::CallTypeParamBindingsT(); + auto ConsistentTypeParams = Info.hasTypeParamBindings(E, Context) + ? Info.getTypeParamBindings(E, Context) + : ProgramInfo::CallTypeParamBindingsT(); // Now do the call: Constrain arguments to parameters (but ignore returns) if (FVCons.empty()) { @@ -240,7 +238,7 @@ class FunctionVisitor : public RecursiveASTVisitor { unsigned I = 0; for (const auto &A : E->arguments()) { CSetBkeyPair ArgumentConstraints; - auto ArgPSL = PersistentSourceLoc::mkPSL(A,*Context); + auto ArgPSL = PersistentSourceLoc::mkPSL(A, *Context); auto Rsn = ReasonLoc("Constrain arguments to parameters", ArgPSL); if (I < TargetFV->numParams()) { // When the function has a void* parameter, Clang will @@ -295,7 +293,7 @@ class FunctionVisitor : public RecursiveASTVisitor { // to the `%s` should be an _Nt_array_ptr // (https://github.com/correctcomputation/checkedc-clang/issues/549). constrainVarsTo(ArgumentConstraints.first, CS.getNTArr(), - ReasonLoc(NT_ARRAY_REASON,ArgPSL)); + ReasonLoc(NT_ARRAY_REASON, ArgPSL)); } if (_3COpts.Verbose) { std::string FuncName = TargetFV->getName(); @@ -315,9 +313,9 @@ class FunctionVisitor : public RecursiveASTVisitor { // e1[e2] bool VisitArraySubscriptExpr(ArraySubscriptExpr *E) { Constraints &CS = Info.getConstraints(); - auto PSL = PersistentSourceLoc::mkPSL(E,*Context); + auto PSL = PersistentSourceLoc::mkPSL(E, *Context); constraintInBodyVariable(E->getBase(), CS.getArr(), - ReasonLoc(ARRAY_REASON,PSL)); + ReasonLoc(ARRAY_REASON, PSL)); return true; } @@ -391,7 +389,8 @@ class FunctionVisitor : public RecursiveASTVisitor { } // Constraint helpers. - void constraintInBodyVariable(Expr *E, ConstAtom *CAtom, const ReasonLoc &Rsn) { + void constraintInBodyVariable(Expr *E, ConstAtom *CAtom, + const ReasonLoc &Rsn) { CVarSet Var = CB.getExprConstraintVarsSet(E); constrainVarsTo(Var, CAtom, Rsn); } @@ -430,11 +429,11 @@ class FunctionVisitor : public RecursiveASTVisitor { std::string Rsn = "Pointer arithmetic performed on a function pointer."; CB.constraintAllCVarsToWild(Var, Rsn, E); } else { - auto PSL = PersistentSourceLoc::mkPSL(E,*Context); + auto PSL = PersistentSourceLoc::mkPSL(E, *Context); if (ModifyingExpr) Info.getABoundsInfo().recordArithmeticOperation(E, &CB); constraintInBodyVariable(E, Info.getConstraints().getArr(), - ReasonLoc(ARRAY_REASON,PSL)); + ReasonLoc(ARRAY_REASON, PSL)); } } diff --git a/clang/lib/3C/ConstraintResolver.cpp b/clang/lib/3C/ConstraintResolver.cpp index 77c264dbfade..6c6cdea16adc 100644 --- a/clang/lib/3C/ConstraintResolver.cpp +++ b/clang/lib/3C/ConstraintResolver.cpp @@ -68,7 +68,7 @@ CVarSet ConstraintResolver::addAtomAll(CVarSet CVS, ConstAtom *PtrTyp, CVarSet Result; for (auto *CV : CVS) { if (PVConstraint *PVC = dyn_cast(CV)) { - Result.insert(PVConstraint::addAtomPVConstraint(PVC, PtrTyp, Rsn,CS)); + Result.insert(PVConstraint::addAtomPVConstraint(PVC, PtrTyp, Rsn, CS)); } else { Result.insert(CV); } @@ -154,23 +154,21 @@ inline CSetBkeyPair pairWithEmptyBkey(const CVarSet &Vars) { // Get the return type of the function from the TypeVars, that is, from // the local instantiation of a generic function. Or the regular return // constraint if it's not generic -ConstraintVariable *localReturnConstraint( - FVConstraint *FV, - ProgramInfo::CallTypeParamBindingsT TypeVars, - Constraints &CS, - ProgramInfo &Info) { +ConstraintVariable * +localReturnConstraint(FVConstraint *FV, + ProgramInfo::CallTypeParamBindingsT TypeVars, + Constraints &CS, ProgramInfo &Info) { int TyVarIdx = FV->getExternalReturn()->getGenericIndex(); // Check if local type vars are available if (TypeVars.find(TyVarIdx) != TypeVars.end() && TypeVars[TyVarIdx].isConsistent()) { - ConstraintVariable *CV = TypeVars[TyVarIdx].getConstraint( - Info.getConstraints().getVariables()); + ConstraintVariable *CV = + TypeVars[TyVarIdx].getConstraint(Info.getConstraints().getVariables()); if (FV->getExternalReturn()->hasBoundsKey()) CV->setBoundsKey(FV->getExternalReturn()->getBoundsKey()); return CV; - } else { - return FV->getExternalReturn(); } + return FV->getExternalReturn(); } // Returns a pair of set of ConstraintVariables and set of BoundsKey @@ -184,7 +182,7 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { auto &CS = Info.getConstraints(); QualType TypE = E->getType(); E = E->IgnoreParens(); - auto ExprPSL = PersistentSourceLoc::mkPSL(E,*Context); + auto ExprPSL = PersistentSourceLoc::mkPSL(E, *Context); // Non-pointer (int, char, etc.) types have a special base PVConstraint. if (isNonPtrType(TypE)) { @@ -245,9 +243,9 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { SubTypE->isVoidPointerType()) && !isCastSafe(TypE, SubTypE)) { CVarSet WildCVar = getInvalidCastPVCons(IE); - auto Rsn = ReasonLoc("Unsafe cast",ExprPSL); - constrainConsVarGeq(CVs.first, WildCVar, CS, Rsn, Safe_to_Wild, - false, &Info); + auto Rsn = ReasonLoc("Unsafe cast", ExprPSL); + constrainConsVarGeq(CVs.first, WildCVar, CS, Rsn, Safe_to_Wild, false, + &Info); Ret = std::make_pair(WildCVar, CVs.second); } else { // Else, return sub-expression's result. @@ -392,10 +390,10 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { } } // Add a VarAtom to UOExpr's PVConstraint, for &. - auto Rsn = ReasonLoc( - "Result of address-of has PTR lower bound",ExprPSL); - Ret = std::make_pair(addAtomAll(T.first, CS.getPtr(), - Rsn, CS), T.second); + auto Rsn = + ReasonLoc("Result of address-of has PTR lower bound", ExprPSL); + Ret = std::make_pair(addAtomAll(T.first, CS.getPtr(), Rsn, CS), + T.second); } break; } @@ -455,10 +453,10 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { for (ConstraintVariable *C : Tmp.first) { if (FVConstraint *FV = dyn_cast(C)) { - ReturnCVs.insert(localReturnConstraint(FV,TypeVars,CS,Info)); + ReturnCVs.insert(localReturnConstraint(FV, TypeVars, CS, Info)); } else if (PVConstraint *PV = dyn_cast(C)) { if (FVConstraint *FV = PV->getFV()) - ReturnCVs.insert(localReturnConstraint(FV,TypeVars,CS,Info)); + ReturnCVs.insert(localReturnConstraint(FV, TypeVars, CS, Info)); } } } else if (DeclaratorDecl *FD = dyn_cast(D)) { @@ -468,8 +466,8 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { IsAllocator = true; if (TypeVars.find(0) != TypeVars.end() && TypeVars[0].isConsistent()) { - ConstraintVariable *CV = TypeVars[0].getConstraint( - Info.getConstraints().getVariables()); + ConstraintVariable *CV = + TypeVars[0].getConstraint(Info.getConstraints().getVariables()); ReturnCVs.insert(CV); DidInsert = true; } else if (CE->getNumArgs() > 0) { @@ -482,8 +480,8 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { ExprType = Context->getPointerType(ArgTy); PVConstraint *PVC = new PVConstraint(ExprType, nullptr, N, Info, *Context, nullptr, 0); - PVC->constrainOuterTo(CS, A, - ReasonLoc(ALLOCATOR_REASON, ExprPSL), true); + PVC->constrainOuterTo(CS, A, ReasonLoc(ALLOCATOR_REASON, ExprPSL), + true); ReturnCVs.insert(PVC); DidInsert = true; if (FuncName.compare("realloc") == 0) { @@ -508,13 +506,13 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { assert(CV.hasValue() && "Function without constraint variable."); /* Direct function call */ if (FVConstraint *FVC = dyn_cast(&CV.getValue())) - ReturnCVs.insert(localReturnConstraint(FVC,TypeVars,CS,Info)); + ReturnCVs.insert(localReturnConstraint(FVC, TypeVars, CS, Info)); /* Call via function pointer */ else { PVConstraint *Tmp = dyn_cast(&CV.getValue()); assert(Tmp != nullptr); if (FVConstraint *FVC = Tmp->getFV()) - ReturnCVs.insert(localReturnConstraint(FVC,TypeVars,CS,Info)); + ReturnCVs.insert(localReturnConstraint(FVC, TypeVars, CS, Info)); else { // No FVConstraint -- make WILD. std::string Rsn = "Can't get return variable of function call."; @@ -597,8 +595,7 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { // Array initialization is similar AddrOf, so the same pattern is // used where a new indirection is added to constraint variables. auto Rsn = ReasonLoc("Array initialization", ExprPSL); - Ret = std::make_pair(addAtomAll(CVars.first, CS.getArr(), - Rsn, CS), + Ret = std::make_pair(addAtomAll(CVars.first, CS.getArr(), Rsn, CS), CVars.second); } else { // This branch should only be taken on compound literal expressions @@ -633,8 +630,9 @@ CSetBkeyPair ConstraintResolver::getExprConstraintVars(Expr *E) { // We create a new constraint variable and constraint it to an Nt_array. PVConstraint *P = new PVConstraint(Str, Info, *Context); - P->constrainOuterTo(CS, CS.getNTArr(), - ReasonLoc(STRING_LITERAL_REASON,ExprPSL)); // NB: ARR already there. + P->constrainOuterTo( + CS, CS.getNTArr(), + ReasonLoc(STRING_LITERAL_REASON, ExprPSL)); // NB: ARR already there. BoundsKey TmpKey = ABI.getRandomBKey(); P->setBoundsKey(TmpKey); diff --git a/clang/lib/3C/ConstraintVariables.cpp b/clang/lib/3C/ConstraintVariables.cpp index 4da97be8b4b0..d8700d759c7e 100644 --- a/clang/lib/3C/ConstraintVariables.cpp +++ b/clang/lib/3C/ConstraintVariables.cpp @@ -52,11 +52,12 @@ std::string ConstraintVariable::getOriginalTypeWithName() const { return OriginalTypeWithName; } -PointerVariableConstraint *PointerVariableConstraint::getWildPVConstraint( - Constraints &CS, const ReasonLoc &Rsn) { +PointerVariableConstraint * +PointerVariableConstraint::getWildPVConstraint(Constraints &CS, + const ReasonLoc &Rsn) { auto *WildPVC = new PointerVariableConstraint("wildvar"); - VarAtom *VA = CS.createFreshGEQ("wildvar", VarAtom::V_Other, CS.getWild(), - Rsn); + VarAtom *VA = + CS.createFreshGEQ("wildvar", VarAtom::V_Other, CS.getWild(), Rsn); WildPVC->Vars.push_back(VA); WildPVC->SrcVars.push_back(CS.getWild()); @@ -102,8 +103,8 @@ PointerVariableConstraint::derefPVConstraint(PointerVariableConstraint *PVC) { } PointerVariableConstraint *PointerVariableConstraint::addAtomPVConstraint( - PointerVariableConstraint *PVC, ConstAtom *PtrTyp, - ReasonLoc &Rsn, Constraints &CS) { + PointerVariableConstraint *PVC, ConstAtom *PtrTyp, ReasonLoc &Rsn, + Constraints &CS) { auto *Copy = new PointerVariableConstraint(PVC); std::vector &Vars = Copy->Vars; std::vector &SrcVars = Copy->SrcVars; @@ -117,8 +118,8 @@ PointerVariableConstraint *PointerVariableConstraint::addAtomPVConstraint( // atoms to be wild if an outer atom is wild. if (!Vars.empty()) if (auto *VA = dyn_cast(*Vars.begin())) - CS.addConstraint(new Geq(VA, NewA, - ReasonLoc(INNER_POINTER_REASON, PersistentSourceLoc()))); + CS.addConstraint(new Geq( + VA, NewA, ReasonLoc(INNER_POINTER_REASON, PersistentSourceLoc()))); Vars.insert(Vars.begin(), NewA); SrcVars.insert(SrcVars.begin(), PtrTyp); @@ -128,18 +129,18 @@ PointerVariableConstraint *PointerVariableConstraint::addAtomPVConstraint( PointerVariableConstraint::PointerVariableConstraint( PointerVariableConstraint *Ot) - : ConstraintVariable(ConstraintVariable::PointerVariable, Ot->OriginalType, - Ot->Name, Ot->OriginalTypeWithName), - BaseType(Ot->BaseType), Vars(Ot->Vars), SrcVars(Ot->SrcVars), FV(Ot->FV), - QualMap(Ot->QualMap), ArrSizes(Ot->ArrSizes), ArrSizeStrs(Ot->ArrSizeStrs), - SrcHasItype(Ot->SrcHasItype), ItypeStr(Ot->ItypeStr), - PartOfFuncPrototype(Ot->PartOfFuncPrototype), Parent(Ot), - BoundsAnnotationStr(Ot->BoundsAnnotationStr), - SourceGenericIndex(Ot->SourceGenericIndex), - InferredGenericIndex(Ot->InferredGenericIndex), - IsZeroWidthArray(Ot->IsZeroWidthArray), - IsTypedef(Ot->IsTypedef), TypedefString(Ot->TypedefString), - TypedefLevelInfo(Ot->TypedefLevelInfo), IsVoidPtr(Ot->IsVoidPtr) { + : ConstraintVariable(ConstraintVariable::PointerVariable, Ot->OriginalType, + Ot->Name, Ot->OriginalTypeWithName), + BaseType(Ot->BaseType), Vars(Ot->Vars), SrcVars(Ot->SrcVars), FV(Ot->FV), + QualMap(Ot->QualMap), ArrSizes(Ot->ArrSizes), + ArrSizeStrs(Ot->ArrSizeStrs), SrcHasItype(Ot->SrcHasItype), + ItypeStr(Ot->ItypeStr), PartOfFuncPrototype(Ot->PartOfFuncPrototype), + Parent(Ot), BoundsAnnotationStr(Ot->BoundsAnnotationStr), + SourceGenericIndex(Ot->SourceGenericIndex), + InferredGenericIndex(Ot->InferredGenericIndex), + IsZeroWidthArray(Ot->IsZeroWidthArray), IsTypedef(Ot->IsTypedef), + TypedefString(Ot->TypedefString), TypedefLevelInfo(Ot->TypedefLevelInfo), + IsVoidPtr(Ot->IsVoidPtr) { // These are fields of the super class Constraint Variable this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints; this->ValidBoundsKey = Ot->ValidBoundsKey; @@ -212,8 +213,8 @@ class TypedefLevelFinder : public RecursiveASTVisitor { PointerVariableConstraint::PointerVariableConstraint( const QualType &QT, DeclaratorDecl *D, std::string N, ProgramInfo &I, const ASTContext &C, std::string *InFunc, int ForceGenericIndex, - bool PotentialGeneric, - bool VarAtomForChecked, TypeSourceInfo *TSInfo, const QualType &ITypeT) + bool PotentialGeneric, bool VarAtomForChecked, TypeSourceInfo *TSInfo, + const QualType &ITypeT) : ConstraintVariable(ConstraintVariable::PointerVariable, QT, N), FV(nullptr), SrcHasItype(false), PartOfFuncPrototype(InFunc != nullptr), Parent(nullptr) { @@ -524,14 +525,14 @@ PointerVariableConstraint::PointerVariableConstraint( IsVoidPtr = QT->isPointerType() && isTypeHasVoid(QT); // varargs are always wild, as are void pointers that are not generic bool IsWild = isVarArgType(BaseType) || - (!(PotentialGeneric || isGeneric()) && IsVoidPtr); + (!(PotentialGeneric || isGeneric()) && IsVoidPtr); if (IsWild) { std::string Rsn = IsVoidPtr ? VOID_TYPE_REASON : "Default Var arg list type"; // TODO: Github issue #61: improve handling of types for variable arguments. for (const auto &V : Vars) if (VarAtom *VA = dyn_cast(V)) - CS.addConstraint(CS.createGeq(VA, CS.getWild(), ReasonLoc(Rsn,PSL))); + CS.addConstraint(CS.createGeq(VA, CS.getWild(), ReasonLoc(Rsn, PSL))); } // Add qualifiers. @@ -796,9 +797,9 @@ PointerVariableConstraint::mkString(Constraints &CS, std::string BaseTypeName = BaseType; if (InferredGenericIndex > -1 && isVoidPtr() && isSolutionChecked(CS.getVariables())) { - assert(InferredGenericIndex < 3 - && "Trying to use an unexpected type variable name"); - BaseTypeName = std::begin({"T","U","V"})[InferredGenericIndex]; + assert(InferredGenericIndex < 3 && + "Trying to use an unexpected type variable name"); + BaseTypeName = std::begin({"T", "U", "V"})[InferredGenericIndex]; } auto It = Vars.begin(); @@ -985,8 +986,7 @@ PointerVariableConstraint::mkString(Constraints &CS, } bool PVConstraint::addArgumentConstraint(ConstraintVariable *DstCons, - ReasonLoc &Rsn, - ProgramInfo &Info) { + ReasonLoc &Rsn, ProgramInfo &Info) { if (this->Parent == nullptr) { bool RetVal = false; if (isPartOfFunctionPrototype()) { @@ -1006,11 +1006,12 @@ const CVarSet &PVConstraint::getArgumentConstraints() const { } FunctionVariableConstraint::FunctionVariableConstraint(FVConstraint *Ot) - : ConstraintVariable(ConstraintVariable::FunctionVariable, Ot->OriginalType, - Ot->getName(), Ot->OriginalTypeWithName), - ReturnVar(Ot->ReturnVar), ParamVars(Ot->ParamVars), FileName(Ot->FileName), - Hasproto(Ot->Hasproto), Hasbody(Ot->Hasbody), IsStatic(Ot->IsStatic), - Parent(Ot), IsFunctionPtr(Ot->IsFunctionPtr), TypeParams(Ot->TypeParams) { + : ConstraintVariable(ConstraintVariable::FunctionVariable, Ot->OriginalType, + Ot->getName(), Ot->OriginalTypeWithName), + ReturnVar(Ot->ReturnVar), ParamVars(Ot->ParamVars), + FileName(Ot->FileName), Hasproto(Ot->Hasproto), Hasbody(Ot->Hasbody), + IsStatic(Ot->IsStatic), IsFunctionPtr(Ot->IsFunctionPtr), + TypeParams(Ot->TypeParams) { this->HasEqArgumentConstraints = Ot->HasEqArgumentConstraints; } @@ -1036,8 +1037,7 @@ FunctionVariableConstraint::FunctionVariableConstraint(TypedefDecl *D, FunctionVariableConstraint::FunctionVariableConstraint( const QualType QT, DeclaratorDecl *D, std::string N, ProgramInfo &I, const ASTContext &Ctx, TypeSourceInfo *TSInfo) - : ConstraintVariable(ConstraintVariable::FunctionVariable, QT, N), - Parent(nullptr) { + : ConstraintVariable(ConstraintVariable::FunctionVariable, QT, N) { const Type *Ty = QT.getTypePtr(); QualType RT, RTIType; Hasproto = false; @@ -1111,9 +1111,8 @@ FunctionVariableConstraint::FunctionVariableConstraint( ParmVD = FTL.getParam(J); std::string PName = ParmVD ? ParmVD->getName().str() : ""; - auto ParamVar = - FVComponentVariable(QT, ITypeT, ParmVD, PName, I, Ctx, - &N, true, ParamHasItype); + auto ParamVar = FVComponentVariable(QT, ITypeT, ParmVD, PName, I, Ctx, &N, + true, ParamHasItype); ParamVars.push_back(ParamVar); } @@ -1127,20 +1126,20 @@ FunctionVariableConstraint::FunctionVariableConstraint( } // ConstraintVariable for the return. - ReturnVar = FVComponentVariable(RT, RTIType, D, RETVAR, I, Ctx, - &N, true, ReturnHasItype); + ReturnVar = FVComponentVariable(RT, RTIType, D, RETVAR, I, Ctx, &N, true, + ReturnHasItype); // Locate the void* params that were not marked wild above // to either do so or use as generics std::vector Voids; - auto Ext = ReturnVar.ExternalConstraint; - if(Ext->isVoidPtr() && !Ext->isGeneric()) { + auto *Ext = ReturnVar.ExternalConstraint; + if (Ext->isVoidPtr() && !Ext->isGeneric()) { Voids.push_back(-1); } - for(unsigned i=0; i < ParamVars.size();i++) { - auto Ext = ParamVars[i].ExternalConstraint; - if(Ext->isVoidPtr() && !Ext->isGeneric()) { - Voids.push_back(i); + for (unsigned I = 0; I < ParamVars.size(); I++) { + auto *Ext = ParamVars[I].ExternalConstraint; + if (Ext->isVoidPtr() && !Ext->isGeneric()) { + Voids.push_back(I); } } // Strategy: If there's one void*, turn this into a generic function. @@ -1149,12 +1148,12 @@ FunctionVariableConstraint::FunctionVariableConstraint( // function pointers, and source generics for now // Also exclude params that are checked or have itypes bool ConvertFunc = canWrite(FileName) && hasBody() && !IsFunctionPtr && - TypeParams == 0 && Voids.size() == 1; + TypeParams == 0 && Voids.size() == 1; bool DidConvert = false; auto &CS = I.getConstraints(); - for(int idx : Voids) { - FVComponentVariable *FVCV = idx == -1 ? &ReturnVar : &ParamVars[idx]; - auto Ext = FVCV->ExternalConstraint; + for (int Idx : Voids) { + FVComponentVariable *FVCV = Idx == -1 ? &ReturnVar : &ParamVars[Idx]; + auto *Ext = FVCV->ExternalConstraint; if (ConvertFunc && !Ext->isOriginallyChecked() && !Ext->srcHasItype() && Ext->getCvars().size() == 1) { FVCV->setGenericIndex(0); @@ -1165,11 +1164,12 @@ FunctionVariableConstraint::FunctionVariableConstraint( } } } - if (DidConvert) TypeParams = 1; + if (DidConvert) + TypeParams = 1; } -void FunctionVariableConstraint::constrainToWild( - Constraints &CS, const ReasonLoc &Rsn) const { +void FunctionVariableConstraint::constrainToWild(Constraints &CS, + const ReasonLoc &Rsn) const { ReturnVar.ExternalConstraint->constrainToWild(CS, Rsn); for (const auto &V : ParamVars) @@ -1225,7 +1225,8 @@ FVConstraint *FunctionVariableConstraint::getCopy(ReasonLoc &Rsn, return Copy; } -void PVConstraint::equateArgumentConstraints(ProgramInfo &Info, ReasonLoc &Rsn) { +void PVConstraint::equateArgumentConstraints(ProgramInfo &Info, + ReasonLoc &Rsn) { if (HasEqArgumentConstraints) { return; } @@ -1238,8 +1239,9 @@ void PVConstraint::equateArgumentConstraints(ProgramInfo &Info, ReasonLoc &Rsn) } } -void FunctionVariableConstraint::equateFVConstraintVars( - ConstraintVariable *CV, ProgramInfo &Info, ReasonLoc &Rsn) const { +void FunctionVariableConstraint::equateFVConstraintVars(ConstraintVariable *CV, + ProgramInfo &Info, + ReasonLoc &Rsn) const { if (FVConstraint *FVCons = dyn_cast(CV)) { for (auto &PCon : FVCons->ParamVars) PCon.InternalConstraint->equateArgumentConstraints(Info, Rsn); @@ -1299,8 +1301,8 @@ void PointerVariableConstraint::constrainToWild(Constraints &CS, void PointerVariableConstraint::constrainIdxTo(Constraints &CS, ConstAtom *C, unsigned int Idx, - const ReasonLoc &Rsn, - bool DoLB, bool Soft) { + const ReasonLoc &Rsn, bool DoLB, + bool Soft) { assert(C == CS.getPtr() || C == CS.getArr() || C == CS.getNTArr()); if (Vars.size() > Idx) { @@ -1390,7 +1392,7 @@ PVConstraint *PointerVariableConstraint::getCopy(ReasonLoc &Rsn, } else if (auto *VA = dyn_cast(*VAIt)) { VarAtom *FreshVA = CS.getFreshVar(VA->getName(), VA->getVarKind()); FreshVars.push_back(FreshVA); - if (!isa(*CAIt)){ + if (!isa(*CAIt)) { CS.addConstraint(CS.createGeq(*CAIt, FreshVA, Rsn, false)); } } @@ -1484,7 +1486,7 @@ bool PointerVariableConstraint::isNtConstantArr(const EnvironmentMap &E) const { const ConstAtom *PtrType = getSolution(Vars[0], E); return isa(PtrType); } - return false; + return false; } bool PointerVariableConstraint::isConstantArr() const { @@ -1520,8 +1522,7 @@ bool PointerVariableConstraint::solutionEqualTo(Constraints &CS, if (CV != nullptr) { if (const auto *PV = dyn_cast(CV)) { auto &OthCVars = PV->Vars; - if (isGeneric() || PV->isGeneric() || - Vars.size() == OthCVars.size()) { + if (isGeneric() || PV->isGeneric() || Vars.size() == OthCVars.size()) { Ret = true; auto I = Vars.begin(); @@ -1707,7 +1708,8 @@ FunctionVariableConstraint::mkString(Constraints &CS, // Action depends on the kind of constraint (checked, ptyp), // which is inferred from the atom type static void createAtomGeq(Constraints &CS, Atom *L, Atom *R, - const ReasonLoc &Rsn, ConsAction CAct, bool DoEqType) { + const ReasonLoc &Rsn, ConsAction CAct, + bool DoEqType) { ConstAtom *CAL, *CAR; VarAtom *VAL, *VAR; ConstAtom *Wild = CS.getWild(); @@ -1820,16 +1822,16 @@ static void createAtomGeq(Constraints &CS, Atom *L, Atom *R, // Generate constraints according to CA |- RHS <: LHS. // If doEqType is true, then also do CA |- LHS <: RHS. void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey) { // If one of the constraint is NULL, make the other constraint WILD. // This can happen when a non-function pointer gets assigned to // a function pointer. if (LHS == nullptr || RHS == nullptr) { - auto Reason = ReasonLoc("Assignment a non-pointer to a pointer", - Rsn.Location); + auto Reason = + ReasonLoc("Assignment a non-pointer to a pointer", Rsn.Location); if (LHS != nullptr) { LHS->constrainToWild(CS, Reason); } @@ -1853,11 +1855,11 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, // Constrain the return values covariantly. // FIXME: Make neg(CA) here? Function pointers equated. constrainConsVarGeq(FCLHS->getExternalReturn(), - FCRHS->getExternalReturn(), CS, Reason, Same_to_Same, - DoEqType, Info, HandleBoundsKey); + FCRHS->getExternalReturn(), CS, Reason, + Same_to_Same, DoEqType, Info, HandleBoundsKey); constrainConsVarGeq(FCLHS->getInternalReturn(), - FCRHS->getInternalReturn(), CS, Reason, Same_to_Same, - DoEqType, Info, HandleBoundsKey); + FCRHS->getInternalReturn(), CS, Reason, + Same_to_Same, DoEqType, Info, HandleBoundsKey); // Constrain the parameters contravariantly. if (FCLHS->numParams() == FCRHS->numParams()) { @@ -1870,14 +1872,14 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, ConstraintVariable *LParam = FCLHS->getInternalParam(I); ConstraintVariable *RParam = FCRHS->getInternalParam(I); - constrainConsVarGeq(RParam, LParam, CS, Reason, Same_to_Same, DoEqType, - Info, HandleBoundsKey); + constrainConsVarGeq(RParam, LParam, CS, Reason, Same_to_Same, + DoEqType, Info, HandleBoundsKey); } } else { // Constrain both to be top. - auto WildReason = ReasonLoc( - "Assigning from " + FCRHS->getName() + " to " + FCLHS->getName(), - Rsn.Location); + auto WildReason = ReasonLoc("Assigning from " + FCRHS->getName() + + " to " + FCLHS->getName(), + Rsn.Location); RHS->constrainToWild(CS, WildReason); LHS->constrainToWild(CS, WildReason); } @@ -1893,9 +1895,9 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, PCRHS->getBoundsKey()); } - auto Reason = ReasonLoc( - "Assigning from " + PCRHS->getName() + " to " + PCLHS->getName(), - Rsn.Location); + auto Reason = ReasonLoc("Assigning from " + PCRHS->getName() + " to " + + PCLHS->getName(), + Rsn.Location); // This is to handle function subtyping. Try to add LHS and RHS // to each others argument constraints. PCLHS->addArgumentConstraint(PCRHS, Reason, *Info); @@ -1928,11 +1930,11 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, // unless assigning to a generic type. } else { // Constrain both to be top. - auto WildReason = ReasonLoc( - "Assigning from " + std::to_string(CRHS.size()) + + auto WildReason = + ReasonLoc("Assigning from " + std::to_string(CRHS.size()) + " depth pointer to " + std::to_string(CLHS.size()) + " depth pointer.", - Rsn.Location); + Rsn.Location); PCLHS->constrainToWild(CS, WildReason); PCRHS->constrainToWild(CS, WildReason); } @@ -1946,9 +1948,9 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, llvm_unreachable("unknown kind"); } else { // Assigning from a function variable to a pointer variable? - auto Reason = ReasonLoc( - "Assigning from a function variable to a pointer variable", - Rsn.Location); + auto Reason = + ReasonLoc("Assigning from a function variable to a pointer variable", + Rsn.Location); PVConstraint *PCLHS = dyn_cast(LHS); FVConstraint *FCRHS = dyn_cast(RHS); if (PCLHS && FCRHS) { @@ -1964,9 +1966,8 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, } } else { // Constrain everything in both to wild. - auto WildReason = ReasonLoc( - "Assignment to functions from variables", - Rsn.Location); + auto WildReason = + ReasonLoc("Assignment to functions from variables", Rsn.Location); LHS->constrainToWild(CS, WildReason); RHS->constrainToWild(CS, WildReason); } @@ -1974,8 +1975,8 @@ void constrainConsVarGeq(ConstraintVariable *LHS, ConstraintVariable *RHS, } void constrainConsVarGeq(ConstraintVariable *LHS, const CVarSet &RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey) { for (const auto &J : RHS) constrainConsVarGeq(LHS, J, CS, Rsn, CA, DoEqType, Info, HandleBoundsKey); @@ -1983,8 +1984,8 @@ void constrainConsVarGeq(ConstraintVariable *LHS, const CVarSet &RHS, // Given an RHS and a LHS, constrain them to be equal. void constrainConsVarGeq(const CVarSet &LHS, const CVarSet &RHS, - Constraints &CS, const ReasonLoc &Rsn, - ConsAction CA, bool DoEqType, ProgramInfo *Info, + Constraints &CS, const ReasonLoc &Rsn, ConsAction CA, + bool DoEqType, ProgramInfo *Info, bool HandleBoundsKey) { for (const auto &I : LHS) constrainConsVarGeq(I, RHS, CS, Rsn, CA, DoEqType, Info, HandleBoundsKey); @@ -2075,7 +2076,8 @@ void PointerVariableConstraint::equateWithItype( for (unsigned VarIdx = 0; VarIdx < Vars.size(); VarIdx++) { ConstAtom *CA = SrcVars[VarIdx]; if (isa(CA)) - CS.addConstraint(CS.createGeq(Vars[VarIdx], CA,ReasonUnchangeable,true)); + CS.addConstraint( + CS.createGeq(Vars[VarIdx], CA, ReasonUnchangeable, true)); else Vars[VarIdx] = SrcVars[VarIdx]; } @@ -2173,7 +2175,8 @@ std::string FVComponentVariable::mkTypeStr(Constraints &CS, bool EmitName, // instead calling mkString the type is generated from the external constraint // variable. Because the call is passed ForItypeBase, it will emit an // unchecked type instead of the solved type. - if (ForItypeBase || hasCheckedSolution(CS) || (EmitName && !UseName.empty())) { + if (ForItypeBase || hasCheckedSolution(CS) || + (EmitName && !UseName.empty())) { Ret = ExternalConstraint->mkString( CS, MKSTRING_OPTS(EmitName = EmitName, UseName = UseName, ForItypeBase = ForItypeBase)); @@ -2199,8 +2202,8 @@ std::string FVComponentVariable::mkTypeStr(Constraints &CS, bool EmitName, return Ret; } -std::string -FVComponentVariable::mkItypeStr(Constraints &CS, bool ForItypeBase) const { +std::string FVComponentVariable::mkItypeStr(Constraints &CS, + bool ForItypeBase) const { if (!ForItypeBase && hasItypeSolution(CS)) return " : itype(" + ExternalConstraint->mkString( @@ -2231,17 +2234,12 @@ bool FVComponentVariable::hasItypeSolution(Constraints &CS) const { !InternalConstraint->solutionEqualTo(CS, ExternalConstraint); } -FVComponentVariable::FVComponentVariable(const QualType &QT, - const QualType &ITypeT, - clang::DeclaratorDecl *D, - std::string N, ProgramInfo &I, - const ASTContext &C, - std::string *InFunc, - bool PotentialGeneric, - bool HasItype) { - ExternalConstraint = - new PVConstraint(QT, D, N, I, C, InFunc, -1, PotentialGeneric, HasItype, - nullptr, ITypeT); +FVComponentVariable::FVComponentVariable( + const QualType &QT, const QualType &ITypeT, clang::DeclaratorDecl *D, + std::string N, ProgramInfo &I, const ASTContext &C, std::string *InFunc, + bool PotentialGeneric, bool HasItype) { + ExternalConstraint = new PVConstraint( + QT, D, N, I, C, InFunc, -1, PotentialGeneric, HasItype, nullptr, ITypeT); if (!HasItype && QT->isVoidPointerType()) { InternalConstraint = ExternalConstraint; } else { @@ -2277,15 +2275,15 @@ FVComponentVariable::FVComponentVariable(const QualType &QT, CSR = CharSourceRange::getTokenRange(DRange); } - SourceDeclaration = getSourceText(CSR , C); + SourceDeclaration = getSourceText(CSR, C); } else { SourceDeclaration = ""; } } } -void FVComponentVariable::equateWithItype(ProgramInfo &I, - const ReasonLoc &ReasonUnchangeable) const { +void FVComponentVariable::equateWithItype( + ProgramInfo &I, const ReasonLoc &ReasonUnchangeable) const { Constraints &CS = I.getConstraints(); const ReasonLoc &ReasonUnchangeable2 = (ReasonUnchangeable.isDefault() && ExternalConstraint->isGeneric()) @@ -2305,8 +2303,8 @@ void FVComponentVariable::equateWithItype(ProgramInfo &I, // losing bounds on array pointers, and converting constant sized arrays into // pointers. We still allow the internal type to change so that the type can // change from an itype to fully checked. - bool MustBeArray = - ExternalConstraint->srcHasBounds() || ExternalConstraint->hasSomeSizedArr(); + bool MustBeArray = ExternalConstraint->srcHasBounds() || + ExternalConstraint->hasSomeSizedArr(); if (HasItype && (MustConstrainInternalType || MustBeArray)) { ExternalConstraint->equateWithItype(I, ReasonUnchangeable2); if (ExternalConstraint != InternalConstraint) @@ -2319,7 +2317,8 @@ void FVComponentVariable::equateWithItype(ProgramInfo &I, void FVComponentVariable::linkInternalExternal(ProgramInfo &I, bool EquateChecked) const { Constraints &CS = I.getConstraints(); - auto LinkReason = ReasonLoc("Function Internal/External Link", PersistentSourceLoc()); + auto LinkReason = + ReasonLoc("Function Internal/External Link", PersistentSourceLoc()); for (unsigned J = 0; J < InternalConstraint->getCvars().size(); J++) { Atom *InternalA = InternalConstraint->getCvars()[J]; Atom *ExternalA = ExternalConstraint->getCvars()[J]; @@ -2335,8 +2334,7 @@ void FVComponentVariable::linkInternalExternal(ProgramInfo &I, // use causes the internal variable to be wild because the external // variable solves to WILD only when there is an unsafe use that // cannot be resolved by inserting casts. - CS.addConstraint(CS.createGeq(InternalA, ExternalA, - LinkReason, true)); + CS.addConstraint(CS.createGeq(InternalA, ExternalA, LinkReason, true)); // Atoms of return constraint variables are unified after the first // level. This is because CheckedC does not allow assignment from e.g. @@ -2344,8 +2342,8 @@ void FVComponentVariable::linkInternalExternal(ProgramInfo &I, // variable with type `int **`. if (DisableFunctionEdges || DisableRDs || EquateChecked || (ExternalConstraint->getName() == RETVAR && J > 0)) - CS.addConstraint(CS.createGeq(ExternalA, InternalA, - LinkReason, true)); + CS.addConstraint( + CS.createGeq(ExternalA, InternalA, LinkReason, true)); } } } @@ -2367,8 +2365,7 @@ bool FVComponentVariable::solutionEqualTo(Constraints &CS, } FVComponentVariable::FVComponentVariable(FVComponentVariable *Ot, - ReasonLoc &Rsn, - Constraints &CS) { - InternalConstraint = Ot->InternalConstraint->getCopy(Rsn,CS); - ExternalConstraint = Ot->ExternalConstraint->getCopy(Rsn,CS); + ReasonLoc &Rsn, Constraints &CS) { + InternalConstraint = Ot->InternalConstraint->getCopy(Rsn, CS); + ExternalConstraint = Ot->ExternalConstraint->getCopy(Rsn, CS); } diff --git a/clang/lib/3C/Constraints.cpp b/clang/lib/3C/Constraints.cpp index 5e6268455777..876dcf1db3bc 100644 --- a/clang/lib/3C/Constraints.cpp +++ b/clang/lib/3C/Constraints.cpp @@ -171,11 +171,9 @@ bool Constraints::removeReasonBasedConstraint(Constraint *C) { //---- for all edges (k --> q) in G, confirm that sol(k) <: q; else fail //---- add k to W -static bool -doSolve(ConstraintsGraph &CG, - ConstraintsEnv &Env, Constraints *CS, bool DoLeastSolution, - std::set *InitVs, - std::set &Conflicts) { +static bool doSolve(ConstraintsGraph &CG, ConstraintsEnv &Env, Constraints *CS, + bool DoLeastSolution, std::set *InitVs, + std::set &Conflicts) { std::vector WorkList; @@ -215,7 +213,7 @@ doSolve(ConstraintsGraph &CG, } // Check Upper/lower bounds hold; collect failures in conflicts set. - std::set IncidentEdges; + std::set IncidentEdges; bool Ok = true; for (ConstAtom *Cbound : CG.getAllConstAtoms()) { if (CG.getIncidentEdges(Cbound, IncidentEdges, !DoLeastSolution)) { @@ -448,7 +446,7 @@ bool Constraints::graphBasedSolve() { for (auto *Succ : Succs) { if (auto *SuccGeq = dyn_cast(Succ->EdgeConstraint)) { if (Env.getAssignment(ConflictAtom) == - Env.getAssignment(SuccGeq->getLHS()) || + Env.getAssignment(SuccGeq->getLHS()) || Env.getAssignment(ConflictAtom) == Env.getAssignment(SuccGeq->getRHS())) { Rsn2 = Succ->EdgeConstraint->getReason(); @@ -456,8 +454,8 @@ bool Constraints::graphBasedSolve() { } } } - auto Rsn = ReasonLoc("Inferred conflicting types", - PersistentSourceLoc()); + auto Rsn = + ReasonLoc("Inferred conflicting types", PersistentSourceLoc()); Geq *ConflictConstraint = createGeq(ConflictAtom, getWild(), Rsn); ConflictConstraint->addReason(Rsn1); ConflictConstraint->addReason(Rsn2); diff --git a/clang/lib/3C/CtxSensAVarBounds.cpp b/clang/lib/3C/CtxSensAVarBounds.cpp index 1fe6d9ff11c7..0e0e9cdce671 100644 --- a/clang/lib/3C/CtxSensAVarBounds.cpp +++ b/clang/lib/3C/CtxSensAVarBounds.cpp @@ -254,7 +254,7 @@ void CtxSensitiveBoundsKeyHandler::contextualizeCVar(MemberExpr *ME, void CtxSensitiveBoundsKeyHandler::contextualizeCVar(VarDecl *VD, ASTContext *C, ProgramInfo &I) { const auto *RT = dyn_cast_or_null( - VD->getType()->getUnqualifiedDesugaredType()); + VD->getType()->getUnqualifiedDesugaredType()); if (RecordDecl *RD = RT != nullptr ? RT->getDecl() : nullptr) { // Get structure access key. StructAccessVisitor SKV(C); diff --git a/clang/lib/3C/DeclRewriter.cpp b/clang/lib/3C/DeclRewriter.cpp index 72ae4289df83..5e0cd5da89e5 100644 --- a/clang/lib/3C/DeclRewriter.cpp +++ b/clang/lib/3C/DeclRewriter.cpp @@ -45,8 +45,8 @@ void DeclRewriter::buildItypeDecl(PVConstraint *Defn, DeclaratorDecl *Decl, // checked type, it is not rewritten, so it remains unchecked in the converted // code. bool IsUncheckedTypedef = - Defn->isTypedef() && (_3COpts.ItypesForExtern || - !Defn->getTypedefVar()->isSolutionChecked(Env)); + Defn->isTypedef() && (_3COpts.ItypesForExtern || + !Defn->getTypedefVar()->isSolutionChecked(Env)); // True if this variable is defined by a typedef, and the constraint variable // representing the typedef solves to a checked type. Notably not the negation // of IsUncheckedTypedef because both require the variable type be defined @@ -69,9 +69,9 @@ void DeclRewriter::buildItypeDecl(PVConstraint *Defn, DeclaratorDecl *Decl, // extra set of parenthesis (e.g. `void ((*f)())` instead of `void (f*)()`) // for the declaration to parse correctly. qtyToStr (which is used by // getOriginalTypeWithName) does not support adding these parentheses. - Type = Defn->mkString(Info.getConstraints(), - MKSTRING_OPTS(UnmaskTypedef = IsCheckedTypedef, - ForItypeBase = true)); + Type = Defn->mkString( + Info.getConstraints(), + MKSTRING_OPTS(UnmaskTypedef = IsCheckedTypedef, ForItypeBase = true)); } else { // In the remaining cases, the unchecked portion of the itype is just the // original type of the pointer. The first branch tries to generate the type @@ -190,8 +190,8 @@ void DeclRewriter::rewriteDecls(ASTContext &Context, ProgramInfo &Info, std::string NewTy = getStorageQualifierString(D); bool IsExternGlobalVar = - isa(D) && - cast(D)->getFormalLinkage() == Linkage::ExternalLinkage; + isa(D) && + cast(D)->getFormalLinkage() == Linkage::ExternalLinkage; if (_3COpts.ItypesForExtern && (isa(D) || IsExternGlobalVar)) { // Give record fields and global variables itypes when using @@ -599,8 +599,8 @@ bool FunctionDeclBuilder::VisitFunctionDecl(FunctionDecl *FD) { } // If we've made this generic we need add "_For_any" or "_Itype_for_any" - if (FDConstraint->getGenericParams() > 0 - && !FD->isGenericFunction() && !FD->isItypeGenericFunction()) + if (FDConstraint->getGenericParams() > 0 && !FD->isGenericFunction() && + !FD->isItypeGenericFunction()) RewriteGeneric = true; // Get rewritten parameter variable declarations. Try to use @@ -656,8 +656,8 @@ bool FunctionDeclBuilder::VisitFunctionDecl(FunctionDecl *FD) { // For now we still need to check if this needs rewriting, see FIXME below // if (!DeclIsTypedef) this->buildDeclVar(FDConstraint->getCombineReturn(), FD, ReturnVar, ItypeStr, - "", RewriteGeneric, RewriteParams, - RewriteReturn, FD->isStatic()); + "", RewriteGeneric, RewriteParams, RewriteReturn, + FD->isStatic()); ProtoHasItype |= !ItypeStr.empty(); @@ -707,8 +707,8 @@ bool FunctionDeclBuilder::VisitFunctionDecl(FunctionDecl *FD) { // Mirrors the check above that sets RewriteGeneric to true. // If we've decided against making this generic, remove the generic params // so later rewrites (of typeparams) don't happen - if (!RewriteGeneric && FDConstraint->getGenericParams() > 0 - && !FD->isGenericFunction() && !FD->isItypeGenericFunction()) + if (!RewriteGeneric && FDConstraint->getGenericParams() > 0 && + !FD->isGenericFunction() && !FD->isItypeGenericFunction()) FDConstraint->resetGenericParams(); // If this was an itype but is now checked, we'll be changing @@ -726,10 +726,9 @@ bool FunctionDeclBuilder::VisitFunctionDecl(FunctionDecl *FD) { NewSig += "_Itype_for_any(T"; else NewSig += "_For_any(T"; - for (int i = 0; i < FDConstraint->getGenericParams() - 1; i++) { - assert(i < 2 && - "Need an unexpected number of type variables"); - NewSig += std::begin({",U",",V"})[i]; + for (int I = 0; I < FDConstraint->getGenericParams() - 1; I++) { + assert(I < 2 && "Need an unexpected number of type variables"); + NewSig += std::begin({",U", ",V"})[I]; } NewSig += ") "; } @@ -758,9 +757,8 @@ bool FunctionDeclBuilder::VisitFunctionDecl(FunctionDecl *FD) { // Add new declarations to RewriteThese if it has changed if (RewriteReturn || RewriteParams) { RewriteThese.insert(std::make_pair( - FD, - new FunctionDeclReplacement(FD, NewSig, RewriteReturn, - RewriteParams, RewriteGeneric))); + FD, new FunctionDeclReplacement(FD, NewSig, RewriteReturn, + RewriteParams, RewriteGeneric))); } return true; @@ -779,7 +777,6 @@ void FunctionDeclBuilder::buildCheckedDecl( RewriteRet |= isa_and_nonnull(Decl); } - void FunctionDeclBuilder::buildItypeDecl(PVConstraint *Defn, DeclaratorDecl *Decl, std::string &Type, std::string &IType, @@ -819,7 +816,7 @@ void FunctionDeclBuilder::buildDeclVar(const FVComponentVariable *CV, if (!CheckedSolution && CV->getExternal()->isGenericChanged()) RewriteGen = false; -// If the type of the pointer hasn't changed, then neither of the above + // If the type of the pointer hasn't changed, then neither of the above // branches will be taken, but it's still possible for the bounds of an array // pointer to change. if (ABRewriter.hasNewBoundsString(CV->getExternal(), Decl)) { diff --git a/clang/lib/3C/PersistentSourceLoc.cpp b/clang/lib/3C/PersistentSourceLoc.cpp index a37e52df92cd..73204138453e 100644 --- a/clang/lib/3C/PersistentSourceLoc.cpp +++ b/clang/lib/3C/PersistentSourceLoc.cpp @@ -21,7 +21,8 @@ using namespace llvm; // will need to the spelling location instead. PersistentSourceLoc PersistentSourceLoc::mkPSL(const Decl *D, const ASTContext &C) { - if (D == nullptr) return PersistentSourceLoc(); + if (D == nullptr) + return PersistentSourceLoc(); SourceLocation SL = C.getSourceManager().getExpansionLoc(D->getLocation()); return mkPSL(D->getSourceRange(), SL, C); } @@ -29,14 +30,17 @@ PersistentSourceLoc PersistentSourceLoc::mkPSL(const Decl *D, // Create a PersistentSourceLoc for a Stmt. PersistentSourceLoc PersistentSourceLoc::mkPSL(const Stmt *S, const ASTContext &Context) { - if (S == nullptr) return PersistentSourceLoc(); + if (S == nullptr) + return PersistentSourceLoc(); return mkPSL(S->getSourceRange(), S->getBeginLoc(), Context); } // Create a PersistentSourceLoc for an Expression. -PersistentSourceLoc PersistentSourceLoc::mkPSL(const clang::Expr *E, - const clang::ASTContext &Context) { - if (E == nullptr) return PersistentSourceLoc(); +PersistentSourceLoc +PersistentSourceLoc::mkPSL(const clang::Expr *E, + const clang::ASTContext &Context) { + if (E == nullptr) + return PersistentSourceLoc(); return mkPSL(E->getSourceRange(), E->getBeginLoc(), Context); } diff --git a/clang/lib/3C/ProgramInfo.cpp b/clang/lib/3C/ProgramInfo.cpp index 3bad8a95a28c..3c5be607cf8d 100644 --- a/clang/lib/3C/ProgramInfo.cpp +++ b/clang/lib/3C/ProgramInfo.cpp @@ -381,8 +381,7 @@ bool ProgramInfo::link() { if (_3COpts.Verbose) llvm::errs() << "Linking!\n"; - auto Rsn = ReasonLoc("Linking global variables", - PersistentSourceLoc()); + auto Rsn = ReasonLoc("Linking global variables", PersistentSourceLoc()); // Equate the constraints for all global variables. // This is needed for variables that are defined as extern. @@ -408,9 +407,9 @@ bool ProgramInfo::link() { // constrain everything about it if (!V.second) { std::string VarName = V.first; - auto WildReason = ReasonLoc( - "External global variable " + VarName + " has no definition", - Rsn.Location); + auto WildReason = ReasonLoc("External global variable " + VarName + + " has no definition", + Rsn.Location); const std::set &C = GlobalVariableSymbols[VarName]; for (const auto &Var : C) { // TODO: Is there an easy way to get a PSL to attach to the constraint? @@ -442,9 +441,10 @@ void ProgramInfo::linkFunction(FunctionVariableConstraint *FV) { // should stay that way. Otherwise, we shouldn't be adding a checked type // to an undefined function. DEFAULT_REASON is a sentinel for // ConstraintVariable::equateWithItype; see the comment there. - std::string Rsn = (FV->hasBody() ? DEFAULT_REASON : "Unchecked pointer in parameter or " - "return of undefined function " + - FV->getName()); + std::string Rsn = (FV->hasBody() ? DEFAULT_REASON + : "Unchecked pointer in parameter or " + "return of undefined function " + + FV->getName()); // Handle the cases where itype parameters should not be treated as their // unchecked type. @@ -461,8 +461,8 @@ void ProgramInfo::linkFunction(FunctionVariableConstraint *FV) { // rewritten to an itype. auto LinkComponent = [this, Reason](const FVComponentVariable *FVC) { FVC->getInternal()->constrainToWild(CS, Reason); - if (!_3COpts.InferTypesForUndefs && - !FVC->getExternal()->srcHasItype() && !FVC->getExternal()->isGeneric()) + if (!_3COpts.InferTypesForUndefs && !FVC->getExternal()->srcHasItype() && + !FVC->getExternal()->isGeneric()) FVC->getExternal()->constrainToWild(CS, Reason); }; @@ -552,10 +552,8 @@ ProgramInfo::insertNewFVConstraint(FunctionDecl *FD, FVConstraint *NewC, return (*Map)[FuncName]; // Error reporting - reportCustomDiagnostic(C->getDiagnostics(), - DiagnosticsEngine::Fatal, - "merging failed for %q0 due to %1", - FD->getLocation()) + reportCustomDiagnostic(C->getDiagnostics(), DiagnosticsEngine::Fatal, + "merging failed for %q0 due to %1", FD->getLocation()) << FD << ReasonFailed; // A failed merge will provide poor data, but the diagnostic error report // will cause the program to terminate after the variable adder step. @@ -607,7 +605,8 @@ void ProgramInfo::addVariable(clang::DeclaratorDecl *D, // function to the function map anyways. The function map indexes by // function name, so there's no collision. insertNewFVConstraint(FD, F, AstContext); - constrainWildIfMacro(F, FD->getLocation(), ReasonLoc(MACRO_REASON, PLoc)); + constrainWildIfMacro(F, FD->getLocation(), + ReasonLoc(MACRO_REASON, PLoc)); } else { // A function with the same name exists in the same source location. // This happens when a function is defined in a header file which is @@ -627,7 +626,7 @@ void ProgramInfo::addVariable(clang::DeclaratorDecl *D, auto RetTy = FD->getReturnType(); unifyIfTypedef(RetTy, *AstContext, F->getExternalReturn(), Wild_to_Safe); unifyIfTypedef(RetTy, *AstContext, F->getInternalReturn(), Safe_to_Wild); - auto PSL = PersistentSourceLoc::mkPSL(FD,*AstContext); + auto PSL = PersistentSourceLoc::mkPSL(FD, *AstContext); ensureNtCorrect(RetTy, PSL, F->getExternalReturn()); ensureNtCorrect(RetTy, PSL, F->getInternalReturn()); @@ -635,7 +634,7 @@ void ProgramInfo::addVariable(clang::DeclaratorDecl *D, // the parameters. for (unsigned I = 0; I < FD->getNumParams(); I++) { ParmVarDecl *PVD = FD->getParamDecl(I); - auto ParamPSL = PersistentSourceLoc::mkPSL(PVD,*AstContext); + auto ParamPSL = PersistentSourceLoc::mkPSL(PVD, *AstContext); QualType ParamTy = PVD->getType(); PVConstraint *PVInternal = F->getInternalParam(I); PVConstraint *PVExternal = F->getExternalParam(I); @@ -714,8 +713,8 @@ void ProgramInfo::ensureNtCorrect(const QualType &QT, const PersistentSourceLoc &PSL, PointerVariableConstraint *PV) { if (_3COpts.AllTypes && !canBeNtArray(QT)) { - PV->constrainOuterTo(CS, CS.getArr(), - ReasonLoc(ARRAY_REASON, PSL), true, true); + PV->constrainOuterTo(CS, CS.getArr(), ReasonLoc(ARRAY_REASON, PSL), true, + true); } } @@ -794,7 +793,7 @@ void ProgramInfo::removePersistentConstraints(Expr *E, ASTContext *C) { // Save VarAtom locations so they can be used to assign source locations to // root causes. for (auto *CV : ExprConstraintVars[Key].first) - if (auto *PVC = dyn_cast(CV)) + if (auto *PVC = dyn_cast(CV)) for (Atom *A : PVC->getCvars()) if (auto *VA = dyn_cast(A)) DeletedAtomLocations[VA->getLoc()] = ExprLocations[Key]; @@ -1128,11 +1127,11 @@ void ProgramInfo::setTypeParamBinding(CallExpr *CE, unsigned int TypeVarIdx, auto Key = getExprKey(CE, C); auto CallMap = TypeParamBindings[Key]; if (CallMap.find(TypeVarIdx) == CallMap.end()) { - TypeParamBindings[Key][TypeVarIdx] = TypeParamConstraint(CV,Ident); + TypeParamBindings[Key][TypeVarIdx] = TypeParamConstraint(CV, Ident); } else { // If this CE/idx is at the same location, it's in a macro, // so mark it as inconsistent. - TypeParamBindings[Key][TypeVarIdx] = TypeParamConstraint(nullptr,nullptr); + TypeParamBindings[Key][TypeVarIdx] = TypeParamConstraint(nullptr, nullptr); } } @@ -1166,8 +1165,9 @@ void ProgramInfo::addTypedef(PersistentSourceLoc PSL, bool CanRewriteDef, V = new PointerVariableConstraint(TD, *this, C); if (!CanRewriteDef) - V->constrainToWild(this->getConstraints(), - ReasonLoc("Unable to rewrite a typedef with multiple names", PSL)); + V->constrainToWild( + this->getConstraints(), + ReasonLoc("Unable to rewrite a typedef with multiple names", PSL)); if (!canWrite(PSL.getFileName())) V->constrainToWild(this->getConstraints(), diff --git a/clang/lib/3C/ProgramVar.cpp b/clang/lib/3C/ProgramVar.cpp index f3df0bdb5c94..a22c25f2de28 100644 --- a/clang/lib/3C/ProgramVar.cpp +++ b/clang/lib/3C/ProgramVar.cpp @@ -108,8 +108,7 @@ ProgramVar *ProgramVar::makeCopy(BoundsKey NK) const { this->ConstantVal); } -ProgramVar *ProgramVar::createNewConstantVar(BoundsKey VK, - uint64_t Value) { +ProgramVar *ProgramVar::createNewConstantVar(BoundsKey VK, uint64_t Value) { return new ProgramVar(VK, Value); } diff --git a/clang/lib/3C/RewriteUtils.cpp b/clang/lib/3C/RewriteUtils.cpp index d9f69597a356..d29e4d72220d 100644 --- a/clang/lib/3C/RewriteUtils.cpp +++ b/clang/lib/3C/RewriteUtils.cpp @@ -98,8 +98,7 @@ void rewriteSourceRange(Rewriter &R, const CharSourceRange &Range, clang::DiagnosticsEngine &DE = R.getSourceMgr().getDiagnostics(); bool ReportError = ErrFail && !_3COpts.AllowRewriteFailures; reportCustomDiagnostic( - DE, - ReportError ? DiagnosticsEngine::Error : DiagnosticsEngine::Warning, + DE, ReportError ? DiagnosticsEngine::Error : DiagnosticsEngine::Warning, "Unable to rewrite converted source range. Intended rewriting: " "\"%0\"", Range.getBegin()) @@ -132,8 +131,8 @@ static void emit(Rewriter &R, ASTContext &C, bool &StdoutModeEmittedMainFile) { DiagnosticsEngine &DE = C.getDiagnostics(); DiagnosticsEngine::Level UnwritableChangeDiagnosticLevel = - _3COpts.AllowUnwritableChanges ? DiagnosticsEngine::Warning - : DiagnosticsEngine::Error; + _3COpts.AllowUnwritableChanges ? DiagnosticsEngine::Warning + : DiagnosticsEngine::Error; auto PrintExtraUnwritableChangeInfo = [&]() { // With -dump-unwritable-changes and not -allow-unwritable-changes, we // want the -allow-unwritable-changes note before the dump. @@ -177,10 +176,9 @@ static void emit(Rewriter &R, ASTContext &C, bool &StdoutModeEmittedMainFile) { "3C internal error: not writing the new version of this file due " "to failure to re-canonicalize the file path provided by Clang", BeginningOfFileSourceLoc); - reportCustomDiagnostic( - DE, DiagnosticsEngine::Note, - "file path from Clang was %0; error was: %1", - SourceLocation()) + reportCustomDiagnostic(DE, DiagnosticsEngine::Note, + "file path from Clang was %0; error was: %1", + SourceLocation()) << ToConv << EC.message(); PrintExtraUnwritableChangeInfo(); continue; @@ -375,7 +373,7 @@ class TypeArgumentAdder : public clang::RecursiveASTVisitor { // If the function is not generic, we have nothing to do. // This could happen even if it has type param binding if we // reset generics because of wildness - if (Info.getFuncConstraint(FD,Context)->getGenericParams() == 0 && + if (Info.getFuncConstraint(FD, Context)->getGenericParams() == 0 && !FD->isItypeGenericFunction()) return true; @@ -387,10 +385,12 @@ class TypeArgumentAdder : public clang::RecursiveASTVisitor { for (auto Entry : Info.getTypeParamBindings(CE, Context)) if (Entry.second.isConsistent()) { AllInconsistent = false; - std::string TyStr = Entry.second.getConstraint( - Info.getConstraints().getVariables() - )->mkString(Info.getConstraints(), MKSTRING_OPTS( - EmitName = false, EmitPointee = true)); + std::string TyStr = + Entry.second + .getConstraint(Info.getConstraints().getVariables()) + ->mkString( + Info.getConstraints(), + MKSTRING_OPTS(EmitName = false, EmitPointee = true)); if (TyStr.back() == ' ') TyStr.pop_back(); TypeParamString += TyStr + ","; @@ -431,7 +431,7 @@ class TypeArgumentAdder : public clang::RecursiveASTVisitor { SourceRange DeclReplacement::getSourceRange(SourceManager &SM) const { SourceRange SR = getDecl()->getSourceRange(); SourceLocation OldEnd = SR.getEnd(); - SourceLocation NewEnd = getCheckedCAnnotationsEnd(getDecl()); + SourceLocation NewEnd = getCheckedCAnnotationsEnd(getDecl()); if (NewEnd.isValid() && (!OldEnd.isValid() || SM.isBeforeInTranslationUnit(OldEnd, NewEnd))) SR.setEnd(NewEnd); @@ -440,8 +440,9 @@ SourceRange DeclReplacement::getSourceRange(SourceManager &SM) const { } SourceRange FunctionDeclReplacement::getSourceRange(SourceManager &SM) const { - SourceLocation Begin = RewriteGeneric ? getDeclBegin(SM) : - (RewriteReturn ? getReturnBegin(SM) : getParamBegin(SM)); + SourceLocation Begin = + RewriteGeneric ? getDeclBegin(SM) + : (RewriteReturn ? getReturnBegin(SM) : getParamBegin(SM)); SourceLocation End = RewriteParams ? getDeclEnd(SM) : getReturnEnd(SM); // Begin can be equal to End if the SourceRange only contains one token. assert("Invalid FunctionDeclReplacement SourceRange!" && @@ -454,7 +455,8 @@ SourceLocation FunctionDeclReplacement::getDeclBegin(SourceManager &SM) const { return Begin; } -SourceLocation FunctionDeclReplacement::getReturnBegin(SourceManager &SM) const { +SourceLocation +FunctionDeclReplacement::getReturnBegin(SourceManager &SM) const { // TODO: more accuracy // This code gets the point after a modifier like "static" // But currently, that leads to multiple "static"s @@ -578,7 +580,7 @@ void RewriteConsumer::emitRootCauseDiagnostics(ASTContext &Context) { SourceManager &SM = Context.getSourceManager(); for (auto &WReason : I.RootWildAtomsWithReason) { // Avoid emitting the same diagnostic message twice. - const PersistentSourceLoc& PSL = WReason.second.getLocation(); + const PersistentSourceLoc &PSL = WReason.second.getLocation(); if (PSL.valid() && EmittedDiagnostics.find(PSL) == EmittedDiagnostics.end()) { @@ -612,7 +614,8 @@ void RewriteConsumer::emitRootCauseDiagnostics(ASTContext &Context) { SourceLocation NSL = SM.translateFileLineCol( *NFile, NPSL.getLineNo(), NPSL.getColSNo()); if (NSL.isValid()) { - unsigned NID = DE.getCustomDiagID(DiagnosticsEngine::Note, "%0"); + unsigned NID = + DE.getCustomDiagID(DiagnosticsEngine::Note, "%0"); DE.Report(NSL, NID) << Note.Reason; } } diff --git a/clang/lib/3C/TypeVariableAnalysis.cpp b/clang/lib/3C/TypeVariableAnalysis.cpp index 365dca6eecb4..6a319dcbad35 100644 --- a/clang/lib/3C/TypeVariableAnalysis.cpp +++ b/clang/lib/3C/TypeVariableAnalysis.cpp @@ -50,10 +50,10 @@ void TypeVariableEntry::updateEntry(QualType Ty, CVarSet &CVs, // passed to the same type param, we have no way of knowing if they were // the same and in general they will not always be, so this must be marked // inconsistent. - if (auto PVC1 = dyn_cast_or_null(GenArgumentCV)) - if (auto PVC2 = dyn_cast_or_null(IdentCV)) - if (PVC1->getGenericIndex() != PVC2->getGenericIndex()) - IsConsistent = false; + if (auto *PVC1 = dyn_cast_or_null(GenArgumentCV)) + if (auto *PVC2 = dyn_cast_or_null(IdentCV)) + if (PVC1->getGenericIndex() != PVC2->getGenericIndex()) + IsConsistent = false; // Record new constraints for the entry. These are used even when the variable // is not consistent. @@ -125,15 +125,15 @@ bool TypeVarVisitor::VisitCallExpr(CallExpr *CE) { const int TyIdx = FVCon->getExternalParam(I)->getGenericIndex(); if (TyIdx >= 0) { Expr *Uncast = A->IgnoreImpCasts(); - std::set CVs = CR.getExprConstraintVarsSet(Uncast); - if (auto *DRE = dyn_cast(Uncast)){ - CVarOption Var = Info.getVariable(DRE->getFoundDecl(),Context); + std::set CVs = + CR.getExprConstraintVarsSet(Uncast); + if (auto *DRE = dyn_cast(Uncast)) { + CVarOption Var = Info.getVariable(DRE->getFoundDecl(), Context); if (Var.hasValue()) if (PVConstraint *GenVar = dyn_cast(&Var.getValue())) if (GenVar->isGeneric()) { - insertBinding(CE,TyIdx,Uncast->getType(), - CVs,GenVar); + insertBinding(CE, TyIdx, Uncast->getType(), CVs, GenVar); ++I; continue; } @@ -150,9 +150,8 @@ bool TypeVarVisitor::VisitCallExpr(CallExpr *CE) { if (TVEntry.second.getIsConsistent()) { std::string Name = FD->getNameAsString() + "_tyarg_" + std::to_string(TVEntry.first); - PVConstraint *P = - new PVConstraint(TVEntry.second.getType(), nullptr, Name, Info, - *Context, nullptr); + PVConstraint *P = new PVConstraint(TVEntry.second.getType(), nullptr, + Name, Info, *Context, nullptr); // Constrain this variable GEQ the function arguments using the type // variable so if any of them are wild, the type argument will also be @@ -160,7 +159,7 @@ bool TypeVarVisitor::VisitCallExpr(CallExpr *CE) { // elsewhere, especially `ConstraintResolver::getExprConstraintVars` // using variable `ReallocFlow`. Because `realloc` can take a wild // pointer and return a safe one. - auto PSL = PersistentSourceLoc::mkPSL(CE,*Context); + auto PSL = PersistentSourceLoc::mkPSL(CE, *Context); auto Rsn = ReasonLoc("Type variable", PSL); if (FD->getNameAsString() == "realloc") { constrainConsVarGeq(P, TVEntry.second.getConstraintVariables(), @@ -169,16 +168,16 @@ bool TypeVarVisitor::VisitCallExpr(CallExpr *CE) { } else { constrainConsVarGeq(P, TVEntry.second.getConstraintVariables(), - Info.getConstraints(), Rsn, Safe_to_Wild, false, - &Info); - } + Info.getConstraints(), Rsn, Safe_to_Wild, false, + &Info); + } TVEntry.second.setTypeParamConsVar(P); // Since we've changed the constraint variable for this context, we // need to remove the cache from the old one. Our new info will be // used next request. - if (Info.hasPersistentConstraints(CE,Context)) - Info.removePersistentConstraints(CE,Context); + if (Info.hasPersistentConstraints(CE, Context)) + Info.removePersistentConstraints(CE, Context); } else { // TODO: This might be too cautious. CR.constraintAllCVarsToWild(TVEntry.second.getConstraintVariables(), @@ -205,8 +204,8 @@ void TypeVarVisitor::insertBinding(CallExpr *CE, const int TyIdx, auto &CallTypeVarMap = TVMap[CE]; if (CallTypeVarMap.find(TyIdx) == CallTypeVarMap.end()) { // If the type variable hasn't been seen before, add it to the map. - TypeVariableEntry TVEntry = TypeVariableEntry(Ty, CVs, ForceInconsistent, - IdentCV); + TypeVariableEntry TVEntry = + TypeVariableEntry(Ty, CVs, ForceInconsistent, IdentCV); CallTypeVarMap[TyIdx] = TVEntry; } else { // Otherwise, update entry with new type and constraints. @@ -236,12 +235,10 @@ void TypeVarVisitor::setProgramInfoTypeVars() { if (TVCallEntry.second.getIsConsistent()) Info.setTypeParamBinding(TVEntry.first, TVCallEntry.first, TVCallEntry.second.getTypeParamConsVar(), - TVCallEntry.second.getGenArgCV(), - Context); + TVCallEntry.second.getGenArgCV(), Context); else - Info.setTypeParamBinding(TVEntry.first, TVCallEntry.first, - nullptr, nullptr, - Context); + Info.setTypeParamBinding(TVEntry.first, TVCallEntry.first, nullptr, + nullptr, Context); } } diff --git a/clang/lib/3C/Utils.cpp b/clang/lib/3C/Utils.cpp index 84ede9a2f98e..cb4b336a4266 100644 --- a/clang/lib/3C/Utils.cpp +++ b/clang/lib/3C/Utils.cpp @@ -325,7 +325,7 @@ static bool castCheck(clang::QualType DstType, clang::QualType SrcType) { // Both are pointers? check their pointee if (SrcPtrTypePtr && DstPtrTypePtr) { return castCheck(DstPtrTypePtr->getPointeeType(), - SrcPtrTypePtr->getPointeeType()); + SrcPtrTypePtr->getPointeeType()); } if (SrcPtrTypePtr || DstPtrTypePtr) @@ -339,8 +339,7 @@ static bool castCheck(clang::QualType DstType, clang::QualType SrcType) { return false; for (unsigned I = 0; I < SrcFnType->getNumParams(); I++) - if (!castCheck(SrcFnType->getParamType(I), - DstFnType->getParamType(I))) + if (!castCheck(SrcFnType->getParamType(I), DstFnType->getParamType(I))) return false; return castCheck(SrcFnType->getReturnType(), DstFnType->getReturnType()); diff --git a/clang/tools/3c/3CStandalone.cpp b/clang/tools/3c/3CStandalone.cpp index 08a63c4d4979..519ef34dda1f 100644 --- a/clang/tools/3c/3CStandalone.cpp +++ b/clang/tools/3c/3CStandalone.cpp @@ -229,30 +229,32 @@ static cl::opt OptAllowRewriteFailures( cl::init(false), cl::cat(_3CCategory)); static cl::opt OptItypesForExtern( - "itypes-for-extern", - cl::desc("All functions with external linkage will be rewritten to use itypes" - "instead checked types. This does not apply to static functions which" - "continue to have itypes only when the function is internally" - "unsafe."), - cl::init(false), cl::cat(_3CCategory)); + "itypes-for-extern", + cl::desc( + "All functions with external linkage will be rewritten to use itypes" + "instead checked types. This does not apply to static functions which" + "continue to have itypes only when the function is internally" + "unsafe."), + cl::init(false), cl::cat(_3CCategory)); static cl::opt OptInferTypesForUndef( - "infer-types-for-undefs", - cl::desc("Enable type inference for undefined functions. Under this flag, " - "types for undefined functions are inferred according to the same " - "rules as defined functions with the caveat that an undefined " - "function will only solve to an itype and not a fully checked type. " - "Because 3c is not able to examine the body of the function, the " - "inferred pointer types (and array bounds) may not be consistent " - "with the actual implementation. By default, the Checked C compiler " - "trusts the declared itypes and will not detect a spatial memory " - "safety violation if the function is used in a way that is " - "consistent with the itypes but not the assumptions actually made " - "by the implementation. Thus, if you want to guarantee spatial " - "memory safety, you must manually check the inferred types against " - "your understanding of what the function actually does (or any " - "available documentation)."), - cl::init(false), cl::cat(_3CCategory)); + "infer-types-for-undefs", + cl::desc( + "Enable type inference for undefined functions. Under this flag, " + "types for undefined functions are inferred according to the same " + "rules as defined functions with the caveat that an undefined " + "function will only solve to an itype and not a fully checked type. " + "Because 3c is not able to examine the body of the function, the " + "inferred pointer types (and array bounds) may not be consistent " + "with the actual implementation. By default, the Checked C compiler " + "trusts the declared itypes and will not detect a spatial memory " + "safety violation if the function is used in a way that is " + "consistent with the itypes but not the assumptions actually made " + "by the implementation. Thus, if you want to guarantee spatial " + "memory safety, you must manually check the inferred types against " + "your understanding of what the function actually does (or any " + "available documentation)."), + cl::init(false), cl::cat(_3CCategory)); #ifdef FIVE_C static cl::opt OptRemoveItypes( diff --git a/clang/tools/3c/CMakeLists.txt b/clang/tools/3c/CMakeLists.txt index f397bda98ed1..0a826308293a 100644 --- a/clang/tools/3c/CMakeLists.txt +++ b/clang/tools/3c/CMakeLists.txt @@ -32,3 +32,7 @@ target_link_libraries(3c install(TARGETS 3c RUNTIME DESTINATION bin) + +# Currently, clang/tools/3c/utils/code_style has a CMakeLists.txt file but +# clang/tools/3c/utils does not. +add_subdirectory(utils/code_style) diff --git a/clang/tools/3c/utils/code_style/CMakeLists.txt b/clang/tools/3c/utils/code_style/CMakeLists.txt new file mode 100644 index 000000000000..f8a50e2144c2 --- /dev/null +++ b/clang/tools/3c/utils/code_style/CMakeLists.txt @@ -0,0 +1,120 @@ +# The clang/tools/3c/utils/code_style directory contains build targets and +# supporting tools to validate the code style of 3C itself. It is for 3C +# developers, not end users. For now, we only care about whether this code works +# in our preferred Linux environment. + +# Note: Several of our build targets (check-3c, lint-3c-clang-tidy) run commands +# that internally run $(nproc) threads but are counted as only 1 job by Ninja. +# When Ninja runs parallel jobs, this could badly overload the system. +# Unfortunately, there doesn't seem to be a way to get Ninja to just count each +# of our internally parallel commands as $(nproc) jobs. The closest we can come +# is to use a job pool +# (https://cmake.org/cmake/help/latest/prop_gbl/JOB_POOLS.html), which would +# still allow Ninja to run some ordinary jobs in parallel with an internally +# parallel job. However, check-3c uses add_lit_target, which is hard-coded to +# use the `console` job pool via USES_TERMINAL, and Microsoft may not look +# kindly on us changing that. So we just specify USES_TERMINAL on our internally +# parallel jobs, even though they don't actually need the terminal. This is a +# bit of a hack but shouldn't cause any problems. + +# Target to run all currently automated style checks on 3C. The `lint-` name +# prefix is modeled after lint-libc in libc/CMakeLists.txt. Remember to use +# `ninja -k 0` if you want to see failures from all the style checks during a +# single build. +# +# This target just reports any style violations as errors. You can use the +# corresponding `fix-all.sh` script in this directory to fix as many errors as +# possible using the options of the respective tools. +# +# Some important checks are currently not automated. For more details, see the +# public 3C coding guidelines in clang/docs/checkedc/3C/development.md and the +# CCI engineering handbook section on code style +# (https://docs.google.com/document/d/1lnlUSOdKqXV3f8oG0GS0BLyA6peNNCY-kzRpvF8e8e8/edit#heading=h.ncfvo5mv1ma), +# parts of which have not yet been propagated to the public documentation. +add_custom_target(lint-3c + DEPENDS + lint-3c-clang-format + lint-3c-clang-tidy + lint-3c-yapf + ) + +# The style checks are currently implemented as targets that re-run +# unconditionally on all relevant files at once (like check-3c, in fact). +# Ideally, we would have one target per file and soundly track the dependencies +# to avoid unnecessary repetition of work and improve parallelism, but this +# would take a lot more CMake code; we can always do it later if we care enough. +# There's some prior art for fine-grained targets for clang-tidy in +# libc/cmake/modules/LLVMLibCObjectRules.cmake. + +# Currently, we use clang-format, clang-tidy, and clang-apply-replacements from +# the system $PATH. On Ubuntu, you can install them with `apt install +# clang-format clang-tidy clang-tools`. +# +# Users (Matt) who refuse to put Clang executables on the global $PATH (to +# ensure that none of our 3C-related scripts ever accidentally run a system +# Clang executable when they should be using a checkedc-clang executable) will +# need to add appropriate wrapper scripts to $PATH while running these targets. +# We considered building clang-format and clang-tidy from this repository, but +# if the build type is set to Debug, clang-tidy will be unacceptably slow. + +add_custom_target(lint-3c-clang-format + COMMENT "Linting 3C (clang-format)" + COMMAND + find + ${CLANG_SOURCE_DIR}/include/clang/3C + ${CLANG_SOURCE_DIR}/lib/3C + # We haven't been keeping clang/test/3C compliant with clang-format + # (https://correct-computation.slack.com/archives/G01GKGKHMFD/p1615415203010700?thread_ts=1614987194.022900&cid=G01GKGKHMFD). + # Now that we have automation, should we reconsider this? + #${CLANG_SOURCE_DIR}/test/3C + ${CLANG_SOURCE_DIR}/tools/3c + '\(' -name '*.h' -or -name '*.cpp' '\)' + -exec clang-format -Werror --dry-run {} + + ) + +# Just backslash all non-alphanumeric characters, like Python's `re.escape`. +string(REGEX REPLACE \([^A-Za-z0-9]\) \\\\\\1 + LINT_3C_CLANG_SOURCE_DIR_REGEX_QUOTED ${CLANG_SOURCE_DIR}) + +add_custom_target(lint-3c-clang-tidy + COMMENT "Linting 3C (clang-tidy)" + # Functionally, there's no need to build 3C before running clang-tidy, but + # this dependency helps avoid overloading the system by running an internally + # parallel clang-tidy job in parallel with many individual 3C compile jobs. + # Also, if the code fails to compile, the user will probably want to fix that + # before worrying about clang-tidy errors. + DEPENDS 3c + COMMAND + # There doesn't seem to be a CLANG_TOOLS_EXTRA_SOURCE_DIR variable. + ${CLANG_SOURCE_DIR}/../clang-tools-extra/clang-tidy/tool/run-clang-tidy.py + -clang-tidy-binary ${CMAKE_CURRENT_SOURCE_DIR}/clang-tidy-wrapper.sh + -p ${CMAKE_BINARY_DIR} + -header-filter '^${LINT_3C_CLANG_SOURCE_DIR_REGEX_QUOTED}/include/clang/3C/' + # Apparently Ninja requires the $ to be doubled. Should CMake be doing that + # for us? + '^${LINT_3C_CLANG_SOURCE_DIR_REGEX_QUOTED}/\(lib/3C|tools/3c\)/.*\\.cpp$$' + USES_TERMINAL + ) + +# This requires that yapf3 be available on $PATH. On Ubuntu, you can install it +# with `apt install yapf3`. +add_custom_target(lint-3c-yapf + COMMENT "Linting 3C (yapf)" + COMMAND + find + ${CLANG_SOURCE_DIR}/test/3C + # ${CLANG_SOURCE_DIR}/tools/3c/utils/*.py are pretty much unmaintained and + # currently don't comply with yapf. We don't want to format them right now + # when we aren't maintaining them otherwise. + ${CLANG_SOURCE_DIR}/tools/3c/utils/port_tools + -name '*.py' + -exec yapf3 --diff {} + + ) + +# Target to fully validate a 3C change by running the regression tests and +# validating code style. +add_custom_target(validate-3c + DEPENDS + check-3c + lint-3c + ) diff --git a/clang/tools/3c/utils/code_style/clang-tidy-wrapper.sh b/clang/tools/3c/utils/code_style/clang-tidy-wrapper.sh new file mode 100755 index 000000000000..675be0683170 --- /dev/null +++ b/clang/tools/3c/utils/code_style/clang-tidy-wrapper.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# Adds some flags we want for the lint-3c-clang-tidy target, since +# run-clang-tidy.py doesn't support passing arbitrary flags through to +# clang-tidy. :( + +exec clang-tidy -warnings-as-errors='*' "$@" diff --git a/clang/tools/3c/utils/code_style/fix-all.sh b/clang/tools/3c/utils/code_style/fix-all.sh new file mode 100755 index 000000000000..d7cef08caeea --- /dev/null +++ b/clang/tools/3c/utils/code_style/fix-all.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e + +# cd from clang/tools/3c/utils/code_style to the monorepo root. +cd "$(dirname "$0")/../../../../.." + +# All of the following duplicates logic in CMakeLists.txt, and the comments +# there apply. TODO: Is there any way to factor out any of the logic? + +# WARNING: See the caveats in the "Things to know about `clang-tidy --fix`" +# section of clang/docs/checkedc/3C/clang-tidy.md. +# TODO: Enhance this script to account for any of those caveats? + +monorepo_root_regex_quoted="$(sed -E 's,[^A-Za-z0-9],\\&,g' <<<"$PWD")" +# TODO: Support nonstandard build directory locations. +clang-tools-extra/clang-tidy/tool/run-clang-tidy.py \ + -p build \ + -fix \ + -header-filter "^$monorepo_root_regex_quoted/clang/include/clang/3C/" \ + "^$monorepo_root_regex_quoted/clang/(lib/3C|tools/3c)/.*\\.cpp\$" + +# clang-tidy may mess up formatting, so clang-format should be run after it. +find clang/{include/clang/3C,lib/3C,tools/3c} \ + '(' -name '*.h' -or -name '*.cpp' ')' \ + -exec clang-format -i {} + + +find clang/{test/3C,tools/3c/utils/port_tools} -name '*.py' \ + -exec yapf3 -i {} +