#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetMachine.h"
#define DEBUG_TYPE "type-promotion"
#define PASS_NAME "Type Promotion"
using namespace llvm;
static cl::opt<bool> DisablePromotion("disable-type-promotion", cl::Hidden,
cl::init(false),
cl::desc("Disable type promotion pass"));
namespace {
class IRPromoter {
LLVMContext &Ctx;
unsigned PromotedWidth = 0;
SetVector<Value *> &Visited;
SetVector<Value *> &Sources;
SetVector<Instruction *> &Sinks;
SmallPtrSetImpl<Instruction *> &SafeWrap;
IntegerType *ExtTy = nullptr;
SmallPtrSet<Value *, 8> NewInsts;
SmallPtrSet<Instruction *, 4> InstsToRemove;
DenseMap<Value *, SmallVector<Type *, 4>> TruncTysMap;
SmallPtrSet<Value *, 8> Promoted;
void ReplaceAllUsersOfWith(Value *From, Value *To);
void ExtendSources();
void ConvertTruncs();
void PromoteTree();
void TruncateSinks();
void Cleanup();
public:
IRPromoter(LLVMContext &C, unsigned Width,
SetVector<Value *> &visited, SetVector<Value *> &sources,
SetVector<Instruction *> &sinks,
SmallPtrSetImpl<Instruction *> &wrap)
: Ctx(C), PromotedWidth(Width), Visited(visited),
Sources(sources), Sinks(sinks), SafeWrap(wrap) {
ExtTy = IntegerType::get(Ctx, PromotedWidth);
}
void Mutate();
};
class TypePromotion : public FunctionPass {
unsigned TypeSize = 0;
LLVMContext *Ctx = nullptr;
unsigned RegisterBitWidth = 0;
SmallPtrSet<Value *, 16> AllVisited;
SmallPtrSet<Instruction *, 8> SafeToPromote;
SmallPtrSet<Instruction *, 4> SafeWrap;
bool EqualTypeSize(Value *V);
bool LessOrEqualTypeSize(Value *V);
bool GreaterThanTypeSize(Value *V);
bool LessThanTypeSize(Value *V);
bool isSource(Value *V);
bool isSink(Value *V);
bool shouldPromote(Value *V);
bool isSafeWrap(Instruction *I);
bool isSupportedType(Value *V);
bool isSupportedValue(Value *V);
bool isLegalToPromote(Value *V);
bool TryToPromote(Value *V, unsigned PromotedWidth);
public:
static char ID;
TypePromotion() : FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addRequired<TargetPassConfig>();
AU.setPreservesCFG();
}
StringRef getPassName() const override { return PASS_NAME; }
bool runOnFunction(Function &F) override;
};
}
static bool GenerateSignBits(Instruction *I) {
unsigned Opc = I->getOpcode();
return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
Opc == Instruction::SRem || Opc == Instruction::SExt;
}
bool TypePromotion::EqualTypeSize(Value *V) {
return V->getType()->getScalarSizeInBits() == TypeSize;
}
bool TypePromotion::LessOrEqualTypeSize(Value *V) {
return V->getType()->getScalarSizeInBits() <= TypeSize;
}
bool TypePromotion::GreaterThanTypeSize(Value *V) {
return V->getType()->getScalarSizeInBits() > TypeSize;
}
bool TypePromotion::LessThanTypeSize(Value *V) {
return V->getType()->getScalarSizeInBits() < TypeSize;
}
bool TypePromotion::isSource(Value *V) {
if (!isa<IntegerType>(V->getType()))
return false;
if (isa<Argument>(V))
return true;
else if (isa<LoadInst>(V))
return true;
else if (isa<BitCastInst>(V))
return true;
else if (auto *Call = dyn_cast<CallInst>(V))
return Call->hasRetAttr(Attribute::AttrKind::ZExt);
else if (auto *Trunc = dyn_cast<TruncInst>(V))
return EqualTypeSize(Trunc);
return false;
}
bool TypePromotion::isSink(Value *V) {
if (auto *Store = dyn_cast<StoreInst>(V))
return LessOrEqualTypeSize(Store->getValueOperand());
if (auto *Return = dyn_cast<ReturnInst>(V))
return LessOrEqualTypeSize(Return->getReturnValue());
if (auto *ZExt = dyn_cast<ZExtInst>(V))
return GreaterThanTypeSize(ZExt);
if (auto *Switch = dyn_cast<SwitchInst>(V))
return LessThanTypeSize(Switch->getCondition());
if (auto *ICmp = dyn_cast<ICmpInst>(V))
return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
return isa<CallInst>(V);
}
bool TypePromotion::isSafeWrap(Instruction *I) {
unsigned Opc = I->getOpcode();
if (Opc != Instruction::Add && Opc != Instruction::Sub)
return false;
if (!I->hasOneUse() || !isa<ICmpInst>(*I->user_begin()) ||
!isa<ConstantInt>(I->getOperand(1)))
return false;
auto *CI = cast<ICmpInst>(*I->user_begin());
if (CI->isSigned() || CI->isEquality())
return false;
ConstantInt *ICmpConstant = nullptr;
if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
ICmpConstant = Const;
else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
ICmpConstant = Const;
else
return false;
const APInt &ICmpConst = ICmpConstant->getValue();
APInt OverflowConst = cast<ConstantInt>(I->getOperand(1))->getValue();
if (Opc == Instruction::Sub)
OverflowConst = -OverflowConst;
if (!OverflowConst.isNonPositive())
return false;
if (OverflowConst.sgt(ICmpConst)) {
LLVM_DEBUG(dbgs() << "IR Promotion: Allowing safe overflow for sext "
<< "const of " << *I << "\n");
SafeWrap.insert(I);
return true;
} else {
LLVM_DEBUG(dbgs() << "IR Promotion: Allowing safe overflow for sext "
<< "const of " << *I << " and " << *CI << "\n");
SafeWrap.insert(I);
SafeWrap.insert(CI);
return true;
}
return false;
}
bool TypePromotion::shouldPromote(Value *V) {
if (!isa<IntegerType>(V->getType()) || isSink(V))
return false;
if (isSource(V))
return true;
auto *I = dyn_cast<Instruction>(V);
if (!I)
return false;
if (isa<ICmpInst>(I))
return false;
return true;
}
static bool isPromotedResultSafe(Instruction *I) {
if (GenerateSignBits(I))
return false;
if (!isa<OverflowingBinaryOperator>(I))
return true;
return I->hasNoUnsignedWrap();
}
void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
SmallVector<Instruction *, 4> Users;
Instruction *InstTo = dyn_cast<Instruction>(To);
bool ReplacedAll = true;
LLVM_DEBUG(dbgs() << "IR Promotion: Replacing " << *From << " with " << *To
<< "\n");
for (Use &U : From->uses()) {
auto *User = cast<Instruction>(U.getUser());
if (InstTo && User->isIdenticalTo(InstTo)) {
ReplacedAll = false;
continue;
}
Users.push_back(User);
}
for (auto *U : Users)
U->replaceUsesOfWith(From, To);
if (ReplacedAll)
if (auto *I = dyn_cast<Instruction>(From))
InstsToRemove.insert(I);
}
void IRPromoter::ExtendSources() {
IRBuilder<> Builder{Ctx};
auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
assert(V->getType() != ExtTy && "zext already extends to i32");
LLVM_DEBUG(dbgs() << "IR Promotion: Inserting ZExt for " << *V << "\n");
Builder.SetInsertPoint(InsertPt);
if (auto *I = dyn_cast<Instruction>(V))
Builder.SetCurrentDebugLocation(I->getDebugLoc());
Value *ZExt = Builder.CreateZExt(V, ExtTy);
if (auto *I = dyn_cast<Instruction>(ZExt)) {
if (isa<Argument>(V))
I->moveBefore(InsertPt);
else
I->moveAfter(InsertPt);
NewInsts.insert(I);
}
ReplaceAllUsersOfWith(V, ZExt);
};
LLVM_DEBUG(dbgs() << "IR Promotion: Promoting sources:\n");
for (auto *V : Sources) {
LLVM_DEBUG(dbgs() << " - " << *V << "\n");
if (auto *I = dyn_cast<Instruction>(V))
InsertZExt(I, I);
else if (auto *Arg = dyn_cast<Argument>(V)) {
BasicBlock &BB = Arg->getParent()->front();
InsertZExt(Arg, &*BB.getFirstInsertionPt());
} else {
llvm_unreachable("unhandled source that needs extending");
}
Promoted.insert(V);
}
}
void IRPromoter::PromoteTree() {
LLVM_DEBUG(dbgs() << "IR Promotion: Mutating the tree..\n");
for (auto *V : Visited) {
if (Sources.count(V))
continue;
auto *I = cast<Instruction>(V);
if (Sinks.count(I))
continue;
for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
Value *Op = I->getOperand(i);
if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
continue;
if (auto *Const = dyn_cast<ConstantInt>(Op)) {
Constant *NewConst = (SafeWrap.contains(I) &&
(I->getOpcode() == Instruction::ICmp || i == 1) &&
I->getOpcode() != Instruction::Sub)
? ConstantExpr::getSExt(Const, ExtTy)
: ConstantExpr::getZExt(Const, ExtTy);
I->setOperand(i, NewConst);
} else if (isa<UndefValue>(Op))
I->setOperand(i, ConstantInt::get(ExtTy, 0));
}
if (!isa<ICmpInst>(I) && !isa<SwitchInst>(I)) {
I->mutateType(ExtTy);
Promoted.insert(I);
}
}
}
void IRPromoter::TruncateSinks() {
LLVM_DEBUG(dbgs() << "IR Promotion: Fixing up the sinks:\n");
IRBuilder<> Builder{Ctx};
auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction * {
if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
return nullptr;
if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources.count(V))
return nullptr;
LLVM_DEBUG(dbgs() << "IR Promotion: Creating " << *TruncTy << " Trunc for "
<< *V << "\n");
Builder.SetInsertPoint(cast<Instruction>(V));
auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
if (Trunc)
NewInsts.insert(Trunc);
return Trunc;
};
for (auto *I : Sinks) {
LLVM_DEBUG(dbgs() << "IR Promotion: For Sink: " << *I << "\n");
if (auto *Call = dyn_cast<CallInst>(I)) {
for (unsigned i = 0; i < Call->arg_size(); ++i) {
Value *Arg = Call->getArgOperand(i);
Type *Ty = TruncTysMap[Call][i];
if (Instruction *Trunc = InsertTrunc(Arg, Ty)) {
Trunc->moveBefore(Call);
Call->setArgOperand(i, Trunc);
}
}
continue;
}
if (auto *Switch = dyn_cast<SwitchInst>(I)) {
Type *Ty = TruncTysMap[Switch][0];
if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
Trunc->moveBefore(Switch);
Switch->setCondition(Trunc);
}
continue;
}
if (auto ZExt = dyn_cast<ZExtInst>(I))
if (ZExt->getType()->getScalarSizeInBits() > PromotedWidth)
continue;
for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Type *Ty = TruncTysMap[I][i];
if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
Trunc->moveBefore(I);
I->setOperand(i, Trunc);
}
}
}
}
void IRPromoter::Cleanup() {
LLVM_DEBUG(dbgs() << "IR Promotion: Cleanup..\n");
for (auto *V : Visited) {
if (!isa<ZExtInst>(V))
continue;
auto ZExt = cast<ZExtInst>(V);
if (ZExt->getDestTy() != ExtTy)
continue;
Value *Src = ZExt->getOperand(0);
if (ZExt->getSrcTy() == ZExt->getDestTy()) {
LLVM_DEBUG(dbgs() << "IR Promotion: Removing unnecessary cast: " << *ZExt
<< "\n");
ReplaceAllUsersOfWith(ZExt, Src);
continue;
}
if (NewInsts.count(Src) && isa<TruncInst>(Src)) {
auto *Trunc = cast<TruncInst>(Src);
assert(Trunc->getOperand(0)->getType() == ExtTy &&
"expected inserted trunc to be operating on i32");
ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
}
}
for (auto *I : InstsToRemove) {
LLVM_DEBUG(dbgs() << "IR Promotion: Removing " << *I << "\n");
I->dropAllReferences();
I->eraseFromParent();
}
}
void IRPromoter::ConvertTruncs() {
LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n");
IRBuilder<> Builder{Ctx};
for (auto *V : Visited) {
if (!isa<TruncInst>(V) || Sources.count(V))
continue;
auto *Trunc = cast<TruncInst>(V);
Builder.SetInsertPoint(Trunc);
IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
unsigned NumBits = DestTy->getScalarSizeInBits();
ConstantInt *Mask =
ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue());
Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
if (SrcTy != ExtTy)
Masked = Builder.CreateTrunc(Masked, ExtTy);
if (auto *I = dyn_cast<Instruction>(Masked))
NewInsts.insert(I);
ReplaceAllUsersOfWith(Trunc, Masked);
}
}
void IRPromoter::Mutate() {
LLVM_DEBUG(dbgs() << "IR Promotion: Promoting use-def chains to "
<< PromotedWidth << "-bits\n");
for (auto *I : Sinks) {
if (auto *Call = dyn_cast<CallInst>(I)) {
for (Value *Arg : Call->args())
TruncTysMap[Call].push_back(Arg->getType());
} else if (auto *Switch = dyn_cast<SwitchInst>(I))
TruncTysMap[I].push_back(Switch->getCondition()->getType());
else {
for (unsigned i = 0; i < I->getNumOperands(); ++i)
TruncTysMap[I].push_back(I->getOperand(i)->getType());
}
}
for (auto *V : Visited) {
if (!isa<TruncInst>(V) || Sources.count(V))
continue;
auto *Trunc = cast<TruncInst>(V);
TruncTysMap[Trunc].push_back(Trunc->getDestTy());
}
ExtendSources();
PromoteTree();
ConvertTruncs();
TruncateSinks();
Cleanup();
LLVM_DEBUG(dbgs() << "IR Promotion: Mutation complete\n");
}
bool TypePromotion::isSupportedType(Value *V) {
Type *Ty = V->getType();
if (Ty->isVoidTy() || Ty->isPointerTy())
return true;
if (!isa<IntegerType>(Ty) || cast<IntegerType>(Ty)->getBitWidth() == 1 ||
cast<IntegerType>(Ty)->getBitWidth() > RegisterBitWidth)
return false;
return LessOrEqualTypeSize(V);
}
bool TypePromotion::isSupportedValue(Value *V) {
if (auto *I = dyn_cast<Instruction>(V)) {
switch (I->getOpcode()) {
default:
return isa<BinaryOperator>(I) && isSupportedType(I) &&
!GenerateSignBits(I);
case Instruction::GetElementPtr:
case Instruction::Store:
case Instruction::Br:
case Instruction::Switch:
return true;
case Instruction::PHI:
case Instruction::Select:
case Instruction::Ret:
case Instruction::Load:
case Instruction::Trunc:
case Instruction::BitCast:
return isSupportedType(I);
case Instruction::ZExt:
return isSupportedType(I->getOperand(0));
case Instruction::ICmp:
if (isa<PointerType>(I->getOperand(0)->getType()))
return true;
return EqualTypeSize(I->getOperand(0));
case Instruction::Call: {
auto *Call = cast<CallInst>(I);
return isSupportedType(Call) &&
Call->hasRetAttr(Attribute::AttrKind::ZExt);
}
}
} else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) {
return isSupportedType(V);
} else if (isa<Argument>(V))
return isSupportedType(V);
return isa<BasicBlock>(V);
}
bool TypePromotion::isLegalToPromote(Value *V) {
auto *I = dyn_cast<Instruction>(V);
if (!I)
return true;
if (SafeToPromote.count(I))
return true;
if (isPromotedResultSafe(I) || isSafeWrap(I)) {
SafeToPromote.insert(I);
return true;
}
return false;
}
bool TypePromotion::TryToPromote(Value *V, unsigned PromotedWidth) {
Type *OrigTy = V->getType();
TypeSize = OrigTy->getPrimitiveSizeInBits().getFixedSize();
SafeToPromote.clear();
SafeWrap.clear();
if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
return false;
LLVM_DEBUG(dbgs() << "IR Promotion: TryToPromote: " << *V << ", from "
<< TypeSize << " bits to " << PromotedWidth << "\n");
SetVector<Value *> WorkList;
SetVector<Value *> Sources;
SetVector<Instruction *> Sinks;
SetVector<Value *> CurrentVisited;
WorkList.insert(V);
auto AddLegalInst = [&](Value *V) {
if (CurrentVisited.count(V))
return true;
if (isa<GetElementPtrInst>(V))
return true;
if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
LLVM_DEBUG(dbgs() << "IR Promotion: Can't handle: " << *V << "\n");
return false;
}
WorkList.insert(V);
return true;
};
while (!WorkList.empty()) {
Value *V = WorkList.pop_back_val();
if (CurrentVisited.count(V))
continue;
if (!isa<Instruction>(V) && !isSource(V))
continue;
if (AllVisited.count(V))
return false;
CurrentVisited.insert(V);
AllVisited.insert(V);
if (isSink(V))
Sinks.insert(cast<Instruction>(V));
if (isSource(V))
Sources.insert(V);
if (!isSink(V) && !isSource(V)) {
if (auto *I = dyn_cast<Instruction>(V)) {
for (auto &U : I->operands()) {
if (!AddLegalInst(U))
return false;
}
}
}
if (isSource(V) || shouldPromote(V)) {
for (Use &U : V->uses()) {
if (!AddLegalInst(U.getUser()))
return false;
}
}
}
LLVM_DEBUG({
dbgs() << "IR Promotion: Visited nodes:\n";
for (auto *I : CurrentVisited)
I->dump();
});
unsigned ToPromote = 0;
unsigned NonFreeArgs = 0;
SmallPtrSet<BasicBlock *, 4> Blocks;
for (auto *V : CurrentVisited) {
if (auto *I = dyn_cast<Instruction>(V))
Blocks.insert(I->getParent());
if (Sources.count(V)) {
if (auto *Arg = dyn_cast<Argument>(V))
if (!Arg->hasZExtAttr() && !Arg->hasSExtAttr())
++NonFreeArgs;
continue;
}
if (Sinks.count(cast<Instruction>(V)))
continue;
++ToPromote;
}
if (ToPromote < 2 || (Blocks.size() == 1 && (NonFreeArgs > SafeWrap.size())))
return false;
IRPromoter Promoter(*Ctx, PromotedWidth, CurrentVisited, Sources, Sinks,
SafeWrap);
Promoter.Mutate();
return true;
}
bool TypePromotion::runOnFunction(Function &F) {
if (skipFunction(F) || DisablePromotion)
return false;
LLVM_DEBUG(dbgs() << "IR Promotion: Running on " << F.getName() << "\n");
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
if (!TPC)
return false;
AllVisited.clear();
SafeToPromote.clear();
SafeWrap.clear();
bool MadeChange = false;
const DataLayout &DL = F.getParent()->getDataLayout();
const TargetMachine &TM = TPC->getTM<TargetMachine>();
const TargetSubtargetInfo *SubtargetInfo = TM.getSubtargetImpl(F);
const TargetLowering *TLI = SubtargetInfo->getTargetLowering();
const TargetTransformInfo &TII =
getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
RegisterBitWidth =
TII.getRegisterBitWidth(TargetTransformInfo::RGK_Scalar).getFixedSize();
Ctx = &F.getParent()->getContext();
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (AllVisited.count(&I))
continue;
if (!isa<ICmpInst>(&I))
continue;
auto *ICmp = cast<ICmpInst>(&I);
if (ICmp->isSigned() || !isa<IntegerType>(ICmp->getOperand(0)->getType()))
continue;
LLVM_DEBUG(dbgs() << "IR Promotion: Searching from: " << *ICmp << "\n");
for (auto &Op : ICmp->operands()) {
if (auto *I = dyn_cast<Instruction>(Op)) {
EVT SrcVT = TLI->getValueType(DL, I->getType());
if (SrcVT.isSimple() && TLI->isTypeLegal(SrcVT.getSimpleVT()))
break;
if (TLI->getTypeAction(*Ctx, SrcVT) !=
TargetLowering::TypePromoteInteger)
break;
EVT PromotedVT = TLI->getTypeToTransformTo(*Ctx, SrcVT);
if (RegisterBitWidth < PromotedVT.getFixedSizeInBits()) {
LLVM_DEBUG(dbgs() << "IR Promotion: Couldn't find target register "
<< "for promoted type\n");
break;
}
MadeChange |= TryToPromote(I, PromotedVT.getFixedSizeInBits());
break;
}
}
}
}
AllVisited.clear();
SafeToPromote.clear();
SafeWrap.clear();
return MadeChange;
}
INITIALIZE_PASS_BEGIN(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
INITIALIZE_PASS_END(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
char TypePromotion::ID = 0;
FunctionPass *llvm::createTypePromotionPass() { return new TypePromotion(); }