brintos

brintos / llvm-project-archived public Read only

0
0
Text · 5.9 KiB · 200e6a5 Raw
164 lines · cpp
1//===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===//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-exception6//7//===----------------------------------------------------------------------===//8//9//  This utility may be invoked in the following manner:10//   llvm-as --help         - Output information about command line switches11//   llvm-as [options]      - Read LLVM asm from stdin, write bitcode to stdout12//   llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bitcode13//                            to the x.bc file.14//15//===----------------------------------------------------------------------===//16 17#include "llvm/AsmParser/Parser.h"18#include "llvm/Bitcode/BitcodeWriter.h"19#include "llvm/IR/LLVMContext.h"20#include "llvm/IR/Module.h"21#include "llvm/IR/ModuleSummaryIndex.h"22#include "llvm/IR/Verifier.h"23#include "llvm/Support/CommandLine.h"24#include "llvm/Support/FileSystem.h"25#include "llvm/Support/InitLLVM.h"26#include "llvm/Support/SourceMgr.h"27#include "llvm/Support/SystemUtils.h"28#include "llvm/Support/ToolOutputFile.h"29#include <memory>30#include <optional>31using namespace llvm;32 33static cl::OptionCategory AsCat("llvm-as Options");34 35static cl::opt<std::string>36    InputFilename(cl::Positional, cl::desc("<input .ll file>"), cl::init("-"));37 38static cl::opt<std::string> OutputFilename("o",39                                           cl::desc("Override output filename"),40                                           cl::value_desc("filename"),41                                           cl::cat(AsCat));42 43static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals"),44                           cl::cat(AsCat));45 46static cl::opt<bool> DisableOutput("disable-output", cl::desc("Disable output"),47                                   cl::init(false), cl::cat(AsCat));48 49static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),50                                    cl::init(false), cl::cat(AsCat));51 52static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as parsed"),53                             cl::Hidden, cl::cat(AsCat));54 55static cl::opt<bool>56    DisableVerify("disable-verify", cl::Hidden,57                  cl::desc("Do not run verifier on input LLVM (dangerous!)"),58                  cl::cat(AsCat));59 60static cl::opt<std::string> ClDataLayout("data-layout",61                                         cl::desc("data layout string to use"),62                                         cl::value_desc("layout-string"),63                                         cl::init(""), cl::cat(AsCat));64 65static void WriteOutputFile(const Module *M, const ModuleSummaryIndex *Index) {66  // Infer the output filename if needed.67  if (OutputFilename.empty()) {68    if (InputFilename == "-") {69      OutputFilename = "-";70    } else {71      StringRef IFN = InputFilename;72      OutputFilename = (IFN.ends_with(".ll") ? IFN.drop_back(3) : IFN).str();73      OutputFilename += ".bc";74    }75  }76 77  std::error_code EC;78  std::unique_ptr<ToolOutputFile> Out(79      new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));80  if (EC) {81    errs() << EC.message() << '\n';82    exit(1);83  }84 85  if (Force || !CheckBitcodeOutputToConsole(Out->os())) {86    const ModuleSummaryIndex *IndexToWrite = nullptr;87    // Don't attempt to write a summary index unless it contains any entries or88    // has non-zero flags. The latter is used to assemble dummy index files for89    // skipping modules by distributed ThinLTO backends. Otherwise we get an empty90    // summary section.91    if (Index && (Index->begin() != Index->end() || Index->getFlags()))92      IndexToWrite = Index;93    if (!IndexToWrite || (M && (!M->empty() || !M->global_empty())))94      // If we have a non-empty Module, then we write the Module plus95      // any non-null Index along with it as a per-module Index.96      // If both are empty, this will give an empty module block, which is97      // the expected behavior.98      WriteBitcodeToFile(*M, Out->os(), /* ShouldPreserveUseListOrder */ true,99                         IndexToWrite, EmitModuleHash);100    else101      // Otherwise, with an empty Module but non-empty Index, we write a102      // combined index.103      writeIndexToFile(*IndexToWrite, Out->os());104  }105 106  // Declare success.107  Out->keep();108}109 110int main(int argc, char **argv) {111  InitLLVM X(argc, argv);112  cl::HideUnrelatedOptions(AsCat);113  cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");114  LLVMContext Context;115 116  // Parse the file now...117  SMDiagnostic Err;118  auto SetDataLayout = [](StringRef, StringRef) -> std::optional<std::string> {119    if (ClDataLayout.empty())120      return std::nullopt;121    return ClDataLayout;122  };123  ParsedModuleAndIndex ModuleAndIndex;124  if (DisableVerify) {125    ModuleAndIndex = parseAssemblyFileWithIndexNoUpgradeDebugInfo(126        InputFilename, Err, Context, nullptr, SetDataLayout);127  } else {128    ModuleAndIndex = parseAssemblyFileWithIndex(InputFilename, Err, Context,129                                                nullptr, SetDataLayout);130  }131  std::unique_ptr<Module> M = std::move(ModuleAndIndex.Mod);132  if (!M) {133    Err.print(argv[0], errs());134    return 1;135  }136 137  M->removeDebugIntrinsicDeclarations();138 139  std::unique_ptr<ModuleSummaryIndex> Index = std::move(ModuleAndIndex.Index);140 141  if (!DisableVerify) {142    std::string ErrorStr;143    raw_string_ostream OS(ErrorStr);144    if (verifyModule(*M, &OS)) {145      errs() << argv[0]146             << ": assembly parsed, but does not verify as correct!\n";147      errs() << OS.str();148      return 1;149    }150    // TODO: Implement and call summary index verifier.151  }152 153  if (DumpAsm) {154    errs() << "Here's the assembly:\n" << *M;155    if (Index.get() && Index->begin() != Index->end())156      Index->print(errs());157  }158 159  if (!DisableOutput)160    WriteOutputFile(M.get(), Index.get());161 162  return 0;163}164