Path: blob/main/contrib/llvm-project/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp
35266 views
//===- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass -------------===//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/// \file This file contains a pass that performs load / store related peephole9/// optimizations. This pass should be run after register allocation.10//11//===----------------------------------------------------------------------===//1213#include "ARM.h"14#include "ARMBaseInstrInfo.h"15#include "ARMBaseRegisterInfo.h"16#include "ARMISelLowering.h"17#include "ARMMachineFunctionInfo.h"18#include "ARMSubtarget.h"19#include "MCTargetDesc/ARMAddressingModes.h"20#include "MCTargetDesc/ARMBaseInfo.h"21#include "Utils/ARMBaseInfo.h"22#include "llvm/ADT/ArrayRef.h"23#include "llvm/ADT/DenseMap.h"24#include "llvm/ADT/DenseSet.h"25#include "llvm/ADT/STLExtras.h"26#include "llvm/ADT/SetVector.h"27#include "llvm/ADT/SmallPtrSet.h"28#include "llvm/ADT/SmallSet.h"29#include "llvm/ADT/SmallVector.h"30#include "llvm/ADT/Statistic.h"31#include "llvm/ADT/iterator_range.h"32#include "llvm/Analysis/AliasAnalysis.h"33#include "llvm/CodeGen/LiveRegUnits.h"34#include "llvm/CodeGen/MachineBasicBlock.h"35#include "llvm/CodeGen/MachineDominators.h"36#include "llvm/CodeGen/MachineFrameInfo.h"37#include "llvm/CodeGen/MachineFunction.h"38#include "llvm/CodeGen/MachineFunctionPass.h"39#include "llvm/CodeGen/MachineInstr.h"40#include "llvm/CodeGen/MachineInstrBuilder.h"41#include "llvm/CodeGen/MachineMemOperand.h"42#include "llvm/CodeGen/MachineOperand.h"43#include "llvm/CodeGen/MachineRegisterInfo.h"44#include "llvm/CodeGen/RegisterClassInfo.h"45#include "llvm/CodeGen/TargetFrameLowering.h"46#include "llvm/CodeGen/TargetInstrInfo.h"47#include "llvm/CodeGen/TargetLowering.h"48#include "llvm/CodeGen/TargetRegisterInfo.h"49#include "llvm/CodeGen/TargetSubtargetInfo.h"50#include "llvm/IR/DataLayout.h"51#include "llvm/IR/DebugLoc.h"52#include "llvm/IR/DerivedTypes.h"53#include "llvm/IR/Function.h"54#include "llvm/IR/Type.h"55#include "llvm/InitializePasses.h"56#include "llvm/MC/MCInstrDesc.h"57#include "llvm/Pass.h"58#include "llvm/Support/Allocator.h"59#include "llvm/Support/CommandLine.h"60#include "llvm/Support/Debug.h"61#include "llvm/Support/ErrorHandling.h"62#include "llvm/Support/raw_ostream.h"63#include <algorithm>64#include <cassert>65#include <cstddef>66#include <cstdlib>67#include <iterator>68#include <limits>69#include <utility>7071using namespace llvm;7273#define DEBUG_TYPE "arm-ldst-opt"7475STATISTIC(NumLDMGened , "Number of ldm instructions generated");76STATISTIC(NumSTMGened , "Number of stm instructions generated");77STATISTIC(NumVLDMGened, "Number of vldm instructions generated");78STATISTIC(NumVSTMGened, "Number of vstm instructions generated");79STATISTIC(NumLdStMoved, "Number of load / store instructions moved");80STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");81STATISTIC(NumSTRDFormed,"Number of strd created before allocation");82STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");83STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");84STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");85STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");8687/// This switch disables formation of double/multi instructions that could88/// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP89/// disabled. This can be used to create libraries that are robust even when90/// users provoke undefined behaviour by supplying misaligned pointers.91/// \see mayCombineMisaligned()92static cl::opt<bool>93AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,94cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));9596#define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"9798namespace {99100/// Post- register allocation pass the combine load / store instructions to101/// form ldm / stm instructions.102struct ARMLoadStoreOpt : public MachineFunctionPass {103static char ID;104105const MachineFunction *MF;106const TargetInstrInfo *TII;107const TargetRegisterInfo *TRI;108const ARMSubtarget *STI;109const TargetLowering *TL;110ARMFunctionInfo *AFI;111LiveRegUnits LiveRegs;112RegisterClassInfo RegClassInfo;113MachineBasicBlock::const_iterator LiveRegPos;114bool LiveRegsValid;115bool RegClassInfoValid;116bool isThumb1, isThumb2;117118ARMLoadStoreOpt() : MachineFunctionPass(ID) {}119120bool runOnMachineFunction(MachineFunction &Fn) override;121122MachineFunctionProperties getRequiredProperties() const override {123return MachineFunctionProperties().set(124MachineFunctionProperties::Property::NoVRegs);125}126127StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }128129private:130/// A set of load/store MachineInstrs with same base register sorted by131/// offset.132struct MemOpQueueEntry {133MachineInstr *MI;134int Offset; ///< Load/Store offset.135unsigned Position; ///< Position as counted from end of basic block.136137MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)138: MI(&MI), Offset(Offset), Position(Position) {}139};140using MemOpQueue = SmallVector<MemOpQueueEntry, 8>;141142/// A set of MachineInstrs that fulfill (nearly all) conditions to get143/// merged into a LDM/STM.144struct MergeCandidate {145/// List of instructions ordered by load/store offset.146SmallVector<MachineInstr*, 4> Instrs;147148/// Index in Instrs of the instruction being latest in the schedule.149unsigned LatestMIIdx;150151/// Index in Instrs of the instruction being earliest in the schedule.152unsigned EarliestMIIdx;153154/// Index into the basic block where the merged instruction will be155/// inserted. (See MemOpQueueEntry.Position)156unsigned InsertPos;157158/// Whether the instructions can be merged into a ldm/stm instruction.159bool CanMergeToLSMulti;160161/// Whether the instructions can be merged into a ldrd/strd instruction.162bool CanMergeToLSDouble;163};164SpecificBumpPtrAllocator<MergeCandidate> Allocator;165SmallVector<const MergeCandidate*,4> Candidates;166SmallVector<MachineInstr*,4> MergeBaseCandidates;167168void moveLiveRegsBefore(const MachineBasicBlock &MBB,169MachineBasicBlock::const_iterator Before);170unsigned findFreeReg(const TargetRegisterClass &RegClass);171void UpdateBaseRegUses(MachineBasicBlock &MBB,172MachineBasicBlock::iterator MBBI, const DebugLoc &DL,173unsigned Base, unsigned WordOffset,174ARMCC::CondCodes Pred, unsigned PredReg);175MachineInstr *CreateLoadStoreMulti(176MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,177int Offset, unsigned Base, bool BaseKill, unsigned Opcode,178ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,179ArrayRef<std::pair<unsigned, bool>> Regs,180ArrayRef<MachineInstr*> Instrs);181MachineInstr *CreateLoadStoreDouble(182MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,183int Offset, unsigned Base, bool BaseKill, unsigned Opcode,184ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,185ArrayRef<std::pair<unsigned, bool>> Regs,186ArrayRef<MachineInstr*> Instrs) const;187void FormCandidates(const MemOpQueue &MemOps);188MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);189bool FixInvalidRegPairOp(MachineBasicBlock &MBB,190MachineBasicBlock::iterator &MBBI);191bool MergeBaseUpdateLoadStore(MachineInstr *MI);192bool MergeBaseUpdateLSMultiple(MachineInstr *MI);193bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;194bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);195bool MergeReturnIntoLDM(MachineBasicBlock &MBB);196bool CombineMovBx(MachineBasicBlock &MBB);197};198199} // end anonymous namespace200201char ARMLoadStoreOpt::ID = 0;202203INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,204false)205206static bool definesCPSR(const MachineInstr &MI) {207for (const auto &MO : MI.operands()) {208if (!MO.isReg())209continue;210if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())211// If the instruction has live CPSR def, then it's not safe to fold it212// into load / store.213return true;214}215216return false;217}218219static int getMemoryOpOffset(const MachineInstr &MI) {220unsigned Opcode = MI.getOpcode();221bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;222unsigned NumOperands = MI.getDesc().getNumOperands();223unsigned OffField = MI.getOperand(NumOperands - 3).getImm();224225if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||226Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||227Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||228Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)229return OffField;230231// Thumb1 immediate offsets are scaled by 4232if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||233Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)234return OffField * 4;235236int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)237: ARM_AM::getAM5Offset(OffField) * 4;238ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)239: ARM_AM::getAM5Op(OffField);240241if (Op == ARM_AM::sub)242return -Offset;243244return Offset;245}246247static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {248return MI.getOperand(1);249}250251static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {252return MI.getOperand(0);253}254255static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {256switch (Opcode) {257default: llvm_unreachable("Unhandled opcode!");258case ARM::LDRi12:259++NumLDMGened;260switch (Mode) {261default: llvm_unreachable("Unhandled submode!");262case ARM_AM::ia: return ARM::LDMIA;263case ARM_AM::da: return ARM::LDMDA;264case ARM_AM::db: return ARM::LDMDB;265case ARM_AM::ib: return ARM::LDMIB;266}267case ARM::STRi12:268++NumSTMGened;269switch (Mode) {270default: llvm_unreachable("Unhandled submode!");271case ARM_AM::ia: return ARM::STMIA;272case ARM_AM::da: return ARM::STMDA;273case ARM_AM::db: return ARM::STMDB;274case ARM_AM::ib: return ARM::STMIB;275}276case ARM::tLDRi:277case ARM::tLDRspi:278// tLDMIA is writeback-only - unless the base register is in the input279// reglist.280++NumLDMGened;281switch (Mode) {282default: llvm_unreachable("Unhandled submode!");283case ARM_AM::ia: return ARM::tLDMIA;284}285case ARM::tSTRi:286case ARM::tSTRspi:287// There is no non-writeback tSTMIA either.288++NumSTMGened;289switch (Mode) {290default: llvm_unreachable("Unhandled submode!");291case ARM_AM::ia: return ARM::tSTMIA_UPD;292}293case ARM::t2LDRi8:294case ARM::t2LDRi12:295++NumLDMGened;296switch (Mode) {297default: llvm_unreachable("Unhandled submode!");298case ARM_AM::ia: return ARM::t2LDMIA;299case ARM_AM::db: return ARM::t2LDMDB;300}301case ARM::t2STRi8:302case ARM::t2STRi12:303++NumSTMGened;304switch (Mode) {305default: llvm_unreachable("Unhandled submode!");306case ARM_AM::ia: return ARM::t2STMIA;307case ARM_AM::db: return ARM::t2STMDB;308}309case ARM::VLDRS:310++NumVLDMGened;311switch (Mode) {312default: llvm_unreachable("Unhandled submode!");313case ARM_AM::ia: return ARM::VLDMSIA;314case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.315}316case ARM::VSTRS:317++NumVSTMGened;318switch (Mode) {319default: llvm_unreachable("Unhandled submode!");320case ARM_AM::ia: return ARM::VSTMSIA;321case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.322}323case ARM::VLDRD:324++NumVLDMGened;325switch (Mode) {326default: llvm_unreachable("Unhandled submode!");327case ARM_AM::ia: return ARM::VLDMDIA;328case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.329}330case ARM::VSTRD:331++NumVSTMGened;332switch (Mode) {333default: llvm_unreachable("Unhandled submode!");334case ARM_AM::ia: return ARM::VSTMDIA;335case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.336}337}338}339340static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {341switch (Opcode) {342default: llvm_unreachable("Unhandled opcode!");343case ARM::LDMIA_RET:344case ARM::LDMIA:345case ARM::LDMIA_UPD:346case ARM::STMIA:347case ARM::STMIA_UPD:348case ARM::tLDMIA:349case ARM::tLDMIA_UPD:350case ARM::tSTMIA_UPD:351case ARM::t2LDMIA_RET:352case ARM::t2LDMIA:353case ARM::t2LDMIA_UPD:354case ARM::t2STMIA:355case ARM::t2STMIA_UPD:356case ARM::VLDMSIA:357case ARM::VLDMSIA_UPD:358case ARM::VSTMSIA:359case ARM::VSTMSIA_UPD:360case ARM::VLDMDIA:361case ARM::VLDMDIA_UPD:362case ARM::VSTMDIA:363case ARM::VSTMDIA_UPD:364return ARM_AM::ia;365366case ARM::LDMDA:367case ARM::LDMDA_UPD:368case ARM::STMDA:369case ARM::STMDA_UPD:370return ARM_AM::da;371372case ARM::LDMDB:373case ARM::LDMDB_UPD:374case ARM::STMDB:375case ARM::STMDB_UPD:376case ARM::t2LDMDB:377case ARM::t2LDMDB_UPD:378case ARM::t2STMDB:379case ARM::t2STMDB_UPD:380case ARM::VLDMSDB_UPD:381case ARM::VSTMSDB_UPD:382case ARM::VLDMDDB_UPD:383case ARM::VSTMDDB_UPD:384return ARM_AM::db;385386case ARM::LDMIB:387case ARM::LDMIB_UPD:388case ARM::STMIB:389case ARM::STMIB_UPD:390return ARM_AM::ib;391}392}393394static bool isT1i32Load(unsigned Opc) {395return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;396}397398static bool isT2i32Load(unsigned Opc) {399return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;400}401402static bool isi32Load(unsigned Opc) {403return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;404}405406static bool isT1i32Store(unsigned Opc) {407return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;408}409410static bool isT2i32Store(unsigned Opc) {411return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;412}413414static bool isi32Store(unsigned Opc) {415return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);416}417418static bool isLoadSingle(unsigned Opc) {419return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;420}421422static unsigned getImmScale(unsigned Opc) {423switch (Opc) {424default: llvm_unreachable("Unhandled opcode!");425case ARM::tLDRi:426case ARM::tSTRi:427case ARM::tLDRspi:428case ARM::tSTRspi:429return 1;430case ARM::tLDRHi:431case ARM::tSTRHi:432return 2;433case ARM::tLDRBi:434case ARM::tSTRBi:435return 4;436}437}438439static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {440switch (MI->getOpcode()) {441default: return 0;442case ARM::LDRi12:443case ARM::STRi12:444case ARM::tLDRi:445case ARM::tSTRi:446case ARM::tLDRspi:447case ARM::tSTRspi:448case ARM::t2LDRi8:449case ARM::t2LDRi12:450case ARM::t2STRi8:451case ARM::t2STRi12:452case ARM::VLDRS:453case ARM::VSTRS:454return 4;455case ARM::VLDRD:456case ARM::VSTRD:457return 8;458case ARM::LDMIA:459case ARM::LDMDA:460case ARM::LDMDB:461case ARM::LDMIB:462case ARM::STMIA:463case ARM::STMDA:464case ARM::STMDB:465case ARM::STMIB:466case ARM::tLDMIA:467case ARM::tLDMIA_UPD:468case ARM::tSTMIA_UPD:469case ARM::t2LDMIA:470case ARM::t2LDMDB:471case ARM::t2STMIA:472case ARM::t2STMDB:473case ARM::VLDMSIA:474case ARM::VSTMSIA:475return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;476case ARM::VLDMDIA:477case ARM::VSTMDIA:478return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;479}480}481482/// Update future uses of the base register with the offset introduced483/// due to writeback. This function only works on Thumb1.484void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,485MachineBasicBlock::iterator MBBI,486const DebugLoc &DL, unsigned Base,487unsigned WordOffset,488ARMCC::CondCodes Pred,489unsigned PredReg) {490assert(isThumb1 && "Can only update base register uses for Thumb1!");491// Start updating any instructions with immediate offsets. Insert a SUB before492// the first non-updateable instruction (if any).493for (; MBBI != MBB.end(); ++MBBI) {494bool InsertSub = false;495unsigned Opc = MBBI->getOpcode();496497if (MBBI->readsRegister(Base, /*TRI=*/nullptr)) {498int Offset;499bool IsLoad =500Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;501bool IsStore =502Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;503504if (IsLoad || IsStore) {505// Loads and stores with immediate offsets can be updated, but only if506// the new offset isn't negative.507// The MachineOperand containing the offset immediate is the last one508// before predicates.509MachineOperand &MO =510MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);511// The offsets are scaled by 1, 2 or 4 depending on the Opcode.512Offset = MO.getImm() - WordOffset * getImmScale(Opc);513514// If storing the base register, it needs to be reset first.515Register InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();516517if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))518MO.setImm(Offset);519else520InsertSub = true;521} else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&522!definesCPSR(*MBBI)) {523// SUBS/ADDS using this register, with a dead def of the CPSR.524// Merge it with the update; if the merged offset is too large,525// insert a new sub instead.526MachineOperand &MO =527MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);528Offset = (Opc == ARM::tSUBi8) ?529MO.getImm() + WordOffset * 4 :530MO.getImm() - WordOffset * 4 ;531if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {532// FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if533// Offset == 0.534MO.setImm(Offset);535// The base register has now been reset, so exit early.536return;537} else {538InsertSub = true;539}540} else {541// Can't update the instruction.542InsertSub = true;543}544} else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {545// Since SUBS sets the condition flags, we can't place the base reset546// after an instruction that has a live CPSR def.547// The base register might also contain an argument for a function call.548InsertSub = true;549}550551if (InsertSub) {552// An instruction above couldn't be updated, so insert a sub.553BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)554.add(t1CondCodeOp(true))555.addReg(Base)556.addImm(WordOffset * 4)557.addImm(Pred)558.addReg(PredReg);559return;560}561562if (MBBI->killsRegister(Base, /*TRI=*/nullptr) ||563MBBI->definesRegister(Base, /*TRI=*/nullptr))564// Register got killed. Stop updating.565return;566}567568// End of block was reached.569if (!MBB.succ_empty()) {570// FIXME: Because of a bug, live registers are sometimes missing from571// the successor blocks' live-in sets. This means we can't trust that572// information and *always* have to reset at the end of a block.573// See PR21029.574if (MBBI != MBB.end()) --MBBI;575BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)576.add(t1CondCodeOp(true))577.addReg(Base)578.addImm(WordOffset * 4)579.addImm(Pred)580.addReg(PredReg);581}582}583584/// Return the first register of class \p RegClass that is not in \p Regs.585unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {586if (!RegClassInfoValid) {587RegClassInfo.runOnMachineFunction(*MF);588RegClassInfoValid = true;589}590591for (unsigned Reg : RegClassInfo.getOrder(&RegClass))592if (LiveRegs.available(Reg) && !MF->getRegInfo().isReserved(Reg))593return Reg;594return 0;595}596597/// Compute live registers just before instruction \p Before (in normal schedule598/// direction). Computes backwards so multiple queries in the same block must599/// come in reverse order.600void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,601MachineBasicBlock::const_iterator Before) {602// Initialize if we never queried in this block.603if (!LiveRegsValid) {604LiveRegs.init(*TRI);605LiveRegs.addLiveOuts(MBB);606LiveRegPos = MBB.end();607LiveRegsValid = true;608}609// Move backward just before the "Before" position.610while (LiveRegPos != Before) {611--LiveRegPos;612LiveRegs.stepBackward(*LiveRegPos);613}614}615616static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,617unsigned Reg) {618for (const std::pair<unsigned, bool> &R : Regs)619if (R.first == Reg)620return true;621return false;622}623624/// Create and insert a LDM or STM with Base as base register and registers in625/// Regs as the register operands that would be loaded / stored. It returns626/// true if the transformation is done.627MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(628MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,629int Offset, unsigned Base, bool BaseKill, unsigned Opcode,630ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,631ArrayRef<std::pair<unsigned, bool>> Regs,632ArrayRef<MachineInstr*> Instrs) {633unsigned NumRegs = Regs.size();634assert(NumRegs > 1);635636// For Thumb1 targets, it might be necessary to clobber the CPSR to merge.637// Compute liveness information for that register to make the decision.638bool SafeToClobberCPSR = !isThumb1 ||639(MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==640MachineBasicBlock::LQR_Dead);641642bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.643644// Exception: If the base register is in the input reglist, Thumb1 LDM is645// non-writeback.646// It's also not possible to merge an STR of the base register in Thumb1.647if (isThumb1 && ContainsReg(Regs, Base)) {648assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");649if (Opcode == ARM::tLDRi)650Writeback = false;651else if (Opcode == ARM::tSTRi)652return nullptr;653}654655ARM_AM::AMSubMode Mode = ARM_AM::ia;656// VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.657bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);658bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;659660if (Offset == 4 && haveIBAndDA) {661Mode = ARM_AM::ib;662} else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {663Mode = ARM_AM::da;664} else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {665// VLDM/VSTM do not support DB mode without also updating the base reg.666Mode = ARM_AM::db;667} else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {668// Check if this is a supported opcode before inserting instructions to669// calculate a new base register.670if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;671672// If starting offset isn't zero, insert a MI to materialize a new base.673// But only do so if it is cost effective, i.e. merging more than two674// loads / stores.675if (NumRegs <= 2)676return nullptr;677678// On Thumb1, it's not worth materializing a new base register without679// clobbering the CPSR (i.e. not using ADDS/SUBS).680if (!SafeToClobberCPSR)681return nullptr;682683unsigned NewBase;684if (isi32Load(Opcode)) {685// If it is a load, then just use one of the destination registers686// as the new base. Will no longer be writeback in Thumb1.687NewBase = Regs[NumRegs-1].first;688Writeback = false;689} else {690// Find a free register that we can use as scratch register.691moveLiveRegsBefore(MBB, InsertBefore);692// The merged instruction does not exist yet but will use several Regs if693// it is a Store.694if (!isLoadSingle(Opcode))695for (const std::pair<unsigned, bool> &R : Regs)696LiveRegs.addReg(R.first);697698NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);699if (NewBase == 0)700return nullptr;701}702703int BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2ADDspImm704: ARM::t2ADDri)705: (isThumb1 && Base == ARM::SP)706? ARM::tADDrSPi707: (isThumb1 && Offset < 8)708? ARM::tADDi3709: isThumb1 ? ARM::tADDi8 : ARM::ADDri;710711if (Offset < 0) {712// FIXME: There are no Thumb1 load/store instructions with negative713// offsets. So the Base != ARM::SP might be unnecessary.714Offset = -Offset;715BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2SUBspImm716: ARM::t2SUBri)717: (isThumb1 && Offset < 8 && Base != ARM::SP)718? ARM::tSUBi3719: isThumb1 ? ARM::tSUBi8 : ARM::SUBri;720}721722if (!TL->isLegalAddImmediate(Offset))723// FIXME: Try add with register operand?724return nullptr; // Probably not worth it then.725726// We can only append a kill flag to the add/sub input if the value is not727// used in the register list of the stm as well.728bool KillOldBase = BaseKill &&729(!isi32Store(Opcode) || !ContainsReg(Regs, Base));730731if (isThumb1) {732// Thumb1: depending on immediate size, use either733// ADDS NewBase, Base, #imm3734// or735// MOV NewBase, Base736// ADDS NewBase, #imm8.737if (Base != NewBase &&738(BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {739// Need to insert a MOV to the new base first.740if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&741!STI->hasV6Ops()) {742// thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr743if (Pred != ARMCC::AL)744return nullptr;745BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)746.addReg(Base, getKillRegState(KillOldBase));747} else748BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)749.addReg(Base, getKillRegState(KillOldBase))750.add(predOps(Pred, PredReg));751752// The following ADDS/SUBS becomes an update.753Base = NewBase;754KillOldBase = true;755}756if (BaseOpc == ARM::tADDrSPi) {757assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");758BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)759.addReg(Base, getKillRegState(KillOldBase))760.addImm(Offset / 4)761.add(predOps(Pred, PredReg));762} else763BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)764.add(t1CondCodeOp(true))765.addReg(Base, getKillRegState(KillOldBase))766.addImm(Offset)767.add(predOps(Pred, PredReg));768} else {769BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)770.addReg(Base, getKillRegState(KillOldBase))771.addImm(Offset)772.add(predOps(Pred, PredReg))773.add(condCodeOp());774}775Base = NewBase;776BaseKill = true; // New base is always killed straight away.777}778779bool isDef = isLoadSingle(Opcode);780781// Get LS multiple opcode. Note that for Thumb1 this might be an opcode with782// base register writeback.783Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);784if (!Opcode)785return nullptr;786787// Check if a Thumb1 LDM/STM merge is safe. This is the case if:788// - There is no writeback (LDM of base register),789// - the base register is killed by the merged instruction,790// - or it's safe to overwrite the condition flags, i.e. to insert a SUBS791// to reset the base register.792// Otherwise, don't merge.793// It's safe to return here since the code to materialize a new base register794// above is also conditional on SafeToClobberCPSR.795if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)796return nullptr;797798MachineInstrBuilder MIB;799800if (Writeback) {801assert(isThumb1 && "expected Writeback only inThumb1");802if (Opcode == ARM::tLDMIA) {803assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");804// Update tLDMIA with writeback if necessary.805Opcode = ARM::tLDMIA_UPD;806}807808MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));809810// Thumb1: we might need to set base writeback when building the MI.811MIB.addReg(Base, getDefRegState(true))812.addReg(Base, getKillRegState(BaseKill));813814// The base isn't dead after a merged instruction with writeback.815// Insert a sub instruction after the newly formed instruction to reset.816if (!BaseKill)817UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);818} else {819// No writeback, simply build the MachineInstr.820MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));821MIB.addReg(Base, getKillRegState(BaseKill));822}823824MIB.addImm(Pred).addReg(PredReg);825826for (const std::pair<unsigned, bool> &R : Regs)827MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));828829MIB.cloneMergedMemRefs(Instrs);830831return MIB.getInstr();832}833834MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(835MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,836int Offset, unsigned Base, bool BaseKill, unsigned Opcode,837ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,838ArrayRef<std::pair<unsigned, bool>> Regs,839ArrayRef<MachineInstr*> Instrs) const {840bool IsLoad = isi32Load(Opcode);841assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");842unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;843844assert(Regs.size() == 2);845MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,846TII->get(LoadStoreOpcode));847if (IsLoad) {848MIB.addReg(Regs[0].first, RegState::Define)849.addReg(Regs[1].first, RegState::Define);850} else {851MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))852.addReg(Regs[1].first, getKillRegState(Regs[1].second));853}854MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);855MIB.cloneMergedMemRefs(Instrs);856return MIB.getInstr();857}858859/// Call MergeOps and update MemOps and merges accordingly on success.860MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {861const MachineInstr *First = Cand.Instrs.front();862unsigned Opcode = First->getOpcode();863bool IsLoad = isLoadSingle(Opcode);864SmallVector<std::pair<unsigned, bool>, 8> Regs;865SmallVector<unsigned, 4> ImpDefs;866DenseSet<unsigned> KilledRegs;867DenseSet<unsigned> UsedRegs;868// Determine list of registers and list of implicit super-register defs.869for (const MachineInstr *MI : Cand.Instrs) {870const MachineOperand &MO = getLoadStoreRegOp(*MI);871Register Reg = MO.getReg();872bool IsKill = MO.isKill();873if (IsKill)874KilledRegs.insert(Reg);875Regs.push_back(std::make_pair(Reg, IsKill));876UsedRegs.insert(Reg);877878if (IsLoad) {879// Collect any implicit defs of super-registers, after merging we can't880// be sure anymore that we properly preserved these live ranges and must881// removed these implicit operands.882for (const MachineOperand &MO : MI->implicit_operands()) {883if (!MO.isReg() || !MO.isDef() || MO.isDead())884continue;885assert(MO.isImplicit());886Register DefReg = MO.getReg();887888if (is_contained(ImpDefs, DefReg))889continue;890// We can ignore cases where the super-reg is read and written.891if (MI->readsRegister(DefReg, /*TRI=*/nullptr))892continue;893ImpDefs.push_back(DefReg);894}895}896}897898// Attempt the merge.899using iterator = MachineBasicBlock::iterator;900901MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];902iterator InsertBefore = std::next(iterator(LatestMI));903MachineBasicBlock &MBB = *LatestMI->getParent();904unsigned Offset = getMemoryOpOffset(*First);905Register Base = getLoadStoreBaseOp(*First).getReg();906bool BaseKill = LatestMI->killsRegister(Base, /*TRI=*/nullptr);907Register PredReg;908ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);909DebugLoc DL = First->getDebugLoc();910MachineInstr *Merged = nullptr;911if (Cand.CanMergeToLSDouble)912Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,913Opcode, Pred, PredReg, DL, Regs,914Cand.Instrs);915if (!Merged && Cand.CanMergeToLSMulti)916Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,917Opcode, Pred, PredReg, DL, Regs, Cand.Instrs);918if (!Merged)919return nullptr;920921// Determine earliest instruction that will get removed. We then keep an922// iterator just above it so the following erases don't invalidated it.923iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);924bool EarliestAtBegin = false;925if (EarliestI == MBB.begin()) {926EarliestAtBegin = true;927} else {928EarliestI = std::prev(EarliestI);929}930931// Remove instructions which have been merged.932for (MachineInstr *MI : Cand.Instrs)933MBB.erase(MI);934935// Determine range between the earliest removed instruction and the new one.936if (EarliestAtBegin)937EarliestI = MBB.begin();938else939EarliestI = std::next(EarliestI);940auto FixupRange = make_range(EarliestI, iterator(Merged));941942if (isLoadSingle(Opcode)) {943// If the previous loads defined a super-reg, then we have to mark earlier944// operands undef; Replicate the super-reg def on the merged instruction.945for (MachineInstr &MI : FixupRange) {946for (unsigned &ImpDefReg : ImpDefs) {947for (MachineOperand &MO : MI.implicit_operands()) {948if (!MO.isReg() || MO.getReg() != ImpDefReg)949continue;950if (MO.readsReg())951MO.setIsUndef();952else if (MO.isDef())953ImpDefReg = 0;954}955}956}957958MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);959for (unsigned ImpDef : ImpDefs)960MIB.addReg(ImpDef, RegState::ImplicitDefine);961} else {962// Remove kill flags: We are possibly storing the values later now.963assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);964for (MachineInstr &MI : FixupRange) {965for (MachineOperand &MO : MI.uses()) {966if (!MO.isReg() || !MO.isKill())967continue;968if (UsedRegs.count(MO.getReg()))969MO.setIsKill(false);970}971}972assert(ImpDefs.empty());973}974975return Merged;976}977978static bool isValidLSDoubleOffset(int Offset) {979unsigned Value = abs(Offset);980// t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally981// multiplied by 4.982return (Value % 4) == 0 && Value < 1024;983}984985/// Return true for loads/stores that can be combined to a double/multi986/// operation without increasing the requirements for alignment.987static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,988const MachineInstr &MI) {989// vldr/vstr trap on misaligned pointers anyway, forming vldm makes no990// difference.991unsigned Opcode = MI.getOpcode();992if (!isi32Load(Opcode) && !isi32Store(Opcode))993return true;994995// Stack pointer alignment is out of the programmers control so we can trust996// SP-relative loads/stores.997if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&998STI.getFrameLowering()->getTransientStackAlign() >= Align(4))999return true;1000return false;1001}10021003/// Find candidates for load/store multiple merge in list of MemOpQueueEntries.1004void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {1005const MachineInstr *FirstMI = MemOps[0].MI;1006unsigned Opcode = FirstMI->getOpcode();1007bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);1008unsigned Size = getLSMultipleTransferSize(FirstMI);10091010unsigned SIndex = 0;1011unsigned EIndex = MemOps.size();1012do {1013// Look at the first instruction.1014const MachineInstr *MI = MemOps[SIndex].MI;1015int Offset = MemOps[SIndex].Offset;1016const MachineOperand &PMO = getLoadStoreRegOp(*MI);1017Register PReg = PMO.getReg();1018unsigned PRegNum = PMO.isUndef() ? std::numeric_limits<unsigned>::max()1019: TRI->getEncodingValue(PReg);1020unsigned Latest = SIndex;1021unsigned Earliest = SIndex;1022unsigned Count = 1;1023bool CanMergeToLSDouble =1024STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);1025// ARM errata 602117: LDRD with base in list may result in incorrect base1026// register when interrupted or faulted.1027if (STI->isCortexM3() && isi32Load(Opcode) &&1028PReg == getLoadStoreBaseOp(*MI).getReg())1029CanMergeToLSDouble = false;10301031bool CanMergeToLSMulti = true;1032// On swift vldm/vstm starting with an odd register number as that needs1033// more uops than single vldrs.1034if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)1035CanMergeToLSMulti = false;10361037// LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it1038// deprecated; LDM to PC is fine but cannot happen here.1039if (PReg == ARM::SP || PReg == ARM::PC)1040CanMergeToLSMulti = CanMergeToLSDouble = false;10411042// Should we be conservative?1043if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))1044CanMergeToLSMulti = CanMergeToLSDouble = false;10451046// vldm / vstm limit are 32 for S variants, 16 for D variants.1047unsigned Limit;1048switch (Opcode) {1049default:1050Limit = UINT_MAX;1051break;1052case ARM::VLDRD:1053case ARM::VSTRD:1054Limit = 16;1055break;1056}10571058// Merge following instructions where possible.1059for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {1060int NewOffset = MemOps[I].Offset;1061if (NewOffset != Offset + (int)Size)1062break;1063const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);1064Register Reg = MO.getReg();1065if (Reg == ARM::SP || Reg == ARM::PC)1066break;1067if (Count == Limit)1068break;10691070// See if the current load/store may be part of a multi load/store.1071unsigned RegNum = MO.isUndef() ? std::numeric_limits<unsigned>::max()1072: TRI->getEncodingValue(Reg);1073bool PartOfLSMulti = CanMergeToLSMulti;1074if (PartOfLSMulti) {1075// Register numbers must be in ascending order.1076if (RegNum <= PRegNum)1077PartOfLSMulti = false;1078// For VFP / NEON load/store multiples, the registers must be1079// consecutive and within the limit on the number of registers per1080// instruction.1081else if (!isNotVFP && RegNum != PRegNum+1)1082PartOfLSMulti = false;1083}1084// See if the current load/store may be part of a double load/store.1085bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;10861087if (!PartOfLSMulti && !PartOfLSDouble)1088break;1089CanMergeToLSMulti &= PartOfLSMulti;1090CanMergeToLSDouble &= PartOfLSDouble;1091// Track MemOp with latest and earliest position (Positions are1092// counted in reverse).1093unsigned Position = MemOps[I].Position;1094if (Position < MemOps[Latest].Position)1095Latest = I;1096else if (Position > MemOps[Earliest].Position)1097Earliest = I;1098// Prepare for next MemOp.1099Offset += Size;1100PRegNum = RegNum;1101}11021103// Form a candidate from the Ops collected so far.1104MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;1105for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)1106Candidate->Instrs.push_back(MemOps[C].MI);1107Candidate->LatestMIIdx = Latest - SIndex;1108Candidate->EarliestMIIdx = Earliest - SIndex;1109Candidate->InsertPos = MemOps[Latest].Position;1110if (Count == 1)1111CanMergeToLSMulti = CanMergeToLSDouble = false;1112Candidate->CanMergeToLSMulti = CanMergeToLSMulti;1113Candidate->CanMergeToLSDouble = CanMergeToLSDouble;1114Candidates.push_back(Candidate);1115// Continue after the chain.1116SIndex += Count;1117} while (SIndex < EIndex);1118}11191120static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,1121ARM_AM::AMSubMode Mode) {1122switch (Opc) {1123default: llvm_unreachable("Unhandled opcode!");1124case ARM::LDMIA:1125case ARM::LDMDA:1126case ARM::LDMDB:1127case ARM::LDMIB:1128switch (Mode) {1129default: llvm_unreachable("Unhandled submode!");1130case ARM_AM::ia: return ARM::LDMIA_UPD;1131case ARM_AM::ib: return ARM::LDMIB_UPD;1132case ARM_AM::da: return ARM::LDMDA_UPD;1133case ARM_AM::db: return ARM::LDMDB_UPD;1134}1135case ARM::STMIA:1136case ARM::STMDA:1137case ARM::STMDB:1138case ARM::STMIB:1139switch (Mode) {1140default: llvm_unreachable("Unhandled submode!");1141case ARM_AM::ia: return ARM::STMIA_UPD;1142case ARM_AM::ib: return ARM::STMIB_UPD;1143case ARM_AM::da: return ARM::STMDA_UPD;1144case ARM_AM::db: return ARM::STMDB_UPD;1145}1146case ARM::t2LDMIA:1147case ARM::t2LDMDB:1148switch (Mode) {1149default: llvm_unreachable("Unhandled submode!");1150case ARM_AM::ia: return ARM::t2LDMIA_UPD;1151case ARM_AM::db: return ARM::t2LDMDB_UPD;1152}1153case ARM::t2STMIA:1154case ARM::t2STMDB:1155switch (Mode) {1156default: llvm_unreachable("Unhandled submode!");1157case ARM_AM::ia: return ARM::t2STMIA_UPD;1158case ARM_AM::db: return ARM::t2STMDB_UPD;1159}1160case ARM::VLDMSIA:1161switch (Mode) {1162default: llvm_unreachable("Unhandled submode!");1163case ARM_AM::ia: return ARM::VLDMSIA_UPD;1164case ARM_AM::db: return ARM::VLDMSDB_UPD;1165}1166case ARM::VLDMDIA:1167switch (Mode) {1168default: llvm_unreachable("Unhandled submode!");1169case ARM_AM::ia: return ARM::VLDMDIA_UPD;1170case ARM_AM::db: return ARM::VLDMDDB_UPD;1171}1172case ARM::VSTMSIA:1173switch (Mode) {1174default: llvm_unreachable("Unhandled submode!");1175case ARM_AM::ia: return ARM::VSTMSIA_UPD;1176case ARM_AM::db: return ARM::VSTMSDB_UPD;1177}1178case ARM::VSTMDIA:1179switch (Mode) {1180default: llvm_unreachable("Unhandled submode!");1181case ARM_AM::ia: return ARM::VSTMDIA_UPD;1182case ARM_AM::db: return ARM::VSTMDDB_UPD;1183}1184}1185}11861187/// Check if the given instruction increments or decrements a register and1188/// return the amount it is incremented/decremented. Returns 0 if the CPSR flags1189/// generated by the instruction are possibly read as well.1190static int isIncrementOrDecrement(const MachineInstr &MI, Register Reg,1191ARMCC::CondCodes Pred, Register PredReg) {1192bool CheckCPSRDef;1193int Scale;1194switch (MI.getOpcode()) {1195case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break;1196case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break;1197case ARM::t2SUBri:1198case ARM::t2SUBspImm:1199case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break;1200case ARM::t2ADDri:1201case ARM::t2ADDspImm:1202case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break;1203case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break;1204case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;1205default: return 0;1206}12071208Register MIPredReg;1209if (MI.getOperand(0).getReg() != Reg ||1210MI.getOperand(1).getReg() != Reg ||1211getInstrPredicate(MI, MIPredReg) != Pred ||1212MIPredReg != PredReg)1213return 0;12141215if (CheckCPSRDef && definesCPSR(MI))1216return 0;1217return MI.getOperand(2).getImm() * Scale;1218}12191220/// Searches for an increment or decrement of \p Reg before \p MBBI.1221static MachineBasicBlock::iterator1222findIncDecBefore(MachineBasicBlock::iterator MBBI, Register Reg,1223ARMCC::CondCodes Pred, Register PredReg, int &Offset) {1224Offset = 0;1225MachineBasicBlock &MBB = *MBBI->getParent();1226MachineBasicBlock::iterator BeginMBBI = MBB.begin();1227MachineBasicBlock::iterator EndMBBI = MBB.end();1228if (MBBI == BeginMBBI)1229return EndMBBI;12301231// Skip debug values.1232MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);1233while (PrevMBBI->isDebugInstr() && PrevMBBI != BeginMBBI)1234--PrevMBBI;12351236Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);1237return Offset == 0 ? EndMBBI : PrevMBBI;1238}12391240/// Searches for a increment or decrement of \p Reg after \p MBBI.1241static MachineBasicBlock::iterator1242findIncDecAfter(MachineBasicBlock::iterator MBBI, Register Reg,1243ARMCC::CondCodes Pred, Register PredReg, int &Offset,1244const TargetRegisterInfo *TRI) {1245Offset = 0;1246MachineBasicBlock &MBB = *MBBI->getParent();1247MachineBasicBlock::iterator EndMBBI = MBB.end();1248MachineBasicBlock::iterator NextMBBI = std::next(MBBI);1249while (NextMBBI != EndMBBI) {1250// Skip debug values.1251while (NextMBBI != EndMBBI && NextMBBI->isDebugInstr())1252++NextMBBI;1253if (NextMBBI == EndMBBI)1254return EndMBBI;12551256unsigned Off = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);1257if (Off) {1258Offset = Off;1259return NextMBBI;1260}12611262// SP can only be combined if it is the next instruction after the original1263// MBBI, otherwise we may be incrementing the stack pointer (invalidating1264// anything below the new pointer) when its frame elements are still in1265// use. Other registers can attempt to look further, until a different use1266// or def of the register is found.1267if (Reg == ARM::SP || NextMBBI->readsRegister(Reg, TRI) ||1268NextMBBI->definesRegister(Reg, TRI))1269return EndMBBI;12701271++NextMBBI;1272}1273return EndMBBI;1274}12751276/// Fold proceeding/trailing inc/dec of base register into the1277/// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:1278///1279/// stmia rn, <ra, rb, rc>1280/// rn := rn + 4 * 3;1281/// =>1282/// stmia rn!, <ra, rb, rc>1283///1284/// rn := rn - 4 * 3;1285/// ldmia rn, <ra, rb, rc>1286/// =>1287/// ldmdb rn!, <ra, rb, rc>1288bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {1289// Thumb1 is already using updating loads/stores.1290if (isThumb1) return false;1291LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);12921293const MachineOperand &BaseOP = MI->getOperand(0);1294Register Base = BaseOP.getReg();1295bool BaseKill = BaseOP.isKill();1296Register PredReg;1297ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);1298unsigned Opcode = MI->getOpcode();1299DebugLoc DL = MI->getDebugLoc();13001301// Can't use an updating ld/st if the base register is also a dest1302// register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.1303for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))1304if (MO.getReg() == Base)1305return false;13061307int Bytes = getLSMultipleTransferSize(MI);1308MachineBasicBlock &MBB = *MI->getParent();1309MachineBasicBlock::iterator MBBI(MI);1310int Offset;1311MachineBasicBlock::iterator MergeInstr1312= findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);1313ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);1314if (Mode == ARM_AM::ia && Offset == -Bytes) {1315Mode = ARM_AM::db;1316} else if (Mode == ARM_AM::ib && Offset == -Bytes) {1317Mode = ARM_AM::da;1318} else {1319MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);1320if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&1321((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {13221323// We couldn't find an inc/dec to merge. But if the base is dead, we1324// can still change to a writeback form as that will save us 2 bytes1325// of code size. It can create WAW hazards though, so only do it if1326// we're minimizing code size.1327if (!STI->hasMinSize() || !BaseKill)1328return false;13291330bool HighRegsUsed = false;1331for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))1332if (MO.getReg() >= ARM::R8) {1333HighRegsUsed = true;1334break;1335}13361337if (!HighRegsUsed)1338MergeInstr = MBB.end();1339else1340return false;1341}1342}1343if (MergeInstr != MBB.end()) {1344LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);1345MBB.erase(MergeInstr);1346}13471348unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);1349MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))1350.addReg(Base, getDefRegState(true)) // WB base register1351.addReg(Base, getKillRegState(BaseKill))1352.addImm(Pred).addReg(PredReg);13531354// Transfer the rest of operands.1355for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3))1356MIB.add(MO);13571358// Transfer memoperands.1359MIB.setMemRefs(MI->memoperands());13601361LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB);1362MBB.erase(MBBI);1363return true;1364}13651366static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,1367ARM_AM::AddrOpc Mode) {1368switch (Opc) {1369case ARM::LDRi12:1370return ARM::LDR_PRE_IMM;1371case ARM::STRi12:1372return ARM::STR_PRE_IMM;1373case ARM::VLDRS:1374return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;1375case ARM::VLDRD:1376return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;1377case ARM::VSTRS:1378return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;1379case ARM::VSTRD:1380return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;1381case ARM::t2LDRi8:1382case ARM::t2LDRi12:1383return ARM::t2LDR_PRE;1384case ARM::t2STRi8:1385case ARM::t2STRi12:1386return ARM::t2STR_PRE;1387default: llvm_unreachable("Unhandled opcode!");1388}1389}13901391static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,1392ARM_AM::AddrOpc Mode) {1393switch (Opc) {1394case ARM::LDRi12:1395return ARM::LDR_POST_IMM;1396case ARM::STRi12:1397return ARM::STR_POST_IMM;1398case ARM::VLDRS:1399return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;1400case ARM::VLDRD:1401return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;1402case ARM::VSTRS:1403return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;1404case ARM::VSTRD:1405return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;1406case ARM::t2LDRi8:1407case ARM::t2LDRi12:1408return ARM::t2LDR_POST;1409case ARM::t2LDRBi8:1410case ARM::t2LDRBi12:1411return ARM::t2LDRB_POST;1412case ARM::t2LDRSBi8:1413case ARM::t2LDRSBi12:1414return ARM::t2LDRSB_POST;1415case ARM::t2LDRHi8:1416case ARM::t2LDRHi12:1417return ARM::t2LDRH_POST;1418case ARM::t2LDRSHi8:1419case ARM::t2LDRSHi12:1420return ARM::t2LDRSH_POST;1421case ARM::t2STRi8:1422case ARM::t2STRi12:1423return ARM::t2STR_POST;1424case ARM::t2STRBi8:1425case ARM::t2STRBi12:1426return ARM::t2STRB_POST;1427case ARM::t2STRHi8:1428case ARM::t2STRHi12:1429return ARM::t2STRH_POST;14301431case ARM::MVE_VLDRBS16:1432return ARM::MVE_VLDRBS16_post;1433case ARM::MVE_VLDRBS32:1434return ARM::MVE_VLDRBS32_post;1435case ARM::MVE_VLDRBU16:1436return ARM::MVE_VLDRBU16_post;1437case ARM::MVE_VLDRBU32:1438return ARM::MVE_VLDRBU32_post;1439case ARM::MVE_VLDRHS32:1440return ARM::MVE_VLDRHS32_post;1441case ARM::MVE_VLDRHU32:1442return ARM::MVE_VLDRHU32_post;1443case ARM::MVE_VLDRBU8:1444return ARM::MVE_VLDRBU8_post;1445case ARM::MVE_VLDRHU16:1446return ARM::MVE_VLDRHU16_post;1447case ARM::MVE_VLDRWU32:1448return ARM::MVE_VLDRWU32_post;1449case ARM::MVE_VSTRB16:1450return ARM::MVE_VSTRB16_post;1451case ARM::MVE_VSTRB32:1452return ARM::MVE_VSTRB32_post;1453case ARM::MVE_VSTRH32:1454return ARM::MVE_VSTRH32_post;1455case ARM::MVE_VSTRBU8:1456return ARM::MVE_VSTRBU8_post;1457case ARM::MVE_VSTRHU16:1458return ARM::MVE_VSTRHU16_post;1459case ARM::MVE_VSTRWU32:1460return ARM::MVE_VSTRWU32_post;14611462default: llvm_unreachable("Unhandled opcode!");1463}1464}14651466/// Fold proceeding/trailing inc/dec of base register into the1467/// LDR/STR/FLD{D|S}/FST{D|S} op when possible:1468bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {1469// Thumb1 doesn't have updating LDR/STR.1470// FIXME: Use LDM/STM with single register instead.1471if (isThumb1) return false;1472LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);14731474Register Base = getLoadStoreBaseOp(*MI).getReg();1475bool BaseKill = getLoadStoreBaseOp(*MI).isKill();1476unsigned Opcode = MI->getOpcode();1477DebugLoc DL = MI->getDebugLoc();1478bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||1479Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);1480bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);1481if (isi32Load(Opcode) || isi32Store(Opcode))1482if (MI->getOperand(2).getImm() != 0)1483return false;1484if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)1485return false;14861487// Can't do the merge if the destination register is the same as the would-be1488// writeback register.1489if (MI->getOperand(0).getReg() == Base)1490return false;14911492Register PredReg;1493ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);1494int Bytes = getLSMultipleTransferSize(MI);1495MachineBasicBlock &MBB = *MI->getParent();1496MachineBasicBlock::iterator MBBI(MI);1497int Offset;1498MachineBasicBlock::iterator MergeInstr1499= findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);1500unsigned NewOpc;1501if (!isAM5 && Offset == Bytes) {1502NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);1503} else if (Offset == -Bytes) {1504NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);1505} else {1506MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);1507if (MergeInstr == MBB.end())1508return false;15091510NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);1511if ((isAM5 && Offset != Bytes) ||1512(!isAM5 && !isLegalAddressImm(NewOpc, Offset, TII))) {1513NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);1514if (isAM5 || !isLegalAddressImm(NewOpc, Offset, TII))1515return false;1516}1517}1518LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);1519MBB.erase(MergeInstr);15201521ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;15221523bool isLd = isLoadSingle(Opcode);1524if (isAM5) {1525// VLDM[SD]_UPD, VSTM[SD]_UPD1526// (There are no base-updating versions of VLDR/VSTR instructions, but the1527// updating load/store-multiple instructions can be used with only one1528// register.)1529MachineOperand &MO = MI->getOperand(0);1530auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))1531.addReg(Base, getDefRegState(true)) // WB base register1532.addReg(Base, getKillRegState(isLd ? BaseKill : false))1533.addImm(Pred)1534.addReg(PredReg)1535.addReg(MO.getReg(), (isLd ? getDefRegState(true)1536: getKillRegState(MO.isKill())))1537.cloneMemRefs(*MI);1538(void)MIB;1539LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1540} else if (isLd) {1541if (isAM2) {1542// LDR_PRE, LDR_POST1543if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {1544auto MIB =1545BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())1546.addReg(Base, RegState::Define)1547.addReg(Base)1548.addImm(Offset)1549.addImm(Pred)1550.addReg(PredReg)1551.cloneMemRefs(*MI);1552(void)MIB;1553LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1554} else {1555int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);1556auto MIB =1557BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())1558.addReg(Base, RegState::Define)1559.addReg(Base)1560.addReg(0)1561.addImm(Imm)1562.add(predOps(Pred, PredReg))1563.cloneMemRefs(*MI);1564(void)MIB;1565LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1566}1567} else {1568// t2LDR_PRE, t2LDR_POST1569auto MIB =1570BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())1571.addReg(Base, RegState::Define)1572.addReg(Base)1573.addImm(Offset)1574.add(predOps(Pred, PredReg))1575.cloneMemRefs(*MI);1576(void)MIB;1577LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1578}1579} else {1580MachineOperand &MO = MI->getOperand(0);1581// FIXME: post-indexed stores use am2offset_imm, which still encodes1582// the vestigal zero-reg offset register. When that's fixed, this clause1583// can be removed entirely.1584if (isAM2 && NewOpc == ARM::STR_POST_IMM) {1585int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);1586// STR_PRE, STR_POST1587auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)1588.addReg(MO.getReg(), getKillRegState(MO.isKill()))1589.addReg(Base)1590.addReg(0)1591.addImm(Imm)1592.add(predOps(Pred, PredReg))1593.cloneMemRefs(*MI);1594(void)MIB;1595LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1596} else {1597// t2STR_PRE, t2STR_POST1598auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)1599.addReg(MO.getReg(), getKillRegState(MO.isKill()))1600.addReg(Base)1601.addImm(Offset)1602.add(predOps(Pred, PredReg))1603.cloneMemRefs(*MI);1604(void)MIB;1605LLVM_DEBUG(dbgs() << " Added new instruction: " << *MIB);1606}1607}1608MBB.erase(MBBI);16091610return true;1611}16121613bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {1614unsigned Opcode = MI.getOpcode();1615assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&1616"Must have t2STRDi8 or t2LDRDi8");1617if (MI.getOperand(3).getImm() != 0)1618return false;1619LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << MI);16201621// Behaviour for writeback is undefined if base register is the same as one1622// of the others.1623const MachineOperand &BaseOp = MI.getOperand(2);1624Register Base = BaseOp.getReg();1625const MachineOperand &Reg0Op = MI.getOperand(0);1626const MachineOperand &Reg1Op = MI.getOperand(1);1627if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)1628return false;16291630Register PredReg;1631ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);1632MachineBasicBlock::iterator MBBI(MI);1633MachineBasicBlock &MBB = *MI.getParent();1634int Offset;1635MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,1636PredReg, Offset);1637unsigned NewOpc;1638if (Offset == 8 || Offset == -8) {1639NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;1640} else {1641MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);1642if (MergeInstr == MBB.end())1643return false;1644NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;1645if (!isLegalAddressImm(NewOpc, Offset, TII))1646return false;1647}1648LLVM_DEBUG(dbgs() << " Erasing old increment: " << *MergeInstr);1649MBB.erase(MergeInstr);16501651DebugLoc DL = MI.getDebugLoc();1652MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));1653if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {1654MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);1655} else {1656assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);1657MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);1658}1659MIB.addReg(BaseOp.getReg(), RegState::Kill)1660.addImm(Offset).addImm(Pred).addReg(PredReg);1661assert(TII->get(Opcode).getNumOperands() == 6 &&1662TII->get(NewOpc).getNumOperands() == 7 &&1663"Unexpected number of operands in Opcode specification.");16641665// Transfer implicit operands.1666for (const MachineOperand &MO : MI.implicit_operands())1667MIB.add(MO);1668MIB.cloneMemRefs(MI);16691670LLVM_DEBUG(dbgs() << " Added new load/store: " << *MIB);1671MBB.erase(MBBI);1672return true;1673}16741675/// Returns true if instruction is a memory operation that this pass is capable1676/// of operating on.1677static bool isMemoryOp(const MachineInstr &MI) {1678unsigned Opcode = MI.getOpcode();1679switch (Opcode) {1680case ARM::VLDRS:1681case ARM::VSTRS:1682case ARM::VLDRD:1683case ARM::VSTRD:1684case ARM::LDRi12:1685case ARM::STRi12:1686case ARM::tLDRi:1687case ARM::tSTRi:1688case ARM::tLDRspi:1689case ARM::tSTRspi:1690case ARM::t2LDRi8:1691case ARM::t2LDRi12:1692case ARM::t2STRi8:1693case ARM::t2STRi12:1694break;1695default:1696return false;1697}1698if (!MI.getOperand(1).isReg())1699return false;17001701// When no memory operands are present, conservatively assume unaligned,1702// volatile, unfoldable.1703if (!MI.hasOneMemOperand())1704return false;17051706const MachineMemOperand &MMO = **MI.memoperands_begin();17071708// Don't touch volatile memory accesses - we may be changing their order.1709// TODO: We could allow unordered and monotonic atomics here, but we need to1710// make sure the resulting ldm/stm is correctly marked as atomic.1711if (MMO.isVolatile() || MMO.isAtomic())1712return false;17131714// Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is1715// not.1716if (MMO.getAlign() < Align(4))1717return false;17181719// str <undef> could probably be eliminated entirely, but for now we just want1720// to avoid making a mess of it.1721// FIXME: Use str <undef> as a wildcard to enable better stm folding.1722if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())1723return false;17241725// Likewise don't mess with references to undefined addresses.1726if (MI.getOperand(1).isUndef())1727return false;17281729return true;1730}17311732static void InsertLDR_STR(MachineBasicBlock &MBB,1733MachineBasicBlock::iterator &MBBI, int Offset,1734bool isDef, unsigned NewOpc, unsigned Reg,1735bool RegDeadKill, bool RegUndef, unsigned BaseReg,1736bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred,1737unsigned PredReg, const TargetInstrInfo *TII,1738MachineInstr *MI) {1739if (isDef) {1740MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),1741TII->get(NewOpc))1742.addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))1743.addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));1744MIB.addImm(Offset).addImm(Pred).addReg(PredReg);1745// FIXME: This is overly conservative; the new instruction accesses 41746// bytes, not 8.1747MIB.cloneMemRefs(*MI);1748} else {1749MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),1750TII->get(NewOpc))1751.addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))1752.addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));1753MIB.addImm(Offset).addImm(Pred).addReg(PredReg);1754// FIXME: This is overly conservative; the new instruction accesses 41755// bytes, not 8.1756MIB.cloneMemRefs(*MI);1757}1758}17591760bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,1761MachineBasicBlock::iterator &MBBI) {1762MachineInstr *MI = &*MBBI;1763unsigned Opcode = MI->getOpcode();1764// FIXME: Code/comments below check Opcode == t2STRDi8, but this check returns1765// if we see this opcode.1766if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)1767return false;17681769const MachineOperand &BaseOp = MI->getOperand(2);1770Register BaseReg = BaseOp.getReg();1771Register EvenReg = MI->getOperand(0).getReg();1772Register OddReg = MI->getOperand(1).getReg();1773unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);1774unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);17751776// ARM errata 602117: LDRD with base in list may result in incorrect base1777// register when interrupted or faulted.1778bool Errata602117 = EvenReg == BaseReg &&1779(Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();1780// ARM LDRD/STRD needs consecutive registers.1781bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&1782(EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);17831784if (!Errata602117 && !NonConsecutiveRegs)1785return false;17861787bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;1788bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;1789bool EvenDeadKill = isLd ?1790MI->getOperand(0).isDead() : MI->getOperand(0).isKill();1791bool EvenUndef = MI->getOperand(0).isUndef();1792bool OddDeadKill = isLd ?1793MI->getOperand(1).isDead() : MI->getOperand(1).isKill();1794bool OddUndef = MI->getOperand(1).isUndef();1795bool BaseKill = BaseOp.isKill();1796bool BaseUndef = BaseOp.isUndef();1797assert((isT2 || MI->getOperand(3).getReg() == ARM::NoRegister) &&1798"register offset not handled below");1799int OffImm = getMemoryOpOffset(*MI);1800Register PredReg;1801ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);18021803if (OddRegNum > EvenRegNum && OffImm == 0) {1804// Ascending register numbers and no offset. It's safe to change it to a1805// ldm or stm.1806unsigned NewOpc = (isLd)1807? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)1808: (isT2 ? ARM::t2STMIA : ARM::STMIA);1809if (isLd) {1810BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))1811.addReg(BaseReg, getKillRegState(BaseKill))1812.addImm(Pred).addReg(PredReg)1813.addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))1814.addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill))1815.cloneMemRefs(*MI);1816++NumLDRD2LDM;1817} else {1818BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))1819.addReg(BaseReg, getKillRegState(BaseKill))1820.addImm(Pred).addReg(PredReg)1821.addReg(EvenReg,1822getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))1823.addReg(OddReg,1824getKillRegState(OddDeadKill) | getUndefRegState(OddUndef))1825.cloneMemRefs(*MI);1826++NumSTRD2STM;1827}1828} else {1829// Split into two instructions.1830unsigned NewOpc = (isLd)1831? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)1832: (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);1833// Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,1834// so adjust and use t2LDRi12 here for that.1835unsigned NewOpc2 = (isLd)1836? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)1837: (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);1838// If this is a load, make sure the first load does not clobber the base1839// register before the second load reads it.1840if (isLd && TRI->regsOverlap(EvenReg, BaseReg)) {1841assert(!TRI->regsOverlap(OddReg, BaseReg));1842InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,1843false, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI);1844InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,1845false, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,1846MI);1847} else {1848if (OddReg == EvenReg && EvenDeadKill) {1849// If the two source operands are the same, the kill marker is1850// probably on the first one. e.g.1851// t2STRDi8 killed %r5, %r5, killed %r9, 0, 14, %reg01852EvenDeadKill = false;1853OddDeadKill = true;1854}1855// Never kill the base register in the first instruction.1856if (EvenReg == BaseReg)1857EvenDeadKill = false;1858InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,1859EvenUndef, BaseReg, false, BaseUndef, Pred, PredReg, TII,1860MI);1861InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,1862OddUndef, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,1863MI);1864}1865if (isLd)1866++NumLDRD2LDR;1867else1868++NumSTRD2STR;1869}18701871MBBI = MBB.erase(MBBI);1872return true;1873}18741875/// An optimization pass to turn multiple LDR / STR ops of the same base and1876/// incrementing offset into LDM / STM ops.1877bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {1878MemOpQueue MemOps;1879unsigned CurrBase = 0;1880unsigned CurrOpc = ~0u;1881ARMCC::CondCodes CurrPred = ARMCC::AL;1882unsigned Position = 0;1883assert(Candidates.size() == 0);1884assert(MergeBaseCandidates.size() == 0);1885LiveRegsValid = false;18861887for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();1888I = MBBI) {1889// The instruction in front of the iterator is the one we look at.1890MBBI = std::prev(I);1891if (FixInvalidRegPairOp(MBB, MBBI))1892continue;1893++Position;18941895if (isMemoryOp(*MBBI)) {1896unsigned Opcode = MBBI->getOpcode();1897const MachineOperand &MO = MBBI->getOperand(0);1898Register Reg = MO.getReg();1899Register Base = getLoadStoreBaseOp(*MBBI).getReg();1900Register PredReg;1901ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);1902int Offset = getMemoryOpOffset(*MBBI);1903if (CurrBase == 0) {1904// Start of a new chain.1905CurrBase = Base;1906CurrOpc = Opcode;1907CurrPred = Pred;1908MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));1909continue;1910}1911// Note: No need to match PredReg in the next if.1912if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {1913// Watch out for:1914// r4 := ldr [r0, #8]1915// r4 := ldr [r0, #4]1916// or1917// r0 := ldr [r0]1918// If a load overrides the base register or a register loaded by1919// another load in our chain, we cannot take this instruction.1920bool Overlap = false;1921if (isLoadSingle(Opcode)) {1922Overlap = (Base == Reg);1923if (!Overlap) {1924for (const MemOpQueueEntry &E : MemOps) {1925if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {1926Overlap = true;1927break;1928}1929}1930}1931}19321933if (!Overlap) {1934// Check offset and sort memory operation into the current chain.1935if (Offset > MemOps.back().Offset) {1936MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));1937continue;1938} else {1939MemOpQueue::iterator MI, ME;1940for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {1941if (Offset < MI->Offset) {1942// Found a place to insert.1943break;1944}1945if (Offset == MI->Offset) {1946// Collision, abort.1947MI = ME;1948break;1949}1950}1951if (MI != MemOps.end()) {1952MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));1953continue;1954}1955}1956}1957}19581959// Don't advance the iterator; The op will start a new chain next.1960MBBI = I;1961--Position;1962// Fallthrough to look into existing chain.1963} else if (MBBI->isDebugInstr()) {1964continue;1965} else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||1966MBBI->getOpcode() == ARM::t2STRDi8) {1967// ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions1968// remember them because we may still be able to merge add/sub into them.1969MergeBaseCandidates.push_back(&*MBBI);1970}19711972// If we are here then the chain is broken; Extract candidates for a merge.1973if (MemOps.size() > 0) {1974FormCandidates(MemOps);1975// Reset for the next chain.1976CurrBase = 0;1977CurrOpc = ~0u;1978CurrPred = ARMCC::AL;1979MemOps.clear();1980}1981}1982if (MemOps.size() > 0)1983FormCandidates(MemOps);19841985// Sort candidates so they get processed from end to begin of the basic1986// block later; This is necessary for liveness calculation.1987auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {1988return M0->InsertPos < M1->InsertPos;1989};1990llvm::sort(Candidates, LessThan);19911992// Go through list of candidates and merge.1993bool Changed = false;1994for (const MergeCandidate *Candidate : Candidates) {1995if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {1996MachineInstr *Merged = MergeOpsUpdate(*Candidate);1997// Merge preceding/trailing base inc/dec into the merged op.1998if (Merged) {1999Changed = true;2000unsigned Opcode = Merged->getOpcode();2001if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)2002MergeBaseUpdateLSDouble(*Merged);2003else2004MergeBaseUpdateLSMultiple(Merged);2005} else {2006for (MachineInstr *MI : Candidate->Instrs) {2007if (MergeBaseUpdateLoadStore(MI))2008Changed = true;2009}2010}2011} else {2012assert(Candidate->Instrs.size() == 1);2013if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))2014Changed = true;2015}2016}2017Candidates.clear();2018// Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.2019for (MachineInstr *MI : MergeBaseCandidates)2020MergeBaseUpdateLSDouble(*MI);2021MergeBaseCandidates.clear();20222023return Changed;2024}20252026/// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")2027/// into the preceding stack restore so it directly restore the value of LR2028/// into pc.2029/// ldmfd sp!, {..., lr}2030/// bx lr2031/// or2032/// ldmfd sp!, {..., lr}2033/// mov pc, lr2034/// =>2035/// ldmfd sp!, {..., pc}2036bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {2037// Thumb1 LDM doesn't allow high registers.2038if (isThumb1) return false;2039if (MBB.empty()) return false;20402041MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();2042if (MBBI != MBB.begin() && MBBI != MBB.end() &&2043(MBBI->getOpcode() == ARM::BX_RET ||2044MBBI->getOpcode() == ARM::tBX_RET ||2045MBBI->getOpcode() == ARM::MOVPCLR)) {2046MachineBasicBlock::iterator PrevI = std::prev(MBBI);2047// Ignore any debug instructions.2048while (PrevI->isDebugInstr() && PrevI != MBB.begin())2049--PrevI;2050MachineInstr &PrevMI = *PrevI;2051unsigned Opcode = PrevMI.getOpcode();2052if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||2053Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||2054Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {2055MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);2056if (MO.getReg() != ARM::LR)2057return false;2058unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);2059assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||2060Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");2061PrevMI.setDesc(TII->get(NewOpc));2062MO.setReg(ARM::PC);2063PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);2064MBB.erase(MBBI);2065return true;2066}2067}2068return false;2069}20702071bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {2072MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();2073if (MBBI == MBB.begin() || MBBI == MBB.end() ||2074MBBI->getOpcode() != ARM::tBX_RET)2075return false;20762077MachineBasicBlock::iterator Prev = MBBI;2078--Prev;2079if (Prev->getOpcode() != ARM::tMOVr ||2080!Prev->definesRegister(ARM::LR, /*TRI=*/nullptr))2081return false;20822083for (auto Use : Prev->uses())2084if (Use.isKill()) {2085assert(STI->hasV4TOps());2086BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))2087.addReg(Use.getReg(), RegState::Kill)2088.add(predOps(ARMCC::AL))2089.copyImplicitOps(*MBBI);2090MBB.erase(MBBI);2091MBB.erase(Prev);2092return true;2093}20942095llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");2096}20972098bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {2099if (skipFunction(Fn.getFunction()))2100return false;21012102MF = &Fn;2103STI = &Fn.getSubtarget<ARMSubtarget>();2104TL = STI->getTargetLowering();2105AFI = Fn.getInfo<ARMFunctionInfo>();2106TII = STI->getInstrInfo();2107TRI = STI->getRegisterInfo();21082109RegClassInfoValid = false;2110isThumb2 = AFI->isThumb2Function();2111isThumb1 = AFI->isThumbFunction() && !isThumb2;21122113bool Modified = false, ModifiedLDMReturn = false;2114for (MachineBasicBlock &MBB : Fn) {2115Modified |= LoadStoreMultipleOpti(MBB);2116if (STI->hasV5TOps() && !AFI->shouldSignReturnAddress())2117ModifiedLDMReturn |= MergeReturnIntoLDM(MBB);2118if (isThumb1)2119Modified |= CombineMovBx(MBB);2120}2121Modified |= ModifiedLDMReturn;21222123// If we merged a BX instruction into an LDM, we need to re-calculate whether2124// LR is restored. This check needs to consider the whole function, not just2125// the instruction(s) we changed, because there may be other BX returns which2126// still need LR to be restored.2127if (ModifiedLDMReturn)2128ARMFrameLowering::updateLRRestored(Fn);21292130Allocator.DestroyAll();2131return Modified;2132}21332134#define ARM_PREALLOC_LOAD_STORE_OPT_NAME \2135"ARM pre- register allocation load / store optimization pass"21362137namespace {21382139/// Pre- register allocation pass that move load / stores from consecutive2140/// locations close to make it more likely they will be combined later.2141struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{2142static char ID;21432144AliasAnalysis *AA;2145const DataLayout *TD;2146const TargetInstrInfo *TII;2147const TargetRegisterInfo *TRI;2148const ARMSubtarget *STI;2149MachineRegisterInfo *MRI;2150MachineDominatorTree *DT;2151MachineFunction *MF;21522153ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}21542155bool runOnMachineFunction(MachineFunction &Fn) override;21562157StringRef getPassName() const override {2158return ARM_PREALLOC_LOAD_STORE_OPT_NAME;2159}21602161void getAnalysisUsage(AnalysisUsage &AU) const override {2162AU.addRequired<AAResultsWrapperPass>();2163AU.addRequired<MachineDominatorTreeWrapperPass>();2164AU.addPreserved<MachineDominatorTreeWrapperPass>();2165MachineFunctionPass::getAnalysisUsage(AU);2166}21672168private:2169bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,2170unsigned &NewOpc, Register &EvenReg, Register &OddReg,2171Register &BaseReg, int &Offset, Register &PredReg,2172ARMCC::CondCodes &Pred, bool &isT2);2173bool RescheduleOps(2174MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops,2175unsigned Base, bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,2176SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap);2177bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);2178bool DistributeIncrements();2179bool DistributeIncrements(Register Base);2180};21812182} // end anonymous namespace21832184char ARMPreAllocLoadStoreOpt::ID = 0;21852186INITIALIZE_PASS_BEGIN(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",2187ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)2188INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)2189INITIALIZE_PASS_END(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",2190ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)21912192// Limit the number of instructions to be rescheduled.2193// FIXME: tune this limit, and/or come up with some better heuristics.2194static cl::opt<unsigned> InstReorderLimit("arm-prera-ldst-opt-reorder-limit",2195cl::init(8), cl::Hidden);21962197bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {2198if (AssumeMisalignedLoadStores || skipFunction(Fn.getFunction()))2199return false;22002201TD = &Fn.getDataLayout();2202STI = &Fn.getSubtarget<ARMSubtarget>();2203TII = STI->getInstrInfo();2204TRI = STI->getRegisterInfo();2205MRI = &Fn.getRegInfo();2206DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();2207MF = &Fn;2208AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();22092210bool Modified = DistributeIncrements();2211for (MachineBasicBlock &MFI : Fn)2212Modified |= RescheduleLoadStoreInstrs(&MFI);22132214return Modified;2215}22162217static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,2218MachineBasicBlock::iterator I,2219MachineBasicBlock::iterator E,2220SmallPtrSetImpl<MachineInstr*> &MemOps,2221SmallSet<unsigned, 4> &MemRegs,2222const TargetRegisterInfo *TRI,2223AliasAnalysis *AA) {2224// Are there stores / loads / calls between them?2225SmallSet<unsigned, 4> AddedRegPressure;2226while (++I != E) {2227if (I->isDebugInstr() || MemOps.count(&*I))2228continue;2229if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())2230return false;2231if (I->mayStore() || (!isLd && I->mayLoad()))2232for (MachineInstr *MemOp : MemOps)2233if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false))2234return false;2235for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {2236MachineOperand &MO = I->getOperand(j);2237if (!MO.isReg())2238continue;2239Register Reg = MO.getReg();2240if (MO.isDef() && TRI->regsOverlap(Reg, Base))2241return false;2242if (Reg != Base && !MemRegs.count(Reg))2243AddedRegPressure.insert(Reg);2244}2245}22462247// Estimate register pressure increase due to the transformation.2248if (MemRegs.size() <= 4)2249// Ok if we are moving small number of instructions.2250return true;2251return AddedRegPressure.size() <= MemRegs.size() * 2;2252}22532254bool ARMPreAllocLoadStoreOpt::CanFormLdStDWord(2255MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc,2256Register &FirstReg, Register &SecondReg, Register &BaseReg, int &Offset,2257Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2) {2258// Make sure we're allowed to generate LDRD/STRD.2259if (!STI->hasV5TEOps())2260return false;22612262// FIXME: VLDRS / VSTRS -> VLDRD / VSTRD2263unsigned Scale = 1;2264unsigned Opcode = Op0->getOpcode();2265if (Opcode == ARM::LDRi12) {2266NewOpc = ARM::LDRD;2267} else if (Opcode == ARM::STRi12) {2268NewOpc = ARM::STRD;2269} else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {2270NewOpc = ARM::t2LDRDi8;2271Scale = 4;2272isT2 = true;2273} else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {2274NewOpc = ARM::t2STRDi8;2275Scale = 4;2276isT2 = true;2277} else {2278return false;2279}22802281// Make sure the base address satisfies i64 ld / st alignment requirement.2282// At the moment, we ignore the memoryoperand's value.2283// If we want to use AliasAnalysis, we should check it accordingly.2284if (!Op0->hasOneMemOperand() ||2285(*Op0->memoperands_begin())->isVolatile() ||2286(*Op0->memoperands_begin())->isAtomic())2287return false;22882289Align Alignment = (*Op0->memoperands_begin())->getAlign();2290Align ReqAlign = STI->getDualLoadStoreAlignment();2291if (Alignment < ReqAlign)2292return false;22932294// Then make sure the immediate offset fits.2295int OffImm = getMemoryOpOffset(*Op0);2296if (isT2) {2297int Limit = (1 << 8) * Scale;2298if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))2299return false;2300Offset = OffImm;2301} else {2302ARM_AM::AddrOpc AddSub = ARM_AM::add;2303if (OffImm < 0) {2304AddSub = ARM_AM::sub;2305OffImm = - OffImm;2306}2307int Limit = (1 << 8) * Scale;2308if (OffImm >= Limit || (OffImm & (Scale-1)))2309return false;2310Offset = ARM_AM::getAM3Opc(AddSub, OffImm);2311}2312FirstReg = Op0->getOperand(0).getReg();2313SecondReg = Op1->getOperand(0).getReg();2314if (FirstReg == SecondReg)2315return false;2316BaseReg = Op0->getOperand(1).getReg();2317Pred = getInstrPredicate(*Op0, PredReg);2318dl = Op0->getDebugLoc();2319return true;2320}23212322bool ARMPreAllocLoadStoreOpt::RescheduleOps(2323MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops, unsigned Base,2324bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,2325SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap) {2326bool RetVal = false;23272328// Sort by offset (in reverse order).2329llvm::sort(Ops, [](const MachineInstr *LHS, const MachineInstr *RHS) {2330int LOffset = getMemoryOpOffset(*LHS);2331int ROffset = getMemoryOpOffset(*RHS);2332assert(LHS == RHS || LOffset != ROffset);2333return LOffset > ROffset;2334});23352336// The loads / stores of the same base are in order. Scan them from first to2337// last and check for the following:2338// 1. Any def of base.2339// 2. Any gaps.2340while (Ops.size() > 1) {2341unsigned FirstLoc = ~0U;2342unsigned LastLoc = 0;2343MachineInstr *FirstOp = nullptr;2344MachineInstr *LastOp = nullptr;2345int LastOffset = 0;2346unsigned LastOpcode = 0;2347unsigned LastBytes = 0;2348unsigned NumMove = 0;2349for (MachineInstr *Op : llvm::reverse(Ops)) {2350// Make sure each operation has the same kind.2351unsigned LSMOpcode2352= getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);2353if (LastOpcode && LSMOpcode != LastOpcode)2354break;23552356// Check that we have a continuous set of offsets.2357int Offset = getMemoryOpOffset(*Op);2358unsigned Bytes = getLSMultipleTransferSize(Op);2359if (LastBytes) {2360if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))2361break;2362}23632364// Don't try to reschedule too many instructions.2365if (NumMove == InstReorderLimit)2366break;23672368// Found a mergable instruction; save information about it.2369++NumMove;2370LastOffset = Offset;2371LastBytes = Bytes;2372LastOpcode = LSMOpcode;23732374unsigned Loc = MI2LocMap[Op];2375if (Loc <= FirstLoc) {2376FirstLoc = Loc;2377FirstOp = Op;2378}2379if (Loc >= LastLoc) {2380LastLoc = Loc;2381LastOp = Op;2382}2383}23842385if (NumMove <= 1)2386Ops.pop_back();2387else {2388SmallPtrSet<MachineInstr*, 4> MemOps;2389SmallSet<unsigned, 4> MemRegs;2390for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) {2391MemOps.insert(Ops[i]);2392MemRegs.insert(Ops[i]->getOperand(0).getReg());2393}23942395// Be conservative, if the instructions are too far apart, don't2396// move them. We want to limit the increase of register pressure.2397bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.2398if (DoMove)2399DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,2400MemOps, MemRegs, TRI, AA);2401if (!DoMove) {2402for (unsigned i = 0; i != NumMove; ++i)2403Ops.pop_back();2404} else {2405// This is the new location for the loads / stores.2406MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;2407while (InsertPos != MBB->end() &&2408(MemOps.count(&*InsertPos) || InsertPos->isDebugInstr()))2409++InsertPos;24102411// If we are moving a pair of loads / stores, see if it makes sense2412// to try to allocate a pair of registers that can form register pairs.2413MachineInstr *Op0 = Ops.back();2414MachineInstr *Op1 = Ops[Ops.size()-2];2415Register FirstReg, SecondReg;2416Register BaseReg, PredReg;2417ARMCC::CondCodes Pred = ARMCC::AL;2418bool isT2 = false;2419unsigned NewOpc = 0;2420int Offset = 0;2421DebugLoc dl;2422if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,2423FirstReg, SecondReg, BaseReg,2424Offset, PredReg, Pred, isT2)) {2425Ops.pop_back();2426Ops.pop_back();24272428const MCInstrDesc &MCID = TII->get(NewOpc);2429const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);2430MRI->constrainRegClass(FirstReg, TRC);2431MRI->constrainRegClass(SecondReg, TRC);24322433// Form the pair instruction.2434if (isLd) {2435MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)2436.addReg(FirstReg, RegState::Define)2437.addReg(SecondReg, RegState::Define)2438.addReg(BaseReg);2439// FIXME: We're converting from LDRi12 to an insn that still2440// uses addrmode2, so we need an explicit offset reg. It should2441// always by reg0 since we're transforming LDRi12s.2442if (!isT2)2443MIB.addReg(0);2444MIB.addImm(Offset).addImm(Pred).addReg(PredReg);2445MIB.cloneMergedMemRefs({Op0, Op1});2446LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");2447++NumLDRDFormed;2448} else {2449MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)2450.addReg(FirstReg)2451.addReg(SecondReg)2452.addReg(BaseReg);2453// FIXME: We're converting from LDRi12 to an insn that still2454// uses addrmode2, so we need an explicit offset reg. It should2455// always by reg0 since we're transforming STRi12s.2456if (!isT2)2457MIB.addReg(0);2458MIB.addImm(Offset).addImm(Pred).addReg(PredReg);2459MIB.cloneMergedMemRefs({Op0, Op1});2460LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");2461++NumSTRDFormed;2462}2463MBB->erase(Op0);2464MBB->erase(Op1);24652466if (!isT2) {2467// Add register allocation hints to form register pairs.2468MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);2469MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);2470}2471} else {2472for (unsigned i = 0; i != NumMove; ++i) {2473MachineInstr *Op = Ops.pop_back_val();2474if (isLd) {2475// Populate RegisterMap with all Registers defined by loads.2476Register Reg = Op->getOperand(0).getReg();2477RegisterMap[Reg];2478}24792480MBB->splice(InsertPos, MBB, Op);2481}2482}24832484NumLdStMoved += NumMove;2485RetVal = true;2486}2487}2488}24892490return RetVal;2491}24922493static void forEachDbgRegOperand(MachineInstr *MI,2494std::function<void(MachineOperand &)> Fn) {2495if (MI->isNonListDebugValue()) {2496auto &Op = MI->getOperand(0);2497if (Op.isReg())2498Fn(Op);2499} else {2500for (unsigned I = 2; I < MI->getNumOperands(); I++) {2501auto &Op = MI->getOperand(I);2502if (Op.isReg())2503Fn(Op);2504}2505}2506}25072508// Update the RegisterMap with the instruction that was moved because a2509// DBG_VALUE_LIST may need to be moved again.2510static void updateRegisterMapForDbgValueListAfterMove(2511SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap,2512MachineInstr *DbgValueListInstr, MachineInstr *InstrToReplace) {25132514forEachDbgRegOperand(DbgValueListInstr, [&](MachineOperand &Op) {2515auto RegIt = RegisterMap.find(Op.getReg());2516if (RegIt == RegisterMap.end())2517return;2518auto &InstrVec = RegIt->getSecond();2519for (unsigned I = 0; I < InstrVec.size(); I++)2520if (InstrVec[I] == InstrToReplace)2521InstrVec[I] = DbgValueListInstr;2522});2523}25242525static DebugVariable createDebugVariableFromMachineInstr(MachineInstr *MI) {2526auto DbgVar = DebugVariable(MI->getDebugVariable(), MI->getDebugExpression(),2527MI->getDebugLoc()->getInlinedAt());2528return DbgVar;2529}25302531bool2532ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {2533bool RetVal = false;25342535DenseMap<MachineInstr*, unsigned> MI2LocMap;2536using MapIt = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>::iterator;2537using Base2InstMap = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>;2538using BaseVec = SmallVector<unsigned, 4>;2539Base2InstMap Base2LdsMap;2540Base2InstMap Base2StsMap;2541BaseVec LdBases;2542BaseVec StBases;2543// This map is used to track the relationship between the virtual2544// register that is the result of a load that is moved and the DBG_VALUE2545// MachineInstr pointer that uses that virtual register.2546SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> RegisterMap;25472548unsigned Loc = 0;2549MachineBasicBlock::iterator MBBI = MBB->begin();2550MachineBasicBlock::iterator E = MBB->end();2551while (MBBI != E) {2552for (; MBBI != E; ++MBBI) {2553MachineInstr &MI = *MBBI;2554if (MI.isCall() || MI.isTerminator()) {2555// Stop at barriers.2556++MBBI;2557break;2558}25592560if (!MI.isDebugInstr())2561MI2LocMap[&MI] = ++Loc;25622563if (!isMemoryOp(MI))2564continue;2565Register PredReg;2566if (getInstrPredicate(MI, PredReg) != ARMCC::AL)2567continue;25682569int Opc = MI.getOpcode();2570bool isLd = isLoadSingle(Opc);2571Register Base = MI.getOperand(1).getReg();2572int Offset = getMemoryOpOffset(MI);2573bool StopHere = false;2574auto FindBases = [&] (Base2InstMap &Base2Ops, BaseVec &Bases) {2575MapIt BI = Base2Ops.find(Base);2576if (BI == Base2Ops.end()) {2577Base2Ops[Base].push_back(&MI);2578Bases.push_back(Base);2579return;2580}2581for (const MachineInstr *MI : BI->second) {2582if (Offset == getMemoryOpOffset(*MI)) {2583StopHere = true;2584break;2585}2586}2587if (!StopHere)2588BI->second.push_back(&MI);2589};25902591if (isLd)2592FindBases(Base2LdsMap, LdBases);2593else2594FindBases(Base2StsMap, StBases);25952596if (StopHere) {2597// Found a duplicate (a base+offset combination that's seen earlier).2598// Backtrack.2599--Loc;2600break;2601}2602}26032604// Re-schedule loads.2605for (unsigned Base : LdBases) {2606SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];2607if (Lds.size() > 1)2608RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap, RegisterMap);2609}26102611// Re-schedule stores.2612for (unsigned Base : StBases) {2613SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];2614if (Sts.size() > 1)2615RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap, RegisterMap);2616}26172618if (MBBI != E) {2619Base2LdsMap.clear();2620Base2StsMap.clear();2621LdBases.clear();2622StBases.clear();2623}2624}26252626// Reschedule DBG_VALUEs to match any loads that were moved. When a load is2627// sunk beyond a DBG_VALUE that is referring to it, the DBG_VALUE becomes a2628// use-before-def, resulting in a loss of debug info.26292630// Example:2631// Before the Pre Register Allocation Load Store Pass2632// inst_a2633// %2 = ld ...2634// inst_b2635// DBG_VALUE %2, "x", ...2636// %3 = ld ...26372638// After the Pass:2639// inst_a2640// inst_b2641// DBG_VALUE %2, "x", ...2642// %2 = ld ...2643// %3 = ld ...26442645// The code below addresses this by moving the DBG_VALUE to the position2646// immediately after the load.26472648// Example:2649// After the code below:2650// inst_a2651// inst_b2652// %2 = ld ...2653// DBG_VALUE %2, "x", ...2654// %3 = ld ...26552656// The algorithm works in two phases: First RescheduleOps() populates the2657// RegisterMap with registers that were moved as keys, there is no value2658// inserted. In the next phase, every MachineInstr in a basic block is2659// iterated over. If it is a valid DBG_VALUE or DBG_VALUE_LIST and it uses one2660// or more registers in the RegisterMap, the RegisterMap and InstrMap are2661// populated with the MachineInstr. If the DBG_VALUE or DBG_VALUE_LIST2662// describes debug information for a variable that already exists in the2663// DbgValueSinkCandidates, the MachineInstr in the DbgValueSinkCandidates must2664// be set to undef. If the current MachineInstr is a load that was moved,2665// undef the corresponding DBG_VALUE or DBG_VALUE_LIST and clone it to below2666// the load.26672668// To illustrate the above algorithm visually let's take this example.26692670// Before the Pre Register Allocation Load Store Pass:2671// %2 = ld ...2672// DBG_VALUE %2, A, .... # X2673// DBG_VALUE 0, A, ... # Y2674// %3 = ld ...2675// DBG_VALUE %3, A, ..., # Z2676// %4 = ld ...26772678// After Pre Register Allocation Load Store Pass:2679// DBG_VALUE %2, A, .... # X2680// DBG_VALUE 0, A, ... # Y2681// DBG_VALUE %3, A, ..., # Z2682// %2 = ld ...2683// %3 = ld ...2684// %4 = ld ...26852686// The algorithm below does the following:26872688// In the beginning, the RegisterMap will have been populated with the virtual2689// registers %2, and %3, the DbgValueSinkCandidates and the InstrMap will be2690// empty. DbgValueSinkCandidates = {}, RegisterMap = {2 -> {}, 3 -> {}},2691// InstrMap {}2692// -> DBG_VALUE %2, A, .... # X2693// DBG_VALUE 0, A, ... # Y2694// DBG_VALUE %3, A, ..., # Z2695// %2 = ld ...2696// %3 = ld ...2697// %4 = ld ...26982699// After the first DBG_VALUE (denoted with an X) is processed, the2700// DbgValueSinkCandidates and InstrMap will be populated and the RegisterMap2701// entry for %2 will be populated as well. DbgValueSinkCandidates = {A -> X},2702// RegisterMap = {2 -> {X}, 3 -> {}}, InstrMap {X -> 2}2703// DBG_VALUE %2, A, .... # X2704// -> DBG_VALUE 0, A, ... # Y2705// DBG_VALUE %3, A, ..., # Z2706// %2 = ld ...2707// %3 = ld ...2708// %4 = ld ...27092710// After the DBG_VALUE Y is processed, the DbgValueSinkCandidates is updated2711// to now hold Y for A and the RegisterMap is also updated to remove X from2712// %2, this is because both X and Y describe the same debug variable A. X is2713// also updated to have a $noreg as the first operand.2714// DbgValueSinkCandidates = {A -> {Y}}, RegisterMap = {2 -> {}, 3 -> {}},2715// InstrMap = {X-> 2}2716// DBG_VALUE $noreg, A, .... # X2717// DBG_VALUE 0, A, ... # Y2718// -> DBG_VALUE %3, A, ..., # Z2719// %2 = ld ...2720// %3 = ld ...2721// %4 = ld ...27222723// After DBG_VALUE Z is processed, the DbgValueSinkCandidates is updated to2724// hold Z fr A, the RegisterMap is updated to hold Z for %3, and the InstrMap2725// is updated to have Z mapped to %3. This is again because Z describes the2726// debug variable A, Y is not updated to have $noreg as first operand because2727// its first operand is an immediate, not a register.2728// DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},2729// InstrMap = {X -> 2, Z -> 3}2730// DBG_VALUE $noreg, A, .... # X2731// DBG_VALUE 0, A, ... # Y2732// DBG_VALUE %3, A, ..., # Z2733// -> %2 = ld ...2734// %3 = ld ...2735// %4 = ld ...27362737// Nothing happens here since the RegisterMap for %2 contains no value.2738// DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},2739// InstrMap = {X -> 2, Z -> 3}2740// DBG_VALUE $noreg, A, .... # X2741// DBG_VALUE 0, A, ... # Y2742// DBG_VALUE %3, A, ..., # Z2743// %2 = ld ...2744// -> %3 = ld ...2745// %4 = ld ...27462747// Since the RegisterMap contains Z as a value for %3, the MachineInstr2748// pointer Z is copied to come after the load for %3 and the old Z's first2749// operand is changed to $noreg the Basic Block iterator is moved to after the2750// DBG_VALUE Z's new position.2751// DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},2752// InstrMap = {X -> 2, Z -> 3}2753// DBG_VALUE $noreg, A, .... # X2754// DBG_VALUE 0, A, ... # Y2755// DBG_VALUE $noreg, A, ..., # Old Z2756// %2 = ld ...2757// %3 = ld ...2758// DBG_VALUE %3, A, ..., # Z2759// -> %4 = ld ...27602761// Nothing happens for %4 and the algorithm exits having processed the entire2762// Basic Block.2763// DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},2764// InstrMap = {X -> 2, Z -> 3}2765// DBG_VALUE $noreg, A, .... # X2766// DBG_VALUE 0, A, ... # Y2767// DBG_VALUE $noreg, A, ..., # Old Z2768// %2 = ld ...2769// %3 = ld ...2770// DBG_VALUE %3, A, ..., # Z2771// %4 = ld ...27722773// This map is used to track the relationship between2774// a Debug Variable and the DBG_VALUE MachineInstr pointer that describes the2775// debug information for that Debug Variable.2776SmallDenseMap<DebugVariable, MachineInstr *, 8> DbgValueSinkCandidates;2777// This map is used to track the relationship between a DBG_VALUE or2778// DBG_VALUE_LIST MachineInstr pointer and Registers that it uses.2779SmallDenseMap<MachineInstr *, SmallVector<Register>, 8> InstrMap;2780for (MBBI = MBB->begin(), E = MBB->end(); MBBI != E; ++MBBI) {2781MachineInstr &MI = *MBBI;27822783auto PopulateRegisterAndInstrMapForDebugInstr = [&](Register Reg) {2784auto RegIt = RegisterMap.find(Reg);2785if (RegIt == RegisterMap.end())2786return;2787auto &InstrVec = RegIt->getSecond();2788InstrVec.push_back(&MI);2789InstrMap[&MI].push_back(Reg);2790};27912792if (MI.isDebugValue()) {2793assert(MI.getDebugVariable() &&2794"DBG_VALUE or DBG_VALUE_LIST must contain a DILocalVariable");27952796auto DbgVar = createDebugVariableFromMachineInstr(&MI);2797// If the first operand is a register and it exists in the RegisterMap, we2798// know this is a DBG_VALUE that uses the result of a load that was moved,2799// and is therefore a candidate to also be moved, add it to the2800// RegisterMap and InstrMap.2801forEachDbgRegOperand(&MI, [&](MachineOperand &Op) {2802PopulateRegisterAndInstrMapForDebugInstr(Op.getReg());2803});28042805// If the current DBG_VALUE describes the same variable as one of the2806// in-flight DBG_VALUEs, remove the candidate from the list and set it to2807// undef. Moving one DBG_VALUE past another would result in the variable's2808// value going back in time when stepping through the block in the2809// debugger.2810auto InstrIt = DbgValueSinkCandidates.find(DbgVar);2811if (InstrIt != DbgValueSinkCandidates.end()) {2812auto *Instr = InstrIt->getSecond();2813auto RegIt = InstrMap.find(Instr);2814if (RegIt != InstrMap.end()) {2815const auto &RegVec = RegIt->getSecond();2816// For every Register in the RegVec, remove the MachineInstr in the2817// RegisterMap that describes the DbgVar.2818for (auto &Reg : RegVec) {2819auto RegIt = RegisterMap.find(Reg);2820if (RegIt == RegisterMap.end())2821continue;2822auto &InstrVec = RegIt->getSecond();2823auto IsDbgVar = [&](MachineInstr *I) -> bool {2824auto Var = createDebugVariableFromMachineInstr(I);2825return Var == DbgVar;2826};28272828llvm::erase_if(InstrVec, IsDbgVar);2829}2830forEachDbgRegOperand(Instr,2831[&](MachineOperand &Op) { Op.setReg(0); });2832}2833}2834DbgValueSinkCandidates[DbgVar] = &MI;2835} else {2836// If the first operand of a load matches with a DBG_VALUE in RegisterMap,2837// then move that DBG_VALUE to below the load.2838auto Opc = MI.getOpcode();2839if (!isLoadSingle(Opc))2840continue;2841auto Reg = MI.getOperand(0).getReg();2842auto RegIt = RegisterMap.find(Reg);2843if (RegIt == RegisterMap.end())2844continue;2845auto &DbgInstrVec = RegIt->getSecond();2846if (!DbgInstrVec.size())2847continue;2848for (auto *DbgInstr : DbgInstrVec) {2849MachineBasicBlock::iterator InsertPos = std::next(MBBI);2850auto *ClonedMI = MI.getMF()->CloneMachineInstr(DbgInstr);2851MBB->insert(InsertPos, ClonedMI);2852MBBI++;2853// Erase the entry into the DbgValueSinkCandidates for the DBG_VALUE2854// that was moved.2855auto DbgVar = createDebugVariableFromMachineInstr(DbgInstr);2856auto DbgIt = DbgValueSinkCandidates.find(DbgVar);2857// If the instruction is a DBG_VALUE_LIST, it may have already been2858// erased from the DbgValueSinkCandidates. Only erase if it exists in2859// the DbgValueSinkCandidates.2860if (DbgIt != DbgValueSinkCandidates.end())2861DbgValueSinkCandidates.erase(DbgIt);2862// Zero out original dbg instr2863forEachDbgRegOperand(DbgInstr,2864[&](MachineOperand &Op) { Op.setReg(0); });2865// Update RegisterMap with ClonedMI because it might have to be moved2866// again.2867if (DbgInstr->isDebugValueList())2868updateRegisterMapForDbgValueListAfterMove(RegisterMap, ClonedMI,2869DbgInstr);2870}2871}2872}2873return RetVal;2874}28752876// Get the Base register operand index from the memory access MachineInst if we2877// should attempt to distribute postinc on it. Return -1 if not of a valid2878// instruction type. If it returns an index, it is assumed that instruction is a2879// r+i indexing mode, and getBaseOperandIndex() + 1 is the Offset index.2880static int getBaseOperandIndex(MachineInstr &MI) {2881switch (MI.getOpcode()) {2882case ARM::MVE_VLDRBS16:2883case ARM::MVE_VLDRBS32:2884case ARM::MVE_VLDRBU16:2885case ARM::MVE_VLDRBU32:2886case ARM::MVE_VLDRHS32:2887case ARM::MVE_VLDRHU32:2888case ARM::MVE_VLDRBU8:2889case ARM::MVE_VLDRHU16:2890case ARM::MVE_VLDRWU32:2891case ARM::MVE_VSTRB16:2892case ARM::MVE_VSTRB32:2893case ARM::MVE_VSTRH32:2894case ARM::MVE_VSTRBU8:2895case ARM::MVE_VSTRHU16:2896case ARM::MVE_VSTRWU32:2897case ARM::t2LDRHi8:2898case ARM::t2LDRHi12:2899case ARM::t2LDRSHi8:2900case ARM::t2LDRSHi12:2901case ARM::t2LDRBi8:2902case ARM::t2LDRBi12:2903case ARM::t2LDRSBi8:2904case ARM::t2LDRSBi12:2905case ARM::t2STRBi8:2906case ARM::t2STRBi12:2907case ARM::t2STRHi8:2908case ARM::t2STRHi12:2909return 1;2910case ARM::MVE_VLDRBS16_post:2911case ARM::MVE_VLDRBS32_post:2912case ARM::MVE_VLDRBU16_post:2913case ARM::MVE_VLDRBU32_post:2914case ARM::MVE_VLDRHS32_post:2915case ARM::MVE_VLDRHU32_post:2916case ARM::MVE_VLDRBU8_post:2917case ARM::MVE_VLDRHU16_post:2918case ARM::MVE_VLDRWU32_post:2919case ARM::MVE_VSTRB16_post:2920case ARM::MVE_VSTRB32_post:2921case ARM::MVE_VSTRH32_post:2922case ARM::MVE_VSTRBU8_post:2923case ARM::MVE_VSTRHU16_post:2924case ARM::MVE_VSTRWU32_post:2925case ARM::MVE_VLDRBS16_pre:2926case ARM::MVE_VLDRBS32_pre:2927case ARM::MVE_VLDRBU16_pre:2928case ARM::MVE_VLDRBU32_pre:2929case ARM::MVE_VLDRHS32_pre:2930case ARM::MVE_VLDRHU32_pre:2931case ARM::MVE_VLDRBU8_pre:2932case ARM::MVE_VLDRHU16_pre:2933case ARM::MVE_VLDRWU32_pre:2934case ARM::MVE_VSTRB16_pre:2935case ARM::MVE_VSTRB32_pre:2936case ARM::MVE_VSTRH32_pre:2937case ARM::MVE_VSTRBU8_pre:2938case ARM::MVE_VSTRHU16_pre:2939case ARM::MVE_VSTRWU32_pre:2940return 2;2941}2942return -1;2943}29442945static bool isPostIndex(MachineInstr &MI) {2946switch (MI.getOpcode()) {2947case ARM::MVE_VLDRBS16_post:2948case ARM::MVE_VLDRBS32_post:2949case ARM::MVE_VLDRBU16_post:2950case ARM::MVE_VLDRBU32_post:2951case ARM::MVE_VLDRHS32_post:2952case ARM::MVE_VLDRHU32_post:2953case ARM::MVE_VLDRBU8_post:2954case ARM::MVE_VLDRHU16_post:2955case ARM::MVE_VLDRWU32_post:2956case ARM::MVE_VSTRB16_post:2957case ARM::MVE_VSTRB32_post:2958case ARM::MVE_VSTRH32_post:2959case ARM::MVE_VSTRBU8_post:2960case ARM::MVE_VSTRHU16_post:2961case ARM::MVE_VSTRWU32_post:2962return true;2963}2964return false;2965}29662967static bool isPreIndex(MachineInstr &MI) {2968switch (MI.getOpcode()) {2969case ARM::MVE_VLDRBS16_pre:2970case ARM::MVE_VLDRBS32_pre:2971case ARM::MVE_VLDRBU16_pre:2972case ARM::MVE_VLDRBU32_pre:2973case ARM::MVE_VLDRHS32_pre:2974case ARM::MVE_VLDRHU32_pre:2975case ARM::MVE_VLDRBU8_pre:2976case ARM::MVE_VLDRHU16_pre:2977case ARM::MVE_VLDRWU32_pre:2978case ARM::MVE_VSTRB16_pre:2979case ARM::MVE_VSTRB32_pre:2980case ARM::MVE_VSTRH32_pre:2981case ARM::MVE_VSTRBU8_pre:2982case ARM::MVE_VSTRHU16_pre:2983case ARM::MVE_VSTRWU32_pre:2984return true;2985}2986return false;2987}29882989// Given a memory access Opcode, check that the give Imm would be a valid Offset2990// for this instruction (same as isLegalAddressImm), Or if the instruction2991// could be easily converted to one where that was valid. For example converting2992// t2LDRi12 to t2LDRi8 for negative offsets. Works in conjunction with2993// AdjustBaseAndOffset below.2994static bool isLegalOrConvertableAddressImm(unsigned Opcode, int Imm,2995const TargetInstrInfo *TII,2996int &CodesizeEstimate) {2997if (isLegalAddressImm(Opcode, Imm, TII))2998return true;29993000// We can convert AddrModeT2_i12 to AddrModeT2_i8neg.3001const MCInstrDesc &Desc = TII->get(Opcode);3002unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);3003switch (AddrMode) {3004case ARMII::AddrModeT2_i12:3005CodesizeEstimate += 1;3006return Imm < 0 && -Imm < ((1 << 8) * 1);3007}3008return false;3009}30103011// Given an MI adjust its address BaseReg to use NewBaseReg and address offset3012// by -Offset. This can either happen in-place or be a replacement as MI is3013// converted to another instruction type.3014static void AdjustBaseAndOffset(MachineInstr *MI, Register NewBaseReg,3015int Offset, const TargetInstrInfo *TII,3016const TargetRegisterInfo *TRI) {3017// Set the Base reg3018unsigned BaseOp = getBaseOperandIndex(*MI);3019MI->getOperand(BaseOp).setReg(NewBaseReg);3020// and constrain the reg class to that required by the instruction.3021MachineFunction *MF = MI->getMF();3022MachineRegisterInfo &MRI = MF->getRegInfo();3023const MCInstrDesc &MCID = TII->get(MI->getOpcode());3024const TargetRegisterClass *TRC = TII->getRegClass(MCID, BaseOp, TRI, *MF);3025MRI.constrainRegClass(NewBaseReg, TRC);30263027int OldOffset = MI->getOperand(BaseOp + 1).getImm();3028if (isLegalAddressImm(MI->getOpcode(), OldOffset - Offset, TII))3029MI->getOperand(BaseOp + 1).setImm(OldOffset - Offset);3030else {3031unsigned ConvOpcode;3032switch (MI->getOpcode()) {3033case ARM::t2LDRHi12:3034ConvOpcode = ARM::t2LDRHi8;3035break;3036case ARM::t2LDRSHi12:3037ConvOpcode = ARM::t2LDRSHi8;3038break;3039case ARM::t2LDRBi12:3040ConvOpcode = ARM::t2LDRBi8;3041break;3042case ARM::t2LDRSBi12:3043ConvOpcode = ARM::t2LDRSBi8;3044break;3045case ARM::t2STRHi12:3046ConvOpcode = ARM::t2STRHi8;3047break;3048case ARM::t2STRBi12:3049ConvOpcode = ARM::t2STRBi8;3050break;3051default:3052llvm_unreachable("Unhandled convertable opcode");3053}3054assert(isLegalAddressImm(ConvOpcode, OldOffset - Offset, TII) &&3055"Illegal Address Immediate after convert!");30563057const MCInstrDesc &MCID = TII->get(ConvOpcode);3058BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)3059.add(MI->getOperand(0))3060.add(MI->getOperand(1))3061.addImm(OldOffset - Offset)3062.add(MI->getOperand(3))3063.add(MI->getOperand(4))3064.cloneMemRefs(*MI);3065MI->eraseFromParent();3066}3067}30683069static MachineInstr *createPostIncLoadStore(MachineInstr *MI, int Offset,3070Register NewReg,3071const TargetInstrInfo *TII,3072const TargetRegisterInfo *TRI) {3073MachineFunction *MF = MI->getMF();3074MachineRegisterInfo &MRI = MF->getRegInfo();30753076unsigned NewOpcode = getPostIndexedLoadStoreOpcode(3077MI->getOpcode(), Offset > 0 ? ARM_AM::add : ARM_AM::sub);30783079const MCInstrDesc &MCID = TII->get(NewOpcode);3080// Constrain the def register class3081const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);3082MRI.constrainRegClass(NewReg, TRC);3083// And do the same for the base operand3084TRC = TII->getRegClass(MCID, 2, TRI, *MF);3085MRI.constrainRegClass(MI->getOperand(1).getReg(), TRC);30863087unsigned AddrMode = (MCID.TSFlags & ARMII::AddrModeMask);3088switch (AddrMode) {3089case ARMII::AddrModeT2_i7:3090case ARMII::AddrModeT2_i7s2:3091case ARMII::AddrModeT2_i7s4:3092// Any MVE load/store3093return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)3094.addReg(NewReg, RegState::Define)3095.add(MI->getOperand(0))3096.add(MI->getOperand(1))3097.addImm(Offset)3098.add(MI->getOperand(3))3099.add(MI->getOperand(4))3100.add(MI->getOperand(5))3101.cloneMemRefs(*MI);3102case ARMII::AddrModeT2_i8:3103if (MI->mayLoad()) {3104return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)3105.add(MI->getOperand(0))3106.addReg(NewReg, RegState::Define)3107.add(MI->getOperand(1))3108.addImm(Offset)3109.add(MI->getOperand(3))3110.add(MI->getOperand(4))3111.cloneMemRefs(*MI);3112} else {3113return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)3114.addReg(NewReg, RegState::Define)3115.add(MI->getOperand(0))3116.add(MI->getOperand(1))3117.addImm(Offset)3118.add(MI->getOperand(3))3119.add(MI->getOperand(4))3120.cloneMemRefs(*MI);3121}3122default:3123llvm_unreachable("Unhandled createPostIncLoadStore");3124}3125}31263127// Given a Base Register, optimise the load/store uses to attempt to create more3128// post-inc accesses and less register moves. We do this by taking zero offset3129// loads/stores with an add, and convert them to a postinc load/store of the3130// same type. Any subsequent accesses will be adjusted to use and account for3131// the post-inc value.3132// For example:3133// LDR #0 LDR_POSTINC #163134// LDR #4 LDR #-123135// LDR #8 LDR #-83136// LDR #12 LDR #-43137// ADD #163138//3139// At the same time if we do not find an increment but do find an existing3140// pre/post inc instruction, we can still adjust the offsets of subsequent3141// instructions to save the register move that would otherwise be needed for the3142// in-place increment.3143bool ARMPreAllocLoadStoreOpt::DistributeIncrements(Register Base) {3144// We are looking for:3145// One zero offset load/store that can become postinc3146MachineInstr *BaseAccess = nullptr;3147MachineInstr *PrePostInc = nullptr;3148// An increment that can be folded in3149MachineInstr *Increment = nullptr;3150// Other accesses after BaseAccess that will need to be updated to use the3151// postinc value.3152SmallPtrSet<MachineInstr *, 8> OtherAccesses;3153for (auto &Use : MRI->use_nodbg_instructions(Base)) {3154if (!Increment && getAddSubImmediate(Use) != 0) {3155Increment = &Use;3156continue;3157}31583159int BaseOp = getBaseOperandIndex(Use);3160if (BaseOp == -1)3161return false;31623163if (!Use.getOperand(BaseOp).isReg() ||3164Use.getOperand(BaseOp).getReg() != Base)3165return false;3166if (isPreIndex(Use) || isPostIndex(Use))3167PrePostInc = &Use;3168else if (Use.getOperand(BaseOp + 1).getImm() == 0)3169BaseAccess = &Use;3170else3171OtherAccesses.insert(&Use);3172}31733174int IncrementOffset;3175Register NewBaseReg;3176if (BaseAccess && Increment) {3177if (PrePostInc || BaseAccess->getParent() != Increment->getParent())3178return false;3179Register PredReg;3180if (Increment->definesRegister(ARM::CPSR, /*TRI=*/nullptr) ||3181getInstrPredicate(*Increment, PredReg) != ARMCC::AL)3182return false;31833184LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on VirtualReg "3185<< Base.virtRegIndex() << "\n");31863187// Make sure that Increment has no uses before BaseAccess that are not PHI3188// uses.3189for (MachineInstr &Use :3190MRI->use_nodbg_instructions(Increment->getOperand(0).getReg())) {3191if (&Use == BaseAccess || (Use.getOpcode() != TargetOpcode::PHI &&3192!DT->dominates(BaseAccess, &Use))) {3193LLVM_DEBUG(dbgs() << " BaseAccess doesn't dominate use of increment\n");3194return false;3195}3196}31973198// Make sure that Increment can be folded into Base3199IncrementOffset = getAddSubImmediate(*Increment);3200unsigned NewPostIncOpcode = getPostIndexedLoadStoreOpcode(3201BaseAccess->getOpcode(), IncrementOffset > 0 ? ARM_AM::add : ARM_AM::sub);3202if (!isLegalAddressImm(NewPostIncOpcode, IncrementOffset, TII)) {3203LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on postinc\n");3204return false;3205}3206}3207else if (PrePostInc) {3208// If we already have a pre/post index load/store then set BaseAccess,3209// IncrementOffset and NewBaseReg to the values it already produces,3210// allowing us to update and subsequent uses of BaseOp reg with the3211// incremented value.3212if (Increment)3213return false;32143215LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on already "3216<< "indexed VirtualReg " << Base.virtRegIndex() << "\n");3217int BaseOp = getBaseOperandIndex(*PrePostInc);3218IncrementOffset = PrePostInc->getOperand(BaseOp+1).getImm();3219BaseAccess = PrePostInc;3220NewBaseReg = PrePostInc->getOperand(0).getReg();3221}3222else3223return false;32243225// And make sure that the negative value of increment can be added to all3226// other offsets after the BaseAccess. We rely on either3227// dominates(BaseAccess, OtherAccess) or dominates(OtherAccess, BaseAccess)3228// to keep things simple.3229// This also adds a simple codesize metric, to detect if an instruction (like3230// t2LDRBi12) which can often be shrunk to a thumb1 instruction (tLDRBi)3231// cannot because it is converted to something else (t2LDRBi8). We start this3232// at -1 for the gain from removing the increment.3233SmallPtrSet<MachineInstr *, 4> SuccessorAccesses;3234int CodesizeEstimate = -1;3235for (auto *Use : OtherAccesses) {3236if (DT->dominates(BaseAccess, Use)) {3237SuccessorAccesses.insert(Use);3238unsigned BaseOp = getBaseOperandIndex(*Use);3239if (!isLegalOrConvertableAddressImm(Use->getOpcode(),3240Use->getOperand(BaseOp + 1).getImm() -3241IncrementOffset,3242TII, CodesizeEstimate)) {3243LLVM_DEBUG(dbgs() << " Illegal addressing mode immediate on use\n");3244return false;3245}3246} else if (!DT->dominates(Use, BaseAccess)) {3247LLVM_DEBUG(3248dbgs() << " Unknown dominance relation between Base and Use\n");3249return false;3250}3251}3252if (STI->hasMinSize() && CodesizeEstimate > 0) {3253LLVM_DEBUG(dbgs() << " Expected to grow instructions under minsize\n");3254return false;3255}32563257if (!PrePostInc) {3258// Replace BaseAccess with a post inc3259LLVM_DEBUG(dbgs() << "Changing: "; BaseAccess->dump());3260LLVM_DEBUG(dbgs() << " And : "; Increment->dump());3261NewBaseReg = Increment->getOperand(0).getReg();3262MachineInstr *BaseAccessPost =3263createPostIncLoadStore(BaseAccess, IncrementOffset, NewBaseReg, TII, TRI);3264BaseAccess->eraseFromParent();3265Increment->eraseFromParent();3266(void)BaseAccessPost;3267LLVM_DEBUG(dbgs() << " To : "; BaseAccessPost->dump());3268}32693270for (auto *Use : SuccessorAccesses) {3271LLVM_DEBUG(dbgs() << "Changing: "; Use->dump());3272AdjustBaseAndOffset(Use, NewBaseReg, IncrementOffset, TII, TRI);3273LLVM_DEBUG(dbgs() << " To : "; Use->dump());3274}32753276// Remove the kill flag from all uses of NewBaseReg, in case any old uses3277// remain.3278for (MachineOperand &Op : MRI->use_nodbg_operands(NewBaseReg))3279Op.setIsKill(false);3280return true;3281}32823283bool ARMPreAllocLoadStoreOpt::DistributeIncrements() {3284bool Changed = false;3285SmallSetVector<Register, 4> Visited;3286for (auto &MBB : *MF) {3287for (auto &MI : MBB) {3288int BaseOp = getBaseOperandIndex(MI);3289if (BaseOp == -1 || !MI.getOperand(BaseOp).isReg())3290continue;32913292Register Base = MI.getOperand(BaseOp).getReg();3293if (!Base.isVirtual() || Visited.count(Base))3294continue;32953296Visited.insert(Base);3297}3298}32993300for (auto Base : Visited)3301Changed |= DistributeIncrements(Base);33023303return Changed;3304}33053306/// Returns an instance of the load / store optimization pass.3307FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {3308if (PreAlloc)3309return new ARMPreAllocLoadStoreOpt();3310return new ARMLoadStoreOpt();3311}331233133314