-
Notifications
You must be signed in to change notification settings - Fork 14.4k
[clang-tidy] Add portability-avoid-platform-specific-fundamental-types #146970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jj-marr
wants to merge
32
commits into
llvm:main
Choose a base branch
from
jj-marr:TypedefsOnly
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+870
−0
Open
Changes from 16 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
3ef4feb
AvoidFundamentalIntegerTypesCheck
jj-marr 48598ef
Test typedefs properly
jj-marr 524fdd8
Document properly
jj-marr d5fd2e7
Rename files
jj-marr 25425cc
Other renaming for portability change
jj-marr 86787ec
Formatting fix
jj-marr c66668e
Make matchers more specific
jj-marr 1b314bb
Remove dead code
jj-marr 411d598
Fix doc
jj-marr b427df7
Fix issue on MSVC
jj-marr 5dd5c72
Merge comment with previous line
jj-marr 7c2031b
Add linter check to release notes
jj-marr 475f1b2
Update documentation
jj-marr 20e43d8
Fix redundant check
jj-marr 20e9b32
In progress work on float check
jj-marr f49a289
Declare const
jj-marr 143fcad
Synchronize with release notes
jj-marr 3c2ccd5
Attempt to format
jj-marr 40b8be3
Allow for int to not be warned
jj-marr 93c8489
Reduce some duplication
jj-marr 91eb765
vibecoding: not even once
jj-marr 723a76e
For each loop
jj-marr a30bedf
Format code
jj-marr 76125bb
Warn on chars
jj-marr 8258324
Fix header doc
jj-marr 8dd606b
Forgot to format
jj-marr 90c9887
Fix typo
jj-marr c487bf3
Fix formatting
jj-marr 09a762d
Declare as const
jj-marr a53b5bc
Add WarnOnInts documentation
jj-marr b525a7a
Enable all checks by default
jj-marr de662e8
Update clang-tools-extra/clang-tidy/portability/AvoidPlatformSpecific…
jj-marr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
246 changes: 246 additions & 0 deletions
246
clang-tools-extra/clang-tidy/portability/AvoidPlatformSpecificFundamentalTypesCheck.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,246 @@ | ||
//===--- AvoidPlatformSpecificFundamentalTypesCheck.cpp - clang-tidy ------===// | ||
// | ||
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
// See https://llvm.org/LICENSE.txt for license information. | ||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "AvoidPlatformSpecificFundamentalTypesCheck.h" | ||
#include "clang/AST/ASTContext.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/ASTMatchers/ASTMatchers.h" | ||
#include "clang/Basic/TargetInfo.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::portability { | ||
|
||
AvoidPlatformSpecificFundamentalTypesCheck:: | ||
AvoidPlatformSpecificFundamentalTypesCheck(StringRef Name, | ||
ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context), | ||
WarnOnFloats(Options.get("WarnOnFloats", false)), | ||
IncludeInserter(Options.getLocalOrGlobal("IncludeStyle", | ||
utils::IncludeSorter::IS_LLVM), | ||
areDiagsSelfContained()) {} | ||
|
||
void AvoidPlatformSpecificFundamentalTypesCheck::registerPPCallbacks( | ||
const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { | ||
IncludeInserter.registerPreprocessor(PP); | ||
} | ||
|
||
void AvoidPlatformSpecificFundamentalTypesCheck::storeOptions( | ||
ClangTidyOptions::OptionMap &Opts) { | ||
Options.store(Opts, "WarnOnFloats", WarnOnFloats); | ||
Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle()); | ||
} | ||
|
||
std::string AvoidPlatformSpecificFundamentalTypesCheck::getFloatReplacement( | ||
const BuiltinType *BT, ASTContext &Context) const { | ||
const TargetInfo &Target = Context.getTargetInfo(); | ||
|
||
auto GetReplacementType = [](unsigned Width) { | ||
switch (Width) { | ||
// This is ambiguous by default since it could be bfloat16 or float16 | ||
case 16U: | ||
return ""; | ||
case 32U: | ||
return "float32_t"; | ||
case 64U: | ||
return "float64_t"; | ||
case 128U: | ||
return "float128_t"; | ||
default: | ||
return ""; | ||
} | ||
}; | ||
|
||
switch (BT->getKind()) { | ||
// Not an ambiguous type | ||
case BuiltinType::BFloat16: | ||
return "bfloat16_t"; | ||
case BuiltinType::Half: | ||
return GetReplacementType(Target.getHalfWidth()); | ||
case BuiltinType::Float: | ||
return GetReplacementType(Target.getFloatWidth()); | ||
case BuiltinType::Double: | ||
return GetReplacementType(Target.getDoubleWidth()); | ||
default: | ||
return ""; | ||
} | ||
} | ||
|
||
void AvoidPlatformSpecificFundamentalTypesCheck::registerMatchers( | ||
MatchFinder *Finder) { | ||
// Build the list of type strings to match | ||
std::vector<std::string> TypeStrings = {"short", | ||
jj-marr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"short int", | ||
"signed short", | ||
"signed short int", | ||
"unsigned short", | ||
"unsigned short int", | ||
"int", | ||
"signed", | ||
"signed int", | ||
"unsigned", | ||
"unsigned int", | ||
"long", | ||
"long int", | ||
"signed long", | ||
"signed long int", | ||
"unsigned long", | ||
"unsigned long int", | ||
"long long", | ||
"long long int", | ||
"signed long long", | ||
"signed long long int", | ||
"unsigned long long", | ||
"unsigned long long int"}; | ||
|
||
// Add float types if the option is enabled | ||
if (WarnOnFloats) { | ||
TypeStrings.push_back("half"); | ||
TypeStrings.push_back("__bf16"); | ||
TypeStrings.push_back("float"); | ||
TypeStrings.push_back("double"); | ||
TypeStrings.push_back("long double"); | ||
} | ||
|
||
// Create the matcher dynamically | ||
auto TypeMatcher = asString(TypeStrings[0]); | ||
for (size_t i = 1; i < TypeStrings.size(); ++i) { | ||
TypeMatcher = anyOf(TypeMatcher, asString(TypeStrings[i])); | ||
} | ||
|
||
auto PlatformSpecificFundamentalType = qualType(allOf( | ||
// Must be a builtin type directly (not through typedef) | ||
builtinType(), | ||
// Match the specific fundamental types we care about | ||
TypeMatcher)); | ||
|
||
// Match variable declarations with platform-specific fundamental types | ||
Finder->addMatcher( | ||
varDecl(hasType(PlatformSpecificFundamentalType)).bind("var_decl"), this); | ||
|
||
// Match function declarations with platform-specific fundamental return types | ||
Finder->addMatcher( | ||
functionDecl(returns(PlatformSpecificFundamentalType)).bind("func_decl"), | ||
this); | ||
|
||
// Match function parameters with platform-specific fundamental types | ||
Finder->addMatcher( | ||
parmVarDecl(hasType(PlatformSpecificFundamentalType)).bind("param_decl"), | ||
this); | ||
|
||
// Match field declarations with platform-specific fundamental types | ||
Finder->addMatcher( | ||
fieldDecl(hasType(PlatformSpecificFundamentalType)).bind("field_decl"), | ||
this); | ||
|
||
// Match typedef declarations with platform-specific fundamental underlying | ||
// types | ||
Finder->addMatcher( | ||
typedefDecl(hasUnderlyingType(PlatformSpecificFundamentalType)) | ||
.bind("typedef_decl"), | ||
this); | ||
|
||
// Match type alias declarations with platform-specific fundamental underlying | ||
// types | ||
Finder->addMatcher(typeAliasDecl(hasType(PlatformSpecificFundamentalType)) | ||
.bind("alias_decl"), | ||
this); | ||
} | ||
|
||
void AvoidPlatformSpecificFundamentalTypesCheck::check( | ||
const MatchFinder::MatchResult &Result) { | ||
SourceLocation Loc; | ||
QualType QT; | ||
SourceRange TypeRange; | ||
|
||
if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var_decl")) { | ||
Loc = VD->getLocation(); | ||
QT = VD->getType(); | ||
if (VD->getTypeSourceInfo()) { | ||
TypeRange = VD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else if (const auto *FD = | ||
Result.Nodes.getNodeAs<FunctionDecl>("func_decl")) { | ||
Loc = FD->getLocation(); | ||
QT = FD->getReturnType(); | ||
if (FD->getTypeSourceInfo()) { | ||
TypeRange = FD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else if (const auto *PD = | ||
Result.Nodes.getNodeAs<ParmVarDecl>("param_decl")) { | ||
Loc = PD->getLocation(); | ||
QT = PD->getType(); | ||
if (PD->getTypeSourceInfo()) { | ||
TypeRange = PD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else if (const auto *FD = Result.Nodes.getNodeAs<FieldDecl>("field_decl")) { | ||
Loc = FD->getLocation(); | ||
QT = FD->getType(); | ||
if (FD->getTypeSourceInfo()) { | ||
TypeRange = FD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else if (const auto *TD = | ||
Result.Nodes.getNodeAs<TypedefDecl>("typedef_decl")) { | ||
Loc = TD->getLocation(); | ||
QT = TD->getUnderlyingType(); | ||
if (TD->getTypeSourceInfo()) { | ||
TypeRange = TD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else if (const auto *AD = | ||
Result.Nodes.getNodeAs<TypeAliasDecl>("alias_decl")) { | ||
Loc = AD->getLocation(); | ||
QT = AD->getUnderlyingType(); | ||
if (AD->getTypeSourceInfo()) { | ||
TypeRange = AD->getTypeSourceInfo()->getTypeLoc().getSourceRange(); | ||
} | ||
} else { | ||
return; | ||
jj-marr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// Get the type name for the diagnostic | ||
const std::string TypeName = QT.getAsString(); | ||
|
||
// Check if this is a floating point type | ||
const auto *BT = QT->getAs<BuiltinType>(); | ||
bool IsFloatingPoint = BT && (BT->getKind() == BuiltinType::Half || | ||
BT->getKind() == BuiltinType::BFloat16 || | ||
BT->getKind() == BuiltinType::Float || | ||
jj-marr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
BT->getKind() == BuiltinType::Double || | ||
BT->getKind() == BuiltinType::LongDouble); | ||
|
||
if (IsFloatingPoint) { | ||
// Handle floating point types | ||
std::string Replacement = getFloatReplacement(BT, *Result.Context); | ||
jj-marr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!Replacement.empty()) { | ||
auto Diag = | ||
diag(Loc, "avoid using platform-dependent floating point type '%0'; " | ||
"consider using '%1' instead") | ||
<< TypeName << Replacement; | ||
|
||
if (TypeRange.isValid()) { | ||
Diag << FixItHint::CreateReplacement(TypeRange, Replacement); | ||
} | ||
|
||
if (auto IncludeFixit = IncludeInserter.createIncludeInsertion( | ||
Result.SourceManager->getFileID(Loc), "<stdfloat>")) { | ||
Diag << *IncludeFixit; | ||
} | ||
} else { | ||
diag(Loc, "avoid using platform-dependent floating point type '%0'; " | ||
"consider using a typedef or fixed-width type instead") | ||
<< TypeName; | ||
} | ||
} else { | ||
// Handle integer types | ||
diag(Loc, "avoid using platform-dependent fundamental integer type '%0'; " | ||
"consider using a typedef or fixed-width type instead") | ||
<< TypeName; | ||
} | ||
} | ||
|
||
} // namespace clang::tidy::portability |
51 changes: 51 additions & 0 deletions
51
clang-tools-extra/clang-tidy/portability/AvoidPlatformSpecificFundamentalTypesCheck.h
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
//===--- AvoidPlatformSpecificFundamentalTypesCheck.h - clang-tidy -------*- C++ -*-===// | ||
// | ||
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
// See https://llvm.org/LICENSE.txt for license information. | ||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
// | ||
//===-------------------------------------------------------------------------------===// | ||
|
||
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PORTABILITY_AVOIDPLATFORMSPECIFICFUNDAMENTALTYPESCHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PORTABILITY_AVOIDPLATFORMSPECIFICFUNDAMENTALTYPESCHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
#include "../utils/IncludeInserter.h" | ||
|
||
namespace clang::tidy::portability { | ||
|
||
/// Find fundamental integer types and recommend using typedefs or fixed-width | ||
/// types. | ||
/// | ||
/// Detects fundamental integer types (int, short, long, long long, and their | ||
/// unsigned variants) and warns against their use due to platform-dependent | ||
/// behavior. Excludes semantic types like char, bool, wchar_t, char16_t, | ||
/// char32_t, size_t, and ptrdiff_t. | ||
jj-marr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/portability/avoid-platform-specific-fundamental-types.html | ||
class AvoidPlatformSpecificFundamentalTypesCheck : public ClangTidyCheck { | ||
public: | ||
AvoidPlatformSpecificFundamentalTypesCheck(StringRef Name, | ||
ClangTidyContext *Context); | ||
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, | ||
Preprocessor *ModuleExpanderPP) override; | ||
void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
void storeOptions(ClangTidyOptions::OptionMap &Opts) override; | ||
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { | ||
return LangOpts.CPlusPlus11; | ||
} | ||
std::optional<TraversalKind> getCheckTraversalKind() const override { | ||
return TK_IgnoreUnlessSpelledInSource; | ||
} | ||
|
||
private: | ||
const bool WarnOnFloats; | ||
utils::IncludeInserter IncludeInserter; | ||
std::string getFloatReplacement(const BuiltinType *BT, ASTContext &Context) const; | ||
}; | ||
|
||
} // namespace clang::tidy::portability | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PORTABILITY_AVOIDPLATFORMSPECIFICFUNDAMENTALTYPESCHECK_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.