Creating your own clang-based tool – Debugging Using LLVM Tools-4

  1. This finishes the visitor’s implementation. In your NamingASTConsumer class, you will now only store a visitor instance:
    std::unique_ptr Visitor;
    public:
    NamingASTConsumer(CompilerInstance &CI)
    : Visitor(std::make_unique(CI)) {}
  1. Remove the HandleTopLevelDecl() method – the functionality is now in the visitor class, so you’ll need to override the HandleTranslationUnit() method instead. This class is called once for each translation unit. You will start the AST traversal here:
    void
    HandleTranslationUnit(ASTContext &ASTCtx) override {
    Visitor->TraverseDecl(
    ASTCtx.getTranslationUnitDecl());
    }

This new implementation has the same functionality. The advantage is that it is easier to extend. For example, if you want to examine variable declarations, then you must implement the VisitVarDecl() method. Alternatively, if you want to work with a statement, then you must implement the VisitStmt() method. With this approach, you have a visitor method for each entity of the C, C++, and Objective C languages.

Having access to the AST allows you to build plugins that perform complex tasks. Enforcing naming conventions, as described in this section, is a useful addition to clang. Another useful addition you could implement as a plugin is the calculation of a software metric such as cyclomatic complexity. You can also add or replace AST nodes, allowing you, for example, to add runtime instrumentation. Adding plugins allows you to extend clang in the way you need it.

Summary

In this chapter, you learned how to apply various sanitizers. You detected pointer errors with the address sanitizer, uninitialized memory access with the memory sanitizer, and performed data races with the thread sanitizer. Application errors are often triggered by malformed input, and you implemented fuzz testing to test your application with random data.

You also instrumented your application with XRay to identify the performance bottlenecks, and you also learned about the various ways you can visualize the data. This chapter also taught you how to utilize the clang static analyzer for identifying potential errors by interpreting the source code, and how to create your own clang plugin.

These skills will help you raise the quality of the applications you build as it is certainly good to find runtime errors before your application users complain about them. Applying the knowledge you’ve gained in this chapter, you can not only find a wide range of common errors, but you can also extend clang with new functionality.

In the next chapter, you will learn how to add a new backend to LLVM.

Leave a Reply

Your email address will not be published. Required fields are marked *