LCOV - code coverage report
Current view: top level - lib/CodeGen - DFAPacketizer.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 118 123 95.9 %
Date: 2018-02-21 17:27:13 Functions: 20 23 87.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : // This class implements a deterministic finite automaton (DFA) based
      10             : // packetizing mechanism for VLIW architectures. It provides APIs to
      11             : // determine whether there exists a legal mapping of instructions to
      12             : // functional unit assignments in a packet. The DFA is auto-generated from
      13             : // the target's Schedule.td file.
      14             : //
      15             : // A DFA consists of 3 major elements: states, inputs, and transitions. For
      16             : // the packetizing mechanism, the input is the set of instruction classes for
      17             : // a target. The state models all possible combinations of functional unit
      18             : // consumption for a given set of instructions in a packet. A transition
      19             : // models the addition of an instruction to a packet. In the DFA constructed
      20             : // by this class, if an instruction can be added to a packet, then a valid
      21             : // transition exists from the corresponding state. Invalid transitions
      22             : // indicate that the instruction cannot be added to the current packet.
      23             : //
      24             : //===----------------------------------------------------------------------===//
      25             : 
      26             : #include "llvm/CodeGen/DFAPacketizer.h"
      27             : #include "llvm/CodeGen/MachineFunction.h"
      28             : #include "llvm/CodeGen/MachineInstr.h"
      29             : #include "llvm/CodeGen/MachineInstrBundle.h"
      30             : #include "llvm/CodeGen/ScheduleDAG.h"
      31             : #include "llvm/CodeGen/ScheduleDAGInstrs.h"
      32             : #include "llvm/CodeGen/TargetInstrInfo.h"
      33             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      34             : #include "llvm/MC/MCInstrDesc.h"
      35             : #include "llvm/MC/MCInstrItineraries.h"
      36             : #include "llvm/Support/CommandLine.h"
      37             : #include "llvm/Support/Debug.h"
      38             : #include "llvm/Support/raw_ostream.h"
      39             : #include <algorithm>
      40             : #include <cassert>
      41             : #include <iterator>
      42             : #include <memory>
      43             : #include <vector>
      44             : 
      45             : using namespace llvm;
      46             : 
      47             : #define DEBUG_TYPE "packets"
      48             : 
      49       97193 : static cl::opt<unsigned> InstrLimit("dfa-instr-limit", cl::Hidden,
      50       97193 :   cl::init(0), cl::desc("If present, stops packetizing after N instructions"));
      51             : 
      52             : static unsigned InstrCount = 0;
      53             : 
      54             : // --------------------------------------------------------------------
      55             : // Definitions shared between DFAPacketizer.cpp and DFAPacketizerEmitter.cpp
      56             : 
      57             : static DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) {
      58      313753 :   return (Inp << DFA_MAX_RESOURCES) | FuncUnits;
      59             : }
      60             : 
      61             : /// Return the DFAInput for an instruction class input vector.
      62             : /// This function is used in both DFAPacketizer.cpp and in
      63             : /// DFAPacketizerEmitter.cpp.
      64             : static DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) {
      65             :   DFAInput InsnInput = 0;
      66             :   assert((InsnClass.size() <= DFA_MAX_RESTERMS) &&
      67             :          "Exceeded maximum number of DFA terms");
      68           0 :   for (auto U : InsnClass)
      69             :     InsnInput = addDFAFuncUnits(InsnInput, U);
      70             :   return InsnInput;
      71             : }
      72             : 
      73             : // --------------------------------------------------------------------
      74             : 
      75       11313 : DFAPacketizer::DFAPacketizer(const InstrItineraryData *I,
      76             :                              const DFAStateInput (*SIT)[2],
      77       11313 :                              const unsigned *SET):
      78       11313 :   InstrItins(I), DFAStateInputTable(SIT), DFAStateEntryTable(SET) {
      79             :   // Make sure DFA types are large enough for the number of terms & resources.
      80             :   static_assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <=
      81             :                     (8 * sizeof(DFAInput)),
      82             :                 "(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput");
      83             :   static_assert(
      84             :       (DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput)),
      85             :       "(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput");
      86       11313 : }
      87             : 
      88             : // Read the DFA transition table and update CachedTable.
      89             : //
      90             : // Format of the transition tables:
      91             : // DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid
      92             : //                           transitions
      93             : // DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable
      94             : //                         for the ith state
      95             : //
      96      258172 : void DFAPacketizer::ReadTable(unsigned int state) {
      97      258172 :   unsigned ThisState = DFAStateEntryTable[state];
      98      258172 :   unsigned NextStateInTable = DFAStateEntryTable[state+1];
      99             :   // Early exit in case CachedTable has already contains this
     100             :   // state's transitions.
     101      490418 :   if (CachedTable.count(UnsignPair(state, DFAStateInputTable[ThisState][0])))
     102             :     return;
     103             : 
     104     1101176 :   for (unsigned i = ThisState; i < NextStateInTable; i++)
     105      537625 :     CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =
     106      537625 :       DFAStateInputTable[i][1];
     107             : }
     108             : 
     109             : // Return the DFAInput for an instruction class.
     110      258172 : DFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {
     111             :   // Note: this logic must match that in DFAPacketizerDefs.h for input vectors.
     112             :   DFAInput InsnInput = 0;
     113             :   unsigned i = 0;
     114             :   (void)i;
     115      571925 :   for (const InstrStage *IS = InstrItins->beginStage(InsnClass),
     116      571925 :        *IE = InstrItins->endStage(InsnClass); IS != IE; ++IS) {
     117      313753 :     InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());
     118             :     assert((i++ < DFA_MAX_RESTERMS) && "Exceeded maximum number of DFA inputs");
     119             :   }
     120      258172 :   return InsnInput;
     121             : }
     122             : 
     123             : // Return the DFAInput for an instruction class input vector.
     124           0 : DFAInput DFAPacketizer::getInsnInput(const std::vector<unsigned> &InsnClass) {
     125           0 :   return getDFAInsnInput(InsnClass);
     126             : }
     127             : 
     128             : // Check if the resources occupied by a MCInstrDesc are available in the
     129             : // current state.
     130      172636 : bool DFAPacketizer::canReserveResources(const MCInstrDesc *MID) {
     131      172636 :   unsigned InsnClass = MID->getSchedClass();
     132      172636 :   DFAInput InsnInput = getInsnInput(InsnClass);
     133             :   UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
     134      172636 :   ReadTable(CurrentState);
     135      345272 :   return CachedTable.count(StateTrans) != 0;
     136             : }
     137             : 
     138             : // Reserve the resources occupied by a MCInstrDesc and change the current
     139             : // state to reflect that change.
     140       85536 : void DFAPacketizer::reserveResources(const MCInstrDesc *MID) {
     141       85536 :   unsigned InsnClass = MID->getSchedClass();
     142       85536 :   DFAInput InsnInput = getInsnInput(InsnClass);
     143             :   UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);
     144       85536 :   ReadTable(CurrentState);
     145             :   assert(CachedTable.count(StateTrans) != 0);
     146      171072 :   CurrentState = CachedTable[StateTrans];
     147       85536 : }
     148             : 
     149             : // Check if the resources occupied by a machine instruction are available
     150             : // in the current state.
     151      172636 : bool DFAPacketizer::canReserveResources(MachineInstr &MI) {
     152      172636 :   const MCInstrDesc &MID = MI.getDesc();
     153      172636 :   return canReserveResources(&MID);
     154             : }
     155             : 
     156             : // Reserve the resources occupied by a machine instruction and change the
     157             : // current state to reflect that change.
     158       85536 : void DFAPacketizer::reserveResources(MachineInstr &MI) {
     159       85536 :   const MCInstrDesc &MID = MI.getDesc();
     160       85536 :   reserveResources(&MID);
     161       85536 : }
     162             : 
     163             : namespace llvm {
     164             : 
     165             : // This class extends ScheduleDAGInstrs and overrides the schedule method
     166             : // to build the dependence graph.
     167        4020 : class DefaultVLIWScheduler : public ScheduleDAGInstrs {
     168             : private:
     169             :   AliasAnalysis *AA;
     170             :   /// Ordered list of DAG postprocessing steps.
     171             :   std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
     172             : 
     173             : public:
     174             :   DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI,
     175             :                        AliasAnalysis *AA);
     176             : 
     177             :   // Actual scheduling work.
     178             :   void schedule() override;
     179             : 
     180             :   /// DefaultVLIWScheduler takes ownership of the Mutation object.
     181             :   void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
     182        5496 :     Mutations.push_back(std::move(Mutation));
     183             :   }
     184             : 
     185             : protected:
     186             :   void postprocessDAG();
     187             : };
     188             : 
     189             : } // end namespace llvm
     190             : 
     191        4020 : DefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,
     192             :                                            MachineLoopInfo &MLI,
     193        4020 :                                            AliasAnalysis *AA)
     194        4020 :     : ScheduleDAGInstrs(MF, &MLI), AA(AA) {
     195        4020 :   CanHandleTerminators = true;
     196        4020 : }
     197             : 
     198             : /// Apply each ScheduleDAGMutation step in order.
     199        4636 : void DefaultVLIWScheduler::postprocessDAG() {
     200       12220 :   for (auto &M : Mutations)
     201        7584 :     M->apply(this);
     202        4636 : }
     203             : 
     204        4636 : void DefaultVLIWScheduler::schedule() {
     205             :   // Build the scheduling graph.
     206        4636 :   buildSchedGraph(AA);
     207        4636 :   postprocessDAG();
     208        4636 : }
     209             : 
     210        4020 : VLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,
     211        4020 :                                        MachineLoopInfo &mli, AliasAnalysis *aa)
     212        4020 :     : MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {
     213        4020 :   ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());
     214        4020 :   VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);
     215        4020 : }
     216             : 
     217        8040 : VLIWPacketizerList::~VLIWPacketizerList() {
     218        4020 :   delete VLIWScheduler;
     219        8040 :   delete ResourceTracker;
     220        4020 : }
     221             : 
     222             : // End the current packet, bundle packet instructions and reset DFA state.
     223       34649 : void VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,
     224             :                                    MachineBasicBlock::iterator MI) {
     225             :   DEBUG({
     226             :     if (!CurrentPacketMIs.empty()) {
     227             :       dbgs() << "Finalizing packet:\n";
     228             :       for (MachineInstr *MI : CurrentPacketMIs)
     229             :         dbgs() << " * " << *MI;
     230             :     }
     231             :   });
     232       69298 :   if (CurrentPacketMIs.size() > 1) {
     233       13368 :     MachineInstr &MIFirst = *CurrentPacketMIs.front();
     234       13368 :     finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());
     235             :   }
     236             :   CurrentPacketMIs.clear();
     237       34649 :   ResourceTracker->clearResources();
     238             :   DEBUG(dbgs() << "End packet\n");
     239       34649 : }
     240             : 
     241             : // Bundle machine instructions into packets.
     242        4636 : void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,
     243             :                                       MachineBasicBlock::iterator BeginItr,
     244             :                                       MachineBasicBlock::iterator EndItr) {
     245             :   assert(VLIWScheduler && "VLIW Scheduler is not initialized!");
     246        4636 :   VLIWScheduler->startBlock(MBB);
     247        9272 :   VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,
     248        4636 :                              std::distance(BeginItr, EndItr));
     249        4636 :   VLIWScheduler->schedule();
     250             : 
     251             :   DEBUG({
     252             :     dbgs() << "Scheduling DAG of the packetize region\n";
     253             :     for (SUnit &SU : VLIWScheduler->SUnits)
     254             :       SU.dumpAll(VLIWScheduler);
     255             :   });
     256             : 
     257             :   // Generate MI -> SU map.
     258        4636 :   MIToSUnit.clear();
     259       83272 :   for (SUnit &SU : VLIWScheduler->SUnits)
     260       74000 :     MIToSUnit[SU.getInstr()] = &SU;
     261             : 
     262        4636 :   bool LimitPresent = InstrLimit.getPosition();
     263             : 
     264             :   // The main packetizer loop.
     265       78643 :   for (; BeginItr != EndItr; ++BeginItr) {
     266       74007 :     if (LimitPresent) {
     267           0 :       if (InstrCount >= InstrLimit) {
     268             :         EndItr = BeginItr;
     269             :         break;
     270             :       }
     271           0 :       InstrCount++;
     272             :     }
     273             :     MachineInstr &MI = *BeginItr;
     274       74007 :     initPacketizerState();
     275             : 
     276             :     // End the current packet if needed.
     277       88365 :     if (isSoloInstruction(MI)) {
     278       28716 :       endPacket(MBB, MI);
     279       14358 :       continue;
     280             :     }
     281             : 
     282             :     // Ignore pseudo instructions.
     283       59649 :     if (ignorePseudoInstruction(MI, MBB))
     284          12 :       continue;
     285             : 
     286       59637 :     SUnit *SUI = MIToSUnit[&MI];
     287             :     assert(SUI && "Missing SUnit Info!");
     288             : 
     289             :     // Ask DFA if machine resource is available for MI.
     290             :     DEBUG(dbgs() << "Checking resources for adding MI to packet " << MI);
     291             : 
     292       59637 :     bool ResourceAvail = ResourceTracker->canReserveResources(MI);
     293             :     DEBUG({
     294             :       if (ResourceAvail)
     295             :         dbgs() << "  Resources are available for adding MI to packet\n";
     296             :       else
     297             :         dbgs() << "  Resources NOT available\n";
     298             :     });
     299       59637 :     if (ResourceAvail && shouldAddToPacket(MI)) {
     300             :       // Dependency check for MI with instructions in CurrentPacketMIs.
     301      114640 :       for (auto MJ : CurrentPacketMIs) {
     302       65479 :         SUnit *SUJ = MIToSUnit[MJ];
     303             :         assert(SUJ && "Missing SUnit Info!");
     304             : 
     305             :         DEBUG(dbgs() << "  Checking against MJ " << *MJ);
     306             :         // Is it legal to packetize SUI and SUJ together.
     307       65479 :         if (!isLegalToPacketizeTogether(SUI, SUJ)) {
     308             :           DEBUG(dbgs() << "  Not legal to add MI, try to prune\n");
     309             :           // Allow packetization if dependency can be pruned.
     310        8122 :           if (!isLegalToPruneDependencies(SUI, SUJ)) {
     311             :             // End the packet if dependency cannot be pruned.
     312             :             DEBUG(dbgs() << "  Could not prune dependencies for adding MI\n");
     313       16242 :             endPacket(MBB, MI);
     314        8121 :             break;
     315             :           }
     316             :           DEBUG(dbgs() << "  Pruned dependence for adding MI\n");
     317             :         }
     318             :       }
     319             :     } else {
     320             :       DEBUG(if (ResourceAvail)
     321             :         dbgs() << "Resources are available, but instruction should not be "
     322             :                   "added to packet\n  " << MI);
     323             :       // End the packet if resource is not available, or if the instruction
     324             :       // shoud not be added to the current packet.
     325        4710 :       endPacket(MBB, MI);
     326             :     }
     327             : 
     328             :     // Add MI to the current packet.
     329             :     DEBUG(dbgs() << "* Adding MI to packet " << MI << '\n');
     330       59637 :     BeginItr = addToPacket(MI);
     331             :   } // For all instructions in the packetization range.
     332             : 
     333             :   // End any packet left behind.
     334        4636 :   endPacket(MBB, EndItr);
     335        4636 :   VLIWScheduler->exitRegion();
     336        4636 :   VLIWScheduler->finishBlock();
     337        4636 : }
     338             : 
     339         134 : bool VLIWPacketizerList::alias(const MachineMemOperand &Op1,
     340             :                                const MachineMemOperand &Op2,
     341             :                                bool UseTBAA) const {
     342         223 :   if (!Op1.getValue() || !Op2.getValue())
     343             :     return true;
     344             : 
     345         222 :   int64_t MinOffset = std::min(Op1.getOffset(), Op2.getOffset());
     346         111 :   int64_t Overlapa = Op1.getSize() + Op1.getOffset() - MinOffset;
     347         111 :   int64_t Overlapb = Op2.getSize() + Op2.getOffset() - MinOffset;
     348             : 
     349             :   AliasResult AAResult =
     350         222 :       AA->alias(MemoryLocation(Op1.getValue(), Overlapa,
     351         111 :                                UseTBAA ? Op1.getAAInfo() : AAMDNodes()),
     352         111 :                 MemoryLocation(Op2.getValue(), Overlapb,
     353         222 :                                UseTBAA ? Op2.getAAInfo() : AAMDNodes()));
     354             : 
     355         111 :   return AAResult != NoAlias;
     356             : }
     357             : 
     358         148 : bool VLIWPacketizerList::alias(const MachineInstr &MI1,
     359             :                                const MachineInstr &MI2,
     360             :                                bool UseTBAA) const {
     361         148 :   if (MI1.memoperands_empty() || MI2.memoperands_empty())
     362             :     return true;
     363             : 
     364         316 :   for (const MachineMemOperand *Op1 : MI1.memoperands())
     365         316 :     for (const MachineMemOperand *Op2 : MI2.memoperands())
     366         134 :       if (alias(*Op1, *Op2, UseTBAA))
     367             :         return true;
     368             :   return false;
     369             : }
     370             : 
     371             : // Add a DAG mutation object to the ordered list.
     372        5496 : void VLIWPacketizerList::addMutation(
     373             :       std::unique_ptr<ScheduleDAGMutation> Mutation) {
     374       10992 :   VLIWScheduler->addMutation(std::move(Mutation));
     375      297075 : }

Generated by: LCOV version 1.13