1 //===- RDFGraph.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 // Target-independent, SSA-based data flow graph for register data flow (RDF). 10 // 11 #include "llvm/ADT/BitVector.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/SetVector.h" 14 #include "llvm/CodeGen/MachineBasicBlock.h" 15 #include "llvm/CodeGen/MachineDominanceFrontier.h" 16 #include "llvm/CodeGen/MachineDominators.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineInstr.h" 19 #include "llvm/CodeGen/MachineOperand.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/RDFGraph.h" 22 #include "llvm/CodeGen/RDFRegisters.h" 23 #include "llvm/CodeGen/TargetInstrInfo.h" 24 #include "llvm/CodeGen/TargetLowering.h" 25 #include "llvm/CodeGen/TargetRegisterInfo.h" 26 #include "llvm/CodeGen/TargetSubtargetInfo.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/MC/LaneBitmask.h" 29 #include "llvm/MC/MCInstrDesc.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdint> 35 #include <cstring> 36 #include <iterator> 37 #include <set> 38 #include <utility> 39 #include <vector> 40 41 // Printing functions. Have them here first, so that the rest of the code 42 // can use them. 43 namespace llvm::rdf { 44 45 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterRef> &P) { 46 P.G.getPRI().print(OS, P.Obj); 47 return OS; 48 } 49 50 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeId> &P) { 51 auto NA = P.G.addr<NodeBase *>(P.Obj); 52 uint16_t Attrs = NA.Addr->getAttrs(); 53 uint16_t Kind = NodeAttrs::kind(Attrs); 54 uint16_t Flags = NodeAttrs::flags(Attrs); 55 switch (NodeAttrs::type(Attrs)) { 56 case NodeAttrs::Code: 57 switch (Kind) { 58 case NodeAttrs::Func: 59 OS << 'f'; 60 break; 61 case NodeAttrs::Block: 62 OS << 'b'; 63 break; 64 case NodeAttrs::Stmt: 65 OS << 's'; 66 break; 67 case NodeAttrs::Phi: 68 OS << 'p'; 69 break; 70 default: 71 OS << "c?"; 72 break; 73 } 74 break; 75 case NodeAttrs::Ref: 76 if (Flags & NodeAttrs::Undef) 77 OS << '/'; 78 if (Flags & NodeAttrs::Dead) 79 OS << '\\'; 80 if (Flags & NodeAttrs::Preserving) 81 OS << '+'; 82 if (Flags & NodeAttrs::Clobbering) 83 OS << '~'; 84 switch (Kind) { 85 case NodeAttrs::Use: 86 OS << 'u'; 87 break; 88 case NodeAttrs::Def: 89 OS << 'd'; 90 break; 91 case NodeAttrs::Block: 92 OS << 'b'; 93 break; 94 default: 95 OS << "r?"; 96 break; 97 } 98 break; 99 default: 100 OS << '?'; 101 break; 102 } 103 OS << P.Obj; 104 if (Flags & NodeAttrs::Shadow) 105 OS << '"'; 106 return OS; 107 } 108 109 static void printRefHeader(raw_ostream &OS, const Ref RA, 110 const DataFlowGraph &G) { 111 OS << Print(RA.Id, G) << '<' << Print(RA.Addr->getRegRef(G), G) << '>'; 112 if (RA.Addr->getFlags() & NodeAttrs::Fixed) 113 OS << '!'; 114 } 115 116 raw_ostream &operator<<(raw_ostream &OS, const Print<Def> &P) { 117 printRefHeader(OS, P.Obj, P.G); 118 OS << '('; 119 if (NodeId N = P.Obj.Addr->getReachingDef()) 120 OS << Print(N, P.G); 121 OS << ','; 122 if (NodeId N = P.Obj.Addr->getReachedDef()) 123 OS << Print(N, P.G); 124 OS << ','; 125 if (NodeId N = P.Obj.Addr->getReachedUse()) 126 OS << Print(N, P.G); 127 OS << "):"; 128 if (NodeId N = P.Obj.Addr->getSibling()) 129 OS << Print(N, P.G); 130 return OS; 131 } 132 133 raw_ostream &operator<<(raw_ostream &OS, const Print<Use> &P) { 134 printRefHeader(OS, P.Obj, P.G); 135 OS << '('; 136 if (NodeId N = P.Obj.Addr->getReachingDef()) 137 OS << Print(N, P.G); 138 OS << "):"; 139 if (NodeId N = P.Obj.Addr->getSibling()) 140 OS << Print(N, P.G); 141 return OS; 142 } 143 144 raw_ostream &operator<<(raw_ostream &OS, const Print<PhiUse> &P) { 145 printRefHeader(OS, P.Obj, P.G); 146 OS << '('; 147 if (NodeId N = P.Obj.Addr->getReachingDef()) 148 OS << Print(N, P.G); 149 OS << ','; 150 if (NodeId N = P.Obj.Addr->getPredecessor()) 151 OS << Print(N, P.G); 152 OS << "):"; 153 if (NodeId N = P.Obj.Addr->getSibling()) 154 OS << Print(N, P.G); 155 return OS; 156 } 157 158 raw_ostream &operator<<(raw_ostream &OS, const Print<Ref> &P) { 159 switch (P.Obj.Addr->getKind()) { 160 case NodeAttrs::Def: 161 OS << PrintNode<DefNode *>(P.Obj, P.G); 162 break; 163 case NodeAttrs::Use: 164 if (P.Obj.Addr->getFlags() & NodeAttrs::PhiRef) 165 OS << PrintNode<PhiUseNode *>(P.Obj, P.G); 166 else 167 OS << PrintNode<UseNode *>(P.Obj, P.G); 168 break; 169 } 170 return OS; 171 } 172 173 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeList> &P) { 174 unsigned N = P.Obj.size(); 175 for (auto I : P.Obj) { 176 OS << Print(I.Id, P.G); 177 if (--N) 178 OS << ' '; 179 } 180 return OS; 181 } 182 183 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeSet> &P) { 184 unsigned N = P.Obj.size(); 185 for (auto I : P.Obj) { 186 OS << Print(I, P.G); 187 if (--N) 188 OS << ' '; 189 } 190 return OS; 191 } 192 193 namespace { 194 195 template <typename T> struct PrintListV { 196 PrintListV(const NodeList &L, const DataFlowGraph &G) : List(L), G(G) {} 197 198 using Type = T; 199 const NodeList &List; 200 const DataFlowGraph &G; 201 }; 202 203 template <typename T> 204 raw_ostream &operator<<(raw_ostream &OS, const PrintListV<T> &P) { 205 unsigned N = P.List.size(); 206 for (NodeAddr<T> A : P.List) { 207 OS << PrintNode<T>(A, P.G); 208 if (--N) 209 OS << ", "; 210 } 211 return OS; 212 } 213 214 } // end anonymous namespace 215 216 raw_ostream &operator<<(raw_ostream &OS, const Print<Phi> &P) { 217 OS << Print(P.Obj.Id, P.G) << ": phi [" 218 << PrintListV<RefNode *>(P.Obj.Addr->members(P.G), P.G) << ']'; 219 return OS; 220 } 221 222 raw_ostream &operator<<(raw_ostream &OS, const Print<Stmt> &P) { 223 const MachineInstr &MI = *P.Obj.Addr->getCode(); 224 unsigned Opc = MI.getOpcode(); 225 OS << Print(P.Obj.Id, P.G) << ": " << P.G.getTII().getName(Opc); 226 // Print the target for calls and branches (for readability). 227 if (MI.isCall() || MI.isBranch()) { 228 MachineInstr::const_mop_iterator T = 229 llvm::find_if(MI.operands(), [](const MachineOperand &Op) -> bool { 230 return Op.isMBB() || Op.isGlobal() || Op.isSymbol(); 231 }); 232 if (T != MI.operands_end()) { 233 OS << ' '; 234 if (T->isMBB()) 235 OS << printMBBReference(*T->getMBB()); 236 else if (T->isGlobal()) 237 OS << T->getGlobal()->getName(); 238 else if (T->isSymbol()) 239 OS << T->getSymbolName(); 240 } 241 } 242 OS << " [" << PrintListV<RefNode *>(P.Obj.Addr->members(P.G), P.G) << ']'; 243 return OS; 244 } 245 246 raw_ostream &operator<<(raw_ostream &OS, const Print<Instr> &P) { 247 switch (P.Obj.Addr->getKind()) { 248 case NodeAttrs::Phi: 249 OS << PrintNode<PhiNode *>(P.Obj, P.G); 250 break; 251 case NodeAttrs::Stmt: 252 OS << PrintNode<StmtNode *>(P.Obj, P.G); 253 break; 254 default: 255 OS << "instr? " << Print(P.Obj.Id, P.G); 256 break; 257 } 258 return OS; 259 } 260 261 raw_ostream &operator<<(raw_ostream &OS, const Print<Block> &P) { 262 MachineBasicBlock *BB = P.Obj.Addr->getCode(); 263 unsigned NP = BB->pred_size(); 264 std::vector<int> Ns; 265 auto PrintBBs = [&OS](std::vector<int> Ns) -> void { 266 unsigned N = Ns.size(); 267 for (int I : Ns) { 268 OS << "%bb." << I; 269 if (--N) 270 OS << ", "; 271 } 272 }; 273 274 OS << Print(P.Obj.Id, P.G) << ": --- " << printMBBReference(*BB) 275 << " --- preds(" << NP << "): "; 276 for (MachineBasicBlock *B : BB->predecessors()) 277 Ns.push_back(B->getNumber()); 278 PrintBBs(Ns); 279 280 unsigned NS = BB->succ_size(); 281 OS << " succs(" << NS << "): "; 282 Ns.clear(); 283 for (MachineBasicBlock *B : BB->successors()) 284 Ns.push_back(B->getNumber()); 285 PrintBBs(Ns); 286 OS << '\n'; 287 288 for (auto I : P.Obj.Addr->members(P.G)) 289 OS << PrintNode<InstrNode *>(I, P.G) << '\n'; 290 return OS; 291 } 292 293 raw_ostream &operator<<(raw_ostream &OS, const Print<Func> &P) { 294 OS << "DFG dump:[\n" 295 << Print(P.Obj.Id, P.G) 296 << ": Function: " << P.Obj.Addr->getCode()->getName() << '\n'; 297 for (auto I : P.Obj.Addr->members(P.G)) 298 OS << PrintNode<BlockNode *>(I, P.G) << '\n'; 299 OS << "]\n"; 300 return OS; 301 } 302 303 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterSet> &P) { 304 OS << '{'; 305 for (auto I : P.Obj) 306 OS << ' ' << Print(I, P.G); 307 OS << " }"; 308 return OS; 309 } 310 311 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterAggr> &P) { 312 OS << P.Obj; 313 return OS; 314 } 315 316 raw_ostream &operator<<(raw_ostream &OS, 317 const Print<DataFlowGraph::DefStack> &P) { 318 for (auto I = P.Obj.top(), E = P.Obj.bottom(); I != E;) { 319 OS << Print(I->Id, P.G) << '<' << Print(I->Addr->getRegRef(P.G), P.G) 320 << '>'; 321 I.down(); 322 if (I != E) 323 OS << ' '; 324 } 325 return OS; 326 } 327 328 // Node allocation functions. 329 // 330 // Node allocator is like a slab memory allocator: it allocates blocks of 331 // memory in sizes that are multiples of the size of a node. Each block has 332 // the same size. Nodes are allocated from the currently active block, and 333 // when it becomes full, a new one is created. 334 // There is a mapping scheme between node id and its location in a block, 335 // and within that block is described in the header file. 336 // 337 void NodeAllocator::startNewBlock() { 338 void *T = MemPool.Allocate(NodesPerBlock * NodeMemSize, NodeMemSize); 339 char *P = static_cast<char *>(T); 340 Blocks.push_back(P); 341 // Check if the block index is still within the allowed range, i.e. less 342 // than 2^N, where N is the number of bits in NodeId for the block index. 343 // BitsPerIndex is the number of bits per node index. 344 assert((Blocks.size() < ((size_t)1 << (8 * sizeof(NodeId) - BitsPerIndex))) && 345 "Out of bits for block index"); 346 ActiveEnd = P; 347 } 348 349 bool NodeAllocator::needNewBlock() { 350 if (Blocks.empty()) 351 return true; 352 353 char *ActiveBegin = Blocks.back(); 354 uint32_t Index = (ActiveEnd - ActiveBegin) / NodeMemSize; 355 return Index >= NodesPerBlock; 356 } 357 358 Node NodeAllocator::New() { 359 if (needNewBlock()) 360 startNewBlock(); 361 362 uint32_t ActiveB = Blocks.size() - 1; 363 uint32_t Index = (ActiveEnd - Blocks[ActiveB]) / NodeMemSize; 364 Node NA = {reinterpret_cast<NodeBase *>(ActiveEnd), makeId(ActiveB, Index)}; 365 ActiveEnd += NodeMemSize; 366 return NA; 367 } 368 369 NodeId NodeAllocator::id(const NodeBase *P) const { 370 uintptr_t A = reinterpret_cast<uintptr_t>(P); 371 for (unsigned i = 0, n = Blocks.size(); i != n; ++i) { 372 uintptr_t B = reinterpret_cast<uintptr_t>(Blocks[i]); 373 if (A < B || A >= B + NodesPerBlock * NodeMemSize) 374 continue; 375 uint32_t Idx = (A - B) / NodeMemSize; 376 return makeId(i, Idx); 377 } 378 llvm_unreachable("Invalid node address"); 379 } 380 381 void NodeAllocator::clear() { 382 MemPool.Reset(); 383 Blocks.clear(); 384 ActiveEnd = nullptr; 385 } 386 387 // Insert node NA after "this" in the circular chain. 388 void NodeBase::append(Node NA) { 389 NodeId Nx = Next; 390 // If NA is already "next", do nothing. 391 if (Next != NA.Id) { 392 Next = NA.Id; 393 NA.Addr->Next = Nx; 394 } 395 } 396 397 // Fundamental node manipulator functions. 398 399 // Obtain the register reference from a reference node. 400 RegisterRef RefNode::getRegRef(const DataFlowGraph &G) const { 401 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref); 402 if (NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef) 403 return G.unpack(RefData.PR); 404 assert(RefData.Op != nullptr); 405 return G.makeRegRef(*RefData.Op); 406 } 407 408 // Set the register reference in the reference node directly (for references 409 // in phi nodes). 410 void RefNode::setRegRef(RegisterRef RR, DataFlowGraph &G) { 411 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref); 412 assert(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef); 413 RefData.PR = G.pack(RR); 414 } 415 416 // Set the register reference in the reference node based on a machine 417 // operand (for references in statement nodes). 418 void RefNode::setRegRef(MachineOperand *Op, DataFlowGraph &G) { 419 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref); 420 assert(!(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef)); 421 (void)G; 422 RefData.Op = Op; 423 } 424 425 // Get the owner of a given reference node. 426 Node RefNode::getOwner(const DataFlowGraph &G) { 427 Node NA = G.addr<NodeBase *>(getNext()); 428 429 while (NA.Addr != this) { 430 if (NA.Addr->getType() == NodeAttrs::Code) 431 return NA; 432 NA = G.addr<NodeBase *>(NA.Addr->getNext()); 433 } 434 llvm_unreachable("No owner in circular list"); 435 } 436 437 // Connect the def node to the reaching def node. 438 void DefNode::linkToDef(NodeId Self, Def DA) { 439 RefData.RD = DA.Id; 440 RefData.Sib = DA.Addr->getReachedDef(); 441 DA.Addr->setReachedDef(Self); 442 } 443 444 // Connect the use node to the reaching def node. 445 void UseNode::linkToDef(NodeId Self, Def DA) { 446 RefData.RD = DA.Id; 447 RefData.Sib = DA.Addr->getReachedUse(); 448 DA.Addr->setReachedUse(Self); 449 } 450 451 // Get the first member of the code node. 452 Node CodeNode::getFirstMember(const DataFlowGraph &G) const { 453 if (CodeData.FirstM == 0) 454 return Node(); 455 return G.addr<NodeBase *>(CodeData.FirstM); 456 } 457 458 // Get the last member of the code node. 459 Node CodeNode::getLastMember(const DataFlowGraph &G) const { 460 if (CodeData.LastM == 0) 461 return Node(); 462 return G.addr<NodeBase *>(CodeData.LastM); 463 } 464 465 // Add node NA at the end of the member list of the given code node. 466 void CodeNode::addMember(Node NA, const DataFlowGraph &G) { 467 Node ML = getLastMember(G); 468 if (ML.Id != 0) { 469 ML.Addr->append(NA); 470 } else { 471 CodeData.FirstM = NA.Id; 472 NodeId Self = G.id(this); 473 NA.Addr->setNext(Self); 474 } 475 CodeData.LastM = NA.Id; 476 } 477 478 // Add node NA after member node MA in the given code node. 479 void CodeNode::addMemberAfter(Node MA, Node NA, const DataFlowGraph &G) { 480 MA.Addr->append(NA); 481 if (CodeData.LastM == MA.Id) 482 CodeData.LastM = NA.Id; 483 } 484 485 // Remove member node NA from the given code node. 486 void CodeNode::removeMember(Node NA, const DataFlowGraph &G) { 487 Node MA = getFirstMember(G); 488 assert(MA.Id != 0); 489 490 // Special handling if the member to remove is the first member. 491 if (MA.Id == NA.Id) { 492 if (CodeData.LastM == MA.Id) { 493 // If it is the only member, set both first and last to 0. 494 CodeData.FirstM = CodeData.LastM = 0; 495 } else { 496 // Otherwise, advance the first member. 497 CodeData.FirstM = MA.Addr->getNext(); 498 } 499 return; 500 } 501 502 while (MA.Addr != this) { 503 NodeId MX = MA.Addr->getNext(); 504 if (MX == NA.Id) { 505 MA.Addr->setNext(NA.Addr->getNext()); 506 // If the member to remove happens to be the last one, update the 507 // LastM indicator. 508 if (CodeData.LastM == NA.Id) 509 CodeData.LastM = MA.Id; 510 return; 511 } 512 MA = G.addr<NodeBase *>(MX); 513 } 514 llvm_unreachable("No such member"); 515 } 516 517 // Return the list of all members of the code node. 518 NodeList CodeNode::members(const DataFlowGraph &G) const { 519 static auto True = [](Node) -> bool { return true; }; 520 return members_if(True, G); 521 } 522 523 // Return the owner of the given instr node. 524 Node InstrNode::getOwner(const DataFlowGraph &G) { 525 Node NA = G.addr<NodeBase *>(getNext()); 526 527 while (NA.Addr != this) { 528 assert(NA.Addr->getType() == NodeAttrs::Code); 529 if (NA.Addr->getKind() == NodeAttrs::Block) 530 return NA; 531 NA = G.addr<NodeBase *>(NA.Addr->getNext()); 532 } 533 llvm_unreachable("No owner in circular list"); 534 } 535 536 // Add the phi node PA to the given block node. 537 void BlockNode::addPhi(Phi PA, const DataFlowGraph &G) { 538 Node M = getFirstMember(G); 539 if (M.Id == 0) { 540 addMember(PA, G); 541 return; 542 } 543 544 assert(M.Addr->getType() == NodeAttrs::Code); 545 if (M.Addr->getKind() == NodeAttrs::Stmt) { 546 // If the first member of the block is a statement, insert the phi as 547 // the first member. 548 CodeData.FirstM = PA.Id; 549 PA.Addr->setNext(M.Id); 550 } else { 551 // If the first member is a phi, find the last phi, and append PA to it. 552 assert(M.Addr->getKind() == NodeAttrs::Phi); 553 Node MN = M; 554 do { 555 M = MN; 556 MN = G.addr<NodeBase *>(M.Addr->getNext()); 557 assert(MN.Addr->getType() == NodeAttrs::Code); 558 } while (MN.Addr->getKind() == NodeAttrs::Phi); 559 560 // M is the last phi. 561 addMemberAfter(M, PA, G); 562 } 563 } 564 565 // Find the block node corresponding to the machine basic block BB in the 566 // given func node. 567 Block FuncNode::findBlock(const MachineBasicBlock *BB, 568 const DataFlowGraph &G) const { 569 auto EqBB = [BB](Node NA) -> bool { return Block(NA).Addr->getCode() == BB; }; 570 NodeList Ms = members_if(EqBB, G); 571 if (!Ms.empty()) 572 return Ms[0]; 573 return Block(); 574 } 575 576 // Get the block node for the entry block in the given function. 577 Block FuncNode::getEntryBlock(const DataFlowGraph &G) { 578 MachineBasicBlock *EntryB = &getCode()->front(); 579 return findBlock(EntryB, G); 580 } 581 582 // Target operand information. 583 // 584 585 // For a given instruction, check if there are any bits of RR that can remain 586 // unchanged across this def. 587 bool TargetOperandInfo::isPreserving(const MachineInstr &In, 588 unsigned OpNum) const { 589 return TII.isPredicated(In); 590 } 591 592 // Check if the definition of RR produces an unspecified value. 593 bool TargetOperandInfo::isClobbering(const MachineInstr &In, 594 unsigned OpNum) const { 595 const MachineOperand &Op = In.getOperand(OpNum); 596 if (Op.isRegMask()) 597 return true; 598 assert(Op.isReg()); 599 if (In.isCall()) 600 if (Op.isDef() && Op.isDead()) 601 return true; 602 return false; 603 } 604 605 // Check if the given instruction specifically requires 606 bool TargetOperandInfo::isFixedReg(const MachineInstr &In, 607 unsigned OpNum) const { 608 if (In.isCall() || In.isReturn() || In.isInlineAsm()) 609 return true; 610 // Check for a tail call. 611 if (In.isBranch()) 612 for (const MachineOperand &O : In.operands()) 613 if (O.isGlobal() || O.isSymbol()) 614 return true; 615 616 const MCInstrDesc &D = In.getDesc(); 617 if (D.implicit_defs().empty() && D.implicit_uses().empty()) 618 return false; 619 const MachineOperand &Op = In.getOperand(OpNum); 620 // If there is a sub-register, treat the operand as non-fixed. Currently, 621 // fixed registers are those that are listed in the descriptor as implicit 622 // uses or defs, and those lists do not allow sub-registers. 623 if (Op.getSubReg() != 0) 624 return false; 625 Register Reg = Op.getReg(); 626 ArrayRef<MCPhysReg> ImpOps = 627 Op.isDef() ? D.implicit_defs() : D.implicit_uses(); 628 return is_contained(ImpOps, Reg); 629 } 630 631 // 632 // The data flow graph construction. 633 // 634 635 DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii, 636 const TargetRegisterInfo &tri, 637 const MachineDominatorTree &mdt, 638 const MachineDominanceFrontier &mdf) 639 : DefaultTOI(std::make_unique<TargetOperandInfo>(tii)), MF(mf), TII(tii), 640 TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(*DefaultTOI), 641 LiveIns(PRI) {} 642 643 DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii, 644 const TargetRegisterInfo &tri, 645 const MachineDominatorTree &mdt, 646 const MachineDominanceFrontier &mdf, 647 const TargetOperandInfo &toi) 648 : MF(mf), TII(tii), TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(toi), 649 LiveIns(PRI) {} 650 651 // The implementation of the definition stack. 652 // Each register reference has its own definition stack. In particular, 653 // for a register references "Reg" and "Reg:subreg" will each have their 654 // own definition stacks. 655 656 // Construct a stack iterator. 657 DataFlowGraph::DefStack::Iterator::Iterator(const DataFlowGraph::DefStack &S, 658 bool Top) 659 : DS(S) { 660 if (!Top) { 661 // Initialize to bottom. 662 Pos = 0; 663 return; 664 } 665 // Initialize to the top, i.e. top-most non-delimiter (or 0, if empty). 666 Pos = DS.Stack.size(); 667 while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos - 1])) 668 Pos--; 669 } 670 671 // Return the size of the stack, including block delimiters. 672 unsigned DataFlowGraph::DefStack::size() const { 673 unsigned S = 0; 674 for (auto I = top(), E = bottom(); I != E; I.down()) 675 S++; 676 return S; 677 } 678 679 // Remove the top entry from the stack. Remove all intervening delimiters 680 // so that after this, the stack is either empty, or the top of the stack 681 // is a non-delimiter. 682 void DataFlowGraph::DefStack::pop() { 683 assert(!empty()); 684 unsigned P = nextDown(Stack.size()); 685 Stack.resize(P); 686 } 687 688 // Push a delimiter for block node N on the stack. 689 void DataFlowGraph::DefStack::start_block(NodeId N) { 690 assert(N != 0); 691 Stack.push_back(Def(nullptr, N)); 692 } 693 694 // Remove all nodes from the top of the stack, until the delimited for 695 // block node N is encountered. Remove the delimiter as well. In effect, 696 // this will remove from the stack all definitions from block N. 697 void DataFlowGraph::DefStack::clear_block(NodeId N) { 698 assert(N != 0); 699 unsigned P = Stack.size(); 700 while (P > 0) { 701 bool Found = isDelimiter(Stack[P - 1], N); 702 P--; 703 if (Found) 704 break; 705 } 706 // This will also remove the delimiter, if found. 707 Stack.resize(P); 708 } 709 710 // Move the stack iterator up by one. 711 unsigned DataFlowGraph::DefStack::nextUp(unsigned P) const { 712 // Get the next valid position after P (skipping all delimiters). 713 // The input position P does not have to point to a non-delimiter. 714 unsigned SS = Stack.size(); 715 bool IsDelim; 716 assert(P < SS); 717 do { 718 P++; 719 IsDelim = isDelimiter(Stack[P - 1]); 720 } while (P < SS && IsDelim); 721 assert(!IsDelim); 722 return P; 723 } 724 725 // Move the stack iterator down by one. 726 unsigned DataFlowGraph::DefStack::nextDown(unsigned P) const { 727 // Get the preceding valid position before P (skipping all delimiters). 728 // The input position P does not have to point to a non-delimiter. 729 assert(P > 0 && P <= Stack.size()); 730 bool IsDelim = isDelimiter(Stack[P - 1]); 731 do { 732 if (--P == 0) 733 break; 734 IsDelim = isDelimiter(Stack[P - 1]); 735 } while (P > 0 && IsDelim); 736 assert(!IsDelim); 737 return P; 738 } 739 740 // Register information. 741 742 RegisterAggr DataFlowGraph::getLandingPadLiveIns() const { 743 RegisterAggr LR(getPRI()); 744 const Function &F = MF.getFunction(); 745 const Constant *PF = F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr; 746 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering(); 747 if (RegisterId R = TLI.getExceptionPointerRegister(PF)) 748 LR.insert(RegisterRef(R)); 749 if (!isFuncletEHPersonality(classifyEHPersonality(PF))) { 750 if (RegisterId R = TLI.getExceptionSelectorRegister(PF)) 751 LR.insert(RegisterRef(R)); 752 } 753 return LR; 754 } 755 756 // Node management functions. 757 758 // Get the pointer to the node with the id N. 759 NodeBase *DataFlowGraph::ptr(NodeId N) const { 760 if (N == 0) 761 return nullptr; 762 return Memory.ptr(N); 763 } 764 765 // Get the id of the node at the address P. 766 NodeId DataFlowGraph::id(const NodeBase *P) const { 767 if (P == nullptr) 768 return 0; 769 return Memory.id(P); 770 } 771 772 // Allocate a new node and set the attributes to Attrs. 773 Node DataFlowGraph::newNode(uint16_t Attrs) { 774 Node P = Memory.New(); 775 P.Addr->init(); 776 P.Addr->setAttrs(Attrs); 777 return P; 778 } 779 780 // Make a copy of the given node B, except for the data-flow links, which 781 // are set to 0. 782 Node DataFlowGraph::cloneNode(const Node B) { 783 Node NA = newNode(0); 784 memcpy(NA.Addr, B.Addr, sizeof(NodeBase)); 785 // Ref nodes need to have the data-flow links reset. 786 if (NA.Addr->getType() == NodeAttrs::Ref) { 787 Ref RA = NA; 788 RA.Addr->setReachingDef(0); 789 RA.Addr->setSibling(0); 790 if (NA.Addr->getKind() == NodeAttrs::Def) { 791 Def DA = NA; 792 DA.Addr->setReachedDef(0); 793 DA.Addr->setReachedUse(0); 794 } 795 } 796 return NA; 797 } 798 799 // Allocation routines for specific node types/kinds. 800 801 Use DataFlowGraph::newUse(Instr Owner, MachineOperand &Op, uint16_t Flags) { 802 Use UA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags); 803 UA.Addr->setRegRef(&Op, *this); 804 return UA; 805 } 806 807 PhiUse DataFlowGraph::newPhiUse(Phi Owner, RegisterRef RR, Block PredB, 808 uint16_t Flags) { 809 PhiUse PUA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags); 810 assert(Flags & NodeAttrs::PhiRef); 811 PUA.Addr->setRegRef(RR, *this); 812 PUA.Addr->setPredecessor(PredB.Id); 813 return PUA; 814 } 815 816 Def DataFlowGraph::newDef(Instr Owner, MachineOperand &Op, uint16_t Flags) { 817 Def DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags); 818 DA.Addr->setRegRef(&Op, *this); 819 return DA; 820 } 821 822 Def DataFlowGraph::newDef(Instr Owner, RegisterRef RR, uint16_t Flags) { 823 Def DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags); 824 assert(Flags & NodeAttrs::PhiRef); 825 DA.Addr->setRegRef(RR, *this); 826 return DA; 827 } 828 829 Phi DataFlowGraph::newPhi(Block Owner) { 830 Phi PA = newNode(NodeAttrs::Code | NodeAttrs::Phi); 831 Owner.Addr->addPhi(PA, *this); 832 return PA; 833 } 834 835 Stmt DataFlowGraph::newStmt(Block Owner, MachineInstr *MI) { 836 Stmt SA = newNode(NodeAttrs::Code | NodeAttrs::Stmt); 837 SA.Addr->setCode(MI); 838 Owner.Addr->addMember(SA, *this); 839 return SA; 840 } 841 842 Block DataFlowGraph::newBlock(Func Owner, MachineBasicBlock *BB) { 843 Block BA = newNode(NodeAttrs::Code | NodeAttrs::Block); 844 BA.Addr->setCode(BB); 845 Owner.Addr->addMember(BA, *this); 846 return BA; 847 } 848 849 Func DataFlowGraph::newFunc(MachineFunction *MF) { 850 Func FA = newNode(NodeAttrs::Code | NodeAttrs::Func); 851 FA.Addr->setCode(MF); 852 return FA; 853 } 854 855 // Build the data flow graph. 856 void DataFlowGraph::build(unsigned Options) { 857 reset(); 858 TheFunc = newFunc(&MF); 859 860 if (MF.empty()) 861 return; 862 863 for (MachineBasicBlock &B : MF) { 864 Block BA = newBlock(TheFunc, &B); 865 BlockNodes.insert(std::make_pair(&B, BA)); 866 for (MachineInstr &I : B) { 867 if (I.isDebugInstr()) 868 continue; 869 buildStmt(BA, I); 870 } 871 } 872 873 Block EA = TheFunc.Addr->getEntryBlock(*this); 874 NodeList Blocks = TheFunc.Addr->members(*this); 875 876 // Collect information about block references. 877 RegisterSet AllRefs(getPRI()); 878 for (Block BA : Blocks) 879 for (Instr IA : BA.Addr->members(*this)) 880 for (Ref RA : IA.Addr->members(*this)) 881 AllRefs.insert(RA.Addr->getRegRef(*this)); 882 883 // Collect function live-ins and entry block live-ins. 884 MachineRegisterInfo &MRI = MF.getRegInfo(); 885 MachineBasicBlock &EntryB = *EA.Addr->getCode(); 886 assert(EntryB.pred_empty() && "Function entry block has predecessors"); 887 for (std::pair<unsigned, unsigned> P : MRI.liveins()) 888 LiveIns.insert(RegisterRef(P.first)); 889 if (MRI.tracksLiveness()) { 890 for (auto I : EntryB.liveins()) 891 LiveIns.insert(RegisterRef(I.PhysReg, I.LaneMask)); 892 } 893 894 // Add function-entry phi nodes for the live-in registers. 895 for (RegisterRef RR : LiveIns.refs()) { 896 Phi PA = newPhi(EA); 897 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving; 898 Def DA = newDef(PA, RR, PhiFlags); 899 PA.Addr->addMember(DA, *this); 900 } 901 902 // Add phis for landing pads. 903 // Landing pads, unlike usual backs blocks, are not entered through 904 // branches in the program, or fall-throughs from other blocks. They 905 // are entered from the exception handling runtime and target's ABI 906 // may define certain registers as defined on entry to such a block. 907 RegisterAggr EHRegs = getLandingPadLiveIns(); 908 if (!EHRegs.empty()) { 909 for (Block BA : Blocks) { 910 const MachineBasicBlock &B = *BA.Addr->getCode(); 911 if (!B.isEHPad()) 912 continue; 913 914 // Prepare a list of NodeIds of the block's predecessors. 915 NodeList Preds; 916 for (MachineBasicBlock *PB : B.predecessors()) 917 Preds.push_back(findBlock(PB)); 918 919 // Build phi nodes for each live-in. 920 for (RegisterRef RR : EHRegs.refs()) { 921 Phi PA = newPhi(BA); 922 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving; 923 // Add def: 924 Def DA = newDef(PA, RR, PhiFlags); 925 PA.Addr->addMember(DA, *this); 926 // Add uses (no reaching defs for phi uses): 927 for (Block PBA : Preds) { 928 PhiUse PUA = newPhiUse(PA, RR, PBA); 929 PA.Addr->addMember(PUA, *this); 930 } 931 } 932 } 933 } 934 935 // Build a map "PhiM" which will contain, for each block, the set 936 // of references that will require phi definitions in that block. 937 BlockRefsMap PhiM(getPRI()); 938 for (Block BA : Blocks) 939 recordDefsForDF(PhiM, BA); 940 for (Block BA : Blocks) 941 buildPhis(PhiM, AllRefs, BA); 942 943 // Link all the refs. This will recursively traverse the dominator tree. 944 DefStackMap DM; 945 linkBlockRefs(DM, EA); 946 947 // Finally, remove all unused phi nodes. 948 if (!(Options & BuildOptions::KeepDeadPhis)) 949 removeUnusedPhis(); 950 } 951 952 RegisterRef DataFlowGraph::makeRegRef(unsigned Reg, unsigned Sub) const { 953 assert(RegisterRef::isRegId(Reg) || RegisterRef::isMaskId(Reg)); 954 assert(Reg != 0); 955 if (Sub != 0) 956 Reg = TRI.getSubReg(Reg, Sub); 957 return RegisterRef(Reg); 958 } 959 960 RegisterRef DataFlowGraph::makeRegRef(const MachineOperand &Op) const { 961 assert(Op.isReg() || Op.isRegMask()); 962 if (Op.isReg()) 963 return makeRegRef(Op.getReg(), Op.getSubReg()); 964 return RegisterRef(getPRI().getRegMaskId(Op.getRegMask()), 965 LaneBitmask::getAll()); 966 } 967 968 // For each stack in the map DefM, push the delimiter for block B on it. 969 void DataFlowGraph::markBlock(NodeId B, DefStackMap &DefM) { 970 // Push block delimiters. 971 for (auto &P : DefM) 972 P.second.start_block(B); 973 } 974 975 // Remove all definitions coming from block B from each stack in DefM. 976 void DataFlowGraph::releaseBlock(NodeId B, DefStackMap &DefM) { 977 // Pop all defs from this block from the definition stack. Defs that were 978 // added to the map during the traversal of instructions will not have a 979 // delimiter, but for those, the whole stack will be emptied. 980 for (auto &P : DefM) 981 P.second.clear_block(B); 982 983 // Finally, remove empty stacks from the map. 984 for (auto I = DefM.begin(), E = DefM.end(), NextI = I; I != E; I = NextI) { 985 NextI = std::next(I); 986 // This preserves the validity of iterators other than I. 987 if (I->second.empty()) 988 DefM.erase(I); 989 } 990 } 991 992 // Push all definitions from the instruction node IA to an appropriate 993 // stack in DefM. 994 void DataFlowGraph::pushAllDefs(Instr IA, DefStackMap &DefM) { 995 pushClobbers(IA, DefM); 996 pushDefs(IA, DefM); 997 } 998 999 // Push all definitions from the instruction node IA to an appropriate 1000 // stack in DefM. 1001 void DataFlowGraph::pushClobbers(Instr IA, DefStackMap &DefM) { 1002 NodeSet Visited; 1003 std::set<RegisterId> Defined; 1004 1005 // The important objectives of this function are: 1006 // - to be able to handle instructions both while the graph is being 1007 // constructed, and after the graph has been constructed, and 1008 // - maintain proper ordering of definitions on the stack for each 1009 // register reference: 1010 // - if there are two or more related defs in IA (i.e. coming from 1011 // the same machine operand), then only push one def on the stack, 1012 // - if there are multiple unrelated defs of non-overlapping 1013 // subregisters of S, then the stack for S will have both (in an 1014 // unspecified order), but the order does not matter from the data- 1015 // -flow perspective. 1016 1017 for (Def DA : IA.Addr->members_if(IsDef, *this)) { 1018 if (Visited.count(DA.Id)) 1019 continue; 1020 if (!(DA.Addr->getFlags() & NodeAttrs::Clobbering)) 1021 continue; 1022 1023 NodeList Rel = getRelatedRefs(IA, DA); 1024 Def PDA = Rel.front(); 1025 RegisterRef RR = PDA.Addr->getRegRef(*this); 1026 1027 // Push the definition on the stack for the register and all aliases. 1028 // The def stack traversal in linkNodeUp will check the exact aliasing. 1029 DefM[RR.Reg].push(DA); 1030 Defined.insert(RR.Reg); 1031 for (RegisterId A : getPRI().getAliasSet(RR.Reg)) { 1032 // Check that we don't push the same def twice. 1033 assert(A != RR.Reg); 1034 if (!Defined.count(A)) 1035 DefM[A].push(DA); 1036 } 1037 // Mark all the related defs as visited. 1038 for (Node T : Rel) 1039 Visited.insert(T.Id); 1040 } 1041 } 1042 1043 // Push all definitions from the instruction node IA to an appropriate 1044 // stack in DefM. 1045 void DataFlowGraph::pushDefs(Instr IA, DefStackMap &DefM) { 1046 NodeSet Visited; 1047 #ifndef NDEBUG 1048 std::set<RegisterId> Defined; 1049 #endif 1050 1051 // The important objectives of this function are: 1052 // - to be able to handle instructions both while the graph is being 1053 // constructed, and after the graph has been constructed, and 1054 // - maintain proper ordering of definitions on the stack for each 1055 // register reference: 1056 // - if there are two or more related defs in IA (i.e. coming from 1057 // the same machine operand), then only push one def on the stack, 1058 // - if there are multiple unrelated defs of non-overlapping 1059 // subregisters of S, then the stack for S will have both (in an 1060 // unspecified order), but the order does not matter from the data- 1061 // -flow perspective. 1062 1063 for (Def DA : IA.Addr->members_if(IsDef, *this)) { 1064 if (Visited.count(DA.Id)) 1065 continue; 1066 if (DA.Addr->getFlags() & NodeAttrs::Clobbering) 1067 continue; 1068 1069 NodeList Rel = getRelatedRefs(IA, DA); 1070 Def PDA = Rel.front(); 1071 RegisterRef RR = PDA.Addr->getRegRef(*this); 1072 #ifndef NDEBUG 1073 // Assert if the register is defined in two or more unrelated defs. 1074 // This could happen if there are two or more def operands defining it. 1075 if (!Defined.insert(RR.Reg).second) { 1076 MachineInstr *MI = Stmt(IA).Addr->getCode(); 1077 dbgs() << "Multiple definitions of register: " << Print(RR, *this) 1078 << " in\n " << *MI << "in " << printMBBReference(*MI->getParent()) 1079 << '\n'; 1080 llvm_unreachable(nullptr); 1081 } 1082 #endif 1083 // Push the definition on the stack for the register and all aliases. 1084 // The def stack traversal in linkNodeUp will check the exact aliasing. 1085 DefM[RR.Reg].push(DA); 1086 for (RegisterId A : getPRI().getAliasSet(RR.Reg)) { 1087 // Check that we don't push the same def twice. 1088 assert(A != RR.Reg); 1089 DefM[A].push(DA); 1090 } 1091 // Mark all the related defs as visited. 1092 for (Node T : Rel) 1093 Visited.insert(T.Id); 1094 } 1095 } 1096 1097 // Return the list of all reference nodes related to RA, including RA itself. 1098 // See "getNextRelated" for the meaning of a "related reference". 1099 NodeList DataFlowGraph::getRelatedRefs(Instr IA, Ref RA) const { 1100 assert(IA.Id != 0 && RA.Id != 0); 1101 1102 NodeList Refs; 1103 NodeId Start = RA.Id; 1104 do { 1105 Refs.push_back(RA); 1106 RA = getNextRelated(IA, RA); 1107 } while (RA.Id != 0 && RA.Id != Start); 1108 return Refs; 1109 } 1110 1111 // Clear all information in the graph. 1112 void DataFlowGraph::reset() { 1113 Memory.clear(); 1114 BlockNodes.clear(); 1115 TheFunc = Func(); 1116 } 1117 1118 // Return the next reference node in the instruction node IA that is related 1119 // to RA. Conceptually, two reference nodes are related if they refer to the 1120 // same instance of a register access, but differ in flags or other minor 1121 // characteristics. Specific examples of related nodes are shadow reference 1122 // nodes. 1123 // Return the equivalent of nullptr if there are no more related references. 1124 Ref DataFlowGraph::getNextRelated(Instr IA, Ref RA) const { 1125 assert(IA.Id != 0 && RA.Id != 0); 1126 1127 auto Related = [this, RA](Ref TA) -> bool { 1128 if (TA.Addr->getKind() != RA.Addr->getKind()) 1129 return false; 1130 if (!getPRI().equal_to(TA.Addr->getRegRef(*this), 1131 RA.Addr->getRegRef(*this))) { 1132 return false; 1133 } 1134 return true; 1135 }; 1136 auto RelatedStmt = [&Related, RA](Ref TA) -> bool { 1137 return Related(TA) && &RA.Addr->getOp() == &TA.Addr->getOp(); 1138 }; 1139 auto RelatedPhi = [&Related, RA](Ref TA) -> bool { 1140 if (!Related(TA)) 1141 return false; 1142 if (TA.Addr->getKind() != NodeAttrs::Use) 1143 return true; 1144 // For phi uses, compare predecessor blocks. 1145 const NodeAddr<const PhiUseNode *> TUA = TA; 1146 const NodeAddr<const PhiUseNode *> RUA = RA; 1147 return TUA.Addr->getPredecessor() == RUA.Addr->getPredecessor(); 1148 }; 1149 1150 RegisterRef RR = RA.Addr->getRegRef(*this); 1151 if (IA.Addr->getKind() == NodeAttrs::Stmt) 1152 return RA.Addr->getNextRef(RR, RelatedStmt, true, *this); 1153 return RA.Addr->getNextRef(RR, RelatedPhi, true, *this); 1154 } 1155 1156 // Find the next node related to RA in IA that satisfies condition P. 1157 // If such a node was found, return a pair where the second element is the 1158 // located node. If such a node does not exist, return a pair where the 1159 // first element is the element after which such a node should be inserted, 1160 // and the second element is a null-address. 1161 template <typename Predicate> 1162 std::pair<Ref, Ref> DataFlowGraph::locateNextRef(Instr IA, Ref RA, 1163 Predicate P) const { 1164 assert(IA.Id != 0 && RA.Id != 0); 1165 1166 Ref NA; 1167 NodeId Start = RA.Id; 1168 while (true) { 1169 NA = getNextRelated(IA, RA); 1170 if (NA.Id == 0 || NA.Id == Start) 1171 break; 1172 if (P(NA)) 1173 break; 1174 RA = NA; 1175 } 1176 1177 if (NA.Id != 0 && NA.Id != Start) 1178 return std::make_pair(RA, NA); 1179 return std::make_pair(RA, Ref()); 1180 } 1181 1182 // Get the next shadow node in IA corresponding to RA, and optionally create 1183 // such a node if it does not exist. 1184 Ref DataFlowGraph::getNextShadow(Instr IA, Ref RA, bool Create) { 1185 assert(IA.Id != 0 && RA.Id != 0); 1186 1187 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow; 1188 auto IsShadow = [Flags](Ref TA) -> bool { 1189 return TA.Addr->getFlags() == Flags; 1190 }; 1191 auto Loc = locateNextRef(IA, RA, IsShadow); 1192 if (Loc.second.Id != 0 || !Create) 1193 return Loc.second; 1194 1195 // Create a copy of RA and mark is as shadow. 1196 Ref NA = cloneNode(RA); 1197 NA.Addr->setFlags(Flags | NodeAttrs::Shadow); 1198 IA.Addr->addMemberAfter(Loc.first, NA, *this); 1199 return NA; 1200 } 1201 1202 // Get the next shadow node in IA corresponding to RA. Return null-address 1203 // if such a node does not exist. 1204 Ref DataFlowGraph::getNextShadow(Instr IA, Ref RA) const { 1205 assert(IA.Id != 0 && RA.Id != 0); 1206 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow; 1207 auto IsShadow = [Flags](Ref TA) -> bool { 1208 return TA.Addr->getFlags() == Flags; 1209 }; 1210 return locateNextRef(IA, RA, IsShadow).second; 1211 } 1212 1213 // Create a new statement node in the block node BA that corresponds to 1214 // the machine instruction MI. 1215 void DataFlowGraph::buildStmt(Block BA, MachineInstr &In) { 1216 Stmt SA = newStmt(BA, &In); 1217 1218 auto isCall = [](const MachineInstr &In) -> bool { 1219 if (In.isCall()) 1220 return true; 1221 // Is tail call? 1222 if (In.isBranch()) { 1223 for (const MachineOperand &Op : In.operands()) 1224 if (Op.isGlobal() || Op.isSymbol()) 1225 return true; 1226 // Assume indirect branches are calls. This is for the purpose of 1227 // keeping implicit operands, and so it won't hurt on intra-function 1228 // indirect branches. 1229 if (In.isIndirectBranch()) 1230 return true; 1231 } 1232 return false; 1233 }; 1234 1235 auto isDefUndef = [this](const MachineInstr &In, RegisterRef DR) -> bool { 1236 // This instruction defines DR. Check if there is a use operand that 1237 // would make DR live on entry to the instruction. 1238 for (const MachineOperand &Op : In.all_uses()) { 1239 if (Op.getReg() == 0 || Op.isUndef()) 1240 continue; 1241 RegisterRef UR = makeRegRef(Op); 1242 if (getPRI().alias(DR, UR)) 1243 return false; 1244 } 1245 return true; 1246 }; 1247 1248 bool IsCall = isCall(In); 1249 unsigned NumOps = In.getNumOperands(); 1250 1251 // Avoid duplicate implicit defs. This will not detect cases of implicit 1252 // defs that define registers that overlap, but it is not clear how to 1253 // interpret that in the absence of explicit defs. Overlapping explicit 1254 // defs are likely illegal already. 1255 BitVector DoneDefs(TRI.getNumRegs()); 1256 // Process explicit defs first. 1257 for (unsigned OpN = 0; OpN < NumOps; ++OpN) { 1258 MachineOperand &Op = In.getOperand(OpN); 1259 if (!Op.isReg() || !Op.isDef() || Op.isImplicit()) 1260 continue; 1261 Register R = Op.getReg(); 1262 if (!R || !R.isPhysical()) 1263 continue; 1264 uint16_t Flags = NodeAttrs::None; 1265 if (TOI.isPreserving(In, OpN)) { 1266 Flags |= NodeAttrs::Preserving; 1267 // If the def is preserving, check if it is also undefined. 1268 if (isDefUndef(In, makeRegRef(Op))) 1269 Flags |= NodeAttrs::Undef; 1270 } 1271 if (TOI.isClobbering(In, OpN)) 1272 Flags |= NodeAttrs::Clobbering; 1273 if (TOI.isFixedReg(In, OpN)) 1274 Flags |= NodeAttrs::Fixed; 1275 if (IsCall && Op.isDead()) 1276 Flags |= NodeAttrs::Dead; 1277 Def DA = newDef(SA, Op, Flags); 1278 SA.Addr->addMember(DA, *this); 1279 assert(!DoneDefs.test(R)); 1280 DoneDefs.set(R); 1281 } 1282 1283 // Process reg-masks (as clobbers). 1284 BitVector DoneClobbers(TRI.getNumRegs()); 1285 for (unsigned OpN = 0; OpN < NumOps; ++OpN) { 1286 MachineOperand &Op = In.getOperand(OpN); 1287 if (!Op.isRegMask()) 1288 continue; 1289 uint16_t Flags = NodeAttrs::Clobbering | NodeAttrs::Fixed | NodeAttrs::Dead; 1290 Def DA = newDef(SA, Op, Flags); 1291 SA.Addr->addMember(DA, *this); 1292 // Record all clobbered registers in DoneDefs. 1293 const uint32_t *RM = Op.getRegMask(); 1294 for (unsigned i = 1, e = TRI.getNumRegs(); i != e; ++i) 1295 if (!(RM[i / 32] & (1u << (i % 32)))) 1296 DoneClobbers.set(i); 1297 } 1298 1299 // Process implicit defs, skipping those that have already been added 1300 // as explicit. 1301 for (unsigned OpN = 0; OpN < NumOps; ++OpN) { 1302 MachineOperand &Op = In.getOperand(OpN); 1303 if (!Op.isReg() || !Op.isDef() || !Op.isImplicit()) 1304 continue; 1305 Register R = Op.getReg(); 1306 if (!R || !R.isPhysical() || DoneDefs.test(R)) 1307 continue; 1308 RegisterRef RR = makeRegRef(Op); 1309 uint16_t Flags = NodeAttrs::None; 1310 if (TOI.isPreserving(In, OpN)) { 1311 Flags |= NodeAttrs::Preserving; 1312 // If the def is preserving, check if it is also undefined. 1313 if (isDefUndef(In, RR)) 1314 Flags |= NodeAttrs::Undef; 1315 } 1316 if (TOI.isClobbering(In, OpN)) 1317 Flags |= NodeAttrs::Clobbering; 1318 if (TOI.isFixedReg(In, OpN)) 1319 Flags |= NodeAttrs::Fixed; 1320 if (IsCall && Op.isDead()) { 1321 if (DoneClobbers.test(R)) 1322 continue; 1323 Flags |= NodeAttrs::Dead; 1324 } 1325 Def DA = newDef(SA, Op, Flags); 1326 SA.Addr->addMember(DA, *this); 1327 DoneDefs.set(R); 1328 } 1329 1330 for (unsigned OpN = 0; OpN < NumOps; ++OpN) { 1331 MachineOperand &Op = In.getOperand(OpN); 1332 if (!Op.isReg() || !Op.isUse()) 1333 continue; 1334 Register R = Op.getReg(); 1335 if (!R || !R.isPhysical()) 1336 continue; 1337 uint16_t Flags = NodeAttrs::None; 1338 if (Op.isUndef()) 1339 Flags |= NodeAttrs::Undef; 1340 if (TOI.isFixedReg(In, OpN)) 1341 Flags |= NodeAttrs::Fixed; 1342 Use UA = newUse(SA, Op, Flags); 1343 SA.Addr->addMember(UA, *this); 1344 } 1345 } 1346 1347 // Scan all defs in the block node BA and record in PhiM the locations of 1348 // phi nodes corresponding to these defs. 1349 void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM, Block BA) { 1350 // Check all defs from block BA and record them in each block in BA's 1351 // iterated dominance frontier. This information will later be used to 1352 // create phi nodes. 1353 MachineBasicBlock *BB = BA.Addr->getCode(); 1354 assert(BB); 1355 auto DFLoc = MDF.find(BB); 1356 if (DFLoc == MDF.end() || DFLoc->second.empty()) 1357 return; 1358 1359 // Traverse all instructions in the block and collect the set of all 1360 // defined references. For each reference there will be a phi created 1361 // in the block's iterated dominance frontier. 1362 // This is done to make sure that each defined reference gets only one 1363 // phi node, even if it is defined multiple times. 1364 RegisterAggr Defs(getPRI()); 1365 for (Instr IA : BA.Addr->members(*this)) 1366 for (Ref RA : IA.Addr->members_if(IsDef, *this)) 1367 Defs.insert(RA.Addr->getRegRef(*this)); 1368 1369 // Calculate the iterated dominance frontier of BB. 1370 const MachineDominanceFrontier::DomSetType &DF = DFLoc->second; 1371 SetVector<MachineBasicBlock *> IDF(DF.begin(), DF.end()); 1372 for (unsigned i = 0; i < IDF.size(); ++i) { 1373 auto F = MDF.find(IDF[i]); 1374 if (F != MDF.end()) 1375 IDF.insert(F->second.begin(), F->second.end()); 1376 } 1377 1378 // Finally, add the set of defs to each block in the iterated dominance 1379 // frontier. 1380 for (auto *DB : IDF) { 1381 Block DBA = findBlock(DB); 1382 PhiM[DBA.Id].insert(Defs); 1383 } 1384 } 1385 1386 // Given the locations of phi nodes in the map PhiM, create the phi nodes 1387 // that are located in the block node BA. 1388 void DataFlowGraph::buildPhis(BlockRefsMap &PhiM, RegisterSet &AllRefs, 1389 Block BA) { 1390 // Check if this blocks has any DF defs, i.e. if there are any defs 1391 // that this block is in the iterated dominance frontier of. 1392 auto HasDF = PhiM.find(BA.Id); 1393 if (HasDF == PhiM.end() || HasDF->second.empty()) 1394 return; 1395 1396 // Prepare a list of NodeIds of the block's predecessors. 1397 NodeList Preds; 1398 const MachineBasicBlock *MBB = BA.Addr->getCode(); 1399 for (MachineBasicBlock *PB : MBB->predecessors()) 1400 Preds.push_back(findBlock(PB)); 1401 1402 const RegisterAggr &Defs = PhiM[BA.Id]; 1403 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving; 1404 1405 for (RegisterRef RR : Defs.refs()) { 1406 Phi PA = newPhi(BA); 1407 PA.Addr->addMember(newDef(PA, RR, PhiFlags), *this); 1408 1409 // Add phi uses. 1410 for (Block PBA : Preds) { 1411 PA.Addr->addMember(newPhiUse(PA, RR, PBA), *this); 1412 } 1413 } 1414 } 1415 1416 // Remove any unneeded phi nodes that were created during the build process. 1417 void DataFlowGraph::removeUnusedPhis() { 1418 // This will remove unused phis, i.e. phis where each def does not reach 1419 // any uses or other defs. This will not detect or remove circular phi 1420 // chains that are otherwise dead. Unused/dead phis are created during 1421 // the build process and this function is intended to remove these cases 1422 // that are easily determinable to be unnecessary. 1423 1424 SetVector<NodeId> PhiQ; 1425 for (Block BA : TheFunc.Addr->members(*this)) { 1426 for (auto P : BA.Addr->members_if(IsPhi, *this)) 1427 PhiQ.insert(P.Id); 1428 } 1429 1430 static auto HasUsedDef = [](NodeList &Ms) -> bool { 1431 for (Node M : Ms) { 1432 if (M.Addr->getKind() != NodeAttrs::Def) 1433 continue; 1434 Def DA = M; 1435 if (DA.Addr->getReachedDef() != 0 || DA.Addr->getReachedUse() != 0) 1436 return true; 1437 } 1438 return false; 1439 }; 1440 1441 // Any phi, if it is removed, may affect other phis (make them dead). 1442 // For each removed phi, collect the potentially affected phis and add 1443 // them back to the queue. 1444 while (!PhiQ.empty()) { 1445 auto PA = addr<PhiNode *>(PhiQ[0]); 1446 PhiQ.remove(PA.Id); 1447 NodeList Refs = PA.Addr->members(*this); 1448 if (HasUsedDef(Refs)) 1449 continue; 1450 for (Ref RA : Refs) { 1451 if (NodeId RD = RA.Addr->getReachingDef()) { 1452 auto RDA = addr<DefNode *>(RD); 1453 Instr OA = RDA.Addr->getOwner(*this); 1454 if (IsPhi(OA)) 1455 PhiQ.insert(OA.Id); 1456 } 1457 if (RA.Addr->isDef()) 1458 unlinkDef(RA, true); 1459 else 1460 unlinkUse(RA, true); 1461 } 1462 Block BA = PA.Addr->getOwner(*this); 1463 BA.Addr->removeMember(PA, *this); 1464 } 1465 } 1466 1467 // For a given reference node TA in an instruction node IA, connect the 1468 // reaching def of TA to the appropriate def node. Create any shadow nodes 1469 // as appropriate. 1470 template <typename T> 1471 void DataFlowGraph::linkRefUp(Instr IA, NodeAddr<T> TA, DefStack &DS) { 1472 if (DS.empty()) 1473 return; 1474 RegisterRef RR = TA.Addr->getRegRef(*this); 1475 NodeAddr<T> TAP; 1476 1477 // References from the def stack that have been examined so far. 1478 RegisterAggr Defs(getPRI()); 1479 1480 for (auto I = DS.top(), E = DS.bottom(); I != E; I.down()) { 1481 RegisterRef QR = I->Addr->getRegRef(*this); 1482 1483 // Skip all defs that are aliased to any of the defs that we have already 1484 // seen. If this completes a cover of RR, stop the stack traversal. 1485 bool Alias = Defs.hasAliasOf(QR); 1486 bool Cover = Defs.insert(QR).hasCoverOf(RR); 1487 if (Alias) { 1488 if (Cover) 1489 break; 1490 continue; 1491 } 1492 1493 // The reaching def. 1494 Def RDA = *I; 1495 1496 // Pick the reached node. 1497 if (TAP.Id == 0) { 1498 TAP = TA; 1499 } else { 1500 // Mark the existing ref as "shadow" and create a new shadow. 1501 TAP.Addr->setFlags(TAP.Addr->getFlags() | NodeAttrs::Shadow); 1502 TAP = getNextShadow(IA, TAP, true); 1503 } 1504 1505 // Create the link. 1506 TAP.Addr->linkToDef(TAP.Id, RDA); 1507 1508 if (Cover) 1509 break; 1510 } 1511 } 1512 1513 // Create data-flow links for all reference nodes in the statement node SA. 1514 template <typename Predicate> 1515 void DataFlowGraph::linkStmtRefs(DefStackMap &DefM, Stmt SA, Predicate P) { 1516 #ifndef NDEBUG 1517 RegisterSet Defs(getPRI()); 1518 #endif 1519 1520 // Link all nodes (upwards in the data-flow) with their reaching defs. 1521 for (Ref RA : SA.Addr->members_if(P, *this)) { 1522 uint16_t Kind = RA.Addr->getKind(); 1523 assert(Kind == NodeAttrs::Def || Kind == NodeAttrs::Use); 1524 RegisterRef RR = RA.Addr->getRegRef(*this); 1525 #ifndef NDEBUG 1526 // Do not expect multiple defs of the same reference. 1527 assert(Kind != NodeAttrs::Def || !Defs.count(RR)); 1528 Defs.insert(RR); 1529 #endif 1530 1531 auto F = DefM.find(RR.Reg); 1532 if (F == DefM.end()) 1533 continue; 1534 DefStack &DS = F->second; 1535 if (Kind == NodeAttrs::Use) 1536 linkRefUp<UseNode *>(SA, RA, DS); 1537 else if (Kind == NodeAttrs::Def) 1538 linkRefUp<DefNode *>(SA, RA, DS); 1539 else 1540 llvm_unreachable("Unexpected node in instruction"); 1541 } 1542 } 1543 1544 // Create data-flow links for all instructions in the block node BA. This 1545 // will include updating any phi nodes in BA. 1546 void DataFlowGraph::linkBlockRefs(DefStackMap &DefM, Block BA) { 1547 // Push block delimiters. 1548 markBlock(BA.Id, DefM); 1549 1550 auto IsClobber = [](Ref RA) -> bool { 1551 return IsDef(RA) && (RA.Addr->getFlags() & NodeAttrs::Clobbering); 1552 }; 1553 auto IsNoClobber = [](Ref RA) -> bool { 1554 return IsDef(RA) && !(RA.Addr->getFlags() & NodeAttrs::Clobbering); 1555 }; 1556 1557 assert(BA.Addr && "block node address is needed to create a data-flow link"); 1558 // For each non-phi instruction in the block, link all the defs and uses 1559 // to their reaching defs. For any member of the block (including phis), 1560 // push the defs on the corresponding stacks. 1561 for (Instr IA : BA.Addr->members(*this)) { 1562 // Ignore phi nodes here. They will be linked part by part from the 1563 // predecessors. 1564 if (IA.Addr->getKind() == NodeAttrs::Stmt) { 1565 linkStmtRefs(DefM, IA, IsUse); 1566 linkStmtRefs(DefM, IA, IsClobber); 1567 } 1568 1569 // Push the definitions on the stack. 1570 pushClobbers(IA, DefM); 1571 1572 if (IA.Addr->getKind() == NodeAttrs::Stmt) 1573 linkStmtRefs(DefM, IA, IsNoClobber); 1574 1575 pushDefs(IA, DefM); 1576 } 1577 1578 // Recursively process all children in the dominator tree. 1579 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode()); 1580 for (auto *I : *N) { 1581 MachineBasicBlock *SB = I->getBlock(); 1582 Block SBA = findBlock(SB); 1583 linkBlockRefs(DefM, SBA); 1584 } 1585 1586 // Link the phi uses from the successor blocks. 1587 auto IsUseForBA = [BA](Node NA) -> bool { 1588 if (NA.Addr->getKind() != NodeAttrs::Use) 1589 return false; 1590 assert(NA.Addr->getFlags() & NodeAttrs::PhiRef); 1591 PhiUse PUA = NA; 1592 return PUA.Addr->getPredecessor() == BA.Id; 1593 }; 1594 1595 RegisterAggr EHLiveIns = getLandingPadLiveIns(); 1596 MachineBasicBlock *MBB = BA.Addr->getCode(); 1597 1598 for (MachineBasicBlock *SB : MBB->successors()) { 1599 bool IsEHPad = SB->isEHPad(); 1600 Block SBA = findBlock(SB); 1601 for (Instr IA : SBA.Addr->members_if(IsPhi, *this)) { 1602 // Do not link phi uses for landing pad live-ins. 1603 if (IsEHPad) { 1604 // Find what register this phi is for. 1605 Ref RA = IA.Addr->getFirstMember(*this); 1606 assert(RA.Id != 0); 1607 if (EHLiveIns.hasCoverOf(RA.Addr->getRegRef(*this))) 1608 continue; 1609 } 1610 // Go over each phi use associated with MBB, and link it. 1611 for (auto U : IA.Addr->members_if(IsUseForBA, *this)) { 1612 PhiUse PUA = U; 1613 RegisterRef RR = PUA.Addr->getRegRef(*this); 1614 linkRefUp<UseNode *>(IA, PUA, DefM[RR.Reg]); 1615 } 1616 } 1617 } 1618 1619 // Pop all defs from this block from the definition stacks. 1620 releaseBlock(BA.Id, DefM); 1621 } 1622 1623 // Remove the use node UA from any data-flow and structural links. 1624 void DataFlowGraph::unlinkUseDF(Use UA) { 1625 NodeId RD = UA.Addr->getReachingDef(); 1626 NodeId Sib = UA.Addr->getSibling(); 1627 1628 if (RD == 0) { 1629 assert(Sib == 0); 1630 return; 1631 } 1632 1633 auto RDA = addr<DefNode *>(RD); 1634 auto TA = addr<UseNode *>(RDA.Addr->getReachedUse()); 1635 if (TA.Id == UA.Id) { 1636 RDA.Addr->setReachedUse(Sib); 1637 return; 1638 } 1639 1640 while (TA.Id != 0) { 1641 NodeId S = TA.Addr->getSibling(); 1642 if (S == UA.Id) { 1643 TA.Addr->setSibling(UA.Addr->getSibling()); 1644 return; 1645 } 1646 TA = addr<UseNode *>(S); 1647 } 1648 } 1649 1650 // Remove the def node DA from any data-flow and structural links. 1651 void DataFlowGraph::unlinkDefDF(Def DA) { 1652 // 1653 // RD 1654 // | reached 1655 // | def 1656 // : 1657 // . 1658 // +----+ 1659 // ... -- | DA | -- ... -- 0 : sibling chain of DA 1660 // +----+ 1661 // | | reached 1662 // | : def 1663 // | . 1664 // | ... : Siblings (defs) 1665 // | 1666 // : reached 1667 // . use 1668 // ... : sibling chain of reached uses 1669 1670 NodeId RD = DA.Addr->getReachingDef(); 1671 1672 // Visit all siblings of the reached def and reset their reaching defs. 1673 // Also, defs reached by DA are now "promoted" to being reached by RD, 1674 // so all of them will need to be spliced into the sibling chain where 1675 // DA belongs. 1676 auto getAllNodes = [this](NodeId N) -> NodeList { 1677 NodeList Res; 1678 while (N) { 1679 auto RA = addr<RefNode *>(N); 1680 // Keep the nodes in the exact sibling order. 1681 Res.push_back(RA); 1682 N = RA.Addr->getSibling(); 1683 } 1684 return Res; 1685 }; 1686 NodeList ReachedDefs = getAllNodes(DA.Addr->getReachedDef()); 1687 NodeList ReachedUses = getAllNodes(DA.Addr->getReachedUse()); 1688 1689 if (RD == 0) { 1690 for (Ref I : ReachedDefs) 1691 I.Addr->setSibling(0); 1692 for (Ref I : ReachedUses) 1693 I.Addr->setSibling(0); 1694 } 1695 for (Def I : ReachedDefs) 1696 I.Addr->setReachingDef(RD); 1697 for (Use I : ReachedUses) 1698 I.Addr->setReachingDef(RD); 1699 1700 NodeId Sib = DA.Addr->getSibling(); 1701 if (RD == 0) { 1702 assert(Sib == 0); 1703 return; 1704 } 1705 1706 // Update the reaching def node and remove DA from the sibling list. 1707 auto RDA = addr<DefNode *>(RD); 1708 auto TA = addr<DefNode *>(RDA.Addr->getReachedDef()); 1709 if (TA.Id == DA.Id) { 1710 // If DA is the first reached def, just update the RD's reached def 1711 // to the DA's sibling. 1712 RDA.Addr->setReachedDef(Sib); 1713 } else { 1714 // Otherwise, traverse the sibling list of the reached defs and remove 1715 // DA from it. 1716 while (TA.Id != 0) { 1717 NodeId S = TA.Addr->getSibling(); 1718 if (S == DA.Id) { 1719 TA.Addr->setSibling(Sib); 1720 break; 1721 } 1722 TA = addr<DefNode *>(S); 1723 } 1724 } 1725 1726 // Splice the DA's reached defs into the RDA's reached def chain. 1727 if (!ReachedDefs.empty()) { 1728 auto Last = Def(ReachedDefs.back()); 1729 Last.Addr->setSibling(RDA.Addr->getReachedDef()); 1730 RDA.Addr->setReachedDef(ReachedDefs.front().Id); 1731 } 1732 // Splice the DA's reached uses into the RDA's reached use chain. 1733 if (!ReachedUses.empty()) { 1734 auto Last = Use(ReachedUses.back()); 1735 Last.Addr->setSibling(RDA.Addr->getReachedUse()); 1736 RDA.Addr->setReachedUse(ReachedUses.front().Id); 1737 } 1738 } 1739 1740 } // end namespace llvm::rdf 1741