Skip to content

Commit 261f064

Browse files
committed
Vendor import of llvm release_60 branch r324090:
https://llvm.org/svn/llvm-project/llvm/branches/release_60@324090
1 parent e514774 commit 261f064

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+1787
-72
lines changed

include/llvm/CodeGen/Passes.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,9 @@ namespace llvm {
417417
// This pass expands memcmp() to load/stores.
418418
FunctionPass *createExpandMemCmpPass();
419419

420+
// This pass expands indirectbr instructions.
421+
FunctionPass *createIndirectBrExpandPass();
422+
420423
} // End llvm namespace
421424

422425
#endif

include/llvm/CodeGen/TargetInstrInfo.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -950,6 +950,10 @@ class TargetInstrInfo : public MCInstrInfo {
950950
/// Return true when a target supports MachineCombiner.
951951
virtual bool useMachineCombiner() const { return false; }
952952

953+
/// Return true if the given SDNode can be copied during scheduling
954+
/// even if it has glue.
955+
virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
956+
953957
protected:
954958
/// Target-dependent implementation for foldMemoryOperand.
955959
/// Target-independent code in foldMemoryOperand will

include/llvm/CodeGen/TargetLowering.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -800,7 +800,7 @@ class TargetLoweringBase {
800800
}
801801

802802
/// Return true if lowering to a jump table is allowed.
803-
bool areJTsAllowed(const Function *Fn) const {
803+
virtual bool areJTsAllowed(const Function *Fn) const {
804804
if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")
805805
return false;
806806

include/llvm/CodeGen/TargetPassConfig.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,13 @@ class TargetPassConfig : public ImmutablePass {
416416
/// immediately before machine code is emitted.
417417
virtual void addPreEmitPass() { }
418418

419+
/// Targets may add passes immediately before machine code is emitted in this
420+
/// callback. This is called even later than `addPreEmitPass`.
421+
// FIXME: Rename `addPreEmitPass` to something more sensible given its actual
422+
// position and remove the `2` suffix here as this callback is what
423+
// `addPreEmitPass` *should* be but in reality isn't.
424+
virtual void addPreEmitPass2() {}
425+
419426
/// Utilities for targets to add passes to the pass manager.
420427
///
421428

include/llvm/CodeGen/TargetSubtargetInfo.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,9 @@ class TargetSubtargetInfo : public MCSubtargetInfo {
174174
/// \brief True if the subtarget should run the atomic expansion pass.
175175
virtual bool enableAtomicExpand() const;
176176

177+
/// True if the subtarget should run the indirectbr expansion pass.
178+
virtual bool enableIndirectBrExpand() const;
179+
177180
/// \brief Override generic scheduling policy within a region.
178181
///
179182
/// This is a convenient way for targets that don't provide any custom

include/llvm/InitializePasses.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ void initializeIVUsersWrapperPassPass(PassRegistry&);
161161
void initializeIfConverterPass(PassRegistry&);
162162
void initializeImplicitNullChecksPass(PassRegistry&);
163163
void initializeIndVarSimplifyLegacyPassPass(PassRegistry&);
164+
void initializeIndirectBrExpandPassPass(PassRegistry&);
164165
void initializeInductiveRangeCheckEliminationPass(PassRegistry&);
165166
void initializeInferAddressSpacesPass(PassRegistry&);
166167
void initializeInferFunctionAttrsLegacyPassPass(PassRegistry&);

lib/CodeGen/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ add_llvm_library(LLVMCodeGen
3333
GlobalMerge.cpp
3434
IfConversion.cpp
3535
ImplicitNullChecks.cpp
36+
IndirectBrExpandPass.cpp
3637
InlineSpiller.cpp
3738
InterferenceCache.cpp
3839
InterleavedAccessPass.cpp

lib/CodeGen/CodeGen.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ void llvm::initializeCodeGen(PassRegistry &Registry) {
3838
initializeGCModuleInfoPass(Registry);
3939
initializeIfConverterPass(Registry);
4040
initializeImplicitNullChecksPass(Registry);
41+
initializeIndirectBrExpandPassPass(Registry);
4142
initializeInterleavedAccessPass(Registry);
4243
initializeLiveDebugValuesPass(Registry);
4344
initializeLiveDebugVariablesPass(Registry);

lib/CodeGen/IndirectBrExpandPass.cpp

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
//===- IndirectBrExpandPass.cpp - Expand indirectbr to switch -------------===//
2+
//
3+
// The LLVM Compiler Infrastructure
4+
//
5+
// This file is distributed under the University of Illinois Open Source
6+
// License. See LICENSE.TXT for details.
7+
//
8+
//===----------------------------------------------------------------------===//
9+
/// \file
10+
///
11+
/// Implements an expansion pass to turn `indirectbr` instructions in the IR
12+
/// into `switch` instructions. This works by enumerating the basic blocks in
13+
/// a dense range of integers, replacing each `blockaddr` constant with the
14+
/// corresponding integer constant, and then building a switch that maps from
15+
/// the integers to the actual blocks. All of the indirectbr instructions in the
16+
/// function are redirected to this common switch.
17+
///
18+
/// While this is generically useful if a target is unable to codegen
19+
/// `indirectbr` natively, it is primarily useful when there is some desire to
20+
/// get the builtin non-jump-table lowering of a switch even when the input
21+
/// source contained an explicit indirect branch construct.
22+
///
23+
/// Note that it doesn't make any sense to enable this pass unless a target also
24+
/// disables jump-table lowering of switches. Doing that is likely to pessimize
25+
/// the code.
26+
///
27+
//===----------------------------------------------------------------------===//
28+
29+
#include "llvm/ADT/STLExtras.h"
30+
#include "llvm/ADT/Sequence.h"
31+
#include "llvm/ADT/SmallVector.h"
32+
#include "llvm/CodeGen/TargetPassConfig.h"
33+
#include "llvm/CodeGen/TargetSubtargetInfo.h"
34+
#include "llvm/IR/BasicBlock.h"
35+
#include "llvm/IR/Function.h"
36+
#include "llvm/IR/IRBuilder.h"
37+
#include "llvm/IR/InstIterator.h"
38+
#include "llvm/IR/Instruction.h"
39+
#include "llvm/IR/Instructions.h"
40+
#include "llvm/Pass.h"
41+
#include "llvm/Support/Debug.h"
42+
#include "llvm/Support/ErrorHandling.h"
43+
#include "llvm/Support/raw_ostream.h"
44+
#include "llvm/Target/TargetMachine.h"
45+
46+
using namespace llvm;
47+
48+
#define DEBUG_TYPE "indirectbr-expand"
49+
50+
namespace {
51+
52+
class IndirectBrExpandPass : public FunctionPass {
53+
const TargetLowering *TLI = nullptr;
54+
55+
public:
56+
static char ID; // Pass identification, replacement for typeid
57+
58+
IndirectBrExpandPass() : FunctionPass(ID) {
59+
initializeIndirectBrExpandPassPass(*PassRegistry::getPassRegistry());
60+
}
61+
62+
bool runOnFunction(Function &F) override;
63+
};
64+
65+
} // end anonymous namespace
66+
67+
char IndirectBrExpandPass::ID = 0;
68+
69+
INITIALIZE_PASS(IndirectBrExpandPass, DEBUG_TYPE,
70+
"Expand indirectbr instructions", false, false)
71+
72+
FunctionPass *llvm::createIndirectBrExpandPass() {
73+
return new IndirectBrExpandPass();
74+
}
75+
76+
bool IndirectBrExpandPass::runOnFunction(Function &F) {
77+
auto &DL = F.getParent()->getDataLayout();
78+
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
79+
if (!TPC)
80+
return false;
81+
82+
auto &TM = TPC->getTM<TargetMachine>();
83+
auto &STI = *TM.getSubtargetImpl(F);
84+
if (!STI.enableIndirectBrExpand())
85+
return false;
86+
TLI = STI.getTargetLowering();
87+
88+
SmallVector<IndirectBrInst *, 1> IndirectBrs;
89+
90+
// Set of all potential successors for indirectbr instructions.
91+
SmallPtrSet<BasicBlock *, 4> IndirectBrSuccs;
92+
93+
// Build a list of indirectbrs that we want to rewrite.
94+
for (BasicBlock &BB : F)
95+
if (auto *IBr = dyn_cast<IndirectBrInst>(BB.getTerminator())) {
96+
// Handle the degenerate case of no successors by replacing the indirectbr
97+
// with unreachable as there is no successor available.
98+
if (IBr->getNumSuccessors() == 0) {
99+
(void)new UnreachableInst(F.getContext(), IBr);
100+
IBr->eraseFromParent();
101+
continue;
102+
}
103+
104+
IndirectBrs.push_back(IBr);
105+
for (BasicBlock *SuccBB : IBr->successors())
106+
IndirectBrSuccs.insert(SuccBB);
107+
}
108+
109+
if (IndirectBrs.empty())
110+
return false;
111+
112+
// If we need to replace any indirectbrs we need to establish integer
113+
// constants that will correspond to each of the basic blocks in the function
114+
// whose address escapes. We do that here and rewrite all the blockaddress
115+
// constants to just be those integer constants cast to a pointer type.
116+
SmallVector<BasicBlock *, 4> BBs;
117+
118+
for (BasicBlock &BB : F) {
119+
// Skip blocks that aren't successors to an indirectbr we're going to
120+
// rewrite.
121+
if (!IndirectBrSuccs.count(&BB))
122+
continue;
123+
124+
auto IsBlockAddressUse = [&](const Use &U) {
125+
return isa<BlockAddress>(U.getUser());
126+
};
127+
auto BlockAddressUseIt = llvm::find_if(BB.uses(), IsBlockAddressUse);
128+
if (BlockAddressUseIt == BB.use_end())
129+
continue;
130+
131+
assert(std::find_if(std::next(BlockAddressUseIt), BB.use_end(),
132+
IsBlockAddressUse) == BB.use_end() &&
133+
"There should only ever be a single blockaddress use because it is "
134+
"a constant and should be uniqued.");
135+
136+
auto *BA = cast<BlockAddress>(BlockAddressUseIt->getUser());
137+
138+
// Skip if the constant was formed but ended up not being used (due to DCE
139+
// or whatever).
140+
if (!BA->isConstantUsed())
141+
continue;
142+
143+
// Compute the index we want to use for this basic block. We can't use zero
144+
// because null can be compared with block addresses.
145+
int BBIndex = BBs.size() + 1;
146+
BBs.push_back(&BB);
147+
148+
auto *ITy = cast<IntegerType>(DL.getIntPtrType(BA->getType()));
149+
ConstantInt *BBIndexC = ConstantInt::get(ITy, BBIndex);
150+
151+
// Now rewrite the blockaddress to an integer constant based on the index.
152+
// FIXME: We could potentially preserve the uses as arguments to inline asm.
153+
// This would allow some uses such as diagnostic information in crashes to
154+
// have higher quality even when this transform is enabled, but would break
155+
// users that round-trip blockaddresses through inline assembly and then
156+
// back into an indirectbr.
157+
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(BBIndexC, BA->getType()));
158+
}
159+
160+
if (BBs.empty()) {
161+
// There are no blocks whose address is taken, so any indirectbr instruction
162+
// cannot get a valid input and we can replace all of them with unreachable.
163+
for (auto *IBr : IndirectBrs) {
164+
(void)new UnreachableInst(F.getContext(), IBr);
165+
IBr->eraseFromParent();
166+
}
167+
return true;
168+
}
169+
170+
BasicBlock *SwitchBB;
171+
Value *SwitchValue;
172+
173+
// Compute a common integer type across all the indirectbr instructions.
174+
IntegerType *CommonITy = nullptr;
175+
for (auto *IBr : IndirectBrs) {
176+
auto *ITy =
177+
cast<IntegerType>(DL.getIntPtrType(IBr->getAddress()->getType()));
178+
if (!CommonITy || ITy->getBitWidth() > CommonITy->getBitWidth())
179+
CommonITy = ITy;
180+
}
181+
182+
auto GetSwitchValue = [DL, CommonITy](IndirectBrInst *IBr) {
183+
return CastInst::CreatePointerCast(
184+
IBr->getAddress(), CommonITy,
185+
Twine(IBr->getAddress()->getName()) + ".switch_cast", IBr);
186+
};
187+
188+
if (IndirectBrs.size() == 1) {
189+
// If we only have one indirectbr, we can just directly replace it within
190+
// its block.
191+
SwitchBB = IndirectBrs[0]->getParent();
192+
SwitchValue = GetSwitchValue(IndirectBrs[0]);
193+
IndirectBrs[0]->eraseFromParent();
194+
} else {
195+
// Otherwise we need to create a new block to hold the switch across BBs,
196+
// jump to that block instead of each indirectbr, and phi together the
197+
// values for the switch.
198+
SwitchBB = BasicBlock::Create(F.getContext(), "switch_bb", &F);
199+
auto *SwitchPN = PHINode::Create(CommonITy, IndirectBrs.size(),
200+
"switch_value_phi", SwitchBB);
201+
SwitchValue = SwitchPN;
202+
203+
// Now replace the indirectbr instructions with direct branches to the
204+
// switch block and fill out the PHI operands.
205+
for (auto *IBr : IndirectBrs) {
206+
SwitchPN->addIncoming(GetSwitchValue(IBr), IBr->getParent());
207+
BranchInst::Create(SwitchBB, IBr);
208+
IBr->eraseFromParent();
209+
}
210+
}
211+
212+
// Now build the switch in the block. The block will have no terminator
213+
// already.
214+
auto *SI = SwitchInst::Create(SwitchValue, BBs[0], BBs.size(), SwitchBB);
215+
216+
// Add a case for each block.
217+
for (int i : llvm::seq<int>(1, BBs.size()))
218+
SI->addCase(ConstantInt::get(CommonITy, i + 1), BBs[i]);
219+
220+
return true;
221+
}

lib/CodeGen/SelectionDAG/LegalizeDAG.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1996,14 +1996,15 @@ SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
19961996
Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19971997
Entry.Node = Op;
19981998
Entry.Ty = ArgTy;
1999-
Entry.IsSExt = isSigned;
2000-
Entry.IsZExt = !isSigned;
1999+
Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2000+
Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
20012001
Args.push_back(Entry);
20022002
}
20032003
SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
20042004
TLI.getPointerTy(DAG.getDataLayout()));
20052005

2006-
Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2006+
EVT RetVT = Node->getValueType(0);
2007+
Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
20072008

20082009
// By default, the input chain to this libcall is the entry node of the
20092010
// function. If the libcall is going to be emitted as a tail call then
@@ -2022,13 +2023,14 @@ SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
20222023
InChain = TCChain;
20232024

20242025
TargetLowering::CallLoweringInfo CLI(DAG);
2026+
bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
20252027
CLI.setDebugLoc(SDLoc(Node))
20262028
.setChain(InChain)
20272029
.setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
20282030
std::move(Args))
20292031
.setTailCall(isTailCall)
2030-
.setSExtResult(isSigned)
2031-
.setZExtResult(!isSigned)
2032+
.setSExtResult(signExtend)
2033+
.setZExtResult(!signExtend)
20322034
.setIsPostTypeLegalization(true);
20332035

20342036
std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);

lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,22 +1117,34 @@ SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
11171117
if (!N)
11181118
return nullptr;
11191119

1120-
if (SU->getNode()->getGluedNode())
1120+
DEBUG(dbgs() << "Considering duplicating the SU\n");
1121+
DEBUG(SU->dump(this));
1122+
1123+
if (N->getGluedNode() &&
1124+
!TII->canCopyGluedNodeDuringSchedule(N)) {
1125+
DEBUG(dbgs()
1126+
<< "Giving up because it has incoming glue and the target does not "
1127+
"want to copy it\n");
11211128
return nullptr;
1129+
}
11221130

11231131
SUnit *NewSU;
11241132
bool TryUnfold = false;
11251133
for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
11261134
MVT VT = N->getSimpleValueType(i);
1127-
if (VT == MVT::Glue)
1135+
if (VT == MVT::Glue) {
1136+
DEBUG(dbgs() << "Giving up because it has outgoing glue\n");
11281137
return nullptr;
1129-
else if (VT == MVT::Other)
1138+
} else if (VT == MVT::Other)
11301139
TryUnfold = true;
11311140
}
11321141
for (const SDValue &Op : N->op_values()) {
11331142
MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
1134-
if (VT == MVT::Glue)
1143+
if (VT == MVT::Glue && !TII->canCopyGluedNodeDuringSchedule(N)) {
1144+
DEBUG(dbgs() << "Giving up because it one of the operands is glue and "
1145+
"the target does not want to copy it\n");
11351146
return nullptr;
1147+
}
11361148
}
11371149

11381150
// If possible unfold instruction.

lib/CodeGen/TargetPassConfig.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,9 @@ void TargetPassConfig::addMachinePasses() {
907907
if (EnableMachineOutliner)
908908
PM->add(createMachineOutlinerPass(EnableLinkOnceODROutlining));
909909

910+
// Add passes that directly emit MI after all other MI passes.
911+
addPreEmitPass2();
912+
910913
AddingMachinePasses = false;
911914
}
912915

lib/CodeGen/TargetSubtargetInfo.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ bool TargetSubtargetInfo::enableAtomicExpand() const {
3838
return true;
3939
}
4040

41+
bool TargetSubtargetInfo::enableIndirectBrExpand() const {
42+
return false;
43+
}
44+
4145
bool TargetSubtargetInfo::enableMachineScheduler() const {
4246
return false;
4347
}

0 commit comments

Comments
 (0)