57 #define DEBUG_TYPE "stack-coloring"
72 cl::desc(
"Do not optimize lifetime zones that "
82 cl::desc(
"Treat stack lifetimes as starting on first use, not on START marker."));
85 STATISTIC(NumMarkerSeen,
"Number of lifetime markers found.");
86 STATISTIC(StackSpaceSaved,
"Number of bytes saved due to merging slots.");
87 STATISTIC(StackSlotMerged,
"Number of stack slot merged.");
88 STATISTIC(EscapedAllocas,
"Number of allocas that escaped the lifetime region");
378 struct BlockLifetimeInfo {
391 LivenessMap BlockLiveness;
423 unsigned NumIterations;
436 void dumpIntervals()
const;
438 void dumpBV(
const char *tag,
const BitVector &BV)
const;
442 bool removeAllMarkers();
447 unsigned collectMarkers(
unsigned NumSlot);
453 void calculateLocalLiveness();
457 bool applyFirstUse(
int Slot) {
460 if (ConservativeSlots.test(Slot))
475 void calculateLiveIntervals(
unsigned NumSlots);
487 void removeInvalidSlotRanges();
502 "Merge disjoint stack slots",
false,
false)
508 void StackColoring::getAnalysisUsage(
AnalysisUsage &AU)
const {
514 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
517 dbgs() << tag <<
" : { ";
518 for (
unsigned I = 0,
E = BV.
size();
I !=
E; ++
I)
524 LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
525 assert(BI != BlockLiveness.end() &&
"Block not found");
526 const BlockLifetimeInfo &BlockInfo = BI->second;
528 dumpBV(
"BEGIN", BlockInfo.Begin);
529 dumpBV(
"END", BlockInfo.End);
530 dumpBV(
"LIVE_IN", BlockInfo.LiveIn);
531 dumpBV(
"LIVE_OUT", BlockInfo.LiveOut);
544 dbgs() <<
"Interval[" <<
I <<
"]:\n";
554 "Expected LIFETIME_START or LIFETIME_END op");
577 if (!InterestingSlots.test(Slot))
584 if (! applyFirstUse(Slot)) {
594 int Slot = MO.getIndex();
597 if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) {
611 unsigned StackColoring::collectMarkers(
unsigned NumSlot)
613 unsigned MarkersFound = 0;
614 BlockBitVecMap SeenStartMap;
615 InterestingSlots.clear();
616 InterestingSlots.resize(NumSlot);
617 ConservativeSlots.clear();
618 ConservativeSlots.resize(NumSlot);
632 BetweenStartEnd.
resize(NumSlot);
634 PE = MBB->
pred_end(); PI != PE; ++PI) {
635 BlockBitVecMap::const_iterator
I = SeenStartMap.find(*PI);
636 if (I != SeenStartMap.end()) {
637 BetweenStartEnd |= I->second;
648 InterestingSlots.set(Slot);
650 BetweenStartEnd.
set(Slot);
651 NumStartLifetimes[Slot] += 1;
653 BetweenStartEnd.
reset(Slot);
654 NumEndLifetimes[Slot] += 1;
662 DEBUG(
dbgs() <<
" marker for slot #" << Slot);
666 Markers.push_back(&MI);
672 int Slot = MO.getIndex();
675 if (! BetweenStartEnd.
test(Slot)) {
676 ConservativeSlots.set(Slot);
681 BitVector &SeenStart = SeenStartMap[MBB];
682 SeenStart |= BetweenStartEnd;
690 for (
unsigned slot = 0; slot < NumSlot; ++slot)
691 if (NumStartLifetimes[slot] > 1 || NumEndLifetimes[slot] > 1)
692 ConservativeSlots.
set(slot);
693 DEBUG(dumpBV(
"Conservative slots", ConservativeSlots));
702 BasicBlocks[MBB] = BasicBlockNumbering.size();
703 BasicBlockNumbering.push_back(MBB);
706 BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
708 BlockInfo.Begin.resize(NumSlot);
709 BlockInfo.End.resize(NumSlot);
713 bool isStart =
false;
715 if (isLifetimeStartOrEnd(MI, slots, isStart)) {
717 assert(slots.
size() == 1 &&
"unexpected: MI ends multiple slots");
719 if (BlockInfo.Begin.test(Slot)) {
720 BlockInfo.Begin.reset(Slot);
722 BlockInfo.End.set(Slot);
724 for (
auto Slot : slots) {
725 DEBUG(
dbgs() <<
"Found a use of slot #" << Slot);
726 DEBUG(
dbgs() <<
" at BB#" << MBB->getNumber() <<
" index ");
727 DEBUG(Indexes->getInstructionIndex(MI).print(
dbgs()));
728 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
730 DEBUG(
dbgs() <<
" with allocation: "<< Allocation->getName());
733 if (BlockInfo.End.test(Slot)) {
734 BlockInfo.End.reset(Slot);
736 BlockInfo.Begin.set(Slot);
744 NumMarkerSeen += MarkersFound;
748 void StackColoring::calculateLocalLiveness()
750 unsigned NumIters = 0;
759 LivenessMap::iterator BI = BlockLiveness.find(BB);
760 assert(BI != BlockLiveness.end() &&
"Block not found");
761 BlockLifetimeInfo &BlockInfo = BI->second;
766 PE = BB->pred_end(); PI != PE; ++PI) {
767 LivenessMap::const_iterator I = BlockLiveness.find(*PI);
768 assert(I != BlockLiveness.end() &&
"Predecessor not found");
769 LocalLiveIn |= I->second.LiveOut;
780 LocalLiveOut.
reset(BlockInfo.End);
781 LocalLiveOut |= BlockInfo.Begin;
784 if (LocalLiveIn.
test(BlockInfo.LiveIn)) {
786 BlockInfo.LiveIn |= LocalLiveIn;
790 if (LocalLiveOut.
test(BlockInfo.LiveOut)) {
792 BlockInfo.LiveOut |= LocalLiveOut;
797 NumIterations = NumIters;
800 void StackColoring::calculateLiveIntervals(
unsigned NumSlots) {
809 DefinitelyInUse.
clear();
810 DefinitelyInUse.
resize(NumSlots);
813 BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
814 for (
int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
815 pos = MBBLiveness.LiveIn.find_next(pos)) {
816 Starts[pos] = Indexes->getMBBStartIdx(&MBB);
823 bool IsStart =
false;
824 if (!isLifetimeStartOrEnd(MI, slots, IsStart))
826 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
827 for (
auto Slot : slots) {
832 if (!DefinitelyInUse[Slot]) {
833 LiveStarts[Slot].push_back(ThisIndex);
834 DefinitelyInUse[Slot] =
true;
837 Starts[Slot] = ThisIndex;
842 LiveInterval::Segment(Starts[Slot], ThisIndex, VNI));
844 DefinitelyInUse[Slot] =
false;
851 for (
unsigned i = 0; i < NumSlots; ++i) {
855 SlotIndex EndIdx = Indexes->getMBBEndIdx(&MBB);
857 Intervals[i]->addSegment(LiveInterval::Segment(Starts[i], EndIdx, VNI));
862 bool StackColoring::removeAllMarkers() {
870 DEBUG(
dbgs()<<
"Removed "<<Count<<
" markers.\n");
875 unsigned FixedInstr = 0;
876 unsigned FixedMemOp = 0;
877 unsigned FixedDbg = 0;
880 for (
auto &
VI : MF->getVariableDbgInfo()) {
883 if (SlotRemap.
count(
VI.Slot)) {
884 DEBUG(
dbgs() <<
"Remapping debug info for ["
885 << cast<DILocalVariable>(
VI.Var)->getName() <<
"].\n");
886 VI.Slot = SlotRemap[
VI.Slot];
897 for (
const std::pair<int, int> &SI : SlotRemap) {
898 const AllocaInst *From = MFI->getObjectAllocation(
SI.first);
899 const AllocaInst *To = MFI->getObjectAllocation(
SI.second);
900 assert(To && From &&
"Invalid allocation object");
917 MergedAllocas.
insert(From);
922 SP->adjustForColoring(From, To);
929 for (
auto &
Use : FromAI->
uses()) {
931 if (BCI->isUsedByMetadata())
953 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
957 if (!Allocas.
count(AI))
960 MMO->setValue(Allocas[AI]);
968 int FromSlot = MO.getIndex();
975 if (!SlotRemap.count(FromSlot))
986 bool TouchesMemory = I.mayLoad() || I.mayStore();
990 SlotIndex Index = Indexes->getInstructionIndex(I);
993 "Found instruction usage outside of live range.");
998 int ToSlot = SlotRemap[FromSlot];
1005 MF->allocateMemRefsArray(I.getNumMemOperands());
1006 unsigned MemOpIdx = 0;
1007 bool ReplaceMemOps =
false;
1011 bool MayHaveConflictingAAMD =
false;
1012 if (MMO->getAAInfo()) {
1013 if (
const Value *MMOV = MMO->getValue()) {
1018 MayHaveConflictingAAMD =
true;
1020 for (
Value *V : Objs) {
1024 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(V);
1025 if (AI && MergedAllocas.
count(AI)) {
1026 MayHaveConflictingAAMD =
true;
1032 if (MayHaveConflictingAAMD) {
1033 NewMemOps[MemOpIdx++] = MF->getMachineMemOperand(MMO,
AAMDNodes());
1034 ReplaceMemOps =
true;
1037 NewMemOps[MemOpIdx++] = MMO;
1043 I.setMemRefs(std::make_pair(NewMemOps, I.getNumMemOperands()));
1054 DEBUG(
dbgs()<<
"Fixed "<<FixedMemOp<<
" machine memory operands.\n");
1055 DEBUG(
dbgs()<<
"Fixed "<<FixedDbg<<
" debug locations.\n");
1056 DEBUG(
dbgs()<<
"Fixed "<<FixedInstr<<
" machine instructions.\n");
1059 void StackColoring::removeInvalidSlotRanges() {
1072 if (!I.mayLoad() && !I.mayStore())
1080 int Slot = MO.getIndex();
1091 SlotIndex Index = Indexes->getInstructionIndex(I);
1092 if (Interval->
find(Index) == Interval->
end()) {
1094 DEBUG(
dbgs()<<
"Invalidating range #"<<Slot<<
"\n");
1102 unsigned NumSlots) {
1104 for (
unsigned i=0; i < NumSlots; ++i) {
1106 if (SlotRemap.
count(i)) {
1107 int Target = SlotRemap[i];
1109 while (SlotRemap.
count(Target)) {
1110 Target = SlotRemap[
Target];
1118 DEBUG(
dbgs() <<
"********** Stack Coloring **********\n"
1119 <<
"********** Function: "
1123 Indexes = &getAnalysis<SlotIndexes>();
1124 SP = &getAnalysis<StackProtector>();
1125 BlockLiveness.clear();
1126 BasicBlocks.clear();
1127 BasicBlockNumbering.clear();
1131 VNInfoAllocator.Reset();
1133 unsigned NumSlots = MFI->getObjectIndexEnd();
1140 SortedSlots.
reserve(NumSlots);
1142 LiveStarts.resize(NumSlots);
1144 unsigned NumMarkers = collectMarkers(NumSlots);
1146 unsigned TotalSize = 0;
1147 DEBUG(
dbgs()<<
"Found "<<NumMarkers<<
" markers and "<<NumSlots<<
" slots\n");
1150 for (
int i=0; i < MFI->getObjectIndexEnd(); ++i) {
1151 DEBUG(
dbgs()<<
"Slot #"<<i<<
" - "<<MFI->getObjectSize(i)<<
" bytes.\n");
1152 TotalSize += MFI->getObjectSize(i);
1155 DEBUG(
dbgs()<<
"Total Stack size: "<<TotalSize<<
" bytes\n\n");
1161 DEBUG(
dbgs()<<
"Will not try to merge slots.\n");
1162 return removeAllMarkers();
1165 for (
unsigned i=0; i < NumSlots; ++i) {
1166 std::unique_ptr<LiveInterval> LI(
new LiveInterval(i, 0));
1167 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
1173 calculateLocalLiveness();
1174 DEBUG(
dbgs() <<
"Dataflow iterations: " << NumIterations <<
"\n");
1178 calculateLiveIntervals(NumSlots);
1179 DEBUG(dumpIntervals());
1184 removeInvalidSlotRanges();
1188 unsigned RemovedSlots = 0;
1189 unsigned ReducedSize = 0;
1192 for (
unsigned I = 0; I < NumSlots; ++
I) {
1194 SortedSlots[
I] = -1;
1205 std::stable_sort(SortedSlots.
begin(), SortedSlots.
end(),
1206 [
this](
int LHS,
int RHS) {
1208 if (LHS == -1)
return false;
1209 if (RHS == -1)
return true;
1211 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
1214 for (
auto &s : LiveStarts)
1217 bool Changed =
true;
1220 for (
unsigned I = 0; I < NumSlots; ++
I) {
1221 if (SortedSlots[I] == -1)
1224 for (
unsigned J=I+1; J < NumSlots; ++J) {
1225 if (SortedSlots[J] == -1)
1228 int FirstSlot = SortedSlots[
I];
1229 int SecondSlot = SortedSlots[J];
1232 auto &FirstS = LiveStarts[FirstSlot];
1233 auto &SecondS = LiveStarts[SecondSlot];
1243 int OldSize = FirstS.size();
1244 FirstS.append(SecondS.begin(), SecondS.end());
1245 auto Mid = FirstS.begin() + OldSize;
1246 std::inplace_merge(FirstS.begin(), Mid, FirstS.end());
1248 SlotRemap[SecondSlot] = FirstSlot;
1249 SortedSlots[J] = -1;
1250 DEBUG(
dbgs()<<
"Merging #"<<FirstSlot<<
" and slots #"<<
1251 SecondSlot<<
" together.\n");
1252 unsigned MaxAlignment =
std::max(MFI->getObjectAlignment(FirstSlot),
1253 MFI->getObjectAlignment(SecondSlot));
1255 assert(MFI->getObjectSize(FirstSlot) >=
1256 MFI->getObjectSize(SecondSlot) &&
1257 "Merging a small object into a larger one");
1260 ReducedSize += MFI->getObjectSize(SecondSlot);
1261 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
1262 MFI->RemoveStackObject(SecondSlot);
1269 StackSpaceSaved += ReducedSize;
1270 StackSlotMerged += RemovedSlots;
1271 DEBUG(
dbgs()<<
"Merge "<<RemovedSlots<<
" slots. Saved "<<
1272 ReducedSize<<
" bytes\n");
1276 expungeSlotMap(SlotRemap, NumSlots);
1277 remapInstructions(SlotRemap);
1279 return removeAllMarkers();
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
void push_back(const T &Elt)
iterator_range< use_iterator > uses()
SmallVector< WinEHHandlerType, 1 > HandlerArray
size_type size() const
size - Returns the number of bits in this bitvector.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static int getStartOrEndSlot(const MachineInstr &MI)
Merge disjoint stack false
STATISTIC(NumFunctions,"Total number of functions")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Merge disjoint stack slots
LiveInterval - This class represents the liveness of a register, or stack slot.
bool isLiveAtIndexes(ArrayRef< SlotIndex > Slots) const
static void dump(StringRef Title, SpillInfo const &Spills)
INITIALIZE_PASS_BEGIN(StackColoring, DEBUG_TYPE,"Merge disjoint stack slots", false, false) INITIALIZE_PASS_END(StackColoring
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
std::vector< MachineBasicBlock * >::const_iterator const_pred_iterator
void reserve(size_type N)
VNInfo - Value Number Information.
iterator_range< mop_iterator > operands()
StringRef getName() const
Return a constant reference to the value's name.
#define INITIALIZE_PASS_DEPENDENCY(depName)
A description of a memory reference used in the backend.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
char & StackColoringID
StackSlotColoring - This pass performs stack coloring and merging.
A Use represents the edge between a Value definition and its users.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
static StringRef getName(Value *V)
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
LLVM_NODISCARD bool empty() const
void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo)
Merge all of the live segments of a specific val# in RHS into this live range as the specified value ...
static cl::opt< bool > ProtectFromEscapedAllocas("protect-from-escaped-allocas", cl::init(false), cl::Hidden, cl::desc("Do not optimize lifetime zones that ""are broken"))
The user may write code that uses allocas outside of the declared lifetime zone.
This class represents a no-op cast from one type to another.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
This corresponds to the llvm.lifetime.
bool isDebugValue() const
Local Stack Slot Allocation
initializer< Ty > init(const Ty &Val)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Allocate memory in an ever growing pool, as if by bump-pointer.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const MachineOperand & getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isUsedByMetadata() const
Return true if there is metadata referencing this value.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
pred_iterator pred_begin()
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
static void Merge(const std::string &Input, const std::vector< std::string > Result, size_t NumNewFeatures)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
bool test(unsigned Idx) const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static const char * Target
void initializeStackColoringPass(PassRegistry &)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
Target - Wrapper for Target specific information.
union llvm::WinEHHandlerType::@158 CatchObj
The CatchObj starts out life as an LLVM alloca and is eventually turned frame index.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
Representation of each machine instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
static cl::opt< bool > LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use", cl::init(true), cl::Hidden, cl::desc("Treat stack lifetimes as starting on first use, not on START marker."))
Enable enhanced dataflow scheme for lifetime analysis (treat first use of stack slot as start of slot...
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static cl::opt< bool > DisableColoring("no-stack-coloring", cl::init(false), cl::Hidden, cl::desc("Disable stack coloring"))
LLVM Value Representation.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
SlotIndex - An opaque wrapper around machine indexes.
void getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL)
This is a wrapper around GetUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
an instruction to allocate memory on the stack