Path: blob/main/contrib/llvm-project/llvm/lib/Target/Lanai/LanaiInstrInfo.cpp
35271 views
//===-- LanaiInstrInfo.cpp - Lanai Instruction Information ------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains the Lanai implementation of the TargetInstrInfo class.9//10//===----------------------------------------------------------------------===//1112#include "LanaiInstrInfo.h"13#include "LanaiAluCode.h"14#include "LanaiCondCode.h"15#include "MCTargetDesc/LanaiBaseInfo.h"16#include "llvm/ADT/STLExtras.h"17#include "llvm/ADT/SmallVector.h"18#include "llvm/CodeGen/MachineFunctionPass.h"19#include "llvm/CodeGen/MachineInstrBuilder.h"20#include "llvm/CodeGen/MachineRegisterInfo.h"21#include "llvm/MC/TargetRegistry.h"22#include "llvm/Support/ErrorHandling.h"2324using namespace llvm;2526#define GET_INSTRINFO_CTOR_DTOR27#include "LanaiGenInstrInfo.inc"2829LanaiInstrInfo::LanaiInstrInfo()30: LanaiGenInstrInfo(Lanai::ADJCALLSTACKDOWN, Lanai::ADJCALLSTACKUP),31RegisterInfo() {}3233void LanaiInstrInfo::copyPhysReg(MachineBasicBlock &MBB,34MachineBasicBlock::iterator Position,35const DebugLoc &DL,36MCRegister DestinationRegister,37MCRegister SourceRegister,38bool KillSource) const {39if (!Lanai::GPRRegClass.contains(DestinationRegister, SourceRegister)) {40llvm_unreachable("Impossible reg-to-reg copy");41}4243BuildMI(MBB, Position, DL, get(Lanai::OR_I_LO), DestinationRegister)44.addReg(SourceRegister, getKillRegState(KillSource))45.addImm(0);46}4748void LanaiInstrInfo::storeRegToStackSlot(49MachineBasicBlock &MBB, MachineBasicBlock::iterator Position,50Register SourceRegister, bool IsKill, int FrameIndex,51const TargetRegisterClass *RegisterClass,52const TargetRegisterInfo * /*RegisterInfo*/, Register /*VReg*/) const {53DebugLoc DL;54if (Position != MBB.end()) {55DL = Position->getDebugLoc();56}5758if (!Lanai::GPRRegClass.hasSubClassEq(RegisterClass)) {59llvm_unreachable("Can't store this register to stack slot");60}61BuildMI(MBB, Position, DL, get(Lanai::SW_RI))62.addReg(SourceRegister, getKillRegState(IsKill))63.addFrameIndex(FrameIndex)64.addImm(0)65.addImm(LPAC::ADD);66}6768void LanaiInstrInfo::loadRegFromStackSlot(69MachineBasicBlock &MBB, MachineBasicBlock::iterator Position,70Register DestinationRegister, int FrameIndex,71const TargetRegisterClass *RegisterClass,72const TargetRegisterInfo * /*RegisterInfo*/, Register /*VReg*/) const {73DebugLoc DL;74if (Position != MBB.end()) {75DL = Position->getDebugLoc();76}7778if (!Lanai::GPRRegClass.hasSubClassEq(RegisterClass)) {79llvm_unreachable("Can't load this register from stack slot");80}81BuildMI(MBB, Position, DL, get(Lanai::LDW_RI), DestinationRegister)82.addFrameIndex(FrameIndex)83.addImm(0)84.addImm(LPAC::ADD);85}8687bool LanaiInstrInfo::areMemAccessesTriviallyDisjoint(88const MachineInstr &MIa, const MachineInstr &MIb) const {89assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");90assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");9192if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||93MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())94return false;9596// Retrieve the base register, offset from the base register and width. Width97// is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If98// base registers are identical, and the offset of a lower memory access +99// the width doesn't overlap the offset of a higher memory access,100// then the memory accesses are different.101const TargetRegisterInfo *TRI = &getRegisterInfo();102const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;103int64_t OffsetA = 0, OffsetB = 0;104LocationSize WidthA = 0, WidthB = 0;105if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&106getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {107if (BaseOpA->isIdenticalTo(*BaseOpB)) {108int LowOffset = std::min(OffsetA, OffsetB);109int HighOffset = std::max(OffsetA, OffsetB);110LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;111if (LowWidth.hasValue() &&112LowOffset + (int)LowWidth.getValue() <= HighOffset)113return true;114}115}116return false;117}118119bool LanaiInstrInfo::expandPostRAPseudo(MachineInstr & /*MI*/) const {120return false;121}122123static LPCC::CondCode getOppositeCondition(LPCC::CondCode CC) {124switch (CC) {125case LPCC::ICC_T: // true126return LPCC::ICC_F;127case LPCC::ICC_F: // false128return LPCC::ICC_T;129case LPCC::ICC_HI: // high130return LPCC::ICC_LS;131case LPCC::ICC_LS: // low or same132return LPCC::ICC_HI;133case LPCC::ICC_CC: // carry cleared134return LPCC::ICC_CS;135case LPCC::ICC_CS: // carry set136return LPCC::ICC_CC;137case LPCC::ICC_NE: // not equal138return LPCC::ICC_EQ;139case LPCC::ICC_EQ: // equal140return LPCC::ICC_NE;141case LPCC::ICC_VC: // oVerflow cleared142return LPCC::ICC_VS;143case LPCC::ICC_VS: // oVerflow set144return LPCC::ICC_VC;145case LPCC::ICC_PL: // plus (note: 0 is "minus" too here)146return LPCC::ICC_MI;147case LPCC::ICC_MI: // minus148return LPCC::ICC_PL;149case LPCC::ICC_GE: // greater than or equal150return LPCC::ICC_LT;151case LPCC::ICC_LT: // less than152return LPCC::ICC_GE;153case LPCC::ICC_GT: // greater than154return LPCC::ICC_LE;155case LPCC::ICC_LE: // less than or equal156return LPCC::ICC_GT;157default:158llvm_unreachable("Invalid condtional code");159}160}161162std::pair<unsigned, unsigned>163LanaiInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {164return std::make_pair(TF, 0u);165}166167ArrayRef<std::pair<unsigned, const char *>>168LanaiInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {169using namespace LanaiII;170static const std::pair<unsigned, const char *> TargetFlags[] = {171{MO_ABS_HI, "lanai-hi"},172{MO_ABS_LO, "lanai-lo"},173{MO_NO_FLAG, "lanai-nf"}};174return ArrayRef(TargetFlags);175}176177bool LanaiInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,178Register &SrcReg2, int64_t &CmpMask,179int64_t &CmpValue) const {180switch (MI.getOpcode()) {181default:182break;183case Lanai::SFSUB_F_RI_LO:184case Lanai::SFSUB_F_RI_HI:185SrcReg = MI.getOperand(0).getReg();186SrcReg2 = Register();187CmpMask = ~0;188CmpValue = MI.getOperand(1).getImm();189return true;190case Lanai::SFSUB_F_RR:191SrcReg = MI.getOperand(0).getReg();192SrcReg2 = MI.getOperand(1).getReg();193CmpMask = ~0;194CmpValue = 0;195return true;196}197198return false;199}200201// isRedundantFlagInstr - check whether the first instruction, whose only202// purpose is to update flags, can be made redundant.203// * SFSUB_F_RR can be made redundant by SUB_RI if the operands are the same.204// * SFSUB_F_RI can be made redundant by SUB_I if the operands are the same.205inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg,206unsigned SrcReg2, int64_t ImmValue,207MachineInstr *OI) {208if (CmpI->getOpcode() == Lanai::SFSUB_F_RR &&209OI->getOpcode() == Lanai::SUB_R &&210((OI->getOperand(1).getReg() == SrcReg &&211OI->getOperand(2).getReg() == SrcReg2) ||212(OI->getOperand(1).getReg() == SrcReg2 &&213OI->getOperand(2).getReg() == SrcReg)))214return true;215216if (((CmpI->getOpcode() == Lanai::SFSUB_F_RI_LO &&217OI->getOpcode() == Lanai::SUB_I_LO) ||218(CmpI->getOpcode() == Lanai::SFSUB_F_RI_HI &&219OI->getOpcode() == Lanai::SUB_I_HI)) &&220OI->getOperand(1).getReg() == SrcReg &&221OI->getOperand(2).getImm() == ImmValue)222return true;223return false;224}225226inline static unsigned flagSettingOpcodeVariant(unsigned OldOpcode) {227switch (OldOpcode) {228case Lanai::ADD_I_HI:229return Lanai::ADD_F_I_HI;230case Lanai::ADD_I_LO:231return Lanai::ADD_F_I_LO;232case Lanai::ADD_R:233return Lanai::ADD_F_R;234case Lanai::ADDC_I_HI:235return Lanai::ADDC_F_I_HI;236case Lanai::ADDC_I_LO:237return Lanai::ADDC_F_I_LO;238case Lanai::ADDC_R:239return Lanai::ADDC_F_R;240case Lanai::AND_I_HI:241return Lanai::AND_F_I_HI;242case Lanai::AND_I_LO:243return Lanai::AND_F_I_LO;244case Lanai::AND_R:245return Lanai::AND_F_R;246case Lanai::OR_I_HI:247return Lanai::OR_F_I_HI;248case Lanai::OR_I_LO:249return Lanai::OR_F_I_LO;250case Lanai::OR_R:251return Lanai::OR_F_R;252case Lanai::SL_I:253return Lanai::SL_F_I;254case Lanai::SRL_R:255return Lanai::SRL_F_R;256case Lanai::SA_I:257return Lanai::SA_F_I;258case Lanai::SRA_R:259return Lanai::SRA_F_R;260case Lanai::SUB_I_HI:261return Lanai::SUB_F_I_HI;262case Lanai::SUB_I_LO:263return Lanai::SUB_F_I_LO;264case Lanai::SUB_R:265return Lanai::SUB_F_R;266case Lanai::SUBB_I_HI:267return Lanai::SUBB_F_I_HI;268case Lanai::SUBB_I_LO:269return Lanai::SUBB_F_I_LO;270case Lanai::SUBB_R:271return Lanai::SUBB_F_R;272case Lanai::XOR_I_HI:273return Lanai::XOR_F_I_HI;274case Lanai::XOR_I_LO:275return Lanai::XOR_F_I_LO;276case Lanai::XOR_R:277return Lanai::XOR_F_R;278default:279return Lanai::NOP;280}281}282283bool LanaiInstrInfo::optimizeCompareInstr(284MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2,285int64_t /*CmpMask*/, int64_t CmpValue,286const MachineRegisterInfo *MRI) const {287// Get the unique definition of SrcReg.288MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);289if (!MI)290return false;291292// Get ready to iterate backward from CmpInstr.293MachineBasicBlock::iterator I = CmpInstr, E = MI,294B = CmpInstr.getParent()->begin();295296// Early exit if CmpInstr is at the beginning of the BB.297if (I == B)298return false;299300// There are two possible candidates which can be changed to set SR:301// One is MI, the other is a SUB instruction.302// * For SFSUB_F_RR(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).303// * For SFSUB_F_RI(r1, CmpValue), we are looking for SUB(r1, CmpValue).304MachineInstr *Sub = nullptr;305if (SrcReg2 != 0)306// MI is not a candidate to transform into a flag setting instruction.307MI = nullptr;308else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {309// Conservatively refuse to convert an instruction which isn't in the same310// BB as the comparison. Don't return if SFSUB_F_RI and CmpValue != 0 as Sub311// may still be a candidate.312if (CmpInstr.getOpcode() == Lanai::SFSUB_F_RI_LO)313MI = nullptr;314else315return false;316}317318// Check that SR isn't set between the comparison instruction and the319// instruction we want to change while searching for Sub.320const TargetRegisterInfo *TRI = &getRegisterInfo();321for (--I; I != E; --I) {322const MachineInstr &Instr = *I;323324if (Instr.modifiesRegister(Lanai::SR, TRI) ||325Instr.readsRegister(Lanai::SR, TRI))326// This instruction modifies or uses SR after the one we want to change.327// We can't do this transformation.328return false;329330// Check whether CmpInstr can be made redundant by the current instruction.331if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) {332Sub = &*I;333break;334}335336// Don't search outside the containing basic block.337if (I == B)338return false;339}340341// Return false if no candidates exist.342if (!MI && !Sub)343return false;344345// The single candidate is called MI.346if (!MI)347MI = Sub;348349if (flagSettingOpcodeVariant(MI->getOpcode()) != Lanai::NOP) {350bool isSafe = false;351352SmallVector<std::pair<MachineOperand *, LPCC::CondCode>, 4>353OperandsToUpdate;354I = CmpInstr;355E = CmpInstr.getParent()->end();356while (!isSafe && ++I != E) {357const MachineInstr &Instr = *I;358for (unsigned IO = 0, EO = Instr.getNumOperands(); !isSafe && IO != EO;359++IO) {360const MachineOperand &MO = Instr.getOperand(IO);361if (MO.isRegMask() && MO.clobbersPhysReg(Lanai::SR)) {362isSafe = true;363break;364}365if (!MO.isReg() || MO.getReg() != Lanai::SR)366continue;367if (MO.isDef()) {368isSafe = true;369break;370}371// Condition code is after the operand before SR.372LPCC::CondCode CC;373CC = (LPCC::CondCode)Instr.getOperand(IO - 1).getImm();374375if (Sub) {376LPCC::CondCode NewCC = getOppositeCondition(CC);377if (NewCC == LPCC::ICC_T)378return false;379// If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on380// CMP needs to be updated to be based on SUB. Push the condition381// code operands to OperandsToUpdate. If it is safe to remove382// CmpInstr, the condition code of these operands will be modified.383if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&384Sub->getOperand(2).getReg() == SrcReg) {385OperandsToUpdate.push_back(386std::make_pair(&((*I).getOperand(IO - 1)), NewCC));387}388} else {389// No Sub, so this is x = <op> y, z; cmp x, 0.390switch (CC) {391case LPCC::ICC_EQ: // Z392case LPCC::ICC_NE: // Z393case LPCC::ICC_MI: // N394case LPCC::ICC_PL: // N395case LPCC::ICC_F: // none396case LPCC::ICC_T: // none397// SR can be used multiple times, we should continue.398break;399case LPCC::ICC_CS: // C400case LPCC::ICC_CC: // C401case LPCC::ICC_VS: // V402case LPCC::ICC_VC: // V403case LPCC::ICC_HI: // C Z404case LPCC::ICC_LS: // C Z405case LPCC::ICC_GE: // N V406case LPCC::ICC_LT: // N V407case LPCC::ICC_GT: // Z N V408case LPCC::ICC_LE: // Z N V409// The instruction uses the V bit or C bit which is not safe.410return false;411case LPCC::UNKNOWN:412return false;413}414}415}416}417418// If SR is not killed nor re-defined, we should check whether it is419// live-out. If it is live-out, do not optimize.420if (!isSafe) {421MachineBasicBlock *MBB = CmpInstr.getParent();422for (const MachineBasicBlock *Succ : MBB->successors())423if (Succ->isLiveIn(Lanai::SR))424return false;425}426427// Toggle the optional operand to SR.428MI->setDesc(get(flagSettingOpcodeVariant(MI->getOpcode())));429MI->addRegisterDefined(Lanai::SR);430CmpInstr.eraseFromParent();431return true;432}433434return false;435}436437bool LanaiInstrInfo::analyzeSelect(const MachineInstr &MI,438SmallVectorImpl<MachineOperand> &Cond,439unsigned &TrueOp, unsigned &FalseOp,440bool &Optimizable) const {441assert(MI.getOpcode() == Lanai::SELECT && "unknown select instruction");442// Select operands:443// 0: Def.444// 1: True use.445// 2: False use.446// 3: Condition code.447TrueOp = 1;448FalseOp = 2;449Cond.push_back(MI.getOperand(3));450Optimizable = true;451return false;452}453454// Identify instructions that can be folded into a SELECT instruction, and455// return the defining instruction.456static MachineInstr *canFoldIntoSelect(Register Reg,457const MachineRegisterInfo &MRI) {458if (!Reg.isVirtual())459return nullptr;460if (!MRI.hasOneNonDBGUse(Reg))461return nullptr;462MachineInstr *MI = MRI.getVRegDef(Reg);463if (!MI)464return nullptr;465// MI is folded into the SELECT by predicating it.466if (!MI->isPredicable())467return nullptr;468// Check if MI has any non-dead defs or physreg uses. This also detects469// predicated instructions which will be reading SR.470for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 1)) {471// Reject frame index operands.472if (MO.isFI() || MO.isCPI() || MO.isJTI())473return nullptr;474if (!MO.isReg())475continue;476// MI can't have any tied operands, that would conflict with predication.477if (MO.isTied())478return nullptr;479if (MO.getReg().isPhysical())480return nullptr;481if (MO.isDef() && !MO.isDead())482return nullptr;483}484bool DontMoveAcrossStores = true;485if (!MI->isSafeToMove(/*AliasAnalysis=*/nullptr, DontMoveAcrossStores))486return nullptr;487return MI;488}489490MachineInstr *491LanaiInstrInfo::optimizeSelect(MachineInstr &MI,492SmallPtrSetImpl<MachineInstr *> &SeenMIs,493bool /*PreferFalse*/) const {494assert(MI.getOpcode() == Lanai::SELECT && "unknown select instruction");495MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();496MachineInstr *DefMI = canFoldIntoSelect(MI.getOperand(1).getReg(), MRI);497bool Invert = !DefMI;498if (!DefMI)499DefMI = canFoldIntoSelect(MI.getOperand(2).getReg(), MRI);500if (!DefMI)501return nullptr;502503// Find new register class to use.504MachineOperand FalseReg = MI.getOperand(Invert ? 1 : 2);505Register DestReg = MI.getOperand(0).getReg();506const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());507if (!MRI.constrainRegClass(DestReg, PreviousClass))508return nullptr;509510// Create a new predicated version of DefMI.511MachineInstrBuilder NewMI =512BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);513514// Copy all the DefMI operands, excluding its (null) predicate.515const MCInstrDesc &DefDesc = DefMI->getDesc();516for (unsigned i = 1, e = DefDesc.getNumOperands();517i != e && !DefDesc.operands()[i].isPredicate(); ++i)518NewMI.add(DefMI->getOperand(i));519520unsigned CondCode = MI.getOperand(3).getImm();521if (Invert)522NewMI.addImm(getOppositeCondition(LPCC::CondCode(CondCode)));523else524NewMI.addImm(CondCode);525NewMI.copyImplicitOps(MI);526527// The output register value when the predicate is false is an implicit528// register operand tied to the first def. The tie makes the register529// allocator ensure the FalseReg is allocated the same register as operand 0.530FalseReg.setImplicit();531NewMI.add(FalseReg);532NewMI->tieOperands(0, NewMI->getNumOperands() - 1);533534// Update SeenMIs set: register newly created MI and erase removed DefMI.535SeenMIs.insert(NewMI);536SeenMIs.erase(DefMI);537538// If MI is inside a loop, and DefMI is outside the loop, then kill flags on539// DefMI would be invalid when transferred inside the loop. Checking for a540// loop is expensive, but at least remove kill flags if they are in different541// BBs.542if (DefMI->getParent() != MI.getParent())543NewMI->clearKillInfo();544545// The caller will erase MI, but not DefMI.546DefMI->eraseFromParent();547return NewMI;548}549550// The analyzeBranch function is used to examine conditional instructions and551// remove unnecessary instructions. This method is used by BranchFolder and552// IfConverter machine function passes to improve the CFG.553// - TrueBlock is set to the destination if condition evaluates true (it is the554// nullptr if the destination is the fall-through branch);555// - FalseBlock is set to the destination if condition evaluates to false (it556// is the nullptr if the branch is unconditional);557// - condition is populated with machine operands needed to generate the branch558// to insert in insertBranch;559// Returns: false if branch could successfully be analyzed.560bool LanaiInstrInfo::analyzeBranch(MachineBasicBlock &MBB,561MachineBasicBlock *&TrueBlock,562MachineBasicBlock *&FalseBlock,563SmallVectorImpl<MachineOperand> &Condition,564bool AllowModify) const {565// Iterator to current instruction being considered.566MachineBasicBlock::iterator Instruction = MBB.end();567568// Start from the bottom of the block and work up, examining the569// terminator instructions.570while (Instruction != MBB.begin()) {571--Instruction;572573// Skip over debug instructions.574if (Instruction->isDebugInstr())575continue;576577// Working from the bottom, when we see a non-terminator578// instruction, we're done.579if (!isUnpredicatedTerminator(*Instruction))580break;581582// A terminator that isn't a branch can't easily be handled583// by this analysis.584if (!Instruction->isBranch())585return true;586587// Handle unconditional branches.588if (Instruction->getOpcode() == Lanai::BT) {589if (!AllowModify) {590TrueBlock = Instruction->getOperand(0).getMBB();591continue;592}593594// If the block has any instructions after a branch, delete them.595MBB.erase(std::next(Instruction), MBB.end());596597Condition.clear();598FalseBlock = nullptr;599600// Delete the jump if it's equivalent to a fall-through.601if (MBB.isLayoutSuccessor(Instruction->getOperand(0).getMBB())) {602TrueBlock = nullptr;603Instruction->eraseFromParent();604Instruction = MBB.end();605continue;606}607608// TrueBlock is used to indicate the unconditional destination.609TrueBlock = Instruction->getOperand(0).getMBB();610continue;611}612613// Handle conditional branches614unsigned Opcode = Instruction->getOpcode();615if (Opcode != Lanai::BRCC)616return true; // Unknown opcode.617618// Multiple conditional branches are not handled here so only proceed if619// there are no conditions enqueued.620if (Condition.empty()) {621LPCC::CondCode BranchCond =622static_cast<LPCC::CondCode>(Instruction->getOperand(1).getImm());623624// TrueBlock is the target of the previously seen unconditional branch.625FalseBlock = TrueBlock;626TrueBlock = Instruction->getOperand(0).getMBB();627Condition.push_back(MachineOperand::CreateImm(BranchCond));628continue;629}630631// Multiple conditional branches are not handled.632return true;633}634635// Return false indicating branch successfully analyzed.636return false;637}638639// reverseBranchCondition - Reverses the branch condition of the specified640// condition list, returning false on success and true if it cannot be641// reversed.642bool LanaiInstrInfo::reverseBranchCondition(643SmallVectorImpl<llvm::MachineOperand> &Condition) const {644assert((Condition.size() == 1) &&645"Lanai branch conditions should have one component.");646647LPCC::CondCode BranchCond =648static_cast<LPCC::CondCode>(Condition[0].getImm());649Condition[0].setImm(getOppositeCondition(BranchCond));650return false;651}652653// Insert the branch with condition specified in condition and given targets654// (TrueBlock and FalseBlock). This function returns the number of machine655// instructions inserted.656unsigned LanaiInstrInfo::insertBranch(MachineBasicBlock &MBB,657MachineBasicBlock *TrueBlock,658MachineBasicBlock *FalseBlock,659ArrayRef<MachineOperand> Condition,660const DebugLoc &DL,661int *BytesAdded) const {662// Shouldn't be a fall through.663assert(TrueBlock && "insertBranch must not be told to insert a fallthrough");664assert(!BytesAdded && "code size not handled");665666// If condition is empty then an unconditional branch is being inserted.667if (Condition.empty()) {668assert(!FalseBlock && "Unconditional branch with multiple successors!");669BuildMI(&MBB, DL, get(Lanai::BT)).addMBB(TrueBlock);670return 1;671}672673// Else a conditional branch is inserted.674assert((Condition.size() == 1) &&675"Lanai branch conditions should have one component.");676unsigned ConditionalCode = Condition[0].getImm();677BuildMI(&MBB, DL, get(Lanai::BRCC)).addMBB(TrueBlock).addImm(ConditionalCode);678679// If no false block, then false behavior is fall through and no branch needs680// to be inserted.681if (!FalseBlock)682return 1;683684BuildMI(&MBB, DL, get(Lanai::BT)).addMBB(FalseBlock);685return 2;686}687688unsigned LanaiInstrInfo::removeBranch(MachineBasicBlock &MBB,689int *BytesRemoved) const {690assert(!BytesRemoved && "code size not handled");691692MachineBasicBlock::iterator Instruction = MBB.end();693unsigned Count = 0;694695while (Instruction != MBB.begin()) {696--Instruction;697if (Instruction->isDebugInstr())698continue;699if (Instruction->getOpcode() != Lanai::BT &&700Instruction->getOpcode() != Lanai::BRCC) {701break;702}703704// Remove the branch.705Instruction->eraseFromParent();706Instruction = MBB.end();707++Count;708}709710return Count;711}712713Register LanaiInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,714int &FrameIndex) const {715if (MI.getOpcode() == Lanai::LDW_RI)716if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&717MI.getOperand(2).getImm() == 0) {718FrameIndex = MI.getOperand(1).getIndex();719return MI.getOperand(0).getReg();720}721return 0;722}723724Register LanaiInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,725int &FrameIndex) const {726if (MI.getOpcode() == Lanai::LDW_RI) {727unsigned Reg;728if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))729return Reg;730// Check for post-frame index elimination operations731SmallVector<const MachineMemOperand *, 1> Accesses;732if (hasLoadFromStackSlot(MI, Accesses)){733FrameIndex =734cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())735->getFrameIndex();736return 1;737}738}739return 0;740}741742Register LanaiInstrInfo::isStoreToStackSlot(const MachineInstr &MI,743int &FrameIndex) const {744if (MI.getOpcode() == Lanai::SW_RI)745if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&746MI.getOperand(1).getImm() == 0) {747FrameIndex = MI.getOperand(0).getIndex();748return MI.getOperand(2).getReg();749}750return 0;751}752753bool LanaiInstrInfo::getMemOperandWithOffsetWidth(754const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,755LocationSize &Width, const TargetRegisterInfo * /*TRI*/) const {756// Handle only loads/stores with base register followed by immediate offset757// and with add as ALU op.758if (LdSt.getNumOperands() != 4)759return false;760if (!LdSt.getOperand(1).isReg() || !LdSt.getOperand(2).isImm() ||761!(LdSt.getOperand(3).isImm() && LdSt.getOperand(3).getImm() == LPAC::ADD))762return false;763764switch (LdSt.getOpcode()) {765default:766return false;767case Lanai::LDW_RI:768case Lanai::LDW_RR:769case Lanai::SW_RR:770case Lanai::SW_RI:771Width = 4;772break;773case Lanai::LDHs_RI:774case Lanai::LDHz_RI:775case Lanai::STH_RI:776Width = 2;777break;778case Lanai::LDBs_RI:779case Lanai::LDBz_RI:780case Lanai::STB_RI:781Width = 1;782break;783}784785BaseOp = &LdSt.getOperand(1);786Offset = LdSt.getOperand(2).getImm();787788if (!BaseOp->isReg())789return false;790791return true;792}793794bool LanaiInstrInfo::getMemOperandsWithOffsetWidth(795const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,796int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,797const TargetRegisterInfo *TRI) const {798switch (LdSt.getOpcode()) {799default:800return false;801case Lanai::LDW_RI:802case Lanai::LDW_RR:803case Lanai::SW_RR:804case Lanai::SW_RI:805case Lanai::LDHs_RI:806case Lanai::LDHz_RI:807case Lanai::STH_RI:808case Lanai::LDBs_RI:809case Lanai::LDBz_RI:810const MachineOperand *BaseOp;811OffsetIsScalable = false;812if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))813return false;814BaseOps.push_back(BaseOp);815return true;816}817}818819820