Path: blob/main/contrib/llvm-project/llvm/lib/Target/X86/X86DynAllocaExpander.cpp
35294 views
//===----- X86DynAllocaExpander.cpp - Expand DynAlloca pseudo instruction -===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines a pass that expands DynAlloca pseudo-instructions.9//10// It performs a conservative analysis to determine whether each allocation11// falls within a region of the stack that is safe to use, or whether stack12// probes must be emitted.13//14//===----------------------------------------------------------------------===//1516#include "X86.h"17#include "X86InstrBuilder.h"18#include "X86InstrInfo.h"19#include "X86MachineFunctionInfo.h"20#include "X86Subtarget.h"21#include "llvm/ADT/MapVector.h"22#include "llvm/ADT/PostOrderIterator.h"23#include "llvm/CodeGen/MachineFunctionPass.h"24#include "llvm/CodeGen/MachineInstrBuilder.h"25#include "llvm/CodeGen/MachineRegisterInfo.h"26#include "llvm/CodeGen/Passes.h"27#include "llvm/CodeGen/TargetInstrInfo.h"28#include "llvm/IR/Function.h"29#include "llvm/Support/raw_ostream.h"3031using namespace llvm;3233namespace {3435class X86DynAllocaExpander : public MachineFunctionPass {36public:37X86DynAllocaExpander() : MachineFunctionPass(ID) {}3839bool runOnMachineFunction(MachineFunction &MF) override;4041private:42/// Strategies for lowering a DynAlloca.43enum Lowering { TouchAndSub, Sub, Probe };4445/// Deterministic-order map from DynAlloca instruction to desired lowering.46typedef MapVector<MachineInstr*, Lowering> LoweringMap;4748/// Compute which lowering to use for each DynAlloca instruction.49void computeLowerings(MachineFunction &MF, LoweringMap& Lowerings);5051/// Get the appropriate lowering based on current offset and amount.52Lowering getLowering(int64_t CurrentOffset, int64_t AllocaAmount);5354/// Lower a DynAlloca instruction.55void lower(MachineInstr* MI, Lowering L);5657MachineRegisterInfo *MRI = nullptr;58const X86Subtarget *STI = nullptr;59const TargetInstrInfo *TII = nullptr;60const X86RegisterInfo *TRI = nullptr;61unsigned StackPtr = 0;62unsigned SlotSize = 0;63int64_t StackProbeSize = 0;64bool NoStackArgProbe = false;6566StringRef getPassName() const override { return "X86 DynAlloca Expander"; }67static char ID;68};6970char X86DynAllocaExpander::ID = 0;7172} // end anonymous namespace7374FunctionPass *llvm::createX86DynAllocaExpander() {75return new X86DynAllocaExpander();76}7778/// Return the allocation amount for a DynAlloca instruction, or -1 if unknown.79static int64_t getDynAllocaAmount(MachineInstr *MI, MachineRegisterInfo *MRI) {80assert(MI->getOpcode() == X86::DYN_ALLOCA_32 ||81MI->getOpcode() == X86::DYN_ALLOCA_64);82assert(MI->getOperand(0).isReg());8384Register AmountReg = MI->getOperand(0).getReg();85MachineInstr *Def = MRI->getUniqueVRegDef(AmountReg);8687if (!Def ||88(Def->getOpcode() != X86::MOV32ri && Def->getOpcode() != X86::MOV64ri) ||89!Def->getOperand(1).isImm())90return -1;9192return Def->getOperand(1).getImm();93}9495X86DynAllocaExpander::Lowering96X86DynAllocaExpander::getLowering(int64_t CurrentOffset,97int64_t AllocaAmount) {98// For a non-constant amount or a large amount, we have to probe.99if (AllocaAmount < 0 || AllocaAmount > StackProbeSize)100return Probe;101102// If it fits within the safe region of the stack, just subtract.103if (CurrentOffset + AllocaAmount <= StackProbeSize)104return Sub;105106// Otherwise, touch the current tip of the stack, then subtract.107return TouchAndSub;108}109110static bool isPushPop(const MachineInstr &MI) {111switch (MI.getOpcode()) {112case X86::PUSH32r:113case X86::PUSH32rmm:114case X86::PUSH32rmr:115case X86::PUSH32i:116case X86::PUSH64r:117case X86::PUSH64rmm:118case X86::PUSH64rmr:119case X86::PUSH64i32:120case X86::POP32r:121case X86::POP64r:122return true;123default:124return false;125}126}127128void X86DynAllocaExpander::computeLowerings(MachineFunction &MF,129LoweringMap &Lowerings) {130// Do a one-pass reverse post-order walk of the CFG to conservatively estimate131// the offset between the stack pointer and the lowest touched part of the132// stack, and use that to decide how to lower each DynAlloca instruction.133134// Initialize OutOffset[B], the stack offset at exit from B, to something big.135DenseMap<MachineBasicBlock *, int64_t> OutOffset;136for (MachineBasicBlock &MBB : MF)137OutOffset[&MBB] = INT32_MAX;138139// Note: we don't know the offset at the start of the entry block since the140// prologue hasn't been inserted yet, and how much that will adjust the stack141// pointer depends on register spills, which have not been computed yet.142143// Compute the reverse post-order.144ReversePostOrderTraversal<MachineFunction*> RPO(&MF);145146for (MachineBasicBlock *MBB : RPO) {147int64_t Offset = -1;148for (MachineBasicBlock *Pred : MBB->predecessors())149Offset = std::max(Offset, OutOffset[Pred]);150if (Offset == -1) Offset = INT32_MAX;151152for (MachineInstr &MI : *MBB) {153if (MI.getOpcode() == X86::DYN_ALLOCA_32 ||154MI.getOpcode() == X86::DYN_ALLOCA_64) {155// A DynAlloca moves StackPtr, and potentially touches it.156int64_t Amount = getDynAllocaAmount(&MI, MRI);157Lowering L = getLowering(Offset, Amount);158Lowerings[&MI] = L;159switch (L) {160case Sub:161Offset += Amount;162break;163case TouchAndSub:164Offset = Amount;165break;166case Probe:167Offset = 0;168break;169}170} else if (MI.isCall() || isPushPop(MI)) {171// Calls, pushes and pops touch the tip of the stack.172Offset = 0;173} else if (MI.getOpcode() == X86::ADJCALLSTACKUP32 ||174MI.getOpcode() == X86::ADJCALLSTACKUP64) {175Offset -= MI.getOperand(0).getImm();176} else if (MI.getOpcode() == X86::ADJCALLSTACKDOWN32 ||177MI.getOpcode() == X86::ADJCALLSTACKDOWN64) {178Offset += MI.getOperand(0).getImm();179} else if (MI.modifiesRegister(StackPtr, TRI)) {180// Any other modification of SP means we've lost track of it.181Offset = INT32_MAX;182}183}184185OutOffset[MBB] = Offset;186}187}188189static unsigned getSubOpcode(bool Is64Bit) {190if (Is64Bit)191return X86::SUB64ri32;192return X86::SUB32ri;193}194195void X86DynAllocaExpander::lower(MachineInstr *MI, Lowering L) {196const DebugLoc &DL = MI->getDebugLoc();197MachineBasicBlock *MBB = MI->getParent();198MachineBasicBlock::iterator I = *MI;199200int64_t Amount = getDynAllocaAmount(MI, MRI);201if (Amount == 0) {202MI->eraseFromParent();203return;204}205206// These two variables differ on x32, which is a 64-bit target with a207// 32-bit alloca.208bool Is64Bit = STI->is64Bit();209bool Is64BitAlloca = MI->getOpcode() == X86::DYN_ALLOCA_64;210assert(SlotSize == 4 || SlotSize == 8);211212std::optional<MachineFunction::DebugInstrOperandPair> InstrNum;213if (unsigned Num = MI->peekDebugInstrNum()) {214// Operand 2 of DYN_ALLOCAs contains the stack def.215InstrNum = {Num, 2};216}217218switch (L) {219case TouchAndSub: {220assert(Amount >= SlotSize);221222// Use a push to touch the top of the stack.223unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;224BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))225.addReg(RegA, RegState::Undef);226Amount -= SlotSize;227if (!Amount)228break;229230// Fall through to make any remaining adjustment.231[[fallthrough]];232}233case Sub:234assert(Amount > 0);235if (Amount == SlotSize) {236// Use push to save size.237unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;238BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))239.addReg(RegA, RegState::Undef);240} else {241// Sub.242BuildMI(*MBB, I, DL, TII->get(getSubOpcode(Is64BitAlloca)), StackPtr)243.addReg(StackPtr)244.addImm(Amount);245}246break;247case Probe:248if (!NoStackArgProbe) {249// The probe lowering expects the amount in RAX/EAX.250unsigned RegA = Is64BitAlloca ? X86::RAX : X86::EAX;251BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY), RegA)252.addReg(MI->getOperand(0).getReg());253254// Do the probe.255STI->getFrameLowering()->emitStackProbe(*MBB->getParent(), *MBB, MI, DL,256/*InProlog=*/false, InstrNum);257} else {258// Sub259BuildMI(*MBB, I, DL,260TII->get(Is64BitAlloca ? X86::SUB64rr : X86::SUB32rr), StackPtr)261.addReg(StackPtr)262.addReg(MI->getOperand(0).getReg());263}264break;265}266267Register AmountReg = MI->getOperand(0).getReg();268MI->eraseFromParent();269270// Delete the definition of AmountReg.271if (MRI->use_empty(AmountReg))272if (MachineInstr *AmountDef = MRI->getUniqueVRegDef(AmountReg))273AmountDef->eraseFromParent();274}275276bool X86DynAllocaExpander::runOnMachineFunction(MachineFunction &MF) {277if (!MF.getInfo<X86MachineFunctionInfo>()->hasDynAlloca())278return false;279280MRI = &MF.getRegInfo();281STI = &MF.getSubtarget<X86Subtarget>();282TII = STI->getInstrInfo();283TRI = STI->getRegisterInfo();284StackPtr = TRI->getStackRegister();285SlotSize = TRI->getSlotSize();286StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);287NoStackArgProbe = MF.getFunction().hasFnAttribute("no-stack-arg-probe");288if (NoStackArgProbe)289StackProbeSize = INT64_MAX;290291LoweringMap Lowerings;292computeLowerings(MF, Lowerings);293for (auto &P : Lowerings)294lower(P.first, P.second);295296return true;297}298299300