-O2 optimizes printf(“%s\n”, str) to puts(str)

前端 未结 3 609
自闭症患者
自闭症患者 2020-12-11 19:54

Toying around with clang, I compiled a C program containing this line:

printf(\"%s\\n\", argv[0]);

When compiling without opti

3条回答
  •  失恋的感觉
    2020-12-11 20:15

    1. How often does function call substitution happen in optimized compilation? Is this frequent or is stdio an exception?

    The optimization that replaces printf with puts in LLVM is in the class LibCallSimplifier. You can see the header file in llvm/include/llvm/Transforms/Utils/SimplifyLibCalls.h and the implementation in llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp. Looking at the files will give an example of some of the other library call replacement optimizations that are done (the header file is probably easier to start with). And of course there are other many other optimizations that LLVM does, you can get an idea of some of them by looking at the list of LLVM passes.

    1. Could I write compiler optimizations for my own libraries? How would I do that?

    Yes you could. LLVM is very modular and performs transformation on the IR in a series of passes. So if you wanted to add a custom pass yourself for your own library you could do so (although it is still a fair amount of work to understand how the LLVM compiler flow works). A good starting point is the document: Writing an LLVM Pass.

提交回复
热议问题