Search code examples
c++llvmllvm-c++-api

Set LLVM assembly output syntax with C++ API


I'm trying to find a way to set the assembly syntax that LLVM outputs (for x86 in particular). Following the Compiling to Object Code section of the Kaleidoscope tutorial, I'm outputting assembly files with

TargetMachine->addPassesToEmitFile(pass, dest, nullptr, llvm::CGFT_AssemblyFile))

But there's no option to set the output syntax.

llc has the command line option --x86-asm-syntax with which you can set the output assembly syntax (for x86), so I'm sure there must be a way to do it.

So is there a way this can be done through LLVM's C++ API?


Solution

  • Here's a few things I found out by reading the LLVM source:

    • The output assembly syntax is controlled by the AssemblyDialect member in llvm::MCAsmInfo. For x86 the derived classes of llvm::MCAsmInfo can be found in X86MCAsmInfo.h and X86MCAsmInfo.cpp.
    • The member AssemblyDialect is initialized to the value of AsmWriterFlavor, which is set by the command line option x86-asm-syntax.

    As far as I could tell AssemblyDialect isn't referenced anywhere else in the code base, so the only way to set it is by the x86-asm-syntax flag. For that you can use llvm::cl::ParseCommandLineOptions. Minimal example for setting the assembly syntax to intel:

    #include <cassert>
    #include <llvm/Support/CommandLine.h>
    
    void set_asm_syntax_to_intel()
    {
        char const *args[] = { "some-exe-name", "--x86-asm-syntax=intel" };
        auto const res = llvm::cl::ParseCommandLineOptions(std::size(args), args);
        assert(res);
    }