[CodeGen] Support bitcode input containing multiple modules
authorFangrui Song <i@maskray.me>
Sat, 22 Jul 2023 03:05:35 +0000 (20:05 -0700)
committerFangrui Song <i@maskray.me>
Sat, 22 Jul 2023 03:05:35 +0000 (20:05 -0700)
commitb2f7b5dbaefe4f2e3f8f279735ea3509a796693f
tree67a6872e672b76631bcec11d084e446959c4aa68
parent9d525bf94b255df89587db955b5fa2d3c03c2c3e
[CodeGen] Support bitcode input containing multiple modules

When using -fsplit-lto-unit (explicitly specified or due to using
-fsanitize=cfi/-fwhole-program-vtables), the emitted LLVM IR contains a module
flag metadata `"EnableSplitLTOUnit"`. If a module contains both type metadata
and `"EnableSplitLTOUnit"`, `ThinLTOBitcodeWriter.cpp` will write two modules
into the bitcode file. Compiling the bitcode (not ThinLTO backend compilation)
will lead to an error due to `parseIR` requiring a single module.

```
% clang -flto=thin a.cc -c -o a.bc
% clang -c a.bc
% clang -fsplit-lto-unit -flto=thin a.cc -c -o a.bc
% clang -c a.bc
error: Expected a single module
1 error generated.
```

There are multiple ways to have just one module in a bitcode file
output: `-Xclang -fno-lto-unit`, not using features like `-fsanitize=cfi`,
using `-fsanitize=cfi` with `-fno-split-lto-unit`. I think whether a
bitcode input file contains 2 modules (internal implementation strategy)
should not be a criterion to require an additional driver option when
the user seek for a non-LTO compile action.

Let's place the extra module (if present) into CodeGenOptions::LinkBitcodeFiles
(originally for -cc1 -mlink-bitcode-file). Linker::linkModules will link the two
modules together. This patch makes the following commands work:

```
clang -S -emit-llvm a.bc
clang -S a.bc
clang -c a.bc
```

Reviewed By: ormris

Differential Revision: https://reviews.llvm.org/D154923
clang/lib/CodeGen/CodeGenAction.cpp
clang/test/CodeGen/split-lto-unit-input.cpp [new file with mode: 0644]