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
26namespace {
27
28class RISCVLandingPadSetup : public MachineFunctionPass {
29public:
30 static char ID;
31
32 RISCVLandingPadSetup() : MachineFunctionPass(ID) {}
33
34 bool runOnMachineFunction(MachineFunction &F) override;
35
36 StringRef getPassName() const override { return PASS_NAME; }
37
38 void getAnalysisUsage(AnalysisUsage &AU) const override {
39 AU.setPreservesCFG();
40 MachineFunctionPass::getAnalysisUsage(AU);
41 }
42};
43
44} // end anonymous namespace
45
46bool RISCVLandingPadSetup::runOnMachineFunction(MachineFunction &MF) {
47 const auto &STI = MF.getSubtarget<RISCVSubtarget>();
48 const RISCVInstrInfo &TII = *STI.getInstrInfo();
49
50 if (!MF.getInfo<RISCVMachineFunctionInfo>()->hasCFProtectionBranch())
51 return false;
52
53 uint32_t Label = 0;
54 if (std::optional<uint32_t> Preferred = STI.getCLOpts().landing_pad_label) {
55 if (!isUInt<20>(x: *Preferred))
56 report_fatal_error(reason: "riscv-landing-pad-label=<val>, <val> needs to fit in "
57 "unsigned 20-bits");
58 Label = *Preferred;
59 }
60
61 // Zicfilp does not check X7 if landing pad label is zero.
62 if (Label == 0)
63 return false;
64
65 bool Changed = false;
66 for (MachineBasicBlock &MBB : MF)
67 for (MachineInstr &MI : llvm::make_early_inc_range(Range&: MBB)) {
68 if (MI.getOpcode() != RISCV::PseudoBRIND &&
69 MI.getOpcode() != RISCV::PseudoCALLIndirect &&
70 MI.getOpcode() != RISCV::PseudoTAILIndirect)
71 continue;
72 BuildMI(BB&: MBB, I&: MI, MIMD: MI.getDebugLoc(), MCID: TII.get(Opcode: RISCV::LUI), DestReg: RISCV::X7)
73 .addImm(Val: Label);
74 MachineInstrBuilder(MF, &MI).addUse(RegNo: RISCV::X7, Flags: RegState::ImplicitKill);
75 Changed = true;
76 }
77
78 return Changed;
79}
80
81INITIALIZE_PASS(RISCVLandingPadSetup, DEBUG_TYPE, PASS_NAME, false, false)
82
83char RISCVLandingPadSetup::ID = 0;
84
85FunctionPass *llvm::createRISCVLandingPadSetupPass() {
86 return new RISCVLandingPadSetup();
87}
88