Files
revng-revng/lib/Lift/DropHelperCallsPass.h
Alessandro Di Federico 1429b526ab Introduce libtcg
This commit drops libptc in favor of its new form libtcg.

It brings several improvements, among which:

* The QEMU version we work on has been upgraded.
* CPUStateAccessAnalysis has been reimplemented in a way that makes it
  easier to debug and solves some limitations (e.g., tracking leaking
  pointers).
* Identification of pieces of the CPU state that are read by each helper
  and fixing access to the CPU state is now performed at build-time.
* We no longer mmap the code we need to translate, dropping all the
  issues related to code that needed to be mapped where something is
  already present.
* We now have two distinct flavors of helper modules: the full one and
  the "slim" one. The latter contains the definition only of functions
  we intend to inline. It is used in most of the pipeline, a good thing
  since we spend less time optimizing code we don't really care about.
  The full module is only used on the re-compilation branch of the
  pipeline.
* We no longer split the `cpu_loop` function.
* We change MetaAddress to rely on architectures from `model::` as
  opposed to the LLVM ones.
* We no longer attach debug info to LLVM IR containing the original
  assembly.
* We now verify that the lifted code only contains code we expect.
2025-10-31 17:25:03 +01:00

188 lines
5.8 KiB
C++

#pragma once
//
// This file is distributed under the MIT License. See LICENSE.md for details.
//
#include <map>
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "revng/Model/FunctionTags.h"
#include "revng/Support/IRHelpers.h"
using CSVToAllocaMap = llvm::DenseMap<llvm::GlobalVariable *,
llvm::AllocaInst *>;
/// Helper class to generate calls that summarize pieces of codes accessing CSVs
class SummaryCallsBuilder {
private:
const CSVToAllocaMap &CSVMap;
llvm::DenseMap<llvm::Type *, llvm::Function *> TemporaryFunctions;
public:
SummaryCallsBuilder(const CSVToAllocaMap &CSVMap) : CSVMap(CSVMap) {}
public:
llvm::CallInst *
buildCall(revng::IRBuilder &Builder,
llvm::Type *ReturnType,
llvm::ArrayRef<llvm::Value *> BaseArguments,
llvm::ArrayRef<llvm::GlobalVariable *> ReadCSVs,
llvm::ArrayRef<llvm::GlobalVariable *> WrittenCSVs) {
using namespace llvm;
Module *M = Builder.GetInsertBlock()->getParent()->getParent();
std::vector<Value *> Arguments;
std::copy(BaseArguments.begin(),
BaseArguments.end(),
std::back_inserter(Arguments));
for (GlobalVariable *CSV : ReadCSVs)
Arguments.push_back(createLoadVariable(Builder, csvToAlloca(CSV)));
CallInst *Result = Builder.CreateCall(getRandom(M, ReturnType), Arguments);
// Put a `store getRandom()` targeting each written CSV
for (GlobalVariable *Written : WrittenCSVs) {
Type *PointeeTy = Written->getValueType();
Value *Random = Builder.CreateCall(getRandom(M, PointeeTy));
Builder.CreateStore(Random, csvToAlloca(Written));
}
return Result;
}
void cleanup() {
for (auto &P : TemporaryFunctions)
eraseFromParent(P.second);
TemporaryFunctions.clear();
}
private:
llvm::Value *csvToAlloca(llvm::GlobalVariable *CSV) const {
auto It = CSVMap.find(CSV);
if (It != CSVMap.end())
return It->second;
else
return CSV;
}
llvm::Function *getRandom(llvm::Module *M, llvm::Type *ReturnType) {
using namespace llvm;
QuickMetadata QMD(M->getContext());
auto It = TemporaryFunctions.find(ReturnType);
if (It != TemporaryFunctions.end())
return It->second;
auto *Type = FunctionType::get(ReturnType, true);
auto *F = Function::Create(Type, GlobalValue::ExternalLinkage, "", M);
F->setOnlyAccessesInaccessibleMemory();
TemporaryFunctions[ReturnType] = F;
return F;
}
};
/// Replace calls to helper functions with read/writes to CSVs they use
///
/// This pass removes all the calls to helper functions replacing them with a
/// function call to `generic_helper` whose arguments (all variadic) are as
/// follows:
///
/// * a pointer to the original helper function;
/// * the original arguments of the call;
/// * the CSVs read by the helper according to CSAA;
///
/// After the replacement call, each CSV written by the helper (according to
/// CSAA) is clobbered with the result of a call to an opaque function.
///
/// This pass also marks the syscall ID argument of syscall helper functions
/// with `revng.syscallid`.
class DropHelperCallsPass : public llvm::PassInfoMixin<DropHelperCallsPass> {
private:
SummaryCallsBuilder &SCB;
llvm::Function *SyscallHelper;
llvm::GlobalVariable *SyscallIDCSV;
public:
DropHelperCallsPass(llvm::Function *SyscallHelper,
llvm::GlobalVariable *SyscallIDCSV,
SummaryCallsBuilder &SCB) :
SCB(SCB), SyscallHelper(SyscallHelper), SyscallIDCSV(SyscallIDCSV) {}
llvm::PreservedAnalyses run(llvm::Function &F,
llvm::FunctionAnalysisManager &);
private:
};
inline llvm::PreservedAnalyses
DropHelperCallsPass::run(llvm::Function &F, llvm::FunctionAnalysisManager &) {
using namespace llvm;
LLVMContext &Context = getContext(&F);
QuickMetadata QMD(Context);
revng::NonDebugInfoCheckingIRBuilder Builder(Context);
std::vector<CallInst *> ToDelete;
// TODO: iterating over users of helper functions would probably be faster
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (auto *Call = getCallToHelper(&I)) {
auto *Callee = cast<Function>(skipCasts(Call->getCalledOperand()));
if (Callee->getName() == AbortFunctionName)
continue;
Builder.SetInsertPoint(Call);
// Collect CSAA data
auto CSVs = getCSVUsedByHelperCall(Call);
// Transform all the calls to helpers to calls to a function that
// takes the following arguments:
//
// * A reference to the called function
// * The original arguments
// * All the registers read
std::vector<Value *> BaseArguments = { Callee };
auto CallArguments = make_range(Call->arg_begin(), Call->arg_end());
for (Value *Argument : CallArguments)
BaseArguments.push_back(Argument);
std::optional<uint32_t> SyscallIDArgumentIndex;
for (GlobalVariable *CSV : CSVs.Read)
if (Callee == SyscallHelper and CSV == SyscallIDCSV)
SyscallIDArgumentIndex = BaseArguments.size();
CallInst *NewCall = SCB.buildCall(Builder,
I.getType(),
BaseArguments,
CSVs.Read,
CSVs.Written);
if (SyscallIDArgumentIndex) {
NewCall->setMetadata("revng.syscallid",
QMD.tuple(*SyscallIDArgumentIndex));
}
// Drop the old function call
I.replaceAllUsesWith(NewCall);
ToDelete.push_back(Call);
}
}
}
for (CallInst *C : ToDelete)
eraseFromParent(C);
return PreservedAnalyses::none();
}