Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/ExpandLargeDivRem.cpp
35233 views
//===--- ExpandLargeDivRem.cpp - Expand large div/rem ---------------------===//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 pass expands div/rem instructions with a bitwidth above a threshold9// into a call to auto-generated functions.10// This is useful for targets like x86_64 that cannot lower divisions11// with more than 128 bits or targets like x86_32 that cannot lower divisions12// with more than 64 bits.13//14//===----------------------------------------------------------------------===//1516#include "llvm/CodeGen/ExpandLargeDivRem.h"17#include "llvm/ADT/SmallVector.h"18#include "llvm/ADT/StringExtras.h"19#include "llvm/Analysis/GlobalsModRef.h"20#include "llvm/CodeGen/Passes.h"21#include "llvm/CodeGen/TargetLowering.h"22#include "llvm/CodeGen/TargetPassConfig.h"23#include "llvm/CodeGen/TargetSubtargetInfo.h"24#include "llvm/IR/IRBuilder.h"25#include "llvm/IR/InstIterator.h"26#include "llvm/IR/PassManager.h"27#include "llvm/InitializePasses.h"28#include "llvm/Pass.h"29#include "llvm/Support/CommandLine.h"30#include "llvm/Target/TargetMachine.h"31#include "llvm/Transforms/Utils/IntegerDivision.h"3233using namespace llvm;3435static cl::opt<unsigned>36ExpandDivRemBits("expand-div-rem-bits", cl::Hidden,37cl::init(llvm::IntegerType::MAX_INT_BITS),38cl::desc("div and rem instructions on integers with "39"more than <N> bits are expanded."));4041static bool isConstantPowerOfTwo(llvm::Value *V, bool SignedOp) {42auto *C = dyn_cast<ConstantInt>(V);43if (!C)44return false;4546APInt Val = C->getValue();47if (SignedOp && Val.isNegative())48Val = -Val;49return Val.isPowerOf2();50}5152static bool isSigned(unsigned int Opcode) {53return Opcode == Instruction::SDiv || Opcode == Instruction::SRem;54}5556static void scalarize(BinaryOperator *BO,57SmallVectorImpl<BinaryOperator *> &Replace) {58VectorType *VTy = cast<FixedVectorType>(BO->getType());5960IRBuilder<> Builder(BO);6162unsigned NumElements = VTy->getElementCount().getFixedValue();63Value *Result = PoisonValue::get(VTy);64for (unsigned Idx = 0; Idx < NumElements; ++Idx) {65Value *LHS = Builder.CreateExtractElement(BO->getOperand(0), Idx);66Value *RHS = Builder.CreateExtractElement(BO->getOperand(1), Idx);67Value *Op = Builder.CreateBinOp(BO->getOpcode(), LHS, RHS);68Result = Builder.CreateInsertElement(Result, Op, Idx);69if (auto *NewBO = dyn_cast<BinaryOperator>(Op)) {70NewBO->copyIRFlags(Op, true);71Replace.push_back(NewBO);72}73}74BO->replaceAllUsesWith(Result);75BO->dropAllReferences();76BO->eraseFromParent();77}7879static bool runImpl(Function &F, const TargetLowering &TLI) {80SmallVector<BinaryOperator *, 4> Replace;81SmallVector<BinaryOperator *, 4> ReplaceVector;82bool Modified = false;8384unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();85if (ExpandDivRemBits != llvm::IntegerType::MAX_INT_BITS)86MaxLegalDivRemBitWidth = ExpandDivRemBits;8788if (MaxLegalDivRemBitWidth >= llvm::IntegerType::MAX_INT_BITS)89return false;9091for (auto &I : instructions(F)) {92switch (I.getOpcode()) {93case Instruction::UDiv:94case Instruction::SDiv:95case Instruction::URem:96case Instruction::SRem: {97// TODO: This pass doesn't handle scalable vectors.98if (I.getOperand(0)->getType()->isScalableTy())99continue;100101auto *IntTy = dyn_cast<IntegerType>(I.getType()->getScalarType());102if (!IntTy || IntTy->getIntegerBitWidth() <= MaxLegalDivRemBitWidth)103continue;104105// The backend has peephole optimizations for powers of two.106// TODO: We don't consider vectors here.107if (isConstantPowerOfTwo(I.getOperand(1), isSigned(I.getOpcode())))108continue;109110if (I.getOperand(0)->getType()->isVectorTy())111ReplaceVector.push_back(&cast<BinaryOperator>(I));112else113Replace.push_back(&cast<BinaryOperator>(I));114Modified = true;115break;116}117default:118break;119}120}121122while (!ReplaceVector.empty()) {123BinaryOperator *BO = ReplaceVector.pop_back_val();124scalarize(BO, Replace);125}126127if (Replace.empty())128return false;129130while (!Replace.empty()) {131BinaryOperator *I = Replace.pop_back_val();132133if (I->getOpcode() == Instruction::UDiv ||134I->getOpcode() == Instruction::SDiv) {135expandDivision(I);136} else {137expandRemainder(I);138}139}140141return Modified;142}143144namespace {145class ExpandLargeDivRemLegacyPass : public FunctionPass {146public:147static char ID;148149ExpandLargeDivRemLegacyPass() : FunctionPass(ID) {150initializeExpandLargeDivRemLegacyPassPass(*PassRegistry::getPassRegistry());151}152153bool runOnFunction(Function &F) override {154auto *TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();155auto *TLI = TM->getSubtargetImpl(F)->getTargetLowering();156return runImpl(F, *TLI);157}158159void getAnalysisUsage(AnalysisUsage &AU) const override {160AU.addRequired<TargetPassConfig>();161AU.addPreserved<AAResultsWrapperPass>();162AU.addPreserved<GlobalsAAWrapperPass>();163}164};165} // namespace166167PreservedAnalyses ExpandLargeDivRemPass::run(Function &F,168FunctionAnalysisManager &FAM) {169const TargetSubtargetInfo *STI = TM->getSubtargetImpl(F);170return runImpl(F, *STI->getTargetLowering()) ? PreservedAnalyses::none()171: PreservedAnalyses::all();172}173174char ExpandLargeDivRemLegacyPass::ID = 0;175INITIALIZE_PASS_BEGIN(ExpandLargeDivRemLegacyPass, "expand-large-div-rem",176"Expand large div/rem", false, false)177INITIALIZE_PASS_END(ExpandLargeDivRemLegacyPass, "expand-large-div-rem",178"Expand large div/rem", false, false)179180FunctionPass *llvm::createExpandLargeDivRemPass() {181return new ExpandLargeDivRemLegacyPass();182}183184185