40 #define DEBUG_TYPE "arm-codegenprepare" 46 cl::desc(
"Disable ARM specific CodeGenPrepare pass"));
50 cl::desc(
"Use DSP instructions for scalar operations"));
54 cl::desc(
"Use DSP instructions for scalar operations\ 55 with immediate operands"));
66 IRPromoter(
Module *M) : M(M), Ctx(M->getContext()) { }
69 for (
auto *
I : InstsToRemove) {
71 I->dropAllReferences();
74 InstsToRemove.clear();
78 void Mutate(
Type *OrigTy,
86 IRPromoter *Promoter =
nullptr;
87 std::set<Value*> AllVisited;
88 Type *OrigTy =
nullptr;
89 unsigned TypeSize = 0;
92 bool isSupportedValue(
Value *V);
94 bool TryToPromote(
Value *V);
105 StringRef getPassName()
const override {
return "ARM IR optimizations"; }
107 bool doInitialization(
Module &M)
override;
109 bool doFinalization(
Module &M)
override;
116 if (!isa<Instruction>(V))
119 unsigned Opc = cast<Instruction>(V)->getOpcode();
120 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
121 Opc == Instruction::SRem;
140 if (
auto *ZExt = dyn_cast<ZExtInst>(V))
149 auto UsesNarrowValue = [](
Value *V) {
153 if (
auto *
Store = dyn_cast<StoreInst>(V))
154 return UsesNarrowValue(
Store->getValueOperand());
155 if (
auto *
Return = dyn_cast<ReturnInst>(V))
156 return UsesNarrowValue(
Return->getReturnValue());
158 return isa<CallInst>(V);
165 else if (isa<TruncInst>(V))
167 else if (
auto *ZExt = dyn_cast<ZExtInst>(V))
169 return isa<LoadInst>(ZExt->getOperand(0)) &&
170 ZExt->getOperand(0)->hasOneUse();
171 else if (
auto *Call = dyn_cast<CallInst>(V))
172 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
173 else if (
auto *
Load = dyn_cast<LoadInst>(V)) {
174 if (!isa<IntegerType>(
Load->getType()))
177 if (
Load->hasOneUse() && isa<ZExtInst>(*
Load->use_begin()))
204 bool NegImm = cast<ConstantInt>(I->
getOperand(1))->isNegative();
205 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
210 LLVM_DEBUG(
dbgs() <<
"ARM CGP: Allowing safe overflow for " << *I <<
"\n");
217 if (
auto *Const = dyn_cast<ConstantInt>(
Op))
218 if (Const->isNegative())
229 if (!isa<IntegerType>(V->
getType()))
232 if (isa<StoreInst>(
I) || isa<TerminatorInst>(
I) || isa<TruncInst>(
I) ||
236 if (
auto *ZExt = dyn_cast<ZExtInst>(
I))
237 return !ZExt->getDestTy()->isIntegerTy(32);
245 if (!isa<Instruction>(V))
253 auto *
I = cast<Instruction>(V);
254 if (
I->hasOneUse() &&
isSink(*
I->use_begin()))
257 if (isa<OverflowingBinaryOperator>(
I))
273 return TypeSize == 16 ? Intrinsic::arm_uadd16 :
274 Intrinsic::arm_uadd8;
275 case Instruction::Sub:
276 return TypeSize == 16 ? Intrinsic::arm_usub16 :
277 Intrinsic::arm_usub8;
282 void IRPromoter::Mutate(
Type *OrigTy,
290 LLVM_DEBUG(
dbgs() <<
"ARM CGP: Promoting use-def chains to from " << TypeSize
293 auto ReplaceAllUsersOfWith = [&](
Value *From,
Value *To) {
297 auto *
User = cast<Instruction>(U.getUser());
298 if (InstTo &&
User->isIdenticalTo(InstTo))
303 for (
auto &U : Users)
304 U->replaceUsesOfWith(From, To);
321 I->replaceUsesOfWith(Const, NewConst);
329 Builder.SetInsertPoint(
I);
330 Builder.SetCurrentDebugLocation(
I->getDebugLoc());
331 Value *
Args[] = {
I->getOperand(0),
I->getOperand(1) };
332 CallInst *Call = Builder.CreateCall(DSPInst, Args);
333 ReplaceAllUsersOfWith(
I, Call);
334 InstsToRemove.push_back(
I);
339 LLVM_DEBUG(
dbgs() <<
"ARM CGP: Inserting ZExt for " << *V <<
"\n");
340 Builder.SetInsertPoint(InsertPt);
341 if (
auto *
I = dyn_cast<Instruction>(V))
342 Builder.SetCurrentDebugLocation(
I->getDebugLoc());
343 auto *ZExt = cast<Instruction>(Builder.CreateZExt(V, ExtTy));
344 if (isa<Argument>(V))
345 ZExt->moveBefore(InsertPt);
347 ZExt->moveAfter(InsertPt);
348 ReplaceAllUsersOfWith(V, ZExt);
354 for (
auto V : Leaves) {
356 if (
auto *ZExt = dyn_cast<ZExtInst>(V))
357 ZExt->mutateType(ExtTy);
358 else if (
auto *
I = dyn_cast<Instruction>(V))
360 else if (
auto *
Arg = dyn_cast<Argument>(V)) {
372 for (
auto *V : Visited) {
376 if (!isa<Instruction>(V))
379 auto *
I = cast<Instruction>(V);
383 for (
auto &U :
I->operands()) {
387 if (
auto *Const = dyn_cast<ConstantInt>(&*U))
389 else if (isa<UndefValue>(&*U))
390 U->mutateType(ExtTy);
394 I->mutateType(ExtTy);
401 for (
auto *V : Visited) {
404 if (
auto *ZExt = dyn_cast<ZExtInst>(V)) {
405 if (ZExt->getDestTy() != ExtTy) {
406 ZExt->mutateType(ExtTy);
409 else if (ZExt->getSrcTy() == ExtTy) {
410 ReplaceAllUsersOfWith(V, ZExt->getOperand(0));
411 InstsToRemove.push_back(ZExt);
420 InsertDSPIntrinsic(cast<Instruction>(V));
426 for (
auto I : Roots) {
428 Type *TruncTy = OrigTy;
429 if (
auto *
Store = dyn_cast<StoreInst>(
I)) {
430 auto *PtrTy = cast<PointerType>(
Store->getPointerOperandType());
431 TruncTy = PtrTy->getElementType();
432 }
else if (isa<ReturnInst>(
I)) {
437 for (
unsigned i = 0; i <
I->getNumOperands(); ++i) {
438 Value *V =
I->getOperand(i);
440 if (
auto *
Op = dyn_cast<Instruction>(V)) {
442 if (
auto *Call = dyn_cast<CallInst>(
I))
443 TruncTy = Call->getFunctionType()->getParamType(i);
445 if (TruncTy == ExtTy)
449 <<
" Trunc for " << *
Op <<
"\n");
450 Builder.SetInsertPoint(
Op);
451 auto *Trunc = cast<Instruction>(Builder.CreateTrunc(
Op, TruncTy));
452 Trunc->moveBefore(
I);
453 I->setOperand(i, Trunc);
462 bool ARMCodeGenPrepare::isNarrowInstSupported(
Instruction *
I) {
466 if (
ST->isThumb() && !
ST->hasThumb2())
478 if (isa<Constant>(
Op)) {
490 bool ARMCodeGenPrepare::isSupportedValue(
Value *V) {
494 if (isa<ConstantInt>(V) || isa<Argument>(V))
498 if (isa<StoreInst>(V) || isa<LoadInst>(V) || isa<GetElementPtrInst>(V))
502 if (
auto *ICmp = dyn_cast<ICmpInst>(V))
503 return ICmp->isEquality() || !ICmp->isSigned();
505 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
508 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V))
514 if (
auto *Call = dyn_cast<CallInst>(V))
515 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
516 else if (
auto *Cast = dyn_cast<CastInst>(V)) {
517 if (isa<ZExtInst>(Cast))
518 return Cast->getDestTy()->getScalarSizeInBits() <= 32;
519 else if (
auto *Trunc = dyn_cast<TruncInst>(V))
520 return Trunc->getDestTy()->getScalarSizeInBits() <= TypeSize;
525 }
else if (!isa<BinaryOperator>(V)) {
532 LLVM_DEBUG(
dbgs() <<
"ARM CGP: No, it's a signed instruction.\n");
544 if (
auto *Ld = dyn_cast<LoadInst>(V)) {
545 auto *PtrTy = cast<PointerType>(Ld->getPointerOperandType());
546 VSize = PtrTy->getElementType()->getPrimitiveSizeInBits();
547 }
else if (
auto *ZExt = dyn_cast<ZExtInst>(V)) {
548 VSize = ZExt->getOperand(0)->getType()->getPrimitiveSizeInBits();
553 if (VSize > TypeSize)
559 if (
auto *I = dyn_cast<Instruction>(V))
560 return isNarrowInstSupported(I);
565 bool ARMCodeGenPrepare::TryToPromote(
Value *V) {
579 CurrentVisited.
clear();
583 auto AddLegalInst = [&](
Value *V) {
584 if (CurrentVisited.
count(V))
597 while (!WorkList.
empty()) {
600 if (CurrentVisited.
count(V))
603 if (!isa<Instruction>(V) && !
isSource(V))
610 if (AllVisited.count(V)) {
611 LLVM_DEBUG(
dbgs() <<
"ARM CGP: Already visited this: " << *V <<
"\n");
616 AllVisited.insert(V);
620 Roots.
insert(cast<Instruction>(V));
623 else if (
auto *I = dyn_cast<Instruction>(V)) {
626 if (!AddLegalInst(U))
635 if (!AddLegalInst(U.getUser()))
641 unsigned NumToPromote = 0;
643 for (
auto *V : CurrentVisited) {
646 if (isa<TruncInst>(V))
648 else if (
auto *
Arg = dyn_cast<Argument>(V)) {
649 if (!
Arg->hasZExtAttr())
655 if (Leaves.
count(V) || isa<StoreInst>(V) || !isa<Instruction>(V))
659 if (Roots.
count(cast<Instruction>(V))) {
669 for (
auto *I : CurrentVisited)
672 LLVM_DEBUG(
dbgs() <<
"ARM CGP: Cost of promoting " << NumToPromote
673 <<
" instructions = " << Cost <<
"\n");
674 if (Cost > NumToPromote || (NumToPromote == 0))
677 Promoter->Mutate(OrigTy, CurrentVisited, Leaves, Roots);
681 bool ARMCodeGenPrepare::doInitialization(
Module &M) {
682 Promoter =
new IRPromoter(&M);
690 auto *TPC = &getAnalysis<TargetPassConfig>();
696 bool MadeChange =
false;
701 auto &Insts = BB.getInstList();
702 for (
auto &I : Insts) {
703 if (AllVisited.count(&I))
706 if (isa<ICmpInst>(I)) {
707 auto &CI = cast<ICmpInst>(
I);
710 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
714 for (
auto &
Op : CI.operands()) {
715 if (
auto *I = dyn_cast<Instruction>(
Op)) {
716 if (isa<ZExtInst>(I))
719 MadeChange |= TryToPromote(I);
736 bool ARMCodeGenPrepare::doFinalization(
Module &M) {
742 "ARM IR optimizations",
false,
false)
746 char ARMCodeGenPrepare::
ID = 0;
749 return new ARMCodeGenPrepare();
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
iterator_range< use_iterator > uses()
static bool isSupportedType(Value *V)
Some instructions can use 8- and 16-bit operands, and we don't need to promote anything larger...
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
This class represents a function call, abstracting a target machine's calling convention.
bool isLegalToPromote(CallSite CS, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
setjmp/longjmp based exceptions
iv Induction Variable Users
static IntegerType * getInt16Ty(LLVMContext &C)
const T & back() const
Return the last element of the SetVector.
void dump() const
Support for debugging, callable in GDB: V->dump()
AnalysisUsage & addRequired()
INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations", false, false) INITIALIZE_PASS_END(ARMCodeGenPrepare
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
static bool isPromotedResultSafe(Value *V)
Return whether we can safely mutate V's type to ExtTy without having to be concerned with zero extend...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
void pop_back()
Remove the last element of the SetVector.
Target-Independent Code Generator Pass Configuration Options.
static bool shouldPromote(Value *V)
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static bool isSource(Value *V)
Return true if the given value is a leaf that will need to be zext'd.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static bool isSafeOverflow(Instruction *I)
Return whether the instruction can be promoted within any modifications to it's operands or result...
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
bool isVoidTy() const
Return true if this is 'void'.
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Class to represent integer types.
static cl::opt< bool > EnableDSPWithImms("arm-enable-scalar-dsp-imms", cl::Hidden, cl::init(false), cl::desc("Use DSP instructions for scalar operations\ with immediate operands"))
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static cl::opt< bool > DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(true), cl::desc("Disable ARM specific CodeGenPrepare pass"))
Type * getReturnType() const
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
amdgpu Simplify well known AMD library false Value Value * Arg
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
static IntegerType * getInt32Ty(LLVMContext &C)
StringRef getName() const
Return a constant reference to the value's name.
static bool isSigned(Value *V)
Can the given value generate sign bits.
static cl::opt< bool > EnableDSP("arm-enable-scalar-dsp", cl::Hidden, cl::init(false), cl::desc("Use DSP instructions for scalar operations"))
bool empty() const
Determine if the SetVector is empty or not.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
user_iterator user_begin()
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
FunctionPass * createARMCodeGenPreparePass()
Primary interface to the complete machine description for the target machine.
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
static Intrinsic::ID getNarrowIntrinsic(Instruction *I, unsigned TypeSize)
Return the intrinsic for the instruction that can perform the same operation but on a narrow type...
Statically lint checks LLVM IR
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static bool isSink(Value *V)
Return true if V will require any promoted values to be truncated for the use to be valid...