1//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===// 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//===----------------------------------------------------------------------===// --- 10 unchanged lines hidden (view full) --- 19// constructs that are not exposed before lowering and instruction selection. 20// 21//===----------------------------------------------------------------------===// 22 23#define DEBUG_TYPE "machine-licm" 24#include "llvm/CodeGen/Passes.h" 25#include "llvm/CodeGen/MachineDominators.h" 26#include "llvm/CodeGen/MachineLoopInfo.h" |
27#include "llvm/CodeGen/MachineMemOperand.h" |
28#include "llvm/CodeGen/MachineRegisterInfo.h" |
29#include "llvm/CodeGen/PseudoSourceValue.h" |
30#include "llvm/Target/TargetRegisterInfo.h" 31#include "llvm/Target/TargetInstrInfo.h" 32#include "llvm/Target/TargetMachine.h" 33#include "llvm/Analysis/AliasAnalysis.h" 34#include "llvm/ADT/DenseMap.h" 35#include "llvm/ADT/Statistic.h" |
36#include "llvm/Support/Debug.h" 37#include "llvm/Support/raw_ostream.h" 38 39using namespace llvm; 40 41STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops"); 42STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed"); 43 44namespace { |
45 class MachineLICM : public MachineFunctionPass { |
46 const TargetMachine *TM; 47 const TargetInstrInfo *TII; 48 const TargetRegisterInfo *TRI; 49 BitVector AllocatableSet; 50 51 // Various analyses that we use... 52 AliasAnalysis *AA; // Alias analysis info. 53 MachineLoopInfo *LI; // Current MachineLoopInfo 54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop 55 MachineRegisterInfo *RegInfo; // Machine register information 56 57 // State that is updated as we process loops 58 bool Changed; // True if a loop is changed. |
59 bool FirstInLoop; // True if it's the first LICM in the loop. |
60 MachineLoop *CurLoop; // The current loop we are working on. 61 MachineBasicBlock *CurPreheader; // The preheader for CurLoop. 62 |
63 // For each opcode, keep a list of potentail CSE instructions. 64 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap; |
65 public: 66 static char ID; // Pass identification, replacement for typeid 67 MachineLICM() : MachineFunctionPass(&ID) {} 68 69 virtual bool runOnMachineFunction(MachineFunction &MF); 70 71 const char *getPassName() const { return "Machine Instruction LICM"; } 72 --- 27 unchanged lines hidden (view full) --- 100 /// HoistRegion - Walk the specified region of the CFG (defined by all 101 /// blocks dominated by the specified block, and that are in the current 102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to 103 /// visit definitions before uses, allowing us to hoist a loop body in one 104 /// pass without iteration. 105 /// 106 void HoistRegion(MachineDomTreeNode *N); 107 |
108 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if 109 /// the load itself could be hoisted. Return the unfolded and hoistable 110 /// load, or null if the load couldn't be unfolded or if it wouldn't 111 /// be hoistable. 112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI); 113 |
114 /// Hoist - When an instruction is found to only use loop invariant operands 115 /// that is safe to hoist, this instruction is called to do the dirty work. 116 /// |
117 void Hoist(MachineInstr *MI); 118 119 /// InitCSEMap - Initialize the CSE map with instructions that are in the 120 /// current loop preheader that may become duplicates of instructions that 121 /// are hoisted out of the loop. 122 void InitCSEMap(MachineBasicBlock *BB); |
123 }; 124} // end anonymous namespace 125 126char MachineLICM::ID = 0; 127static RegisterPass<MachineLICM> 128X("machinelicm", "Machine Loop Invariant Code Motion"); 129 130FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); } --- 9 unchanged lines hidden (view full) --- 140 141/// Hoist expressions out of the specified loop. Note, alias info for inner loop 142/// is not preserved so it is not a good idea to run LICM multiple times on one 143/// loop. 144/// 145bool MachineLICM::runOnMachineFunction(MachineFunction &MF) { 146 DEBUG(errs() << "******** Machine LICM ********\n"); 147 |
148 Changed = FirstInLoop = false; |
149 TM = &MF.getTarget(); 150 TII = TM->getInstrInfo(); 151 TRI = TM->getRegisterInfo(); 152 RegInfo = &MF.getRegInfo(); 153 AllocatableSet = TRI->getAllocatableSet(MF); 154 155 // Get our Loop information... 156 LI = &getAnalysis<MachineLoopInfo>(); 157 DT = &getAnalysis<MachineDominatorTree>(); 158 AA = &getAnalysis<AliasAnalysis>(); 159 |
160 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { |
161 CurLoop = *I; 162 163 // Only visit outer-most preheader-sporting loops. 164 if (!LoopIsOuterMostWithPreheader(CurLoop)) 165 continue; 166 167 // Determine the block to which to hoist instructions. If we can't find a 168 // suitable loop preheader, we can't do any hoisting. 169 // 170 // FIXME: We are only hoisting if the basic block coming into this loop 171 // has only one successor. This isn't the case in general because we haven't 172 // broken critical edges or added preheaders. 173 CurPreheader = CurLoop->getLoopPreheader(); 174 if (!CurPreheader) 175 continue; 176 |
177 // CSEMap is initialized for loop header when the first instruction is 178 // being hoisted. 179 FirstInLoop = true; |
180 HoistRegion(DT->getNode(CurLoop->getHeader())); |
181 CSEMap.clear(); |
182 } 183 184 return Changed; 185} 186 187/// HoistRegion - Walk the specified region of the CFG (defined by all blocks 188/// dominated by the specified block, and that are in the current loop) in depth 189/// first order w.r.t the DominatorTree. This allows us to visit definitions --- 4 unchanged lines hidden (view full) --- 194 MachineBasicBlock *BB = N->getBlock(); 195 196 // If this subregion is not in the top level loop at all, exit. 197 if (!CurLoop->contains(BB)) return; 198 199 for (MachineBasicBlock::iterator 200 MII = BB->begin(), E = BB->end(); MII != E; ) { 201 MachineBasicBlock::iterator NextMII = MII; ++NextMII; |
202 Hoist(&*MII); |
203 MII = NextMII; 204 } 205 206 const std::vector<MachineDomTreeNode*> &Children = N->getChildren(); 207 208 for (unsigned I = 0, E = Children.size(); I != E; ++I) 209 HoistRegion(Children[I]); 210} --- 164 unchanged lines hidden (view full) --- 375 } 376 } 377 if (IsSame) 378 return PrevMI; 379 } 380 return 0; 381} 382 |
383MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) { 384 // If not, we may be able to unfold a load and hoist that. 385 // First test whether the instruction is loading from an amenable 386 // memory location. 387 if (!MI->getDesc().mayLoad()) return 0; 388 if (!MI->hasOneMemOperand()) return 0; 389 MachineMemOperand *MMO = *MI->memoperands_begin(); 390 if (MMO->isVolatile()) return 0; 391 MachineFunction &MF = *MI->getParent()->getParent(); 392 if (!MMO->getValue()) return 0; 393 if (const PseudoSourceValue *PSV = 394 dyn_cast<PseudoSourceValue>(MMO->getValue())) { 395 if (!PSV->isConstant(MF.getFrameInfo())) return 0; 396 } else { 397 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0; 398 } 399 // Next determine the register class for a temporary register. 400 unsigned LoadRegIndex; 401 unsigned NewOpc = 402 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), 403 /*UnfoldLoad=*/true, 404 /*UnfoldStore=*/false, 405 &LoadRegIndex); 406 if (NewOpc == 0) return 0; 407 const TargetInstrDesc &TID = TII->get(NewOpc); 408 if (TID.getNumDefs() != 1) return 0; 409 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI); 410 // Ok, we're unfolding. Create a temporary register and do the unfold. 411 unsigned Reg = RegInfo->createVirtualRegister(RC); 412 SmallVector<MachineInstr *, 2> NewMIs; 413 bool Success = 414 TII->unfoldMemoryOperand(MF, MI, Reg, 415 /*UnfoldLoad=*/true, /*UnfoldStore=*/false, 416 NewMIs); 417 (void)Success; 418 assert(Success && 419 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold " 420 "succeeded!"); 421 assert(NewMIs.size() == 2 && 422 "Unfolded a load into multiple instructions!"); 423 MachineBasicBlock *MBB = MI->getParent(); 424 MBB->insert(MI, NewMIs[0]); 425 MBB->insert(MI, NewMIs[1]); 426 // If unfolding produced a load that wasn't loop-invariant or profitable to 427 // hoist, discard the new instructions and bail. 428 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) { 429 NewMIs[0]->eraseFromParent(); 430 NewMIs[1]->eraseFromParent(); 431 return 0; 432 } 433 // Otherwise we successfully unfolded a load that we can hoist. 434 MI->eraseFromParent(); 435 return NewMIs[0]; 436} 437 438void MachineLICM::InitCSEMap(MachineBasicBlock *BB) { 439 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) { 440 const MachineInstr *MI = &*I; 441 // FIXME: For now, only hoist re-materilizable instructions. LICM will 442 // increase register pressure. We want to make sure it doesn't increase 443 // spilling. 444 if (TII->isTriviallyReMaterializable(MI, AA)) { 445 unsigned Opcode = MI->getOpcode(); 446 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator 447 CI = CSEMap.find(Opcode); 448 if (CI != CSEMap.end()) 449 CI->second.push_back(MI); 450 else { 451 std::vector<const MachineInstr*> CSEMIs; 452 CSEMIs.push_back(MI); 453 CSEMap.insert(std::make_pair(Opcode, CSEMIs)); 454 } 455 } 456 } 457} 458 |
459/// Hoist - When an instruction is found to use only loop invariant operands 460/// that are safe to hoist, this instruction is called to do the dirty work. 461/// |
462void MachineLICM::Hoist(MachineInstr *MI) { 463 // First check whether we should hoist this instruction. 464 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) { 465 // If not, try unfolding a hoistable load. 466 MI = ExtractHoistableLoad(MI); 467 if (!MI) return; 468 } |
469 470 // Now move the instructions to the predecessor, inserting it before any 471 // terminator instructions. 472 DEBUG({ |
473 errs() << "Hoisting " << *MI; |
474 if (CurPreheader->getBasicBlock()) 475 errs() << " to MachineBasicBlock " 476 << CurPreheader->getBasicBlock()->getName(); |
477 if (MI->getParent()->getBasicBlock()) |
478 errs() << " from MachineBasicBlock " |
479 << MI->getParent()->getBasicBlock()->getName(); |
480 errs() << "\n"; 481 }); 482 |
483 // If this is the first instruction being hoisted to the preheader, 484 // initialize the CSE map with potential common expressions. 485 InitCSEMap(CurPreheader); 486 |
487 // Look for opportunity to CSE the hoisted instruction. |
488 unsigned Opcode = MI->getOpcode(); 489 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator 490 CI = CSEMap.find(Opcode); |
491 bool DoneCSE = false; 492 if (CI != CSEMap.end()) { |
493 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo); |
494 if (Dup) { |
495 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup); 496 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 497 const MachineOperand &MO = MI->getOperand(i); |
498 if (MO.isReg() && MO.isDef()) 499 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg()); 500 } |
501 MI->eraseFromParent(); |
502 DoneCSE = true; 503 ++NumCSEed; 504 } 505 } 506 507 // Otherwise, splice the instruction to the preheader. 508 if (!DoneCSE) { |
509 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI); 510 |
511 // Add to the CSE map. 512 if (CI != CSEMap.end()) |
513 CI->second.push_back(MI); |
514 else { 515 std::vector<const MachineInstr*> CSEMIs; |
516 CSEMIs.push_back(MI); 517 CSEMap.insert(std::make_pair(Opcode, CSEMIs)); |
518 } 519 } 520 521 ++NumHoisted; 522 Changed = true; 523} |