1//===------------ RISCVLandingPadSetup.cpp ---------------------------------==//
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 is a RISC-V pass to setup landing pad labels for indirect jumps.
10// Currently this pass only supports fixed labels.
11//
12//===----------------------------------------------------------------------===//
13
14#include "RISCV.h"
15#include "RISCVInstrInfo.h"
16#include "RISCVMachineFunctionInfo.h"
17#include "RISCVSubtarget.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20
21using namespace llvm;
22
23#define DEBUG_TYPE "riscv-lpad-setup"
24#define PASS_NAME "RISC-V Landing Pad Setup"
25
26extern cl::opt<uint32_t> PreferredLandingPadLabel;
27
28namespace {
29
30class RISCVLandingPadSetup : public MachineFunctionPass {
31public:
32 static char ID;
33
34 RISCVLandingPadSetup() : MachineFunctionPass(ID) {}
35
36 bool runOnMachineFunction(MachineFunction &F) override;
37
38 StringRef getPassName() const override { return PASS_NAME; }
39
40 void getAnalysisUsage(AnalysisUsage &AU) const override {
41 AU.setPreservesCFG();
42 MachineFunctionPass::getAnalysisUsage(AU);
43 }
44};
45
46} // end anonymous namespace
47
48bool RISCVLandingPadSetup::runOnMachineFunction(MachineFunction &MF) {
49 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
50 const RISCVInstrInfo &TII = *STI.getInstrInfo();
51
52 if (!MF.getInfo<RISCVMachineFunctionInfo>()->hasCFProtectionBranch())
53 return false;
54
55 uint32_t Label = 0;
56 if (PreferredLandingPadLabel.getNumOccurrences() > 0) {
57 if (!isUInt<20>(x: PreferredLandingPadLabel))
58 report_fatal_error(reason: "riscv-landing-pad-label=<val>, <val> needs to fit in "
59 "unsigned 20-bits");
60 Label = PreferredLandingPadLabel;
61 }
62
63 // Zicfilp does not check X7 if landing pad label is zero.
64 if (Label == 0)
65 return false;
66
67 bool Changed = false;
68 for (MachineBasicBlock &MBB : MF)
69 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: MBB)) {
70 if (MI.getOpcode() != RISCV::PseudoBRIND &&
71 MI.getOpcode() != RISCV::PseudoCALLIndirect &&
72 MI.getOpcode() != RISCV::PseudoTAILIndirect)
73 continue;
74 BuildMI(BB&: MBB, I&: MI, MIMD: MI.getDebugLoc(), MCID: TII.get(Opcode: RISCV::LUI), DestReg: RISCV::X7)
75 .addImm(Val: Label);
76 MachineInstrBuilder(MF, &MI).addUse(RegNo: RISCV::X7, Flags: RegState::ImplicitKill);
77 Changed = true;
78 }
79
80 return Changed;
81}
82
83INITIALIZE_PASS(RISCVLandingPadSetup, DEBUG_TYPE, PASS_NAME, false, false)
84
85char RISCVLandingPadSetup::ID = 0;
86
87FunctionPass *llvm::createRISCVLandingPadSetupPass() {
88 return new RISCVLandingPadSetup();
89}
90