#include "AArch64InstrInfo.h"
#include "AArch64MachineFunctionInfo.h"
#include "AArch64Subtarget.h"
#include "MCTargetDesc/AArch64AddressingModes.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
#include <functional>
#include <iterator>
#include <limits>
using namespace llvm;
#define DEBUG_TYPE "aarch64-ldst-opt"
STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
STATISTIC(NumPostFolded, "Number of post-index updates folded");
STATISTIC(NumPreFolded, "Number of pre-index updates folded");
STATISTIC(NumUnscaledPairCreated,
"Number of load/store from unscaled generated");
STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
"Controls which pairs are considered for renaming");
static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
cl::init(20), cl::Hidden);
static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
cl::Hidden);
static cl::opt<bool> EnableRenaming("aarch64-load-store-renaming",
cl::init(true), cl::Hidden);
#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
namespace {
using LdStPairFlags = struct LdStPairFlags {
bool MergeForward = false;
int SExtIdx = -1;
Optional<MCPhysReg> RenameReg = None;
LdStPairFlags() = default;
void setMergeForward(bool V = true) { MergeForward = V; }
bool getMergeForward() const { return MergeForward; }
void setSExtIdx(int V) { SExtIdx = V; }
int getSExtIdx() const { return SExtIdx; }
void setRenameReg(MCPhysReg R) { RenameReg = R; }
void clearRenameReg() { RenameReg = None; }
Optional<MCPhysReg> getRenameReg() const { return RenameReg; }
};
struct AArch64LoadStoreOpt : public MachineFunctionPass {
static char ID;
AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
}
AliasAnalysis *AA;
const AArch64InstrInfo *TII;
const TargetRegisterInfo *TRI;
const AArch64Subtarget *Subtarget;
LiveRegUnits ModifiedRegUnits, UsedRegUnits;
LiveRegUnits DefinedInBB;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AAResultsWrapperPass>();
MachineFunctionPass::getAnalysisUsage(AU);
}
MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
LdStPairFlags &Flags,
unsigned Limit,
bool FindNarrowMerge);
bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
MachineBasicBlock::iterator &StoreI);
MachineBasicBlock::iterator
mergeNarrowZeroStores(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator MergeMI,
const LdStPairFlags &Flags);
MachineBasicBlock::iterator
mergePairedInsns(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator Paired,
const LdStPairFlags &Flags);
MachineBasicBlock::iterator
promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
MachineBasicBlock::iterator StoreI);
MachineBasicBlock::iterator
findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
int UnscaledOffset, unsigned Limit);
MachineBasicBlock::iterator
findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
unsigned BaseReg, int Offset);
MachineBasicBlock::iterator
mergeUpdateInsn(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator Update, bool IsPreIdx);
bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
bool runOnMachineFunction(MachineFunction &Fn) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
};
char AArch64LoadStoreOpt::ID = 0;
}
INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
AARCH64_LOAD_STORE_OPT_NAME, false, false)
static bool isNarrowStore(unsigned Opc) {
switch (Opc) {
default:
return false;
case AArch64::STRBBui:
case AArch64::STURBBi:
case AArch64::STRHHui:
case AArch64::STURHHi:
return true;
}
}
static bool isTagStore(const MachineInstr &MI) {
switch (MI.getOpcode()) {
default:
return false;
case AArch64::STGOffset:
case AArch64::STZGOffset:
case AArch64::ST2GOffset:
case AArch64::STZ2GOffset:
return true;
}
}
static unsigned getMatchingNonSExtOpcode(unsigned Opc,
bool *IsValidLdStrOpc = nullptr) {
if (IsValidLdStrOpc)
*IsValidLdStrOpc = true;
switch (Opc) {
default:
if (IsValidLdStrOpc)
*IsValidLdStrOpc = false;
return std::numeric_limits<unsigned>::max();
case AArch64::STRDui:
case AArch64::STURDi:
case AArch64::STRDpre:
case AArch64::STRQui:
case AArch64::STURQi:
case AArch64::STRQpre:
case AArch64::STRBBui:
case AArch64::STURBBi:
case AArch64::STRHHui:
case AArch64::STURHHi:
case AArch64::STRWui:
case AArch64::STRWpre:
case AArch64::STURWi:
case AArch64::STRXui:
case AArch64::STRXpre:
case AArch64::STURXi:
case AArch64::LDRDui:
case AArch64::LDURDi:
case AArch64::LDRDpre:
case AArch64::LDRQui:
case AArch64::LDURQi:
case AArch64::LDRQpre:
case AArch64::LDRWui:
case AArch64::LDURWi:
case AArch64::LDRWpre:
case AArch64::LDRXui:
case AArch64::LDURXi:
case AArch64::LDRXpre:
case AArch64::STRSui:
case AArch64::STURSi:
case AArch64::STRSpre:
case AArch64::LDRSui:
case AArch64::LDURSi:
case AArch64::LDRSpre:
return Opc;
case AArch64::LDRSWui:
return AArch64::LDRWui;
case AArch64::LDURSWi:
return AArch64::LDURWi;
}
}
static unsigned getMatchingWideOpcode(unsigned Opc) {
switch (Opc) {
default:
llvm_unreachable("Opcode has no wide equivalent!");
case AArch64::STRBBui:
return AArch64::STRHHui;
case AArch64::STRHHui:
return AArch64::STRWui;
case AArch64::STURBBi:
return AArch64::STURHHi;
case AArch64::STURHHi:
return AArch64::STURWi;
case AArch64::STURWi:
return AArch64::STURXi;
case AArch64::STRWui:
return AArch64::STRXui;
}
}
static unsigned getMatchingPairOpcode(unsigned Opc) {
switch (Opc) {
default:
llvm_unreachable("Opcode has no pairwise equivalent!");
case AArch64::STRSui:
case AArch64::STURSi:
return AArch64::STPSi;
case AArch64::STRSpre:
return AArch64::STPSpre;
case AArch64::STRDui:
case AArch64::STURDi:
return AArch64::STPDi;
case AArch64::STRDpre:
return AArch64::STPDpre;
case AArch64::STRQui:
case AArch64::STURQi:
return AArch64::STPQi;
case AArch64::STRQpre:
return AArch64::STPQpre;
case AArch64::STRWui:
case AArch64::STURWi:
return AArch64::STPWi;
case AArch64::STRWpre:
return AArch64::STPWpre;
case AArch64::STRXui:
case AArch64::STURXi:
return AArch64::STPXi;
case AArch64::STRXpre:
return AArch64::STPXpre;
case AArch64::LDRSui:
case AArch64::LDURSi:
return AArch64::LDPSi;
case AArch64::LDRSpre:
return AArch64::LDPSpre;
case AArch64::LDRDui:
case AArch64::LDURDi:
return AArch64::LDPDi;
case AArch64::LDRDpre:
return AArch64::LDPDpre;
case AArch64::LDRQui:
case AArch64::LDURQi:
return AArch64::LDPQi;
case AArch64::LDRQpre:
return AArch64::LDPQpre;
case AArch64::LDRWui:
case AArch64::LDURWi:
return AArch64::LDPWi;
case AArch64::LDRWpre:
return AArch64::LDPWpre;
case AArch64::LDRXui:
case AArch64::LDURXi:
return AArch64::LDPXi;
case AArch64::LDRXpre:
return AArch64::LDPXpre;
case AArch64::LDRSWui:
case AArch64::LDURSWi:
return AArch64::LDPSWi;
}
}
static unsigned isMatchingStore(MachineInstr &LoadInst,
MachineInstr &StoreInst) {
unsigned LdOpc = LoadInst.getOpcode();
unsigned StOpc = StoreInst.getOpcode();
switch (LdOpc) {
default:
llvm_unreachable("Unsupported load instruction!");
case AArch64::LDRBBui:
return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
case AArch64::LDURBBi:
return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
case AArch64::LDRHHui:
return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
StOpc == AArch64::STRXui;
case AArch64::LDURHHi:
return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
StOpc == AArch64::STURXi;
case AArch64::LDRWui:
return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
case AArch64::LDURWi:
return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
case AArch64::LDRXui:
return StOpc == AArch64::STRXui;
case AArch64::LDURXi:
return StOpc == AArch64::STURXi;
}
}
static unsigned getPreIndexedOpcode(unsigned Opc) {
switch (Opc) {
default:
llvm_unreachable("Opcode has no pre-indexed equivalent!");
case AArch64::STRSui:
return AArch64::STRSpre;
case AArch64::STRDui:
return AArch64::STRDpre;
case AArch64::STRQui:
return AArch64::STRQpre;
case AArch64::STRBBui:
return AArch64::STRBBpre;
case AArch64::STRHHui:
return AArch64::STRHHpre;
case AArch64::STRWui:
return AArch64::STRWpre;
case AArch64::STRXui:
return AArch64::STRXpre;
case AArch64::LDRSui:
return AArch64::LDRSpre;
case AArch64::LDRDui:
return AArch64::LDRDpre;
case AArch64::LDRQui:
return AArch64::LDRQpre;
case AArch64::LDRBBui:
return AArch64::LDRBBpre;
case AArch64::LDRHHui:
return AArch64::LDRHHpre;
case AArch64::LDRWui:
return AArch64::LDRWpre;
case AArch64::LDRXui:
return AArch64::LDRXpre;
case AArch64::LDRSWui:
return AArch64::LDRSWpre;
case AArch64::LDPSi:
return AArch64::LDPSpre;
case AArch64::LDPSWi:
return AArch64::LDPSWpre;
case AArch64::LDPDi:
return AArch64::LDPDpre;
case AArch64::LDPQi:
return AArch64::LDPQpre;
case AArch64::LDPWi:
return AArch64::LDPWpre;
case AArch64::LDPXi:
return AArch64::LDPXpre;
case AArch64::STPSi:
return AArch64::STPSpre;
case AArch64::STPDi:
return AArch64::STPDpre;
case AArch64::STPQi:
return AArch64::STPQpre;
case AArch64::STPWi:
return AArch64::STPWpre;
case AArch64::STPXi:
return AArch64::STPXpre;
case AArch64::STGOffset:
return AArch64::STGPreIndex;
case AArch64::STZGOffset:
return AArch64::STZGPreIndex;
case AArch64::ST2GOffset:
return AArch64::ST2GPreIndex;
case AArch64::STZ2GOffset:
return AArch64::STZ2GPreIndex;
case AArch64::STGPi:
return AArch64::STGPpre;
}
}
static unsigned getPostIndexedOpcode(unsigned Opc) {
switch (Opc) {
default:
llvm_unreachable("Opcode has no post-indexed wise equivalent!");
case AArch64::STRSui:
case AArch64::STURSi:
return AArch64::STRSpost;
case AArch64::STRDui:
case AArch64::STURDi:
return AArch64::STRDpost;
case AArch64::STRQui:
case AArch64::STURQi:
return AArch64::STRQpost;
case AArch64::STRBBui:
return AArch64::STRBBpost;
case AArch64::STRHHui:
return AArch64::STRHHpost;
case AArch64::STRWui:
case AArch64::STURWi:
return AArch64::STRWpost;
case AArch64::STRXui:
case AArch64::STURXi:
return AArch64::STRXpost;
case AArch64::LDRSui:
case AArch64::LDURSi:
return AArch64::LDRSpost;
case AArch64::LDRDui:
case AArch64::LDURDi:
return AArch64::LDRDpost;
case AArch64::LDRQui:
case AArch64::LDURQi:
return AArch64::LDRQpost;
case AArch64::LDRBBui:
return AArch64::LDRBBpost;
case AArch64::LDRHHui:
return AArch64::LDRHHpost;
case AArch64::LDRWui:
case AArch64::LDURWi:
return AArch64::LDRWpost;
case AArch64::LDRXui:
case AArch64::LDURXi:
return AArch64::LDRXpost;
case AArch64::LDRSWui:
return AArch64::LDRSWpost;
case AArch64::LDPSi:
return AArch64::LDPSpost;
case AArch64::LDPSWi:
return AArch64::LDPSWpost;
case AArch64::LDPDi:
return AArch64::LDPDpost;
case AArch64::LDPQi:
return AArch64::LDPQpost;
case AArch64::LDPWi:
return AArch64::LDPWpost;
case AArch64::LDPXi:
return AArch64::LDPXpost;
case AArch64::STPSi:
return AArch64::STPSpost;
case AArch64::STPDi:
return AArch64::STPDpost;
case AArch64::STPQi:
return AArch64::STPQpost;
case AArch64::STPWi:
return AArch64::STPWpost;
case AArch64::STPXi:
return AArch64::STPXpost;
case AArch64::STGOffset:
return AArch64::STGPostIndex;
case AArch64::STZGOffset:
return AArch64::STZGPostIndex;
case AArch64::ST2GOffset:
return AArch64::ST2GPostIndex;
case AArch64::STZ2GOffset:
return AArch64::STZ2GPostIndex;
case AArch64::STGPi:
return AArch64::STGPpost;
}
}
static bool isPreLdStPairCandidate(MachineInstr &FirstMI, MachineInstr &MI) {
unsigned OpcA = FirstMI.getOpcode();
unsigned OpcB = MI.getOpcode();
switch (OpcA) {
default:
return false;
case AArch64::STRSpre:
return (OpcB == AArch64::STRSui) || (OpcB == AArch64::STURSi);
case AArch64::STRDpre:
return (OpcB == AArch64::STRDui) || (OpcB == AArch64::STURDi);
case AArch64::STRQpre:
return (OpcB == AArch64::STRQui) || (OpcB == AArch64::STURQi);
case AArch64::STRWpre:
return (OpcB == AArch64::STRWui) || (OpcB == AArch64::STURWi);
case AArch64::STRXpre:
return (OpcB == AArch64::STRXui) || (OpcB == AArch64::STURXi);
case AArch64::LDRSpre:
return (OpcB == AArch64::LDRSui) || (OpcB == AArch64::LDURSi);
case AArch64::LDRDpre:
return (OpcB == AArch64::LDRDui) || (OpcB == AArch64::LDURDi);
case AArch64::LDRQpre:
return (OpcB == AArch64::LDRQui) || (OpcB == AArch64::LDURQi);
case AArch64::LDRWpre:
return (OpcB == AArch64::LDRWui) || (OpcB == AArch64::LDURWi);
case AArch64::LDRXpre:
return (OpcB == AArch64::LDRXui) || (OpcB == AArch64::LDURXi);
}
}
static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
int &MinOffset, int &MaxOffset) {
bool IsPaired = AArch64InstrInfo::isPairedLdSt(MI);
bool IsTagStore = isTagStore(MI);
Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
if (IsPaired) {
MinOffset = -64;
MaxOffset = 63;
} else {
MinOffset = -256;
MaxOffset = 255;
}
}
static MachineOperand &getLdStRegOp(MachineInstr &MI,
unsigned PairedRegOp = 0) {
assert(PairedRegOp < 2 && "Unexpected register operand idx.");
bool IsPreLdSt = AArch64InstrInfo::isPreLdSt(MI);
if (IsPreLdSt)
PairedRegOp += 1;
unsigned Idx =
AArch64InstrInfo::isPairedLdSt(MI) || IsPreLdSt ? PairedRegOp : 0;
return MI.getOperand(Idx);
}
static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
MachineInstr &StoreInst,
const AArch64InstrInfo *TII) {
assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
int LoadSize = TII->getMemScale(LoadInst);
int StoreSize = TII->getMemScale(StoreInst);
int UnscaledStOffset =
TII->hasUnscaledLdStOffset(StoreInst)
? AArch64InstrInfo::getLdStOffsetOp(StoreInst).getImm()
: AArch64InstrInfo::getLdStOffsetOp(StoreInst).getImm() * StoreSize;
int UnscaledLdOffset =
TII->hasUnscaledLdStOffset(LoadInst)
? AArch64InstrInfo::getLdStOffsetOp(LoadInst).getImm()
: AArch64InstrInfo::getLdStOffsetOp(LoadInst).getImm() * LoadSize;
return (UnscaledStOffset <= UnscaledLdOffset) &&
(UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
}
static bool isPromotableZeroStoreInst(MachineInstr &MI) {
unsigned Opc = MI.getOpcode();
return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
isNarrowStore(Opc)) &&
getLdStRegOp(MI).getReg() == AArch64::WZR;
}
static bool isPromotableLoadFromStore(MachineInstr &MI) {
switch (MI.getOpcode()) {
default:
return false;
case AArch64::LDRBBui:
case AArch64::LDRHHui:
case AArch64::LDRWui:
case AArch64::LDRXui:
case AArch64::LDURBBi:
case AArch64::LDURHHi:
case AArch64::LDURWi:
case AArch64::LDURXi:
return true;
}
}
static bool isMergeableLdStUpdate(MachineInstr &MI) {
unsigned Opc = MI.getOpcode();
switch (Opc) {
default:
return false;
case AArch64::STRSui:
case AArch64::STRDui:
case AArch64::STRQui:
case AArch64::STRXui:
case AArch64::STRWui:
case AArch64::STRHHui:
case AArch64::STRBBui:
case AArch64::LDRSui:
case AArch64::LDRDui:
case AArch64::LDRQui:
case AArch64::LDRXui:
case AArch64::LDRWui:
case AArch64::LDRHHui:
case AArch64::LDRBBui:
case AArch64::STGOffset:
case AArch64::STZGOffset:
case AArch64::ST2GOffset:
case AArch64::STZ2GOffset:
case AArch64::STGPi:
case AArch64::STURSi:
case AArch64::STURDi:
case AArch64::STURQi:
case AArch64::STURWi:
case AArch64::STURXi:
case AArch64::LDURSi:
case AArch64::LDURDi:
case AArch64::LDURQi:
case AArch64::LDURWi:
case AArch64::LDURXi:
case AArch64::LDPSi:
case AArch64::LDPSWi:
case AArch64::LDPDi:
case AArch64::LDPQi:
case AArch64::LDPWi:
case AArch64::LDPXi:
case AArch64::STPSi:
case AArch64::STPDi:
case AArch64::STPQi:
case AArch64::STPWi:
case AArch64::STPXi:
if (!AArch64InstrInfo::getLdStOffsetOp(MI).isImm())
return false;
return true;
}
}
MachineBasicBlock::iterator
AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator MergeMI,
const LdStPairFlags &Flags) {
assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
"Expected promotable zero stores.");
MachineBasicBlock::iterator E = I->getParent()->end();
MachineBasicBlock::iterator NextI = next_nodbg(I, E);
if (NextI == MergeMI)
NextI = next_nodbg(NextI, E);
unsigned Opc = I->getOpcode();
bool IsScaled = !TII->hasUnscaledLdStOffset(Opc);
int OffsetStride = IsScaled ? 1 : TII->getMemScale(*I);
bool MergeForward = Flags.getMergeForward();
MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
const MachineOperand &BaseRegOp =
MergeForward ? AArch64InstrInfo::getLdStBaseOp(*MergeMI)
: AArch64InstrInfo::getLdStBaseOp(*I);
MachineInstr *RtMI;
if (AArch64InstrInfo::getLdStOffsetOp(*I).getImm() ==
AArch64InstrInfo::getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
RtMI = &*MergeMI;
else
RtMI = &*I;
int OffsetImm = AArch64InstrInfo::getLdStOffsetOp(*RtMI).getImm();
if (IsScaled) {
assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
OffsetImm /= 2;
}
DebugLoc DL = I->getDebugLoc();
MachineBasicBlock *MBB = I->getParent();
MachineInstrBuilder MIB;
MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
.addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
.add(BaseRegOp)
.addImm(OffsetImm)
.cloneMergedMemRefs({&*I, &*MergeMI})
.setMIFlags(I->mergeFlagsWith(*MergeMI));
(void)MIB;
LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
LLVM_DEBUG(I->print(dbgs()));
LLVM_DEBUG(dbgs() << " ");
LLVM_DEBUG(MergeMI->print(dbgs()));
LLVM_DEBUG(dbgs() << " with instruction:\n ");
LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
I->eraseFromParent();
MergeMI->eraseFromParent();
return NextI;
}
static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg,
const TargetRegisterInfo *TRI, unsigned Limit,
std::function<bool(MachineInstr &, bool)> &Fn) {
auto MBB = MI.getParent();
for (MachineInstr &I :
instructionsWithoutDebug(MI.getReverseIterator(), MBB->instr_rend())) {
if (!Limit)
return false;
--Limit;
bool isDef = any_of(I.operands(), [DefReg, TRI](MachineOperand &MOP) {
return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
TRI->regsOverlap(MOP.getReg(), DefReg);
});
if (!Fn(I, isDef))
return false;
if (isDef)
break;
}
return true;
}
static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
const TargetRegisterInfo *TRI) {
for (const MachineOperand &MOP : phys_regs_and_masks(MI))
if (MOP.isReg() && MOP.isKill())
Units.removeReg(MOP.getReg());
for (const MachineOperand &MOP : phys_regs_and_masks(MI))
if (MOP.isReg() && !MOP.isKill())
Units.addReg(MOP.getReg());
}
MachineBasicBlock::iterator
AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator Paired,
const LdStPairFlags &Flags) {
MachineBasicBlock::iterator E = I->getParent()->end();
MachineBasicBlock::iterator NextI = next_nodbg(I, E);
if (NextI == Paired)
NextI = next_nodbg(NextI, E);
int SExtIdx = Flags.getSExtIdx();
unsigned Opc =
SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
bool IsUnscaled = TII->hasUnscaledLdStOffset(Opc);
int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
bool MergeForward = Flags.getMergeForward();
Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
if (MergeForward && RenameReg) {
MCRegister RegToRename = getLdStRegOp(*I).getReg();
DefinedInBB.addReg(*RenameReg);
auto GetMatchingSubReg = [this,
RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
if (TRI->getMinimalPhysRegClass(OriginalReg) ==
TRI->getMinimalPhysRegClass(SubOrSuper))
return SubOrSuper;
llvm_unreachable("Should have found matching sub or super register!");
};
std::function<bool(MachineInstr &, bool)> UpdateMIs =
[this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
if (IsDef) {
bool SeenDef = false;
for (auto &MOP : MI.operands()) {
if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
(!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
TRI->regsOverlap(MOP.getReg(), RegToRename)) {
assert((MOP.isImplicit() ||
(MOP.isRenamable() && !MOP.isEarlyClobber())) &&
"Need renamable operands");
MOP.setReg(GetMatchingSubReg(MOP.getReg()));
SeenDef = true;
}
}
} else {
for (auto &MOP : MI.operands()) {
if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
TRI->regsOverlap(MOP.getReg(), RegToRename)) {
assert((MOP.isImplicit() ||
(MOP.isRenamable() && !MOP.isEarlyClobber())) &&
"Need renamable operands");
MOP.setReg(GetMatchingSubReg(MOP.getReg()));
}
}
}
LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
return true;
};
forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
#if !defined(NDEBUG)
for (auto &MI :
iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
std::next(I), std::next(Paired)))
assert(all_of(MI.operands(),
[this, &RenameReg](const MachineOperand &MOP) {
return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
MOP.isUndef() ||
!TRI->regsOverlap(MOP.getReg(), *RenameReg);
}) &&
"Rename register used between paired instruction, trashing the "
"content");
#endif
}
MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
const MachineOperand &BaseRegOp =
MergeForward ? AArch64InstrInfo::getLdStBaseOp(*Paired)
: AArch64InstrInfo::getLdStBaseOp(*I);
int Offset = AArch64InstrInfo::getLdStOffsetOp(*I).getImm();
int PairedOffset = AArch64InstrInfo::getLdStOffsetOp(*Paired).getImm();
bool PairedIsUnscaled = TII->hasUnscaledLdStOffset(Paired->getOpcode());
if (IsUnscaled != PairedIsUnscaled) {
int MemSize = TII->getMemScale(*Paired);
if (PairedIsUnscaled) {
assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
"Offset should be a multiple of the stride!");
PairedOffset /= MemSize;
} else {
PairedOffset *= MemSize;
}
}
MachineInstr *RtMI, *Rt2MI;
if (Offset == PairedOffset + OffsetStride &&
!AArch64InstrInfo::isPreLdSt(*I)) {
RtMI = &*Paired;
Rt2MI = &*I;
if (SExtIdx != -1)
SExtIdx = (SExtIdx + 1) % 2;
} else {
RtMI = &*I;
Rt2MI = &*Paired;
}
int OffsetImm = AArch64InstrInfo::getLdStOffsetOp(*RtMI).getImm();
if (TII->hasUnscaledLdStOffset(RtMI->getOpcode())) {
assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
"Unscaled offset cannot be scaled.");
OffsetImm /= TII->getMemScale(*RtMI);
}
MachineInstrBuilder MIB;
DebugLoc DL = I->getDebugLoc();
MachineBasicBlock *MBB = I->getParent();
MachineOperand RegOp0 = getLdStRegOp(*RtMI);
MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
if (RegOp0.isUse()) {
if (!MergeForward) {
RegOp0.setIsKill(false);
RegOp1.setIsKill(false);
} else {
Register Reg = getLdStRegOp(*I).getReg();
for (MachineInstr &MI : make_range(std::next(I), Paired))
MI.clearRegisterKills(Reg, TRI);
}
}
unsigned int MatchPairOpcode = getMatchingPairOpcode(Opc);
MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(MatchPairOpcode));
if (AArch64InstrInfo::isPreLdSt(*RtMI))
MIB.addReg(BaseRegOp.getReg(), RegState::Define);
MIB.add(RegOp0)
.add(RegOp1)
.add(BaseRegOp)
.addImm(OffsetImm)
.cloneMergedMemRefs({&*I, &*Paired})
.setMIFlags(I->mergeFlagsWith(*Paired));
(void)MIB;
LLVM_DEBUG(
dbgs() << "Creating pair load/store. Replacing instructions:\n ");
LLVM_DEBUG(I->print(dbgs()));
LLVM_DEBUG(dbgs() << " ");
LLVM_DEBUG(Paired->print(dbgs()));
LLVM_DEBUG(dbgs() << " with instruction:\n ");
if (SExtIdx != -1) {
MachineOperand &DstMO = MIB->getOperand(SExtIdx);
Register DstRegX = DstMO.getReg();
Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
DstMO.setReg(DstRegW);
LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
MachineInstrBuilder MIBKill =
BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
.addReg(DstRegW)
.addReg(DstRegX, RegState::Define);
MIBKill->getOperand(2).setImplicit();
MachineInstrBuilder MIBSXTW =
BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
.addReg(DstRegX)
.addImm(0)
.addImm(31);
(void)MIBSXTW;
LLVM_DEBUG(dbgs() << " Extend operand:\n ");
LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
} else {
LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
}
LLVM_DEBUG(dbgs() << "\n");
if (MergeForward)
for (const MachineOperand &MOP : phys_regs_and_masks(*I))
if (MOP.isReg() && MOP.isKill())
DefinedInBB.addReg(MOP.getReg());
I->eraseFromParent();
Paired->eraseFromParent();
return NextI;
}
MachineBasicBlock::iterator
AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
MachineBasicBlock::iterator StoreI) {
MachineBasicBlock::iterator NextI =
next_nodbg(LoadI, LoadI->getParent()->end());
int LoadSize = TII->getMemScale(*LoadI);
int StoreSize = TII->getMemScale(*StoreI);
Register LdRt = getLdStRegOp(*LoadI).getReg();
const MachineOperand &StMO = getLdStRegOp(*StoreI);
Register StRt = getLdStRegOp(*StoreI).getReg();
bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
assert((IsStoreXReg ||
TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
"Unexpected RegClass");
MachineInstr *BitExtMI;
if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
if (StRt == LdRt && LoadSize == 8) {
for (MachineInstr &MI : make_range(StoreI->getIterator(),
LoadI->getIterator())) {
if (MI.killsRegister(StRt, TRI)) {
MI.clearRegisterKills(StRt, TRI);
break;
}
}
LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
LLVM_DEBUG(LoadI->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
LoadI->eraseFromParent();
return NextI;
}
BitExtMI =
BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
.addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
.add(StMO)
.addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
.setMIFlags(LoadI->getFlags());
} else {
if (!Subtarget->isLittleEndian())
return NextI;
bool IsUnscaled = TII->hasUnscaledLdStOffset(*LoadI);
assert(IsUnscaled == TII->hasUnscaledLdStOffset(*StoreI) &&
"Unsupported ld/st match");
assert(LoadSize <= StoreSize && "Invalid load size");
int UnscaledLdOffset =
IsUnscaled
? AArch64InstrInfo::getLdStOffsetOp(*LoadI).getImm()
: AArch64InstrInfo::getLdStOffsetOp(*LoadI).getImm() * LoadSize;
int UnscaledStOffset =
IsUnscaled
? AArch64InstrInfo::getLdStOffsetOp(*StoreI).getImm()
: AArch64InstrInfo::getLdStOffsetOp(*StoreI).getImm() * StoreSize;
int Width = LoadSize * 8;
Register DestReg =
IsStoreXReg ? Register(TRI->getMatchingSuperReg(
LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
: LdRt;
assert((UnscaledLdOffset >= UnscaledStOffset &&
(UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
"Invalid offset");
int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
int Imms = Immr + Width - 1;
if (UnscaledLdOffset == UnscaledStOffset) {
uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) | ((Immr) << 6) | ((Imms) << 0) ;
BitExtMI =
BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
DestReg)
.add(StMO)
.addImm(AndMaskEncoded)
.setMIFlags(LoadI->getFlags());
} else {
BitExtMI =
BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
DestReg)
.add(StMO)
.addImm(Immr)
.addImm(Imms)
.setMIFlags(LoadI->getFlags());
}
}
for (MachineInstr &MI : make_range(StoreI->getIterator(),
BitExtMI->getIterator()))
if (MI.killsRegister(StRt, TRI)) {
MI.clearRegisterKills(StRt, TRI);
break;
}
LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
LLVM_DEBUG(StoreI->print(dbgs()));
LLVM_DEBUG(dbgs() << " ");
LLVM_DEBUG(LoadI->print(dbgs()));
LLVM_DEBUG(dbgs() << " with instructions:\n ");
LLVM_DEBUG(StoreI->print(dbgs()));
LLVM_DEBUG(dbgs() << " ");
LLVM_DEBUG((BitExtMI)->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
LoadI->eraseFromParent();
return NextI;
}
static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
if (IsUnscaled) {
if (Offset % OffsetStride)
return false;
Offset /= OffsetStride;
}
return Offset <= 63 && Offset >= -64;
}
static int alignTo(int Num, int PowOf2) {
return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
}
static bool mayAlias(MachineInstr &MIa,
SmallVectorImpl<MachineInstr *> &MemInsns,
AliasAnalysis *AA) {
for (MachineInstr *MIb : MemInsns)
if (MIa.mayAlias(AA, *MIb, false))
return true;
return false;
}
bool AArch64LoadStoreOpt::findMatchingStore(
MachineBasicBlock::iterator I, unsigned Limit,
MachineBasicBlock::iterator &StoreI) {
MachineBasicBlock::iterator B = I->getParent()->begin();
MachineBasicBlock::iterator MBBI = I;
MachineInstr &LoadMI = *I;
Register BaseReg = AArch64InstrInfo::getLdStBaseOp(LoadMI).getReg();
if (MBBI == B)
return false;
ModifiedRegUnits.clear();
UsedRegUnits.clear();
unsigned Count = 0;
do {
MBBI = prev_nodbg(MBBI, B);
MachineInstr &MI = *MBBI;
if (!MI.isTransient())
++Count;
if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
BaseReg == AArch64InstrInfo::getLdStBaseOp(MI).getReg() &&
AArch64InstrInfo::getLdStOffsetOp(MI).isImm() &&
isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
StoreI = MBBI;
return true;
}
if (MI.isCall())
return false;
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
if (!ModifiedRegUnits.available(BaseReg))
return false;
if (MI.mayStore() && LoadMI.mayAlias(AA, MI, false))
return false;
} while (MBBI != B && Count < Limit);
return false;
}
static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
LdStPairFlags &Flags,
const AArch64InstrInfo *TII) {
if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
return false;
assert(!FirstMI.hasOrderedMemoryRef() &&
!TII->isLdStPairSuppressed(FirstMI) &&
"FirstMI shouldn't get here if either of these checks are true.");
unsigned OpcA = FirstMI.getOpcode();
unsigned OpcB = MI.getOpcode();
if (OpcA == OpcB)
return !AArch64InstrInfo::isPreLdSt(FirstMI);
bool IsValidLdStrOpc, PairIsValidLdStrOpc;
unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
assert(IsValidLdStrOpc &&
"Given Opc should be a Load or Store with an immediate");
if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
return true;
}
if (!PairIsValidLdStrOpc)
return false;
if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
return false;
if (isPreLdStPairCandidate(FirstMI, MI))
return true;
return TII->hasUnscaledLdStOffset(OpcA) != TII->hasUnscaledLdStOffset(OpcB) &&
getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
}
static bool
canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
const TargetRegisterInfo *TRI) {
if (!FirstMI.mayStore())
return false;
auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
MachineFunction &MF = *FirstMI.getParent()->getParent();
if (!RegClass || !MF.getRegInfo().tracksLiveness())
return false;
auto RegToRename = getLdStRegOp(FirstMI).getReg();
if (!getLdStRegOp(FirstMI).isKill() &&
!any_of(FirstMI.operands(),
[TRI, RegToRename](const MachineOperand &MOP) {
return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
MOP.isImplicit() && MOP.isKill() &&
TRI->regsOverlap(RegToRename, MOP.getReg());
})) {
LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI << "\n");
return false;
}
auto canRenameMOP = [TRI](const MachineOperand &MOP) {
if (MOP.isReg()) {
auto *RegClass = TRI->getMinimalPhysRegClass(MOP.getReg());
if (RegClass->HasDisjunctSubRegs) {
LLVM_DEBUG(
dbgs()
<< " Cannot rename operands with multiple disjunct subregisters ("
<< MOP << ")\n");
return false;
}
}
return MOP.isImplicit() ||
(MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
};
bool FoundDef = false;
std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
bool IsDef) {
LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
if (MI.getFlag(MachineInstr::FrameSetup)) {
LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions currently ("
<< MI << ")\n");
return false;
}
UsedInBetween.accumulate(MI);
FoundDef = IsDef;
if (FoundDef) {
if (MI.isPseudo()) {
LLVM_DEBUG(dbgs() << " Cannot rename pseudo instruction " << MI
<< "\n");
return false;
}
for (auto &MOP : MI.operands()) {
if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
!TRI->regsOverlap(MOP.getReg(), RegToRename))
continue;
if (!canRenameMOP(MOP)) {
LLVM_DEBUG(dbgs()
<< " Cannot rename " << MOP << " in " << MI << "\n");
return false;
}
RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
}
return true;
} else {
for (auto &MOP : MI.operands()) {
if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
!TRI->regsOverlap(MOP.getReg(), RegToRename))
continue;
if (!canRenameMOP(MOP)) {
LLVM_DEBUG(dbgs()
<< " Cannot rename " << MOP << " in " << MI << "\n");
return false;
}
RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
}
}
return true;
};
if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
return false;
if (!FoundDef) {
LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
return false;
}
return true;
}
static Optional<MCPhysReg> tryToFindRegisterToRename(
const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB,
LiveRegUnits &UsedInBetween,
SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
const TargetRegisterInfo *TRI) {
const MachineRegisterInfo &RegInfo = MF.getRegInfo();
auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
return any_of(TRI->sub_and_superregs_inclusive(PR),
[&MF, TRI](MCPhysReg SubOrSuper) {
return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
});
};
auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
return any_of(TRI->sub_and_superregs_inclusive(PR),
[C, TRI](MCPhysReg SubOrSuper) {
return C == TRI->getMinimalPhysRegClass(SubOrSuper);
});
});
};
auto *RegClass = TRI->getMinimalPhysRegClass(Reg);
for (const MCPhysReg &PR : *RegClass) {
if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
!RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
CanBeUsedForAllClasses(PR)) {
DefinedInBB.addReg(PR);
LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
<< "\n");
return {PR};
}
}
LLVM_DEBUG(dbgs() << "No rename register found from "
<< TRI->getRegClassName(RegClass) << "\n");
return None;
}
MachineBasicBlock::iterator
AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
LdStPairFlags &Flags, unsigned Limit,
bool FindNarrowMerge) {
MachineBasicBlock::iterator E = I->getParent()->end();
MachineBasicBlock::iterator MBBI = I;
MachineBasicBlock::iterator MBBIWithRenameReg;
MachineInstr &FirstMI = *I;
MBBI = next_nodbg(MBBI, E);
bool MayLoad = FirstMI.mayLoad();
bool IsUnscaled = TII->hasUnscaledLdStOffset(FirstMI);
Register Reg = getLdStRegOp(FirstMI).getReg();
Register BaseReg = AArch64InstrInfo::getLdStBaseOp(FirstMI).getReg();
int Offset = AArch64InstrInfo::getLdStOffsetOp(FirstMI).getImm();
int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Optional<bool> MaybeCanRename = None;
if (!EnableRenaming)
MaybeCanRename = {false};
SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
LiveRegUnits UsedInBetween;
UsedInBetween.init(*TRI);
Flags.clearRenameReg();
ModifiedRegUnits.clear();
UsedRegUnits.clear();
SmallVector<MachineInstr *, 4> MemInsns;
for (unsigned Count = 0; MBBI != E && Count < Limit;
MBBI = next_nodbg(MBBI, E)) {
MachineInstr &MI = *MBBI;
UsedInBetween.accumulate(MI);
if (!MI.isTransient())
++Count;
Flags.setSExtIdx(-1);
if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
AArch64InstrInfo::getLdStOffsetOp(MI).isImm()) {
assert(MI.mayLoadOrStore() && "Expected memory operation.");
Register MIBaseReg = AArch64InstrInfo::getLdStBaseOp(MI).getReg();
int MIOffset = AArch64InstrInfo::getLdStOffsetOp(MI).getImm();
bool MIIsUnscaled = TII->hasUnscaledLdStOffset(MI);
if (IsUnscaled != MIIsUnscaled) {
int MemSize = TII->getMemScale(MI);
if (MIIsUnscaled) {
if (MIOffset % MemSize) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
MIOffset /= MemSize;
} else {
MIOffset *= MemSize;
}
}
bool IsPreLdSt = isPreLdStPairCandidate(FirstMI, MI);
if (BaseReg == MIBaseReg) {
if (IsPreLdSt) {
bool IsOutOfBounds = MIOffset != TII->getMemScale(MI);
bool IsBaseRegUsed = !UsedRegUnits.available(
AArch64InstrInfo::getLdStBaseOp(MI).getReg());
bool IsBaseRegModified = !ModifiedRegUnits.available(
AArch64InstrInfo::getLdStBaseOp(MI).getReg());
bool IsMIRegTheSame =
TRI->regsOverlap(getLdStRegOp(MI).getReg(),
AArch64InstrInfo::getLdStBaseOp(MI).getReg());
if (IsOutOfBounds || IsBaseRegUsed || IsBaseRegModified ||
IsMIRegTheSame) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
} else {
if ((Offset != MIOffset + OffsetStride) &&
(Offset + OffsetStride != MIOffset)) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
}
int MinOffset = Offset < MIOffset ? Offset : MIOffset;
if (FindNarrowMerge) {
if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
(IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
} else {
if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
UsedRegUnits, TRI);
MemInsns.push_back(&MI);
continue;
}
}
if (MayLoad &&
TRI->isSuperOrSubRegisterEq(Reg, getLdStRegOp(MI).getReg())) {
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
TRI);
MemInsns.push_back(&MI);
continue;
}
if (!ModifiedRegUnits.available(BaseReg))
return E;
if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
!(MI.mayLoad() &&
!UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
!mayAlias(MI, MemInsns, AA)) {
Flags.setMergeForward(false);
Flags.clearRenameReg();
return MBBI;
}
if (!(MayLoad &&
!UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
!mayAlias(FirstMI, MemInsns, AA)) {
if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
Flags.setMergeForward(true);
Flags.clearRenameReg();
return MBBI;
}
if (DebugCounter::shouldExecute(RegRenamingCounter)) {
if (!MaybeCanRename)
MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
RequiredClasses, TRI)};
if (*MaybeCanRename) {
Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
*FirstMI.getParent()->getParent(), Reg, DefinedInBB,
UsedInBetween, RequiredClasses, TRI);
if (MaybeRenameReg) {
Flags.setRenameReg(*MaybeRenameReg);
Flags.setMergeForward(true);
MBBIWithRenameReg = MBBI;
}
}
}
}
}
}
if (Flags.getRenameReg())
return MBBIWithRenameReg;
if (MI.isCall())
return E;
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
if (!ModifiedRegUnits.available(BaseReg))
return E;
if (MI.mayLoadOrStore())
MemInsns.push_back(&MI);
}
return E;
}
static MachineBasicBlock::iterator
maybeMoveCFI(MachineInstr &MI, MachineBasicBlock::iterator MaybeCFI) {
auto End = MI.getParent()->end();
if (MaybeCFI == End ||
MaybeCFI->getOpcode() != TargetOpcode::CFI_INSTRUCTION ||
!(MI.getFlag(MachineInstr::FrameSetup) ||
MI.getFlag(MachineInstr::FrameDestroy)) ||
AArch64InstrInfo::getLdStBaseOp(MI).getReg() != AArch64::SP)
return End;
const MachineFunction &MF = *MI.getParent()->getParent();
unsigned CFIIndex = MaybeCFI->getOperand(0).getCFIIndex();
const MCCFIInstruction &CFI = MF.getFrameInstructions()[CFIIndex];
switch (CFI.getOperation()) {
case MCCFIInstruction::OpDefCfa:
case MCCFIInstruction::OpDefCfaOffset:
return MaybeCFI;
default:
return End;
}
}
MachineBasicBlock::iterator
AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator Update,
bool IsPreIdx) {
assert((Update->getOpcode() == AArch64::ADDXri ||
Update->getOpcode() == AArch64::SUBXri) &&
"Unexpected base register update instruction to merge!");
MachineBasicBlock::iterator E = I->getParent()->end();
MachineBasicBlock::iterator NextI = next_nodbg(I, E);
MachineBasicBlock::iterator CFI =
IsPreIdx ? maybeMoveCFI(*Update, next_nodbg(Update, E)) : E;
if (NextI == Update)
NextI = next_nodbg(NextI, E);
int Value = Update->getOperand(2).getImm();
assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
"Can't merge 1 << 12 offset into pre-/post-indexed load / store");
if (Update->getOpcode() == AArch64::SUBXri)
Value = -Value;
unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
: getPostIndexedOpcode(I->getOpcode());
MachineInstrBuilder MIB;
int Scale, MinOffset, MaxOffset;
getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
if (!AArch64InstrInfo::isPairedLdSt(*I)) {
MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
.add(getLdStRegOp(*Update))
.add(getLdStRegOp(*I))
.add(AArch64InstrInfo::getLdStBaseOp(*I))
.addImm(Value / Scale)
.setMemRefs(I->memoperands())
.setMIFlags(I->mergeFlagsWith(*Update));
} else {
MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
.add(getLdStRegOp(*Update))
.add(getLdStRegOp(*I, 0))
.add(getLdStRegOp(*I, 1))
.add(AArch64InstrInfo::getLdStBaseOp(*I))
.addImm(Value / Scale)
.setMemRefs(I->memoperands())
.setMIFlags(I->mergeFlagsWith(*Update));
}
if (CFI != E) {
MachineBasicBlock *MBB = I->getParent();
MBB->splice(std::next(MIB.getInstr()->getIterator()), MBB, CFI);
}
if (IsPreIdx) {
++NumPreFolded;
LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
} else {
++NumPostFolded;
LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
}
LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
LLVM_DEBUG(I->print(dbgs()));
LLVM_DEBUG(dbgs() << " ");
LLVM_DEBUG(Update->print(dbgs()));
LLVM_DEBUG(dbgs() << " with instruction:\n ");
LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
LLVM_DEBUG(dbgs() << "\n");
I->eraseFromParent();
Update->eraseFromParent();
return NextI;
}
bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
MachineInstr &MI,
unsigned BaseReg, int Offset) {
switch (MI.getOpcode()) {
default:
break;
case AArch64::SUBXri:
case AArch64::ADDXri:
if (!MI.getOperand(2).isImm())
break;
if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
break;
if (MI.getOperand(0).getReg() != BaseReg ||
MI.getOperand(1).getReg() != BaseReg)
break;
int UpdateOffset = MI.getOperand(2).getImm();
if (MI.getOpcode() == AArch64::SUBXri)
UpdateOffset = -UpdateOffset;
int Scale, MinOffset, MaxOffset;
getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
if (UpdateOffset % Scale != 0)
break;
int ScaledOffset = UpdateOffset / Scale;
if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
break;
if (!Offset || Offset == UpdateOffset)
return true;
break;
}
return false;
}
static bool needsWinCFI(const MachineFunction *MF) {
return MF->getTarget().getMCAsmInfo()->usesWindowsCFI() &&
MF->getFunction().needsUnwindTableEntry();
}
MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
MachineBasicBlock::iterator E = I->getParent()->end();
MachineInstr &MemMI = *I;
MachineBasicBlock::iterator MBBI = I;
Register BaseReg = AArch64InstrInfo::getLdStBaseOp(MemMI).getReg();
int MIUnscaledOffset = AArch64InstrInfo::getLdStOffsetOp(MemMI).getImm() *
TII->getMemScale(MemMI);
if (MIUnscaledOffset != UnscaledOffset)
return E;
if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
Register DestReg = getLdStRegOp(MemMI, i).getReg();
if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
return E;
}
}
ModifiedRegUnits.clear();
UsedRegUnits.clear();
MBBI = next_nodbg(MBBI, E);
const bool BaseRegSP = BaseReg == AArch64::SP;
if (BaseRegSP && needsWinCFI(I->getMF())) {
return E;
}
for (unsigned Count = 0; MBBI != E && Count < Limit;
MBBI = next_nodbg(MBBI, E)) {
MachineInstr &MI = *MBBI;
if (!MI.isTransient())
++Count;
if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
return MBBI;
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
if (!ModifiedRegUnits.available(BaseReg) ||
!UsedRegUnits.available(BaseReg) ||
(BaseRegSP && MBBI->mayLoadOrStore()))
return E;
}
return E;
}
MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
MachineBasicBlock::iterator I, unsigned Limit) {
MachineBasicBlock::iterator B = I->getParent()->begin();
MachineBasicBlock::iterator E = I->getParent()->end();
MachineInstr &MemMI = *I;
MachineBasicBlock::iterator MBBI = I;
MachineFunction &MF = *MemMI.getMF();
Register BaseReg = AArch64InstrInfo::getLdStBaseOp(MemMI).getReg();
int Offset = AArch64InstrInfo::getLdStOffsetOp(MemMI).getImm();
if (MBBI == B || Offset != 0)
return E;
if (!isTagStore(MemMI)) {
bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
Register DestReg = getLdStRegOp(MemMI, i).getReg();
if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
return E;
}
}
const bool BaseRegSP = BaseReg == AArch64::SP;
if (BaseRegSP && needsWinCFI(I->getMF())) {
return E;
}
const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
unsigned RedZoneSize =
Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
ModifiedRegUnits.clear();
UsedRegUnits.clear();
unsigned Count = 0;
bool MemAcessBeforeSPPreInc = false;
do {
MBBI = prev_nodbg(MBBI, B);
MachineInstr &MI = *MBBI;
if (!MI.isTransient())
++Count;
if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset)) {
if (MemAcessBeforeSPPreInc && MBBI->getOperand(2).getImm() > RedZoneSize)
return E;
return MBBI;
}
LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
if (!ModifiedRegUnits.available(BaseReg) ||
!UsedRegUnits.available(BaseReg))
return E;
if (BaseRegSP && MBBI->mayLoadOrStore())
MemAcessBeforeSPPreInc = true;
} while (MBBI != B && Count < Limit);
return E;
}
bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
MachineBasicBlock::iterator &MBBI) {
MachineInstr &MI = *MBBI;
if (MI.hasOrderedMemoryRef())
return false;
if (!AArch64InstrInfo::getLdStOffsetOp(MI).isImm())
return false;
MachineBasicBlock::iterator StoreI;
if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
++NumLoadsFromStoresPromoted;
MBBI = promoteLoadFromStore(MBBI, StoreI);
return true;
}
return false;
}
bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
MachineBasicBlock::iterator &MBBI) {
assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
MachineInstr &MI = *MBBI;
MachineBasicBlock::iterator E = MI.getParent()->end();
if (!TII->isCandidateToMergeOrPair(MI))
return false;
LdStPairFlags Flags;
MachineBasicBlock::iterator MergeMI =
findMatchingInsn(MBBI, Flags, LdStLimit, true);
if (MergeMI != E) {
++NumZeroStoresPromoted;
MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
return true;
}
return false;
}
bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
MachineInstr &MI = *MBBI;
MachineBasicBlock::iterator E = MI.getParent()->end();
if (!TII->isCandidateToMergeOrPair(MI))
return false;
bool IsUnscaled = TII->hasUnscaledLdStOffset(MI);
int Offset = AArch64InstrInfo::getLdStOffsetOp(MI).getImm();
int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
if (Offset > 0)
Offset -= OffsetStride;
if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
return false;
LdStPairFlags Flags;
MachineBasicBlock::iterator Paired =
findMatchingInsn(MBBI, Flags, LdStLimit, false);
if (Paired != E) {
++NumPairCreated;
if (TII->hasUnscaledLdStOffset(MI))
++NumUnscaledPairCreated;
auto Prev = std::prev(MBBI);
MBBI = mergePairedInsns(MBBI, Paired, Flags);
for (auto I = std::next(Prev); I != MBBI; I++)
updateDefinedRegisters(*I, DefinedInBB, TRI);
return true;
}
return false;
}
bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
(MachineBasicBlock::iterator &MBBI) {
MachineInstr &MI = *MBBI;
MachineBasicBlock::iterator E = MI.getParent()->end();
MachineBasicBlock::iterator Update;
Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
if (Update != E) {
MBBI = mergeUpdateInsn(MBBI, Update, false);
return true;
}
if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
return false;
Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
if (Update != E) {
MBBI = mergeUpdateInsn(MBBI, Update, true);
return true;
}
int UnscaledOffset =
AArch64InstrInfo::getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
if (Update != E) {
MBBI = mergeUpdateInsn(MBBI, Update, true);
return true;
}
return false;
}
bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
bool EnableNarrowZeroStOpt) {
bool Modified = false;
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;) {
if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
Modified = true;
else
++MBBI;
}
if (EnableNarrowZeroStOpt)
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;) {
if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
Modified = true;
else
++MBBI;
}
if (MBB.getParent()->getRegInfo().tracksLiveness()) {
DefinedInBB.clear();
DefinedInBB.addLiveIns(MBB);
}
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;) {
updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
Modified = true;
else
++MBBI;
}
for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
MBBI != E;) {
if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
Modified = true;
else
++MBBI;
}
return Modified;
}
bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
if (skipFunction(Fn.getFunction()))
return false;
Subtarget = &Fn.getSubtarget<AArch64Subtarget>();
TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
TRI = Subtarget->getRegisterInfo();
AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
ModifiedRegUnits.init(*TRI);
UsedRegUnits.init(*TRI);
DefinedInBB.init(*TRI);
bool Modified = false;
bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
for (auto &MBB : Fn) {
auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
Modified |= M;
}
return Modified;
}
FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
return new AArch64LoadStoreOpt();
}