[libc] Switch to using the generic `<gpuintrin.h>` implementations (#121810)
[llvm-project.git] / llvm / tools / llvm-dis / llvm-dis.cpp
blob49acc9cd456ff468a59ec6593a1d0c7889a896b6
1 //===-- llvm-dis.cpp - The low-level LLVM disassembler --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility may be invoked in the following manner:
10 // llvm-dis [options] - Read LLVM bitcode from stdin, write asm to stdout
11 // llvm-dis [options] x.bc - Read LLVM bitcode from the x.bc file, write asm
12 // to the x.ll file.
13 // Options:
15 // Color Options:
16 // --color - Use colors in output (default=autodetect)
18 // Disassembler Options:
19 // -f - Enable binary output on terminals
20 // --materialize-metadata - Load module without materializing metadata,
21 // then materialize only the metadata
22 // -o <filename> - Override output filename
23 // --show-annotations - Add informational comments to the .ll file
25 // Generic Options:
26 // --help - Display available options
27 // (--help-hidden for more)
28 // --help-list - Display list of available options
29 // (--help-list-hidden for more)
30 // --version - Display the version of this program
32 //===----------------------------------------------------------------------===//
34 #include "llvm/Bitcode/BitcodeReader.h"
35 #include "llvm/IR/AssemblyAnnotationWriter.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/IR/DiagnosticPrinter.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/ModuleSummaryIndex.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/Support/InitLLVM.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/WithColor.h"
52 #include <system_error>
53 using namespace llvm;
55 static cl::OptionCategory DisCategory("Disassembler Options");
57 static cl::list<std::string> InputFilenames(cl::Positional,
58 cl::desc("[input bitcode]..."),
59 cl::cat(DisCategory));
61 static cl::opt<std::string> OutputFilename("o",
62 cl::desc("Override output filename"),
63 cl::value_desc("filename"),
64 cl::cat(DisCategory));
66 static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),
67 cl::cat(DisCategory));
69 static cl::opt<bool> DontPrint("disable-output",
70 cl::desc("Don't output the .ll file"),
71 cl::Hidden, cl::cat(DisCategory));
73 static cl::opt<bool>
74 SetImporting("set-importing",
75 cl::desc("Set lazy loading to pretend to import a module"),
76 cl::Hidden, cl::cat(DisCategory));
78 static cl::opt<bool>
79 ShowAnnotations("show-annotations",
80 cl::desc("Add informational comments to the .ll file"),
81 cl::cat(DisCategory));
83 static cl::opt<bool> PreserveAssemblyUseListOrder(
84 "preserve-ll-uselistorder",
85 cl::desc("Preserve use-list order when writing LLVM assembly."),
86 cl::init(false), cl::Hidden, cl::cat(DisCategory));
88 static cl::opt<bool>
89 MaterializeMetadata("materialize-metadata",
90 cl::desc("Load module without materializing metadata, "
91 "then materialize only the metadata"),
92 cl::cat(DisCategory));
94 static cl::opt<bool> PrintThinLTOIndexOnly(
95 "print-thinlto-index-only",
96 cl::desc("Only read thinlto index and print the index as LLVM assembly."),
97 cl::init(false), cl::Hidden, cl::cat(DisCategory));
99 extern cl::opt<bool> WriteNewDbgInfoFormat;
101 extern cl::opt<cl::boolOrDefault> LoadBitcodeIntoNewDbgInfoFormat;
103 namespace {
105 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
106 OS << DL.getLine() << ":" << DL.getCol();
107 if (DILocation *IDL = DL.getInlinedAt()) {
108 OS << "@";
109 printDebugLoc(IDL, OS);
112 class CommentWriter : public AssemblyAnnotationWriter {
113 public:
114 void emitFunctionAnnot(const Function *F,
115 formatted_raw_ostream &OS) override {
116 OS << "; [#uses=" << F->getNumUses() << ']'; // Output # uses
117 OS << '\n';
119 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
120 bool Padded = false;
121 if (!V.getType()->isVoidTy()) {
122 OS.PadToColumn(50);
123 Padded = true;
124 // Output # uses and type
125 OS << "; [#uses=" << V.getNumUses() << " type=" << *V.getType() << "]";
127 if (const Instruction *I = dyn_cast<Instruction>(&V)) {
128 if (const DebugLoc &DL = I->getDebugLoc()) {
129 if (!Padded) {
130 OS.PadToColumn(50);
131 Padded = true;
132 OS << ";";
134 OS << " [debug line = ";
135 printDebugLoc(DL,OS);
136 OS << "]";
138 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
139 if (!Padded) {
140 OS.PadToColumn(50);
141 OS << ";";
143 OS << " [debug variable = " << DDI->getVariable()->getName() << "]";
145 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
146 if (!Padded) {
147 OS.PadToColumn(50);
148 OS << ";";
150 OS << " [debug variable = " << DVI->getVariable()->getName() << "]";
156 struct LLVMDisDiagnosticHandler : public DiagnosticHandler {
157 char *Prefix;
158 LLVMDisDiagnosticHandler(char *PrefixPtr) : Prefix(PrefixPtr) {}
159 bool handleDiagnostics(const DiagnosticInfo &DI) override {
160 raw_ostream &OS = errs();
161 OS << Prefix << ": ";
162 switch (DI.getSeverity()) {
163 case DS_Error: WithColor::error(OS); break;
164 case DS_Warning: WithColor::warning(OS); break;
165 case DS_Remark: OS << "remark: "; break;
166 case DS_Note: WithColor::note(OS); break;
169 DiagnosticPrinterRawOStream DP(OS);
170 DI.print(DP);
171 OS << '\n';
173 if (DI.getSeverity() == DS_Error)
174 exit(1);
175 return true;
178 } // end anon namespace
180 static ExitOnError ExitOnErr;
182 int main(int argc, char **argv) {
183 InitLLVM X(argc, argv);
185 ExitOnErr.setBanner(std::string(argv[0]) + ": error: ");
187 cl::HideUnrelatedOptions({&DisCategory, &getColorCategory()});
188 cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
190 // Load bitcode into the new debug info format by default.
191 if (LoadBitcodeIntoNewDbgInfoFormat == cl::boolOrDefault::BOU_UNSET)
192 LoadBitcodeIntoNewDbgInfoFormat = cl::boolOrDefault::BOU_TRUE;
194 if (InputFilenames.size() < 1) {
195 InputFilenames.push_back("-");
196 } else if (InputFilenames.size() > 1 && !OutputFilename.empty()) {
197 errs()
198 << "error: output file name cannot be set for multiple input files\n";
199 return 1;
202 for (const auto &InputFilename : InputFilenames) {
203 // Use a fresh context for each input to avoid state
204 // cross-contamination across inputs (e.g. type name collisions).
205 LLVMContext Context;
206 Context.setDiagnosticHandler(
207 std::make_unique<LLVMDisDiagnosticHandler>(argv[0]));
209 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
210 MemoryBuffer::getFileOrSTDIN(InputFilename);
211 if (std::error_code EC = BufferOrErr.getError()) {
212 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
213 return 1;
215 std::unique_ptr<MemoryBuffer> MB = std::move(BufferOrErr.get());
217 BitcodeFileContents IF = ExitOnErr(llvm::getBitcodeFileContents(*MB));
219 const size_t N = IF.Mods.size();
221 if (OutputFilename == "-" && N > 1)
222 errs() << "only single module bitcode files can be written to stdout\n";
224 for (size_t I = 0; I < N; ++I) {
225 BitcodeModule MB = IF.Mods[I];
227 std::unique_ptr<Module> M;
229 if (!PrintThinLTOIndexOnly) {
230 M = ExitOnErr(
231 MB.getLazyModule(Context, MaterializeMetadata, SetImporting));
232 if (MaterializeMetadata)
233 ExitOnErr(M->materializeMetadata());
234 else
235 ExitOnErr(M->materializeAll());
238 BitcodeLTOInfo LTOInfo = ExitOnErr(MB.getLTOInfo());
239 std::unique_ptr<ModuleSummaryIndex> Index;
240 if (LTOInfo.HasSummary)
241 Index = ExitOnErr(MB.getSummary());
243 std::string FinalFilename(OutputFilename);
245 // Just use stdout. We won't actually print anything on it.
246 if (DontPrint)
247 FinalFilename = "-";
249 if (FinalFilename.empty()) { // Unspecified output, infer it.
250 if (InputFilename == "-") {
251 FinalFilename = "-";
252 } else {
253 StringRef IFN = InputFilename;
254 FinalFilename = (IFN.ends_with(".bc") ? IFN.drop_back(3) : IFN).str();
255 if (N > 1)
256 FinalFilename += std::string(".") + std::to_string(I);
257 FinalFilename += ".ll";
259 } else {
260 if (N > 1)
261 FinalFilename += std::string(".") + std::to_string(I);
264 std::error_code EC;
265 std::unique_ptr<ToolOutputFile> Out(
266 new ToolOutputFile(FinalFilename, EC, sys::fs::OF_TextWithCRLF));
267 if (EC) {
268 errs() << EC.message() << '\n';
269 return 1;
272 std::unique_ptr<AssemblyAnnotationWriter> Annotator;
273 if (ShowAnnotations)
274 Annotator.reset(new CommentWriter());
276 // All that llvm-dis does is write the assembly to a file.
277 if (!DontPrint) {
278 if (M) {
279 M->setIsNewDbgInfoFormat(WriteNewDbgInfoFormat);
280 if (WriteNewDbgInfoFormat)
281 M->removeDebugIntrinsicDeclarations();
282 M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);
284 if (Index)
285 Index->print(Out->os());
288 // Declare success.
289 Out->keep();
293 return 0;