1 //===- bolt/Passes/ShrinkWrapping.cpp -------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the ShrinkWrapping class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/ShrinkWrapping.h"
14 #include "bolt/Core/MCPlus.h"
15 #include "bolt/Passes/DataflowInfoManager.h"
16 #include "bolt/Passes/MCF.h"
17 #include "bolt/Utils/CommandLineOpts.h"
18 #include <numeric>
19 #include <stack>
20 
21 #define DEBUG_TYPE "shrinkwrapping"
22 
23 using namespace llvm;
24 
25 namespace opts {
26 
27 extern cl::opt<bool> TimeOpts;
28 extern cl::OptionCategory BoltOptCategory;
29 
30 static cl::opt<unsigned> ShrinkWrappingThreshold(
31     "shrink-wrapping-threshold",
32     cl::desc("Percentage of prologue execution count to use as threshold when"
33              " evaluating whether a block is cold enough to be profitable to"
34              " move eligible spills there"),
35     cl::init(30), cl::ZeroOrMore, cl::cat(BoltOptCategory));
36 } // namespace opts
37 
38 namespace llvm {
39 namespace bolt {
40 
41 void CalleeSavedAnalysis::analyzeSaves() {
42   ReachingDefOrUse</*Def=*/true> &RD = Info.getReachingDefs();
43   StackReachingUses &SRU = Info.getStackReachingUses();
44   auto &InsnToBB = Info.getInsnToBBMap();
45   BitVector BlacklistedRegs(BC.MRI->getNumRegs(), false);
46 
47   LLVM_DEBUG(dbgs() << "Checking spill locations\n");
48   for (BinaryBasicBlock &BB : BF) {
49     LLVM_DEBUG(dbgs() << "\tNow at BB " << BB.getName() << "\n");
50     const MCInst *Prev = nullptr;
51     for (MCInst &Inst : BB) {
52       if (ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(Inst)) {
53         // Blacklist weird stores we don't understand
54         if ((!FIE->IsSimple || FIE->StackOffset >= 0) && FIE->IsStore &&
55             FIE->IsStoreFromReg) {
56           BlacklistedRegs.set(FIE->RegOrImm);
57           CalleeSaved.reset(FIE->RegOrImm);
58           Prev = &Inst;
59           continue;
60         }
61 
62         if (!FIE->IsStore || !FIE->IsStoreFromReg ||
63             BlacklistedRegs[FIE->RegOrImm]) {
64           Prev = &Inst;
65           continue;
66         }
67 
68         // If this reg is defined locally, it is not a callee-saved reg
69         if (RD.isReachedBy(FIE->RegOrImm,
70                            Prev ? RD.expr_begin(*Prev) : RD.expr_begin(BB))) {
71           BlacklistedRegs.set(FIE->RegOrImm);
72           CalleeSaved.reset(FIE->RegOrImm);
73           Prev = &Inst;
74           continue;
75         }
76 
77         // If this stack position is accessed in another function, we are
78         // probably dealing with a parameter passed in a stack -- do not mess
79         // with it
80         if (SRU.isStoreUsed(*FIE,
81                             Prev ? SRU.expr_begin(*Prev) : SRU.expr_begin(BB)),
82             /*IncludeLocalAccesses=*/false) {
83           BlacklistedRegs.set(FIE->RegOrImm);
84           CalleeSaved.reset(FIE->RegOrImm);
85           Prev = &Inst;
86           continue;
87         }
88 
89         // If this stack position is loaded elsewhere in another reg, we can't
90         // update it, so blacklist it.
91         if (SRU.isLoadedInDifferentReg(*FIE, Prev ? SRU.expr_begin(*Prev)
92                                                   : SRU.expr_begin(BB))) {
93           BlacklistedRegs.set(FIE->RegOrImm);
94           CalleeSaved.reset(FIE->RegOrImm);
95           Prev = &Inst;
96           continue;
97         }
98 
99         // Ignore regs with multiple saves
100         if (CalleeSaved[FIE->RegOrImm]) {
101           BlacklistedRegs.set(FIE->RegOrImm);
102           CalleeSaved.reset(FIE->RegOrImm);
103           Prev = &Inst;
104           continue;
105         }
106 
107         CalleeSaved.set(FIE->RegOrImm);
108         SaveFIEByReg[FIE->RegOrImm] = &*FIE;
109         SavingCost[FIE->RegOrImm] += InsnToBB[&Inst]->getKnownExecutionCount();
110         BC.MIB->addAnnotation(Inst, getSaveTag(), FIE->RegOrImm, AllocatorId);
111         OffsetsByReg[FIE->RegOrImm] = FIE->StackOffset;
112         LLVM_DEBUG(dbgs() << "Logging new candidate for Callee-Saved Reg: "
113                           << FIE->RegOrImm << "\n");
114       }
115       Prev = &Inst;
116     }
117   }
118 }
119 
120 void CalleeSavedAnalysis::analyzeRestores() {
121   ReachingDefOrUse</*Def=*/false> &RU = Info.getReachingUses();
122 
123   // Now compute all restores of these callee-saved regs
124   for (BinaryBasicBlock &BB : BF) {
125     const MCInst *Prev = nullptr;
126     for (auto I = BB.rbegin(), E = BB.rend(); I != E; ++I) {
127       MCInst &Inst = *I;
128       if (ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(Inst)) {
129         if (!FIE->IsLoad || !CalleeSaved[FIE->RegOrImm]) {
130           Prev = &Inst;
131           continue;
132         }
133 
134         // If this reg is used locally after a restore, then we are probably
135         // not dealing with a callee-saved reg. Except if this use is by
136         // another store, but we don't cover this case yet.
137         // Also not callee-saved if this load accesses caller stack or isn't
138         // simple.
139         if (!FIE->IsSimple || FIE->StackOffset >= 0 ||
140             RU.isReachedBy(FIE->RegOrImm,
141                            Prev ? RU.expr_begin(*Prev) : RU.expr_begin(BB))) {
142           CalleeSaved.reset(FIE->RegOrImm);
143           Prev = &Inst;
144           continue;
145         }
146         // If stack offsets between saves/store don't agree with each other,
147         // we don't completely understand what's happening here
148         if (FIE->StackOffset != OffsetsByReg[FIE->RegOrImm]) {
149           CalleeSaved.reset(FIE->RegOrImm);
150           LLVM_DEBUG(dbgs() << "Dismissing Callee-Saved Reg because we found a "
151                                "mismatching restore: "
152                             << FIE->RegOrImm << "\n");
153           Prev = &Inst;
154           continue;
155         }
156 
157         LLVM_DEBUG(dbgs() << "Adding matching restore for: " << FIE->RegOrImm
158                           << "\n");
159         if (LoadFIEByReg[FIE->RegOrImm] == nullptr)
160           LoadFIEByReg[FIE->RegOrImm] = &*FIE;
161         BC.MIB->addAnnotation(Inst, getRestoreTag(), FIE->RegOrImm,
162                               AllocatorId);
163         HasRestores.set(FIE->RegOrImm);
164       }
165       Prev = &Inst;
166     }
167   }
168 }
169 
170 std::vector<MCInst *> CalleeSavedAnalysis::getSavesByReg(uint16_t Reg) {
171   std::vector<MCInst *> Results;
172   for (BinaryBasicBlock &BB : BF)
173     for (MCInst &Inst : BB)
174       if (getSavedReg(Inst) == Reg)
175         Results.push_back(&Inst);
176   return Results;
177 }
178 
179 std::vector<MCInst *> CalleeSavedAnalysis::getRestoresByReg(uint16_t Reg) {
180   std::vector<MCInst *> Results;
181   for (BinaryBasicBlock &BB : BF)
182     for (MCInst &Inst : BB)
183       if (getRestoredReg(Inst) == Reg)
184         Results.push_back(&Inst);
185   return Results;
186 }
187 
188 CalleeSavedAnalysis::~CalleeSavedAnalysis() {
189   for (BinaryBasicBlock &BB : BF) {
190     for (MCInst &Inst : BB) {
191       BC.MIB->removeAnnotation(Inst, getSaveTag());
192       BC.MIB->removeAnnotation(Inst, getRestoreTag());
193     }
194   }
195 }
196 
197 void StackLayoutModifier::blacklistRegion(int64_t Offset, int64_t Size) {
198   if (BlacklistedRegions[Offset] < Size)
199     BlacklistedRegions[Offset] = Size;
200 }
201 
202 bool StackLayoutModifier::isRegionBlacklisted(int64_t Offset, int64_t Size) {
203   for (std::pair<const int64_t, int64_t> Elem : BlacklistedRegions)
204     if (Offset + Size > Elem.first && Offset < Elem.first + Elem.second)
205       return true;
206   return false;
207 }
208 
209 bool StackLayoutModifier::blacklistAllInConflictWith(int64_t Offset,
210                                                      int64_t Size) {
211   bool HasConflict = false;
212   for (auto Iter = AvailableRegions.begin(); Iter != AvailableRegions.end();) {
213     std::pair<const int64_t, int64_t> &Elem = *Iter;
214     if (Offset + Size > Elem.first && Offset < Elem.first + Elem.second &&
215         (Offset != Elem.first || Size != Elem.second)) {
216       Iter = AvailableRegions.erase(Iter);
217       HasConflict = true;
218       continue;
219     }
220     ++Iter;
221   }
222   if (HasConflict) {
223     blacklistRegion(Offset, Size);
224     return true;
225   }
226   return false;
227 }
228 
229 void StackLayoutModifier::checkFramePointerInitialization(MCInst &Point) {
230   StackPointerTracking &SPT = Info.getStackPointerTracking();
231   if (!BC.MII->get(Point.getOpcode())
232            .hasDefOfPhysReg(Point, BC.MIB->getFramePointer(), *BC.MRI))
233     return;
234 
235   int SPVal, FPVal;
236   std::tie(SPVal, FPVal) = *SPT.getStateBefore(Point);
237   std::pair<MCPhysReg, int64_t> FP;
238 
239   if (FPVal != SPT.EMPTY && FPVal != SPT.SUPERPOSITION)
240     FP = std::make_pair(BC.MIB->getFramePointer(), FPVal);
241   else
242     FP = std::make_pair(0, 0);
243   std::pair<MCPhysReg, int64_t> SP;
244 
245   if (SPVal != SPT.EMPTY && SPVal != SPT.SUPERPOSITION)
246     SP = std::make_pair(BC.MIB->getStackPointer(), SPVal);
247   else
248     SP = std::make_pair(0, 0);
249 
250   int64_t Output;
251   if (!BC.MIB->evaluateStackOffsetExpr(Point, Output, SP, FP))
252     return;
253 
254   // Not your regular frame pointer initialization... bail
255   if (Output != SPVal)
256     blacklistRegion(0, 0);
257 }
258 
259 void StackLayoutModifier::checkStackPointerRestore(MCInst &Point) {
260   StackPointerTracking &SPT = Info.getStackPointerTracking();
261   if (!BC.MII->get(Point.getOpcode())
262            .hasDefOfPhysReg(Point, BC.MIB->getStackPointer(), *BC.MRI))
263     return;
264   // Check if the definition of SP comes from FP -- in this case, this
265   // value may need to be updated depending on our stack layout changes
266   const MCInstrDesc &InstInfo = BC.MII->get(Point.getOpcode());
267   unsigned NumDefs = InstInfo.getNumDefs();
268   bool UsesFP = false;
269   for (unsigned I = NumDefs, E = MCPlus::getNumPrimeOperands(Point); I < E;
270        ++I) {
271     MCOperand &Operand = Point.getOperand(I);
272     if (!Operand.isReg())
273       continue;
274     if (Operand.getReg() == BC.MIB->getFramePointer()) {
275       UsesFP = true;
276       break;
277     }
278   }
279   if (!UsesFP)
280     return;
281 
282   // Setting up evaluation
283   int SPVal, FPVal;
284   std::tie(SPVal, FPVal) = *SPT.getStateBefore(Point);
285   std::pair<MCPhysReg, int64_t> FP;
286 
287   if (FPVal != SPT.EMPTY && FPVal != SPT.SUPERPOSITION)
288     FP = std::make_pair(BC.MIB->getFramePointer(), FPVal);
289   else
290     FP = std::make_pair(0, 0);
291   std::pair<MCPhysReg, int64_t> SP;
292 
293   if (SPVal != SPT.EMPTY && SPVal != SPT.SUPERPOSITION)
294     SP = std::make_pair(BC.MIB->getStackPointer(), SPVal);
295   else
296     SP = std::make_pair(0, 0);
297 
298   int64_t Output;
299   if (!BC.MIB->evaluateStackOffsetExpr(Point, Output, SP, FP))
300     return;
301 
302   // If the value is the same of FP, no need to adjust it
303   if (Output == FPVal)
304     return;
305 
306   // If an allocation happened through FP, bail
307   if (Output <= SPVal) {
308     blacklistRegion(0, 0);
309     return;
310   }
311 
312   // We are restoring SP to an old value based on FP. Mark it as a stack
313   // access to be fixed later.
314   BC.MIB->addAnnotation(Point, getSlotTag(), Output, AllocatorId);
315 }
316 
317 void StackLayoutModifier::classifyStackAccesses() {
318   // Understand when stack slots are being used non-locally
319   StackReachingUses &SRU = Info.getStackReachingUses();
320 
321   for (BinaryBasicBlock &BB : BF) {
322     const MCInst *Prev = nullptr;
323     for (auto I = BB.rbegin(), E = BB.rend(); I != E; ++I) {
324       MCInst &Inst = *I;
325       checkFramePointerInitialization(Inst);
326       checkStackPointerRestore(Inst);
327       ErrorOr<const FrameIndexEntry &> FIEX = FA.getFIEFor(Inst);
328       if (!FIEX) {
329         Prev = &Inst;
330         continue;
331       }
332       if (!FIEX->IsSimple || (FIEX->IsStore && !FIEX->IsStoreFromReg)) {
333         blacklistRegion(FIEX->StackOffset, FIEX->Size);
334         Prev = &Inst;
335         continue;
336       }
337       // If this stack position is accessed in another function, we are
338       // probably dealing with a parameter passed in a stack -- do not mess
339       // with it
340       if (SRU.isStoreUsed(*FIEX,
341                           Prev ? SRU.expr_begin(*Prev) : SRU.expr_begin(BB),
342                           /*IncludeLocalAccesses=*/false)) {
343         blacklistRegion(FIEX->StackOffset, FIEX->Size);
344         Prev = &Inst;
345         continue;
346       }
347       // Now we have a clear stack slot access. Check if its blacklisted or if
348       // it conflicts with another chunk.
349       if (isRegionBlacklisted(FIEX->StackOffset, FIEX->Size) ||
350           blacklistAllInConflictWith(FIEX->StackOffset, FIEX->Size)) {
351         Prev = &Inst;
352         continue;
353       }
354       // We are free to go. Add it as available stack slot which we know how
355       // to move it.
356       AvailableRegions[FIEX->StackOffset] = FIEX->Size;
357       BC.MIB->addAnnotation(Inst, getSlotTag(), FIEX->StackOffset, AllocatorId);
358       RegionToRegMap[FIEX->StackOffset].insert(FIEX->RegOrImm);
359       RegToRegionMap[FIEX->RegOrImm].insert(FIEX->StackOffset);
360       LLVM_DEBUG(dbgs() << "Adding region " << FIEX->StackOffset << " size "
361                         << (int)FIEX->Size << "\n");
362     }
363   }
364 }
365 
366 void StackLayoutModifier::classifyCFIs() {
367   std::stack<std::pair<int64_t, uint16_t>> CFIStack;
368   int64_t CfaOffset = -8;
369   uint16_t CfaReg = 7;
370 
371   auto recordAccess = [&](MCInst *Inst, int64_t Offset) {
372     const uint16_t Reg = *BC.MRI->getLLVMRegNum(CfaReg, /*isEH=*/false);
373     if (Reg == BC.MIB->getStackPointer() || Reg == BC.MIB->getFramePointer()) {
374       BC.MIB->addAnnotation(*Inst, getSlotTag(), Offset, AllocatorId);
375       LLVM_DEBUG(dbgs() << "Recording CFI " << Offset << "\n");
376     } else {
377       IsSimple = false;
378       return;
379     }
380   };
381 
382   for (BinaryBasicBlock *&BB : BF.layout()) {
383     for (MCInst &Inst : *BB) {
384       if (!BC.MIB->isCFI(Inst))
385         continue;
386       const MCCFIInstruction *CFI = BF.getCFIFor(Inst);
387       switch (CFI->getOperation()) {
388       case MCCFIInstruction::OpDefCfa:
389         CfaOffset = -CFI->getOffset();
390         recordAccess(&Inst, CfaOffset);
391         LLVM_FALLTHROUGH;
392       case MCCFIInstruction::OpDefCfaRegister:
393         CfaReg = CFI->getRegister();
394         break;
395       case MCCFIInstruction::OpDefCfaOffset:
396         CfaOffset = -CFI->getOffset();
397         recordAccess(&Inst, CfaOffset);
398         break;
399       case MCCFIInstruction::OpOffset:
400         recordAccess(&Inst, CFI->getOffset());
401         BC.MIB->addAnnotation(Inst, getOffsetCFIRegTag(),
402                               BC.MRI->getLLVMRegNum(CFI->getRegister(),
403                                                     /*isEH=*/false),
404                               AllocatorId);
405         break;
406       case MCCFIInstruction::OpSameValue:
407         BC.MIB->addAnnotation(Inst, getOffsetCFIRegTag(),
408                               BC.MRI->getLLVMRegNum(CFI->getRegister(),
409                                                     /*isEH=*/false),
410                               AllocatorId);
411         break;
412       case MCCFIInstruction::OpRememberState:
413         CFIStack.push(std::make_pair(CfaOffset, CfaReg));
414         break;
415       case MCCFIInstruction::OpRestoreState: {
416         assert(!CFIStack.empty() && "Corrupt CFI stack");
417         std::pair<int64_t, uint16_t> &Elem = CFIStack.top();
418         CFIStack.pop();
419         CfaOffset = Elem.first;
420         CfaReg = Elem.second;
421         break;
422       }
423       case MCCFIInstruction::OpRelOffset:
424       case MCCFIInstruction::OpAdjustCfaOffset:
425         llvm_unreachable("Unhandled AdjustCfaOffset");
426         break;
427       default:
428         break;
429       }
430     }
431   }
432 }
433 
434 void StackLayoutModifier::scheduleChange(
435     MCInst &Inst, StackLayoutModifier::WorklistItem Item) {
436   auto &WList = BC.MIB->getOrCreateAnnotationAs<std::vector<WorklistItem>>(
437       Inst, getTodoTag(), AllocatorId);
438   WList.push_back(Item);
439 }
440 
441 bool StackLayoutModifier::canCollapseRegion(MCInst *DeletedPush) {
442   if (!IsSimple || !BC.MIB->isPush(*DeletedPush))
443     return false;
444 
445   ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(*DeletedPush);
446   if (!FIE)
447     return false;
448 
449   return canCollapseRegion(FIE->StackOffset);
450 }
451 
452 bool StackLayoutModifier::canCollapseRegion(int64_t RegionAddr) {
453   if (!IsInitialized)
454     initialize();
455   if (!IsSimple)
456     return false;
457 
458   if (CollapsedRegions.count(RegionAddr))
459     return true;
460 
461   // Check if it is possible to readjust all accesses below RegionAddr
462   if (!BlacklistedRegions.empty())
463     return false;
464 
465   return true;
466 }
467 
468 bool StackLayoutModifier::collapseRegion(MCInst *DeletedPush) {
469   ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(*DeletedPush);
470   if (!FIE)
471     return false;
472   int64_t RegionAddr = FIE->StackOffset;
473   int64_t RegionSz = FIE->Size;
474   return collapseRegion(DeletedPush, RegionAddr, RegionSz);
475 }
476 
477 bool StackLayoutModifier::collapseRegion(MCInst *Alloc, int64_t RegionAddr,
478                                          int64_t RegionSz) {
479   if (!canCollapseRegion(RegionAddr))
480     return false;
481 
482   assert(IsInitialized);
483   StackAllocationAnalysis &SAA = Info.getStackAllocationAnalysis();
484 
485   for (BinaryBasicBlock &BB : BF) {
486     for (MCInst &Inst : BB) {
487       if (!BC.MIB->hasAnnotation(Inst, getSlotTag()))
488         continue;
489       auto Slot =
490           BC.MIB->getAnnotationAs<decltype(FrameIndexEntry::StackOffset)>(
491               Inst, getSlotTag());
492       if (!AvailableRegions.count(Slot))
493         continue;
494       // We need to ensure this access is affected by the deleted push
495       if (!(*SAA.getStateBefore(Inst))[SAA.ExprToIdx[Alloc]])
496         continue;
497 
498       if (BC.MIB->isCFI(Inst)) {
499         if (Slot > RegionAddr)
500           continue;
501         scheduleChange(Inst, WorklistItem(WorklistItem::AdjustCFI, RegionSz));
502         continue;
503       }
504       ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(Inst);
505       if (!FIE) {
506         if (Slot > RegionAddr)
507           continue;
508         // SP update based on frame pointer
509         scheduleChange(
510             Inst, WorklistItem(WorklistItem::AdjustLoadStoreOffset, RegionSz));
511         continue;
512       }
513 
514       if (Slot == RegionAddr) {
515         BC.MIB->addAnnotation(Inst, "AccessesDeletedPos", 0U, AllocatorId);
516         continue;
517       }
518       if (BC.MIB->isPush(Inst) || BC.MIB->isPop(Inst))
519         continue;
520 
521       if (FIE->StackPtrReg == BC.MIB->getStackPointer() && Slot < RegionAddr)
522         continue;
523 
524       if (FIE->StackPtrReg == BC.MIB->getFramePointer() && Slot > RegionAddr)
525         continue;
526 
527       scheduleChange(
528           Inst, WorklistItem(WorklistItem::AdjustLoadStoreOffset, RegionSz));
529     }
530   }
531 
532   CollapsedRegions.insert(RegionAddr);
533   return true;
534 }
535 
536 void StackLayoutModifier::setOffsetForCollapsedAccesses(int64_t NewOffset) {
537   for (BinaryBasicBlock &BB : BF) {
538     for (MCInst &Inst : BB) {
539       if (!BC.MIB->hasAnnotation(Inst, "AccessesDeletedPos"))
540         continue;
541       BC.MIB->removeAnnotation(Inst, "AccessesDeletedPos");
542       scheduleChange(
543           Inst, WorklistItem(WorklistItem::AdjustLoadStoreOffset, NewOffset));
544     }
545   }
546 }
547 
548 bool StackLayoutModifier::canInsertRegion(ProgramPoint P) {
549   if (!IsInitialized)
550     initialize();
551   if (!IsSimple)
552     return false;
553 
554   StackPointerTracking &SPT = Info.getStackPointerTracking();
555   int64_t RegionAddr = SPT.getStateBefore(P)->first;
556   if (RegionAddr == SPT.SUPERPOSITION || RegionAddr == SPT.EMPTY)
557     return false;
558 
559   if (InsertedRegions.count(RegionAddr))
560     return true;
561 
562   // Check if we are going to screw up stack accesses at call sites that
563   // pass parameters via stack
564   if (!BlacklistedRegions.empty())
565     return false;
566 
567   return true;
568 }
569 
570 bool StackLayoutModifier::insertRegion(ProgramPoint P, int64_t RegionSz) {
571   if (!canInsertRegion(P))
572     return false;
573 
574   assert(IsInitialized);
575   StackPointerTracking &SPT = Info.getStackPointerTracking();
576   // This RegionAddr is slightly different from the one seen in collapseRegion
577   // This is the value of SP before the allocation the user wants to make.
578   int64_t RegionAddr = SPT.getStateBefore(P)->first;
579   if (RegionAddr == SPT.SUPERPOSITION || RegionAddr == SPT.EMPTY)
580     return false;
581 
582   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
583 
584   for (BinaryBasicBlock &BB : BF) {
585     for (MCInst &Inst : BB) {
586       if (!BC.MIB->hasAnnotation(Inst, getSlotTag()))
587         continue;
588       auto Slot =
589           BC.MIB->getAnnotationAs<decltype(FrameIndexEntry::StackOffset)>(
590               Inst, getSlotTag());
591       if (!AvailableRegions.count(Slot))
592         continue;
593 
594       if (!(DA.doesADominateB(P, Inst)))
595         continue;
596 
597       if (BC.MIB->isCFI(Inst)) {
598         if (Slot >= RegionAddr)
599           continue;
600         scheduleChange(Inst, WorklistItem(WorklistItem::AdjustCFI, -RegionSz));
601         continue;
602       }
603       ErrorOr<const FrameIndexEntry &> FIE = FA.getFIEFor(Inst);
604       if (!FIE) {
605         if (Slot >= RegionAddr)
606           continue;
607         scheduleChange(
608             Inst, WorklistItem(WorklistItem::AdjustLoadStoreOffset, -RegionSz));
609         continue;
610       }
611 
612       if (FIE->StackPtrReg == BC.MIB->getStackPointer() && Slot < RegionAddr)
613         continue;
614       if (FIE->StackPtrReg == BC.MIB->getFramePointer() && Slot >= RegionAddr)
615         continue;
616       if (BC.MIB->isPush(Inst) || BC.MIB->isPop(Inst))
617         continue;
618       scheduleChange(
619           Inst, WorklistItem(WorklistItem::AdjustLoadStoreOffset, -RegionSz));
620     }
621   }
622 
623   InsertedRegions.insert(RegionAddr);
624   return true;
625 }
626 
627 void StackLayoutModifier::performChanges() {
628   std::set<uint32_t> ModifiedCFIIndices;
629   for (BinaryBasicBlock &BB : BF) {
630     for (auto I = BB.rbegin(), E = BB.rend(); I != E; ++I) {
631       MCInst &Inst = *I;
632       if (BC.MIB->hasAnnotation(Inst, "AccessesDeletedPos")) {
633         assert(BC.MIB->isPop(Inst) || BC.MIB->isPush(Inst));
634         BC.MIB->removeAnnotation(Inst, "AccessesDeletedPos");
635       }
636       if (!BC.MIB->hasAnnotation(Inst, getTodoTag()))
637         continue;
638       auto &WList = BC.MIB->getAnnotationAs<std::vector<WorklistItem>>(
639           Inst, getTodoTag());
640       int64_t Adjustment = 0;
641       WorklistItem::ActionType AdjustmentType = WorklistItem::None;
642       for (WorklistItem &WI : WList) {
643         if (WI.Action == WorklistItem::None)
644           continue;
645         assert(WI.Action == WorklistItem::AdjustLoadStoreOffset ||
646                WI.Action == WorklistItem::AdjustCFI);
647         assert((AdjustmentType == WorklistItem::None ||
648                 AdjustmentType == WI.Action) &&
649                "Conflicting actions requested at the same program point");
650         AdjustmentType = WI.Action;
651         Adjustment += WI.OffsetUpdate;
652       }
653       if (!Adjustment)
654         continue;
655       if (AdjustmentType != WorklistItem::AdjustLoadStoreOffset) {
656         assert(BC.MIB->isCFI(Inst));
657         uint32_t CFINum = Inst.getOperand(0).getImm();
658         if (ModifiedCFIIndices.count(CFINum))
659           continue;
660         ModifiedCFIIndices.insert(CFINum);
661         const MCCFIInstruction *CFI = BF.getCFIFor(Inst);
662         const MCCFIInstruction::OpType Operation = CFI->getOperation();
663         if (Operation == MCCFIInstruction::OpDefCfa ||
664             Operation == MCCFIInstruction::OpDefCfaOffset)
665           Adjustment = 0 - Adjustment;
666         LLVM_DEBUG(dbgs() << "Changing CFI offset from " << CFI->getOffset()
667                           << " to " << (CFI->getOffset() + Adjustment) << "\n");
668         BF.mutateCFIOffsetFor(Inst, CFI->getOffset() + Adjustment);
669         continue;
670       }
671       int32_t SrcImm = 0;
672       MCPhysReg Reg = 0;
673       MCPhysReg StackPtrReg = 0;
674       int64_t StackOffset = 0;
675       bool IsIndexed = false;
676       bool IsLoad = false;
677       bool IsStore = false;
678       bool IsSimple = false;
679       bool IsStoreFromReg = false;
680       uint8_t Size = 0;
681       bool Success = false;
682       Success = BC.MIB->isStackAccess(Inst, IsLoad, IsStore, IsStoreFromReg,
683                                       Reg, SrcImm, StackPtrReg, StackOffset,
684                                       Size, IsSimple, IsIndexed);
685       if (!Success) {
686         // SP update based on FP value
687         Success = BC.MIB->addToImm(Inst, Adjustment, &*BC.Ctx);
688         assert(Success);
689         continue;
690       }
691       assert(Success && IsSimple && !IsIndexed && (!IsStore || IsStoreFromReg));
692       if (StackPtrReg != BC.MIB->getFramePointer())
693         Adjustment = -Adjustment;
694       if (IsLoad)
695         Success = BC.MIB->createRestoreFromStack(
696             Inst, StackPtrReg, StackOffset + Adjustment, Reg, Size);
697       else if (IsStore)
698         Success = BC.MIB->createSaveToStack(
699             Inst, StackPtrReg, StackOffset + Adjustment, Reg, Size);
700       LLVM_DEBUG({
701         dbgs() << "Adjusted instruction: ";
702         Inst.dump();
703       });
704       assert(Success);
705     }
706   }
707 }
708 
709 void StackLayoutModifier::initialize() {
710   classifyStackAccesses();
711   classifyCFIs();
712   IsInitialized = true;
713 }
714 
715 std::atomic_uint64_t ShrinkWrapping::SpillsMovedRegularMode{0};
716 std::atomic_uint64_t ShrinkWrapping::SpillsMovedPushPopMode{0};
717 std::atomic_uint64_t ShrinkWrapping::SpillsMovedDynamicCount{0};
718 std::atomic_uint64_t ShrinkWrapping::SpillsFailedDynamicCount{0};
719 std::atomic_uint64_t ShrinkWrapping::InstrDynamicCount{0};
720 std::atomic_uint64_t ShrinkWrapping::StoreDynamicCount{0};
721 
722 using BBIterTy = BinaryBasicBlock::iterator;
723 
724 void ShrinkWrapping::classifyCSRUses() {
725   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
726   StackPointerTracking &SPT = Info.getStackPointerTracking();
727   UsesByReg = std::vector<BitVector>(BC.MRI->getNumRegs(),
728                                      BitVector(DA.NumInstrs, false));
729 
730   const BitVector &FPAliases = BC.MIB->getAliases(BC.MIB->getFramePointer());
731   for (BinaryBasicBlock &BB : BF) {
732     for (MCInst &Inst : BB) {
733       if (BC.MIB->isCFI(Inst))
734         continue;
735       BitVector BV = BitVector(BC.MRI->getNumRegs(), false);
736       BC.MIB->getTouchedRegs(Inst, BV);
737       BV &= CSA.CalleeSaved;
738       for (int I : BV.set_bits()) {
739         if (I == 0)
740           continue;
741         if (CSA.getSavedReg(Inst) != I && CSA.getRestoredReg(Inst) != I)
742           UsesByReg[I].set(DA.ExprToIdx[&Inst]);
743       }
744       if (!SPT.HasFramePointer || !BC.MIB->isCall(Inst))
745         continue;
746       BV = CSA.CalleeSaved;
747       BV &= FPAliases;
748       for (int I : BV.set_bits())
749         UsesByReg[I].set(DA.ExprToIdx[&Inst]);
750     }
751   }
752 }
753 
754 void ShrinkWrapping::pruneUnwantedCSRs() {
755   BitVector ParamRegs = BC.MIB->getRegsUsedAsParams();
756   for (unsigned I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
757     if (!CSA.CalleeSaved[I])
758       continue;
759     if (ParamRegs[I]) {
760       CSA.CalleeSaved.reset(I);
761       continue;
762     }
763     if (UsesByReg[I].empty()) {
764       LLVM_DEBUG(
765           dbgs()
766           << "Dismissing Callee-Saved Reg because we found no uses of it:" << I
767           << "\n");
768       CSA.CalleeSaved.reset(I);
769       continue;
770     }
771     if (!CSA.HasRestores[I]) {
772       LLVM_DEBUG(
773           dbgs() << "Dismissing Callee-Saved Reg because it does not have "
774                     "restores:"
775                  << I << "\n");
776       CSA.CalleeSaved.reset(I);
777     }
778   }
779 }
780 
781 void ShrinkWrapping::computeSaveLocations() {
782   BestSavePos = std::vector<std::vector<MCInst *>>(BC.MRI->getNumRegs());
783   ReachingInsns<true> &RI = Info.getReachingInsnsBackwards();
784   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
785   StackPointerTracking &SPT = Info.getStackPointerTracking();
786 
787   LLVM_DEBUG(dbgs() << "Checking save/restore possibilities\n");
788   for (BinaryBasicBlock &BB : BF) {
789     LLVM_DEBUG(dbgs() << "\tNow at BB " << BB.getName() << "\n");
790 
791     MCInst *First = BB.begin() != BB.end() ? &*BB.begin() : nullptr;
792     if (!First)
793       continue;
794 
795     // Use reaching instructions to detect if we are inside a loop - if we
796     // are, do not consider this BB as valid placement for saves.
797     if (RI.isInLoop(BB))
798       continue;
799 
800     const std::pair<int, int> SPFP = *SPT.getStateBefore(*First);
801     // If we don't know stack state at this point, bail
802     if ((SPFP.first == SPT.SUPERPOSITION || SPFP.first == SPT.EMPTY) &&
803         (SPFP.second == SPT.SUPERPOSITION || SPFP.second == SPT.EMPTY))
804       continue;
805 
806     for (unsigned I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
807       if (!CSA.CalleeSaved[I])
808         continue;
809 
810       BitVector BBDominatedUses = BitVector(DA.NumInstrs, false);
811       for (int J : UsesByReg[I].set_bits())
812         if (DA.doesADominateB(*First, J))
813           BBDominatedUses.set(J);
814       LLVM_DEBUG(dbgs() << "\t\tBB " << BB.getName() << " dominates "
815                         << BBDominatedUses.count() << " uses for reg " << I
816                         << ". Total uses for reg is " << UsesByReg[I].count()
817                         << "\n");
818       BBDominatedUses &= UsesByReg[I];
819       if (BBDominatedUses == UsesByReg[I]) {
820         LLVM_DEBUG(dbgs() << "\t\t\tAdded " << BB.getName()
821                           << " as a save pos for " << I << "\n");
822         BestSavePos[I].push_back(First);
823         LLVM_DEBUG({
824           dbgs() << "Dominated uses are:\n";
825           for (int J : UsesByReg[I].set_bits()) {
826             dbgs() << "Idx " << J << ": ";
827             BC.printInstruction(dbgs(), *DA.Expressions[J]);
828             DA.Expressions[J]->dump();
829           }
830         });
831       }
832     }
833   }
834 
835   BestSaveCount = std::vector<std::vector<uint64_t>>(BC.MRI->getNumRegs());
836 
837   auto &InsnToBB = Info.getInsnToBBMap();
838   for (unsigned I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
839     if (!CSA.CalleeSaved[I])
840       continue;
841 
842     std::stable_sort(BestSavePos[I].begin(), BestSavePos[I].end(),
843                      [&](const MCInst *A, const MCInst *B) {
844                        const BinaryBasicBlock *BBA = InsnToBB[A];
845                        const BinaryBasicBlock *BBB = InsnToBB[B];
846                        const uint64_t CountA = BBA->getKnownExecutionCount();
847                        const uint64_t CountB = BBB->getKnownExecutionCount();
848                        return CountB < CountA;
849                      });
850 
851     for (MCInst *Pos : BestSavePos[I]) {
852       const BinaryBasicBlock *BB = InsnToBB[Pos];
853       const uint64_t Count = BB->getKnownExecutionCount();
854       BestSaveCount[I].push_back(Count);
855     }
856   }
857 }
858 
859 void ShrinkWrapping::computeDomOrder() {
860   DomOrder = std::vector<MCPhysReg>(BC.MRI->getNumRegs(), 0);
861   std::vector<MCPhysReg> Order;
862   for (MCPhysReg I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
863     Order.push_back(I);
864   }
865 
866   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
867   auto &InsnToBB = Info.getInsnToBBMap();
868   llvm::sort(Order, [&](const MCPhysReg &A, const MCPhysReg &B) {
869     BinaryBasicBlock *BBA =
870         BestSavePos[A].size() ? InsnToBB[BestSavePos[A].back()] : nullptr;
871     BinaryBasicBlock *BBB =
872         BestSavePos[B].size() ? InsnToBB[BestSavePos[B].back()] : nullptr;
873     if (BBA == BBB)
874       return A < B;
875     if (!BBA && BBB)
876       return false;
877     if (BBA && !BBB)
878       return true;
879     if (DA.doesADominateB(*BestSavePos[A].back(), *BestSavePos[B].back()))
880       return true;
881     if (DA.doesADominateB(*BestSavePos[B].back(), *BestSavePos[A].back()))
882       return false;
883     return A < B;
884   });
885 
886   for (MCPhysReg I = 0, E = BC.MRI->getNumRegs(); I != E; ++I)
887     DomOrder[Order[I]] = I;
888 }
889 
890 bool ShrinkWrapping::isBestSavePosCold(unsigned CSR, MCInst *&BestPosSave,
891                                        uint64_t &TotalEstimatedWin) {
892   const uint64_t CurSavingCost = CSA.SavingCost[CSR];
893   if (!CSA.CalleeSaved[CSR])
894     return false;
895 
896   assert(BestSaveCount[CSR].size() == BestSavePos[CSR].size() &&
897          "save position vectors out of sync");
898   if (BestSaveCount[CSR].empty())
899     return false;
900 
901   const uint64_t BestCount = BestSaveCount[CSR].back();
902   BestPosSave = BestSavePos[CSR].back();
903   if (BestCount >= (opts::ShrinkWrappingThreshold / 100.0) * CurSavingCost)
904     return false;
905 
906   LLVM_DEBUG({
907     auto &InsnToBB = Info.getInsnToBBMap();
908     dbgs() << "Better position for saves found in func " << BF.getPrintName()
909            << " count << " << BF.getKnownExecutionCount() << "\n";
910     dbgs() << "Reg: " << CSR << "; New BB: " << InsnToBB[BestPosSave]->getName()
911            << " Freq reduction: " << (CurSavingCost - BestCount) << "\n";
912   });
913 
914   TotalEstimatedWin = CurSavingCost - BestCount;
915   return true;
916 }
917 
918 /// Auxiliar function used to create basic blocks for critical edges and update
919 /// the dominance frontier with these new locations
920 void ShrinkWrapping::splitFrontierCritEdges(
921     BinaryFunction *Func, SmallVector<ProgramPoint, 4> &Frontier,
922     const SmallVector<bool, 4> &IsCritEdge,
923     const SmallVector<BinaryBasicBlock *, 4> &From,
924     const SmallVector<SmallVector<BinaryBasicBlock *, 4>, 4> &To) {
925   LLVM_DEBUG(dbgs() << "splitFrontierCritEdges: Now handling func "
926                     << BF.getPrintName() << "\n");
927   // For every FromBB, there might be one or more critical edges, with
928   // To[I] containing destination BBs. It's important to memorize
929   // the original size of the Frontier as we may append to it while splitting
930   // critical edges originating with blocks with multiple destinations.
931   for (size_t I = 0, IE = Frontier.size(); I < IE; ++I) {
932     if (!IsCritEdge[I])
933       continue;
934     if (To[I].empty())
935       continue;
936     BinaryBasicBlock *FromBB = From[I];
937     LLVM_DEBUG(dbgs() << " - Now handling FrontierBB " << FromBB->getName()
938                       << "\n");
939     // Split edge for every DestinationBBs
940     for (size_t DI = 0, DIE = To[I].size(); DI < DIE; ++DI) {
941       BinaryBasicBlock *DestinationBB = To[I][DI];
942       LLVM_DEBUG(dbgs() << "   - Dest : " << DestinationBB->getName() << "\n");
943       BinaryBasicBlock *NewBB = Func->splitEdge(FromBB, DestinationBB);
944       // Insert dummy instruction so this BB is never empty (we need this for
945       // PredictiveStackPointerTracking to work, since it annotates instructions
946       // and not BBs).
947       if (NewBB->empty()) {
948         MCInst NewInst;
949         BC.MIB->createNoop(NewInst);
950         NewBB->addInstruction(std::move(NewInst));
951         scheduleChange(&*NewBB->begin(), WorklistItem(WorklistItem::Erase, 0));
952       }
953 
954       // Update frontier
955       ProgramPoint NewFrontierPP = ProgramPoint::getLastPointAt(*NewBB);
956       if (DI == 0) {
957         // Update frontier inplace
958         Frontier[I] = NewFrontierPP;
959         LLVM_DEBUG(dbgs() << "   - Update frontier with " << NewBB->getName()
960                           << '\n');
961       } else {
962         // Append new frontier to the end of the list
963         Frontier.push_back(NewFrontierPP);
964         LLVM_DEBUG(dbgs() << "   - Append frontier " << NewBB->getName()
965                           << '\n');
966       }
967     }
968   }
969 }
970 
971 SmallVector<ProgramPoint, 4>
972 ShrinkWrapping::doRestorePlacement(MCInst *BestPosSave, unsigned CSR,
973                                    uint64_t TotalEstimatedWin) {
974   SmallVector<ProgramPoint, 4> Frontier;
975   SmallVector<bool, 4> IsCritEdge;
976   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
977 
978   SmallVector<BinaryBasicBlock *, 4> CritEdgesFrom;
979   SmallVector<SmallVector<BinaryBasicBlock *, 4>, 4> CritEdgesTo;
980   // In case of a critical edge, we need to create extra BBs to host restores
981   // into edges transitioning to the dominance frontier, otherwise we pull these
982   // restores to inside the dominated area.
983   Frontier = DA.getDominanceFrontierFor(*BestPosSave).takeVector();
984   LLVM_DEBUG({
985     dbgs() << "Dumping dominance frontier for ";
986     BC.printInstruction(dbgs(), *BestPosSave);
987     for (ProgramPoint &PP : Frontier)
988       if (PP.isInst())
989         BC.printInstruction(dbgs(), *PP.getInst());
990       else
991         dbgs() << PP.getBB()->getName() << "\n";
992   });
993   for (ProgramPoint &PP : Frontier) {
994     bool HasCritEdges = false;
995     if (PP.isInst() && BC.MIB->isTerminator(*PP.getInst()) &&
996         doesInstUsesCSR(*PP.getInst(), CSR)) {
997       Frontier.clear();
998       return Frontier;
999     }
1000     BinaryBasicBlock *FrontierBB = Info.getParentBB(PP);
1001     CritEdgesFrom.emplace_back(FrontierBB);
1002     CritEdgesTo.emplace_back(0);
1003     SmallVector<BinaryBasicBlock *, 4> &Dests = CritEdgesTo.back();
1004     // Check for invoke instructions at the dominance frontier, which indicates
1005     // the landing pad is not dominated.
1006     if (PP.isInst() && BC.MIB->isInvoke(*PP.getInst())) {
1007       Frontier.clear();
1008       return Frontier;
1009     }
1010     doForAllSuccs(*FrontierBB, [&](ProgramPoint P) {
1011       if (!DA.doesADominateB(*BestPosSave, P)) {
1012         Dests.emplace_back(Info.getParentBB(P));
1013         return;
1014       }
1015       HasCritEdges = true;
1016     });
1017     IsCritEdge.push_back(HasCritEdges);
1018   }
1019   // Restores cannot be placed in empty BBs because we have a dataflow
1020   // analysis that depends on insertions happening before real instructions
1021   // (PredictiveStackPointerTracking). Detect now for empty BBs and add a
1022   // dummy nop that is scheduled to be removed later.
1023   bool InvalidateRequired = false;
1024   for (BinaryBasicBlock *&BB : BF.layout()) {
1025     if (BB->size() != 0)
1026       continue;
1027     MCInst NewInst;
1028     BC.MIB->createNoop(NewInst);
1029     auto II = BB->addInstruction(std::move(NewInst));
1030     scheduleChange(&*II, WorklistItem(WorklistItem::Erase, 0));
1031     InvalidateRequired = true;
1032   }
1033   if (std::accumulate(IsCritEdge.begin(), IsCritEdge.end(), 0)) {
1034     LLVM_DEBUG({
1035       dbgs() << "Now detected critical edges in the following frontier:\n";
1036       for (ProgramPoint &PP : Frontier) {
1037         if (PP.isBB()) {
1038           dbgs() << "  BB: " << PP.getBB()->getName() << "\n";
1039         } else {
1040           dbgs() << "  Inst: ";
1041           PP.getInst()->dump();
1042         }
1043       }
1044     });
1045     splitFrontierCritEdges(&BF, Frontier, IsCritEdge, CritEdgesFrom,
1046                            CritEdgesTo);
1047     InvalidateRequired = true;
1048   }
1049   if (InvalidateRequired) {
1050     // BitVectors that represent all insns of the function are invalid now
1051     // since we changed BBs/Insts. Re-run steps that depend on pointers being
1052     // valid
1053     Info.invalidateAll();
1054     classifyCSRUses();
1055   }
1056   return Frontier;
1057 }
1058 
1059 bool ShrinkWrapping::validatePushPopsMode(unsigned CSR, MCInst *BestPosSave,
1060                                           int64_t SaveOffset) {
1061   if (FA.requiresAlignment(BF)) {
1062     LLVM_DEBUG({
1063       dbgs() << "Reg " << CSR
1064              << " is not using push/pops due to function "
1065                 "alignment requirements.\n";
1066     });
1067     return false;
1068   }
1069   for (MCInst *Save : CSA.getSavesByReg(CSR)) {
1070     if (!SLM.canCollapseRegion(Save)) {
1071       LLVM_DEBUG(dbgs() << "Reg " << CSR << " cannot collapse region.\n");
1072       return false;
1073     }
1074   }
1075   // Abort if one of the restores for this CSR is not a POP.
1076   for (MCInst *Load : CSA.getRestoresByReg(CSR)) {
1077     if (!BC.MIB->isPop(*Load)) {
1078       LLVM_DEBUG(dbgs() << "Reg " << CSR << " has a mismatching restore.\n");
1079       return false;
1080     }
1081   }
1082 
1083   StackPointerTracking &SPT = Info.getStackPointerTracking();
1084   // Abort if we are inserting a push into an entry BB (offset -8) and this
1085   // func sets up a frame pointer.
1086   if (!SLM.canInsertRegion(BestPosSave) || SaveOffset == SPT.SUPERPOSITION ||
1087       SaveOffset == SPT.EMPTY || (SaveOffset == -8 && SPT.HasFramePointer)) {
1088     LLVM_DEBUG({
1089       dbgs() << "Reg " << CSR
1090              << " cannot insert region or we are "
1091                 "trying to insert a push into entry bb.\n";
1092     });
1093     return false;
1094   }
1095   return true;
1096 }
1097 
1098 SmallVector<ProgramPoint, 4> ShrinkWrapping::fixPopsPlacements(
1099     const SmallVector<ProgramPoint, 4> &RestorePoints, int64_t SaveOffset,
1100     unsigned CSR) {
1101   SmallVector<ProgramPoint, 4> FixedRestorePoints = RestorePoints;
1102   // Moving pop locations to the correct sp offset
1103   ReachingInsns<true> &RI = Info.getReachingInsnsBackwards();
1104   StackPointerTracking &SPT = Info.getStackPointerTracking();
1105   for (ProgramPoint &PP : FixedRestorePoints) {
1106     BinaryBasicBlock *BB = Info.getParentBB(PP);
1107     bool Found = false;
1108     if (SPT.getStateAt(ProgramPoint::getLastPointAt(*BB))->first ==
1109         SaveOffset) {
1110       BitVector BV = *RI.getStateAt(ProgramPoint::getLastPointAt(*BB));
1111       BV &= UsesByReg[CSR];
1112       if (!BV.any()) {
1113         Found = true;
1114         PP = BB;
1115         continue;
1116       }
1117     }
1118     for (auto RIt = BB->rbegin(), End = BB->rend(); RIt != End; ++RIt) {
1119       if (SPT.getStateBefore(*RIt)->first == SaveOffset) {
1120         BitVector BV = *RI.getStateAt(*RIt);
1121         BV &= UsesByReg[CSR];
1122         if (!BV.any()) {
1123           Found = true;
1124           PP = &*RIt;
1125           break;
1126         }
1127       }
1128     }
1129     if (!Found) {
1130       LLVM_DEBUG({
1131         dbgs() << "Could not find restore insertion point for " << CSR
1132                << ", falling back to load/store mode\n";
1133       });
1134       FixedRestorePoints.clear();
1135       return FixedRestorePoints;
1136     }
1137   }
1138   return FixedRestorePoints;
1139 }
1140 
1141 void ShrinkWrapping::scheduleOldSaveRestoresRemoval(unsigned CSR,
1142                                                     bool UsePushPops) {
1143 
1144   for (BinaryBasicBlock *&BB : BF.layout()) {
1145     std::vector<MCInst *> CFIs;
1146     for (auto I = BB->rbegin(), E = BB->rend(); I != E; ++I) {
1147       MCInst &Inst = *I;
1148       if (BC.MIB->isCFI(Inst)) {
1149         // Delete all offset CFIs related to this CSR
1150         if (SLM.getOffsetCFIReg(Inst) == CSR) {
1151           HasDeletedOffsetCFIs[CSR] = true;
1152           scheduleChange(&Inst, WorklistItem(WorklistItem::Erase, CSR));
1153           continue;
1154         }
1155         CFIs.push_back(&Inst);
1156         continue;
1157       }
1158 
1159       uint16_t SavedReg = CSA.getSavedReg(Inst);
1160       uint16_t RestoredReg = CSA.getRestoredReg(Inst);
1161       if (SavedReg != CSR && RestoredReg != CSR) {
1162         CFIs.clear();
1163         continue;
1164       }
1165 
1166       scheduleChange(&Inst, WorklistItem(UsePushPops
1167                                              ? WorklistItem::Erase
1168                                              : WorklistItem::ChangeToAdjustment,
1169                                          CSR));
1170 
1171       // Delete associated CFIs
1172       const bool RecordDeletedPushCFIs =
1173           SavedReg == CSR && DeletedPushCFIs[CSR].empty();
1174       const bool RecordDeletedPopCFIs =
1175           RestoredReg == CSR && DeletedPopCFIs[CSR].empty();
1176       for (MCInst *CFI : CFIs) {
1177         const MCCFIInstruction *MCCFI = BF.getCFIFor(*CFI);
1178         // Do not touch these...
1179         if (MCCFI->getOperation() == MCCFIInstruction::OpRestoreState ||
1180             MCCFI->getOperation() == MCCFIInstruction::OpRememberState)
1181           continue;
1182         scheduleChange(CFI, WorklistItem(WorklistItem::Erase, CSR));
1183         if (RecordDeletedPushCFIs) {
1184           // Do not record this to be replayed later because we are going to
1185           // rebuild it.
1186           if (MCCFI->getOperation() == MCCFIInstruction::OpDefCfaOffset)
1187             continue;
1188           DeletedPushCFIs[CSR].push_back(CFI->getOperand(0).getImm());
1189         }
1190         if (RecordDeletedPopCFIs) {
1191           if (MCCFI->getOperation() == MCCFIInstruction::OpDefCfaOffset)
1192             continue;
1193           DeletedPopCFIs[CSR].push_back(CFI->getOperand(0).getImm());
1194         }
1195       }
1196       CFIs.clear();
1197     }
1198   }
1199 }
1200 
1201 bool ShrinkWrapping::doesInstUsesCSR(const MCInst &Inst, uint16_t CSR) {
1202   if (BC.MIB->isCFI(Inst) || CSA.getSavedReg(Inst) == CSR ||
1203       CSA.getRestoredReg(Inst) == CSR)
1204     return false;
1205   BitVector BV = BitVector(BC.MRI->getNumRegs(), false);
1206   BC.MIB->getTouchedRegs(Inst, BV);
1207   return BV[CSR];
1208 }
1209 
1210 void ShrinkWrapping::scheduleSaveRestoreInsertions(
1211     unsigned CSR, MCInst *BestPosSave,
1212     SmallVector<ProgramPoint, 4> &RestorePoints, bool UsePushPops) {
1213   auto &InsnToBB = Info.getInsnToBBMap();
1214   const FrameIndexEntry *FIESave = CSA.SaveFIEByReg[CSR];
1215   const FrameIndexEntry *FIELoad = CSA.LoadFIEByReg[CSR];
1216   assert(FIESave && FIELoad && "Invalid CSR");
1217 
1218   LLVM_DEBUG({
1219     dbgs() << "Scheduling save insertion at: ";
1220     BestPosSave->dump();
1221   });
1222 
1223   scheduleChange(BestPosSave,
1224                  UsePushPops ? WorklistItem::InsertPushOrPop
1225                              : WorklistItem::InsertLoadOrStore,
1226                  *FIESave, CSR);
1227 
1228   for (ProgramPoint &PP : RestorePoints) {
1229     BinaryBasicBlock *FrontierBB = Info.getParentBB(PP);
1230     LLVM_DEBUG({
1231       dbgs() << "Scheduling restore insertion at: ";
1232       if (PP.isInst())
1233         PP.getInst()->dump();
1234       else
1235         dbgs() << PP.getBB()->getName() << "\n";
1236     });
1237     MCInst *Term =
1238         FrontierBB->getTerminatorBefore(PP.isInst() ? PP.getInst() : nullptr);
1239     if (Term)
1240       PP = Term;
1241     bool PrecededByPrefix = false;
1242     if (PP.isInst()) {
1243       auto Iter = FrontierBB->findInstruction(PP.getInst());
1244       if (Iter != FrontierBB->end() && Iter != FrontierBB->begin()) {
1245         --Iter;
1246         PrecededByPrefix = BC.MIB->isPrefix(*Iter);
1247       }
1248     }
1249     if (PP.isInst() &&
1250         (doesInstUsesCSR(*PP.getInst(), CSR) || PrecededByPrefix)) {
1251       assert(!InsnToBB[PP.getInst()]->hasTerminatorAfter(PP.getInst()) &&
1252              "cannot move to end of bb");
1253       scheduleChange(InsnToBB[PP.getInst()],
1254                      UsePushPops ? WorklistItem::InsertPushOrPop
1255                                  : WorklistItem::InsertLoadOrStore,
1256                      *FIELoad, CSR);
1257       continue;
1258     }
1259     scheduleChange(PP,
1260                    UsePushPops ? WorklistItem::InsertPushOrPop
1261                                : WorklistItem::InsertLoadOrStore,
1262                    *FIELoad, CSR);
1263   }
1264 }
1265 
1266 void ShrinkWrapping::moveSaveRestores() {
1267   bool DisablePushPopMode = false;
1268   bool UsedPushPopMode = false;
1269   // Keeps info about successfully moved regs: reg index, save position and
1270   // save size
1271   std::vector<std::tuple<unsigned, MCInst *, size_t>> MovedRegs;
1272   uint64_t TotalEstimatedWin = 0;
1273 
1274   computeDomOrder();
1275   for (unsigned I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
1276     MCInst *BestPosSave = nullptr;
1277     uint64_t EstimatedWin = 0;
1278     SmallVector<ProgramPoint, 4> RestorePoints;
1279     while (RestorePoints.empty() &&
1280            isBestSavePosCold(I, BestPosSave, EstimatedWin)) {
1281       RestorePoints = doRestorePlacement(BestPosSave, I, EstimatedWin);
1282       if (RestorePoints.empty()) {
1283         LLVM_DEBUG({
1284           dbgs() << "Dropping opportunity because restore placement failed"
1285                     " -- total est. freq reduc: "
1286                  << EstimatedWin << ". Will try "
1287                  << (BestSaveCount[I].size() - 1) << " more times.\n";
1288         });
1289         BestSaveCount[I].pop_back();
1290         BestSavePos[I].pop_back();
1291         computeDomOrder();
1292       }
1293     }
1294     if (RestorePoints.empty()) {
1295       SpillsFailedDynamicCount += EstimatedWin;
1296       continue;
1297     }
1298 
1299     const FrameIndexEntry *FIESave = CSA.SaveFIEByReg[I];
1300     const FrameIndexEntry *FIELoad = CSA.LoadFIEByReg[I];
1301     (void)FIELoad;
1302     assert(FIESave && FIELoad);
1303     StackPointerTracking &SPT = Info.getStackPointerTracking();
1304     const std::pair<int, int> SPFP = *SPT.getStateBefore(*BestPosSave);
1305     int SaveOffset = SPFP.first;
1306     uint8_t SaveSize = FIESave->Size;
1307 
1308     // If we don't know stack state at this point, bail
1309     if ((SPFP.first == SPT.SUPERPOSITION || SPFP.first == SPT.EMPTY) &&
1310         (SPFP.second == SPT.SUPERPOSITION || SPFP.second == SPT.EMPTY)) {
1311       SpillsFailedDynamicCount += EstimatedWin;
1312       continue;
1313     }
1314 
1315     // Operation mode: if true, will insert push/pops instead of loads/restores
1316     bool UsePushPops = validatePushPopsMode(I, BestPosSave, SaveOffset);
1317 
1318     if (UsePushPops) {
1319       SmallVector<ProgramPoint, 4> FixedRestorePoints =
1320           fixPopsPlacements(RestorePoints, SaveOffset, I);
1321       if (FixedRestorePoints.empty())
1322         UsePushPops = false;
1323       else
1324         RestorePoints = FixedRestorePoints;
1325     }
1326 
1327     // Disable push-pop mode for all CSRs in this function
1328     if (!UsePushPops)
1329       DisablePushPopMode = true;
1330     else
1331       UsedPushPopMode = true;
1332 
1333     scheduleOldSaveRestoresRemoval(I, UsePushPops);
1334     scheduleSaveRestoreInsertions(I, BestPosSave, RestorePoints, UsePushPops);
1335     MovedRegs.emplace_back(std::make_tuple(I, BestPosSave, SaveSize));
1336     TotalEstimatedWin += EstimatedWin;
1337   }
1338 
1339   // Revert push-pop mode if it failed for a single CSR
1340   if (DisablePushPopMode && UsedPushPopMode) {
1341     UsedPushPopMode = false;
1342     for (BinaryBasicBlock &BB : BF) {
1343       auto WRI = Todo.find(&BB);
1344       if (WRI != Todo.end()) {
1345         std::vector<WorklistItem> &TodoList = WRI->second;
1346         for (WorklistItem &Item : TodoList)
1347           if (Item.Action == WorklistItem::InsertPushOrPop)
1348             Item.Action = WorklistItem::InsertLoadOrStore;
1349       }
1350       for (auto I = BB.rbegin(), E = BB.rend(); I != E; ++I) {
1351         MCInst &Inst = *I;
1352         auto TodoList = BC.MIB->tryGetAnnotationAs<std::vector<WorklistItem>>(
1353             Inst, getAnnotationIndex());
1354         if (!TodoList)
1355           continue;
1356         bool isCFI = BC.MIB->isCFI(Inst);
1357         for (WorklistItem &Item : *TodoList) {
1358           if (Item.Action == WorklistItem::InsertPushOrPop)
1359             Item.Action = WorklistItem::InsertLoadOrStore;
1360           if (!isCFI && Item.Action == WorklistItem::Erase)
1361             Item.Action = WorklistItem::ChangeToAdjustment;
1362         }
1363       }
1364     }
1365   }
1366   SpillsMovedDynamicCount += TotalEstimatedWin;
1367 
1368   // Update statistics
1369   if (!UsedPushPopMode) {
1370     SpillsMovedRegularMode += MovedRegs.size();
1371     return;
1372   }
1373 
1374   // Schedule modifications to stack-accessing instructions via
1375   // StackLayoutModifier.
1376   SpillsMovedPushPopMode += MovedRegs.size();
1377   for (std::tuple<unsigned, MCInst *, size_t> &I : MovedRegs) {
1378     unsigned RegNdx;
1379     MCInst *SavePos;
1380     size_t SaveSize;
1381     std::tie(RegNdx, SavePos, SaveSize) = I;
1382     for (MCInst *Save : CSA.getSavesByReg(RegNdx))
1383       SLM.collapseRegion(Save);
1384     SLM.insertRegion(SavePos, SaveSize);
1385   }
1386 }
1387 
1388 namespace {
1389 /// Helper function to identify whether two basic blocks created by splitting
1390 /// a critical edge have the same contents.
1391 bool isIdenticalSplitEdgeBB(const BinaryContext &BC, const BinaryBasicBlock &A,
1392                             const BinaryBasicBlock &B) {
1393   if (A.succ_size() != B.succ_size())
1394     return false;
1395   if (A.succ_size() != 1)
1396     return false;
1397 
1398   if (*A.succ_begin() != *B.succ_begin())
1399     return false;
1400 
1401   if (A.size() != B.size())
1402     return false;
1403 
1404   // Compare instructions
1405   auto I = A.begin(), E = A.end();
1406   auto OtherI = B.begin(), OtherE = B.end();
1407   while (I != E && OtherI != OtherE) {
1408     if (I->getOpcode() != OtherI->getOpcode())
1409       return false;
1410     if (!BC.MIB->equals(*I, *OtherI, [](const MCSymbol *A, const MCSymbol *B) {
1411           return true;
1412         }))
1413       return false;
1414     ++I;
1415     ++OtherI;
1416   }
1417   return true;
1418 }
1419 } // namespace
1420 
1421 bool ShrinkWrapping::foldIdenticalSplitEdges() {
1422   bool Changed = false;
1423   for (auto Iter = BF.begin(); Iter != BF.end(); ++Iter) {
1424     BinaryBasicBlock &BB = *Iter;
1425     if (!BB.getName().startswith(".LSplitEdge"))
1426       continue;
1427     for (auto RIter = BF.rbegin(); RIter != BF.rend(); ++RIter) {
1428       BinaryBasicBlock &RBB = *RIter;
1429       if (&RBB == &BB)
1430         break;
1431       if (!RBB.getName().startswith(".LSplitEdge") || !RBB.isValid() ||
1432           !isIdenticalSplitEdgeBB(BC, *Iter, RBB))
1433         continue;
1434       assert(RBB.pred_size() == 1 && "Invalid split edge BB");
1435       BinaryBasicBlock *Pred = *RBB.pred_begin();
1436       uint64_t OrigCount = Pred->branch_info_begin()->Count;
1437       uint64_t OrigMispreds = Pred->branch_info_begin()->MispredictedCount;
1438       BF.replaceJumpTableEntryIn(Pred, &RBB, &BB);
1439       Pred->replaceSuccessor(&RBB, &BB, OrigCount, OrigMispreds);
1440       Changed = true;
1441       // Remove the block from CFG
1442       RBB.markValid(false);
1443     }
1444   }
1445 
1446   return Changed;
1447 }
1448 
1449 namespace {
1450 
1451 // A special StackPointerTracking that compensates for our future plans
1452 // in removing/adding insn.
1453 class PredictiveStackPointerTracking
1454     : public StackPointerTrackingBase<PredictiveStackPointerTracking> {
1455   friend class DataflowAnalysis<PredictiveStackPointerTracking,
1456                                 std::pair<int, int>>;
1457   decltype(ShrinkWrapping::Todo) &TodoMap;
1458   DataflowInfoManager &Info;
1459 
1460   Optional<unsigned> AnnotationIndex;
1461 
1462 protected:
1463   void compNextAux(const MCInst &Point,
1464                    const std::vector<ShrinkWrapping::WorklistItem> &TodoItems,
1465                    std::pair<int, int> &Res) {
1466     for (const ShrinkWrapping::WorklistItem &Item : TodoItems) {
1467       if (Item.Action == ShrinkWrapping::WorklistItem::Erase &&
1468           BC.MIB->isPush(Point)) {
1469         Res.first += BC.MIB->getPushSize(Point);
1470         continue;
1471       }
1472       if (Item.Action == ShrinkWrapping::WorklistItem::Erase &&
1473           BC.MIB->isPop(Point)) {
1474         Res.first -= BC.MIB->getPopSize(Point);
1475         continue;
1476       }
1477       if (Item.Action == ShrinkWrapping::WorklistItem::InsertPushOrPop &&
1478           Item.FIEToInsert.IsStore) {
1479         Res.first -= Item.FIEToInsert.Size;
1480         continue;
1481       }
1482       if (Item.Action == ShrinkWrapping::WorklistItem::InsertPushOrPop &&
1483           Item.FIEToInsert.IsLoad) {
1484         Res.first += Item.FIEToInsert.Size;
1485         continue;
1486       }
1487     }
1488   }
1489 
1490   std::pair<int, int> computeNext(const MCInst &Point,
1491                                   const std::pair<int, int> &Cur) {
1492     std::pair<int, int> Res =
1493         StackPointerTrackingBase<PredictiveStackPointerTracking>::computeNext(
1494             Point, Cur);
1495     if (Res.first == StackPointerTracking::SUPERPOSITION ||
1496         Res.first == StackPointerTracking::EMPTY)
1497       return Res;
1498     auto TodoItems =
1499         BC.MIB->tryGetAnnotationAs<std::vector<ShrinkWrapping::WorklistItem>>(
1500             Point, ShrinkWrapping::getAnnotationName());
1501     if (TodoItems)
1502       compNextAux(Point, *TodoItems, Res);
1503     auto &InsnToBBMap = Info.getInsnToBBMap();
1504     if (&*InsnToBBMap[&Point]->rbegin() != &Point)
1505       return Res;
1506     auto WRI = TodoMap.find(InsnToBBMap[&Point]);
1507     if (WRI == TodoMap.end())
1508       return Res;
1509     compNextAux(Point, WRI->second, Res);
1510     return Res;
1511   }
1512 
1513   StringRef getAnnotationName() const {
1514     return StringRef("PredictiveStackPointerTracking");
1515   }
1516 
1517 public:
1518   PredictiveStackPointerTracking(BinaryFunction &BF,
1519                                  decltype(ShrinkWrapping::Todo) &TodoMap,
1520                                  DataflowInfoManager &Info,
1521                                  MCPlusBuilder::AllocatorIdTy AllocatorId = 0)
1522       : StackPointerTrackingBase<PredictiveStackPointerTracking>(BF,
1523                                                                  AllocatorId),
1524         TodoMap(TodoMap), Info(Info) {}
1525 
1526   void run() {
1527     StackPointerTrackingBase<PredictiveStackPointerTracking>::run();
1528   }
1529 };
1530 
1531 } // end anonymous namespace
1532 
1533 void ShrinkWrapping::insertUpdatedCFI(unsigned CSR, int SPValPush,
1534                                       int SPValPop) {
1535   MCInst *SavePoint = nullptr;
1536   for (BinaryBasicBlock &BB : BF) {
1537     for (auto InstIter = BB.rbegin(), EndIter = BB.rend(); InstIter != EndIter;
1538          ++InstIter) {
1539       int32_t SrcImm = 0;
1540       MCPhysReg Reg = 0;
1541       MCPhysReg StackPtrReg = 0;
1542       int64_t StackOffset = 0;
1543       bool IsIndexed = false;
1544       bool IsLoad = false;
1545       bool IsStore = false;
1546       bool IsSimple = false;
1547       bool IsStoreFromReg = false;
1548       uint8_t Size = 0;
1549       if (!BC.MIB->isStackAccess(*InstIter, IsLoad, IsStore, IsStoreFromReg,
1550                                  Reg, SrcImm, StackPtrReg, StackOffset, Size,
1551                                  IsSimple, IsIndexed))
1552         continue;
1553       if (Reg != CSR || !IsStore || !IsSimple)
1554         continue;
1555       SavePoint = &*InstIter;
1556       break;
1557     }
1558     if (SavePoint)
1559       break;
1560   }
1561   assert(SavePoint);
1562   LLVM_DEBUG({
1563     dbgs() << "Now using as save point for reg " << CSR << " :";
1564     SavePoint->dump();
1565   });
1566   bool PrevAffectedZone = false;
1567   BinaryBasicBlock *PrevBB = nullptr;
1568   DominatorAnalysis<false> &DA = Info.getDominatorAnalysis();
1569   for (BinaryBasicBlock *BB : BF.layout()) {
1570     if (BB->size() == 0)
1571       continue;
1572     const bool InAffectedZoneAtEnd = DA.count(*BB->rbegin(), *SavePoint);
1573     const bool InAffectedZoneAtBegin =
1574         (*DA.getStateBefore(*BB->begin()))[DA.ExprToIdx[SavePoint]];
1575     bool InAffectedZone = InAffectedZoneAtBegin;
1576     for (auto InstIter = BB->begin(); InstIter != BB->end(); ++InstIter) {
1577       const bool CurZone = DA.count(*InstIter, *SavePoint);
1578       if (InAffectedZone != CurZone) {
1579         auto InsertionIter = InstIter;
1580         ++InsertionIter;
1581         InAffectedZone = CurZone;
1582         if (InAffectedZone)
1583           InstIter = insertCFIsForPushOrPop(*BB, InsertionIter, CSR, true, 0,
1584                                             SPValPop);
1585         else
1586           InstIter = insertCFIsForPushOrPop(*BB, InsertionIter, CSR, false, 0,
1587                                             SPValPush);
1588         --InstIter;
1589       }
1590     }
1591     // Are we at the first basic block or hot-cold split point?
1592     if (!PrevBB || (BF.isSplit() && BB->isCold() != PrevBB->isCold())) {
1593       if (InAffectedZoneAtBegin)
1594         insertCFIsForPushOrPop(*BB, BB->begin(), CSR, true, 0, SPValPush);
1595     } else if (InAffectedZoneAtBegin != PrevAffectedZone) {
1596       if (InAffectedZoneAtBegin)
1597         insertCFIsForPushOrPop(*PrevBB, PrevBB->end(), CSR, true, 0, SPValPush);
1598       else
1599         insertCFIsForPushOrPop(*PrevBB, PrevBB->end(), CSR, false, 0, SPValPop);
1600     }
1601     PrevAffectedZone = InAffectedZoneAtEnd;
1602     PrevBB = BB;
1603   }
1604 }
1605 
1606 void ShrinkWrapping::rebuildCFIForSP() {
1607   for (BinaryBasicBlock &BB : BF) {
1608     for (MCInst &Inst : BB) {
1609       if (!BC.MIB->isCFI(Inst))
1610         continue;
1611       const MCCFIInstruction *CFI = BF.getCFIFor(Inst);
1612       if (CFI->getOperation() == MCCFIInstruction::OpDefCfaOffset)
1613         BC.MIB->addAnnotation(Inst, "DeleteMe", 0U, AllocatorId);
1614     }
1615   }
1616 
1617   int PrevSPVal = -8;
1618   BinaryBasicBlock *PrevBB = nullptr;
1619   StackPointerTracking &SPT = Info.getStackPointerTracking();
1620   for (BinaryBasicBlock *BB : BF.layout()) {
1621     if (BB->size() == 0)
1622       continue;
1623     const int SPValAtEnd = SPT.getStateAt(*BB->rbegin())->first;
1624     const int SPValAtBegin = SPT.getStateBefore(*BB->begin())->first;
1625     int SPVal = SPValAtBegin;
1626     for (auto Iter = BB->begin(); Iter != BB->end(); ++Iter) {
1627       const int CurVal = SPT.getStateAt(*Iter)->first;
1628       if (SPVal != CurVal) {
1629         auto InsertionIter = Iter;
1630         ++InsertionIter;
1631         Iter = BF.addCFIInstruction(
1632             BB, InsertionIter,
1633             MCCFIInstruction::cfiDefCfaOffset(nullptr, -CurVal));
1634         SPVal = CurVal;
1635       }
1636     }
1637     if (BF.isSplit() && PrevBB && BB->isCold() != PrevBB->isCold())
1638       BF.addCFIInstruction(
1639           BB, BB->begin(),
1640           MCCFIInstruction::cfiDefCfaOffset(nullptr, -SPValAtBegin));
1641     else if (SPValAtBegin != PrevSPVal)
1642       BF.addCFIInstruction(
1643           PrevBB, PrevBB->end(),
1644           MCCFIInstruction::cfiDefCfaOffset(nullptr, -SPValAtBegin));
1645     PrevSPVal = SPValAtEnd;
1646     PrevBB = BB;
1647   }
1648 
1649   for (BinaryBasicBlock &BB : BF)
1650     for (auto I = BB.begin(); I != BB.end();)
1651       if (BC.MIB->hasAnnotation(*I, "DeleteMe"))
1652         I = BB.eraseInstruction(I);
1653       else
1654         ++I;
1655 }
1656 
1657 MCInst ShrinkWrapping::createStackAccess(int SPVal, int FPVal,
1658                                          const FrameIndexEntry &FIE,
1659                                          bool CreatePushOrPop) {
1660   MCInst NewInst;
1661   if (SPVal != StackPointerTracking::SUPERPOSITION &&
1662       SPVal != StackPointerTracking::EMPTY) {
1663     if (FIE.IsLoad) {
1664       if (!BC.MIB->createRestoreFromStack(NewInst, BC.MIB->getStackPointer(),
1665                                           FIE.StackOffset - SPVal, FIE.RegOrImm,
1666                                           FIE.Size)) {
1667         errs() << "createRestoreFromStack: not supported on this platform\n";
1668         abort();
1669       }
1670     } else {
1671       if (!BC.MIB->createSaveToStack(NewInst, BC.MIB->getStackPointer(),
1672                                      FIE.StackOffset - SPVal, FIE.RegOrImm,
1673                                      FIE.Size)) {
1674         errs() << "createSaveToStack: not supported on this platform\n";
1675         abort();
1676       }
1677     }
1678     if (CreatePushOrPop)
1679       BC.MIB->changeToPushOrPop(NewInst);
1680     return NewInst;
1681   }
1682   assert(FPVal != StackPointerTracking::SUPERPOSITION &&
1683          FPVal != StackPointerTracking::EMPTY);
1684 
1685   if (FIE.IsLoad) {
1686     if (!BC.MIB->createRestoreFromStack(NewInst, BC.MIB->getFramePointer(),
1687                                         FIE.StackOffset - FPVal, FIE.RegOrImm,
1688                                         FIE.Size)) {
1689       errs() << "createRestoreFromStack: not supported on this platform\n";
1690       abort();
1691     }
1692   } else {
1693     if (!BC.MIB->createSaveToStack(NewInst, BC.MIB->getFramePointer(),
1694                                    FIE.StackOffset - FPVal, FIE.RegOrImm,
1695                                    FIE.Size)) {
1696       errs() << "createSaveToStack: not supported on this platform\n";
1697       abort();
1698     }
1699   }
1700   return NewInst;
1701 }
1702 
1703 void ShrinkWrapping::updateCFIInstOffset(MCInst &Inst, int64_t NewOffset) {
1704   const MCCFIInstruction *CFI = BF.getCFIFor(Inst);
1705   if (UpdatedCFIs.count(CFI))
1706     return;
1707 
1708   switch (CFI->getOperation()) {
1709   case MCCFIInstruction::OpDefCfa:
1710   case MCCFIInstruction::OpDefCfaRegister:
1711   case MCCFIInstruction::OpDefCfaOffset:
1712     CFI = BF.mutateCFIOffsetFor(Inst, -NewOffset);
1713     break;
1714   case MCCFIInstruction::OpOffset:
1715   default:
1716     break;
1717   }
1718 
1719   UpdatedCFIs.insert(CFI);
1720 }
1721 
1722 BBIterTy ShrinkWrapping::insertCFIsForPushOrPop(BinaryBasicBlock &BB,
1723                                                 BBIterTy Pos, unsigned Reg,
1724                                                 bool isPush, int Sz,
1725                                                 int64_t NewOffset) {
1726   if (isPush) {
1727     for (uint32_t Idx : DeletedPushCFIs[Reg]) {
1728       Pos = BF.addCFIPseudo(&BB, Pos, Idx);
1729       updateCFIInstOffset(*Pos++, NewOffset);
1730     }
1731     if (HasDeletedOffsetCFIs[Reg]) {
1732       Pos = BF.addCFIInstruction(
1733           &BB, Pos,
1734           MCCFIInstruction::createOffset(
1735               nullptr, BC.MRI->getDwarfRegNum(Reg, false), NewOffset));
1736       ++Pos;
1737     }
1738   } else {
1739     for (uint32_t Idx : DeletedPopCFIs[Reg]) {
1740       Pos = BF.addCFIPseudo(&BB, Pos, Idx);
1741       updateCFIInstOffset(*Pos++, NewOffset);
1742     }
1743     if (HasDeletedOffsetCFIs[Reg]) {
1744       Pos = BF.addCFIInstruction(
1745           &BB, Pos,
1746           MCCFIInstruction::createSameValue(
1747               nullptr, BC.MRI->getDwarfRegNum(Reg, false)));
1748       ++Pos;
1749     }
1750   }
1751   return Pos;
1752 }
1753 
1754 BBIterTy ShrinkWrapping::processInsertion(BBIterTy InsertionPoint,
1755                                           BinaryBasicBlock *CurBB,
1756                                           const WorklistItem &Item,
1757                                           int64_t SPVal, int64_t FPVal) {
1758   // Trigger CFI reconstruction for this CSR if necessary - writing to
1759   // PushOffsetByReg/PopOffsetByReg *will* trigger CFI update
1760   if ((Item.FIEToInsert.IsStore &&
1761        !DeletedPushCFIs[Item.AffectedReg].empty()) ||
1762       (Item.FIEToInsert.IsLoad && !DeletedPopCFIs[Item.AffectedReg].empty()) ||
1763       HasDeletedOffsetCFIs[Item.AffectedReg]) {
1764     if (Item.Action == WorklistItem::InsertPushOrPop) {
1765       if (Item.FIEToInsert.IsStore)
1766         PushOffsetByReg[Item.AffectedReg] = SPVal - Item.FIEToInsert.Size;
1767       else
1768         PopOffsetByReg[Item.AffectedReg] = SPVal;
1769     } else {
1770       if (Item.FIEToInsert.IsStore)
1771         PushOffsetByReg[Item.AffectedReg] = Item.FIEToInsert.StackOffset;
1772       else
1773         PopOffsetByReg[Item.AffectedReg] = Item.FIEToInsert.StackOffset;
1774     }
1775   }
1776 
1777   LLVM_DEBUG({
1778     dbgs() << "Creating stack access with SPVal = " << SPVal
1779            << "; stack offset = " << Item.FIEToInsert.StackOffset
1780            << " Is push = " << (Item.Action == WorklistItem::InsertPushOrPop)
1781            << "\n";
1782   });
1783   MCInst NewInst =
1784       createStackAccess(SPVal, FPVal, Item.FIEToInsert,
1785                         Item.Action == WorklistItem::InsertPushOrPop);
1786   if (InsertionPoint != CurBB->end()) {
1787     LLVM_DEBUG({
1788       dbgs() << "Adding before Inst: ";
1789       InsertionPoint->dump();
1790       dbgs() << "the following inst: ";
1791       NewInst.dump();
1792     });
1793     BBIterTy Iter =
1794         CurBB->insertInstruction(InsertionPoint, std::move(NewInst));
1795     return ++Iter;
1796   }
1797   CurBB->addInstruction(std::move(NewInst));
1798   LLVM_DEBUG(dbgs() << "Adding to BB!\n");
1799   return CurBB->end();
1800 }
1801 
1802 BBIterTy ShrinkWrapping::processInsertionsList(
1803     BBIterTy InsertionPoint, BinaryBasicBlock *CurBB,
1804     std::vector<WorklistItem> &TodoList, int64_t SPVal, int64_t FPVal) {
1805   bool HasInsertions = false;
1806   for (WorklistItem &Item : TodoList) {
1807     if (Item.Action == WorklistItem::Erase ||
1808         Item.Action == WorklistItem::ChangeToAdjustment)
1809       continue;
1810     HasInsertions = true;
1811     break;
1812   }
1813 
1814   if (!HasInsertions)
1815     return InsertionPoint;
1816 
1817   assert(((SPVal != StackPointerTracking::SUPERPOSITION &&
1818            SPVal != StackPointerTracking::EMPTY) ||
1819           (FPVal != StackPointerTracking::SUPERPOSITION &&
1820            FPVal != StackPointerTracking::EMPTY)) &&
1821          "Cannot insert if we have no idea of the stack state here");
1822 
1823   // Revert the effect of PSPT for this location, we want SP Value before
1824   // insertions
1825   if (InsertionPoint == CurBB->end()) {
1826     for (WorklistItem &Item : TodoList) {
1827       if (Item.Action != WorklistItem::InsertPushOrPop)
1828         continue;
1829       if (Item.FIEToInsert.IsStore)
1830         SPVal += Item.FIEToInsert.Size;
1831       if (Item.FIEToInsert.IsLoad)
1832         SPVal -= Item.FIEToInsert.Size;
1833     }
1834   }
1835 
1836   // Reorder POPs to obey the correct dominance relation between them
1837   llvm::stable_sort(TodoList, [&](const WorklistItem &A,
1838                                   const WorklistItem &B) {
1839     if ((A.Action != WorklistItem::InsertPushOrPop || !A.FIEToInsert.IsLoad) &&
1840         (B.Action != WorklistItem::InsertPushOrPop || !B.FIEToInsert.IsLoad))
1841       return false;
1842     if ((A.Action != WorklistItem::InsertPushOrPop || !A.FIEToInsert.IsLoad))
1843       return true;
1844     if ((B.Action != WorklistItem::InsertPushOrPop || !B.FIEToInsert.IsLoad))
1845       return false;
1846     return DomOrder[B.AffectedReg] < DomOrder[A.AffectedReg];
1847   });
1848 
1849   // Process insertions
1850   for (WorklistItem &Item : TodoList) {
1851     if (Item.Action == WorklistItem::Erase ||
1852         Item.Action == WorklistItem::ChangeToAdjustment)
1853       continue;
1854 
1855     InsertionPoint =
1856         processInsertion(InsertionPoint, CurBB, Item, SPVal, FPVal);
1857     if (Item.Action == WorklistItem::InsertPushOrPop &&
1858         Item.FIEToInsert.IsStore)
1859       SPVal -= Item.FIEToInsert.Size;
1860     if (Item.Action == WorklistItem::InsertPushOrPop &&
1861         Item.FIEToInsert.IsLoad)
1862       SPVal += Item.FIEToInsert.Size;
1863   }
1864   return InsertionPoint;
1865 }
1866 
1867 bool ShrinkWrapping::processInsertions() {
1868   PredictiveStackPointerTracking PSPT(BF, Todo, Info, AllocatorId);
1869   PSPT.run();
1870 
1871   bool Changes = false;
1872   for (BinaryBasicBlock &BB : BF) {
1873     // Process insertions before some inst.
1874     for (auto I = BB.begin(); I != BB.end(); ++I) {
1875       MCInst &Inst = *I;
1876       auto TodoList = BC.MIB->tryGetAnnotationAs<std::vector<WorklistItem>>(
1877           Inst, getAnnotationIndex());
1878       if (!TodoList)
1879         continue;
1880       Changes = true;
1881       std::vector<WorklistItem> List = *TodoList;
1882       LLVM_DEBUG({
1883         dbgs() << "Now processing insertions in " << BB.getName()
1884                << " before inst: ";
1885         Inst.dump();
1886       });
1887       auto Iter = I;
1888       std::pair<int, int> SPTState =
1889           *PSPT.getStateAt(Iter == BB.begin() ? (ProgramPoint)&BB : &*(--Iter));
1890       I = processInsertionsList(I, &BB, List, SPTState.first, SPTState.second);
1891     }
1892     // Process insertions at the end of bb
1893     auto WRI = Todo.find(&BB);
1894     if (WRI != Todo.end()) {
1895       std::pair<int, int> SPTState = *PSPT.getStateAt(*BB.rbegin());
1896       processInsertionsList(BB.end(), &BB, WRI->second, SPTState.first,
1897                             SPTState.second);
1898       Changes = true;
1899     }
1900   }
1901   return Changes;
1902 }
1903 
1904 void ShrinkWrapping::processDeletions() {
1905   LivenessAnalysis &LA = Info.getLivenessAnalysis();
1906   for (BinaryBasicBlock &BB : BF) {
1907     for (auto II = BB.begin(); II != BB.end(); ++II) {
1908       MCInst &Inst = *II;
1909       auto TodoList = BC.MIB->tryGetAnnotationAs<std::vector<WorklistItem>>(
1910           Inst, getAnnotationIndex());
1911       if (!TodoList)
1912         continue;
1913       // Process all deletions
1914       for (WorklistItem &Item : *TodoList) {
1915         if (Item.Action != WorklistItem::Erase &&
1916             Item.Action != WorklistItem::ChangeToAdjustment)
1917           continue;
1918 
1919         if (Item.Action == WorklistItem::ChangeToAdjustment) {
1920           // Is flag reg alive across this func?
1921           bool DontClobberFlags = LA.isAlive(&Inst, BC.MIB->getFlagsReg());
1922           if (int Sz = BC.MIB->getPushSize(Inst)) {
1923             BC.MIB->createStackPointerIncrement(Inst, Sz, DontClobberFlags);
1924             continue;
1925           }
1926           if (int Sz = BC.MIB->getPopSize(Inst)) {
1927             BC.MIB->createStackPointerDecrement(Inst, Sz, DontClobberFlags);
1928             continue;
1929           }
1930         }
1931 
1932         LLVM_DEBUG({
1933           dbgs() << "Erasing: ";
1934           BC.printInstruction(dbgs(), Inst);
1935         });
1936         II = std::prev(BB.eraseInstruction(II));
1937         break;
1938       }
1939     }
1940   }
1941 }
1942 
1943 void ShrinkWrapping::rebuildCFI() {
1944   const bool FP = Info.getStackPointerTracking().HasFramePointer;
1945   Info.invalidateAll();
1946   if (!FP) {
1947     rebuildCFIForSP();
1948     Info.invalidateAll();
1949   }
1950   for (unsigned I = 0, E = BC.MRI->getNumRegs(); I != E; ++I) {
1951     if (PushOffsetByReg[I] == 0 || PopOffsetByReg[I] == 0)
1952       continue;
1953     const int64_t SPValPush = PushOffsetByReg[I];
1954     const int64_t SPValPop = PopOffsetByReg[I];
1955     insertUpdatedCFI(I, SPValPush, SPValPop);
1956     Info.invalidateAll();
1957   }
1958 }
1959 
1960 bool ShrinkWrapping::perform(bool HotOnly) {
1961   HasDeletedOffsetCFIs = BitVector(BC.MRI->getNumRegs(), false);
1962   PushOffsetByReg = std::vector<int64_t>(BC.MRI->getNumRegs(), 0LL);
1963   PopOffsetByReg = std::vector<int64_t>(BC.MRI->getNumRegs(), 0LL);
1964 
1965   // Update pass statistics
1966   uint64_t TotalInstrs = 0ULL;
1967   uint64_t TotalStoreInstrs = 0ULL;
1968   for (BinaryBasicBlock *BB : BF.layout()) {
1969     uint64_t BBExecCount = BB->getExecutionCount();
1970     if (!BBExecCount || BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
1971       continue;
1972     for (const auto &Instr : *BB) {
1973       if (BC.MIB->isPseudo(Instr))
1974         continue;
1975       if (BC.MIB->isStore(Instr))
1976         TotalStoreInstrs += BBExecCount;
1977       TotalInstrs += BBExecCount;
1978     }
1979   }
1980   InstrDynamicCount += TotalInstrs;
1981   StoreDynamicCount += TotalStoreInstrs;
1982 
1983   if (!FA.hasFrameInfo(BF))
1984     return false;
1985 
1986   if (HotOnly && (BF.getKnownExecutionCount() < BC.getHotThreshold()))
1987     return false;
1988 
1989   if (opts::EqualizeBBCounts)
1990     equalizeBBCounts(Info, BF);
1991 
1992   if (BF.checkForAmbiguousJumpTables()) {
1993     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ambiguous JTs in " << BF.getPrintName()
1994                       << ".\n");
1995     // We could call disambiguateJumpTables here, but it is probably not worth
1996     // the cost (of duplicating potentially large jump tables that could regress
1997     // dcache misses). Moreover, ambiguous JTs are rare and coming from code
1998     // written in assembly language. Just bail.
1999     return false;
2000   }
2001   SLM.initialize();
2002   CSA.compute();
2003   classifyCSRUses();
2004   pruneUnwantedCSRs();
2005   computeSaveLocations();
2006   moveSaveRestores();
2007   LLVM_DEBUG({
2008     dbgs() << "Func before shrink-wrapping: \n";
2009     BF.dump();
2010   });
2011   SLM.performChanges();
2012   // Early exit if processInsertions doesn't detect any todo items
2013   if (!processInsertions())
2014     return false;
2015   processDeletions();
2016   if (foldIdenticalSplitEdges()) {
2017     const std::pair<unsigned, uint64_t> Stats = BF.eraseInvalidBBs();
2018     (void)Stats;
2019     LLVM_DEBUG(dbgs() << "Deleted " << Stats.first
2020                       << " redundant split edge BBs (" << Stats.second
2021                       << " bytes) for " << BF.getPrintName() << "\n");
2022   }
2023   rebuildCFI();
2024   // We may have split edges, creating BBs that need correct branching
2025   BF.fixBranches();
2026   LLVM_DEBUG({
2027     dbgs() << "Func after shrink-wrapping: \n";
2028     BF.dump();
2029   });
2030   return true;
2031 }
2032 
2033 void ShrinkWrapping::printStats() {
2034   outs() << "BOLT-INFO: Shrink wrapping moved " << SpillsMovedRegularMode
2035          << " spills inserting load/stores and " << SpillsMovedPushPopMode
2036          << " spills inserting push/pops\n";
2037   if (!InstrDynamicCount || !StoreDynamicCount)
2038     return;
2039   outs() << "BOLT-INFO: Shrink wrapping reduced " << SpillsMovedDynamicCount
2040          << " store executions ("
2041          << format("%.1lf%%",
2042                    (100.0 * SpillsMovedDynamicCount / InstrDynamicCount))
2043          << " total instructions executed, "
2044          << format("%.1lf%%",
2045                    (100.0 * SpillsMovedDynamicCount / StoreDynamicCount))
2046          << " store instructions)\n";
2047   outs() << "BOLT-INFO: Shrink wrapping failed at reducing "
2048          << SpillsFailedDynamicCount << " store executions ("
2049          << format("%.1lf%%",
2050                    (100.0 * SpillsFailedDynamicCount / InstrDynamicCount))
2051          << " total instructions executed, "
2052          << format("%.1lf%%",
2053                    (100.0 * SpillsFailedDynamicCount / StoreDynamicCount))
2054          << " store instructions)\n";
2055 }
2056 
2057 // Operators necessary as a result of using MCAnnotation
2058 raw_ostream &operator<<(raw_ostream &OS,
2059                         const std::vector<ShrinkWrapping::WorklistItem> &Vec) {
2060   OS << "SWTodo[";
2061   const char *Sep = "";
2062   for (const ShrinkWrapping::WorklistItem &Item : Vec) {
2063     OS << Sep;
2064     switch (Item.Action) {
2065     case ShrinkWrapping::WorklistItem::Erase:
2066       OS << "Erase";
2067       break;
2068     case ShrinkWrapping::WorklistItem::ChangeToAdjustment:
2069       OS << "ChangeToAdjustment";
2070       break;
2071     case ShrinkWrapping::WorklistItem::InsertLoadOrStore:
2072       OS << "InsertLoadOrStore";
2073       break;
2074     case ShrinkWrapping::WorklistItem::InsertPushOrPop:
2075       OS << "InsertPushOrPop";
2076       break;
2077     }
2078     Sep = ", ";
2079   }
2080   OS << "]";
2081   return OS;
2082 }
2083 
2084 raw_ostream &
2085 operator<<(raw_ostream &OS,
2086            const std::vector<StackLayoutModifier::WorklistItem> &Vec) {
2087   OS << "SLMTodo[";
2088   const char *Sep = "";
2089   for (const StackLayoutModifier::WorklistItem &Item : Vec) {
2090     OS << Sep;
2091     switch (Item.Action) {
2092     case StackLayoutModifier::WorklistItem::None:
2093       OS << "None";
2094       break;
2095     case StackLayoutModifier::WorklistItem::AdjustLoadStoreOffset:
2096       OS << "AdjustLoadStoreOffset";
2097       break;
2098     case StackLayoutModifier::WorklistItem::AdjustCFI:
2099       OS << "AdjustCFI";
2100       break;
2101     }
2102     Sep = ", ";
2103   }
2104   OS << "]";
2105   return OS;
2106 }
2107 
2108 bool operator==(const ShrinkWrapping::WorklistItem &A,
2109                 const ShrinkWrapping::WorklistItem &B) {
2110   return (A.Action == B.Action && A.AffectedReg == B.AffectedReg &&
2111           A.Adjustment == B.Adjustment &&
2112           A.FIEToInsert.IsLoad == B.FIEToInsert.IsLoad &&
2113           A.FIEToInsert.IsStore == B.FIEToInsert.IsStore &&
2114           A.FIEToInsert.RegOrImm == B.FIEToInsert.RegOrImm &&
2115           A.FIEToInsert.Size == B.FIEToInsert.Size &&
2116           A.FIEToInsert.IsSimple == B.FIEToInsert.IsSimple &&
2117           A.FIEToInsert.StackOffset == B.FIEToInsert.StackOffset);
2118 }
2119 
2120 bool operator==(const StackLayoutModifier::WorklistItem &A,
2121                 const StackLayoutModifier::WorklistItem &B) {
2122   return (A.Action == B.Action && A.OffsetUpdate == B.OffsetUpdate);
2123 }
2124 
2125 } // end namespace bolt
2126 } // end namespace llvm
2127