How to replace llvm-ld with clang?

2019-03-19 09:07发布

问题:

Summary: llvm-ld has been removed from the LLVM 3.2 release. I am trying to figure out how to use clang in its place in my build system.

Note that I figured out the answer to my own question while writing it but I am still posting it in case it is useful to anyone else. Alternative answers are also welcome.

Details:

I have a build process which first generates bitcode using clang++ -emit-llvm. Then I take the bitcode files and link them together with llvm-link. Then I apply some standard optimization passes with opt. Then I apply another custom compiler pass with opt. Then I apply the standard optimization passes again using opt a third time. Finally I take the output from the last run of opt and use llvm-link to link with appropriate libraries to generate my executable. When I tried to replace llvm-link with clang++ in this process I get the error message: file not recognized: File format not recognized

To make this question more concrete I created a simplified example of what I am trying to do. First there are two files that I want to compile and link together

test1.cpp:

#include <stdio.h>

int getNum();

int main()
{
  int value = getNum();
  printf("value is %d\n", value);
  return 0;
}

test2.cpp

int getNum()
{
  return 5;
}

I executed the following sequence of commands:

clang++ -emit-llvm -c test1.cpp test2.cpp
llvm-link -o test.bc1 test1.o test2.o 
opt test.bc1 -o test.bc2 -std-compile-opts

(Note that I am currently running llvm 3.1, but I'm trying to figure out the steps that will work for llvm 3.2. I assume that I should be able to make the LLVM 3.1 version work correctly using clang instead of llvm-ld)

Then if I run:

llvm-ld test.bc2 -o a.out -native

everything is fine and a.out prints out 5.

However, if I run:

clang++ test.bc2 -o a.out

Then I get the error message:

test.bc2: file not recognized: File format not recognized clang-3:
error: linker command failed with exit code 1 (use -v to see invocation)

Obviously I know that I can produce an executable file by running clang directly on the .cpp files. But I'm wondering what the best way to integrate clang with opt is.

回答1:

The test case described in the question can be compiled using the following steps:

clang++ -emit-llvm -c test1.cpp test2.cpp
llvm-link -o test.bc1 test1.o test2.o 
opt test.bc1 -o test.bc2 -std-compile-opts

llc -filetype=obj test.bc2 -o test.o
clang++ test.o

This produces a working a.out file.

It seems that llc is needed to convert from bitcode to machine code which can then be processed by clang as it normally would.



回答2:

In general I've found that

llvm-ld x.bc y.bc

can be replaced with

llc x.bc
llc y.bc
clang x.s y.s


标签: llvm clang ld