1 //===--- NoAssemblerCheck.cpp - clang-tidy---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "NoAssemblerCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace hicpp {
18 
19 namespace {
AST_MATCHER(VarDecl,isAsm)20 AST_MATCHER(VarDecl, isAsm) { return Node.hasAttr<clang::AsmLabelAttr>(); }
21 const ast_matchers::internal::VariadicDynCastAllOfMatcher<Decl,
22                                                           FileScopeAsmDecl>
23     fileScopeAsmDecl;
24 } // namespace
25 
registerMatchers(MatchFinder * Finder)26 void NoAssemblerCheck::registerMatchers(MatchFinder *Finder) {
27   Finder->addMatcher(asmStmt().bind("asm-stmt"), this);
28   Finder->addMatcher(fileScopeAsmDecl().bind("asm-file-scope"), this);
29   Finder->addMatcher(varDecl(isAsm()).bind("asm-var"), this);
30 }
31 
check(const MatchFinder::MatchResult & Result)32 void NoAssemblerCheck::check(const MatchFinder::MatchResult &Result) {
33   SourceLocation ASMLocation;
34   if (const auto *ASM = Result.Nodes.getNodeAs<AsmStmt>("asm-stmt"))
35     ASMLocation = ASM->getAsmLoc();
36   else if (const auto *ASM =
37                Result.Nodes.getNodeAs<FileScopeAsmDecl>("asm-file-scope"))
38     ASMLocation = ASM->getAsmLoc();
39   else if (const auto *ASM = Result.Nodes.getNodeAs<VarDecl>("asm-var"))
40     ASMLocation = ASM->getLocation();
41   else
42     llvm_unreachable("Unhandled case in matcher.");
43 
44   diag(ASMLocation, "do not use inline assembler in safety-critical code");
45 }
46 
47 } // namespace hicpp
48 } // namespace tidy
49 } // namespace clang
50