1 //===--- HexagonCommonGEP.cpp ---------------------------------------------===// 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 10 #define DEBUG_TYPE "commgep" 11 12 #include "llvm/Pass.h" 13 #include "llvm/ADT/FoldingSet.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Analysis/LoopInfo.h" 16 #include "llvm/Analysis/PostDominators.h" 17 #include "llvm/IR/Constants.h" 18 #include "llvm/IR/Dominators.h" 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/Instructions.h" 21 #include "llvm/IR/Verifier.h" 22 #include "llvm/Support/Allocator.h" 23 #include "llvm/Support/CommandLine.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/Scalar.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 29 #include <map> 30 #include <set> 31 #include <vector> 32 33 #include "HexagonTargetMachine.h" 34 35 using namespace llvm; 36 37 static cl::opt<bool> OptSpeculate("commgep-speculate", cl::init(true), 38 cl::Hidden, cl::ZeroOrMore); 39 40 static cl::opt<bool> OptEnableInv("commgep-inv", cl::init(true), cl::Hidden, 41 cl::ZeroOrMore); 42 43 static cl::opt<bool> OptEnableConst("commgep-const", cl::init(true), 44 cl::Hidden, cl::ZeroOrMore); 45 46 namespace llvm { 47 void initializeHexagonCommonGEPPass(PassRegistry&); 48 } 49 50 namespace { 51 struct GepNode; 52 typedef std::set<GepNode*> NodeSet; 53 typedef std::map<GepNode*,Value*> NodeToValueMap; 54 typedef std::vector<GepNode*> NodeVect; 55 typedef std::map<GepNode*,NodeVect> NodeChildrenMap; 56 typedef std::set<Use*> UseSet; 57 typedef std::map<GepNode*,UseSet> NodeToUsesMap; 58 59 // Numbering map for gep nodes. Used to keep track of ordering for 60 // gep nodes. 61 struct NodeOrdering { 62 NodeOrdering() : LastNum(0) {} 63 64 void insert(const GepNode *N) { Map.insert(std::make_pair(N, ++LastNum)); } 65 void clear() { Map.clear(); } 66 67 bool operator()(const GepNode *N1, const GepNode *N2) const { 68 auto F1 = Map.find(N1), F2 = Map.find(N2); 69 assert(F1 != Map.end() && F2 != Map.end()); 70 return F1->second < F2->second; 71 } 72 73 private: 74 std::map<const GepNode *, unsigned> Map; 75 unsigned LastNum; 76 }; 77 78 class HexagonCommonGEP : public FunctionPass { 79 public: 80 static char ID; 81 HexagonCommonGEP() : FunctionPass(ID) { 82 initializeHexagonCommonGEPPass(*PassRegistry::getPassRegistry()); 83 } 84 virtual bool runOnFunction(Function &F); 85 virtual const char *getPassName() const { 86 return "Hexagon Common GEP"; 87 } 88 89 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 90 AU.addRequired<DominatorTreeWrapperPass>(); 91 AU.addPreserved<DominatorTreeWrapperPass>(); 92 AU.addRequired<PostDominatorTreeWrapperPass>(); 93 AU.addPreserved<PostDominatorTreeWrapperPass>(); 94 AU.addRequired<LoopInfoWrapperPass>(); 95 AU.addPreserved<LoopInfoWrapperPass>(); 96 FunctionPass::getAnalysisUsage(AU); 97 } 98 99 private: 100 typedef std::map<Value*,GepNode*> ValueToNodeMap; 101 typedef std::vector<Value*> ValueVect; 102 typedef std::map<GepNode*,ValueVect> NodeToValuesMap; 103 104 void getBlockTraversalOrder(BasicBlock *Root, ValueVect &Order); 105 bool isHandledGepForm(GetElementPtrInst *GepI); 106 void processGepInst(GetElementPtrInst *GepI, ValueToNodeMap &NM); 107 void collect(); 108 void common(); 109 110 BasicBlock *recalculatePlacement(GepNode *Node, NodeChildrenMap &NCM, 111 NodeToValueMap &Loc); 112 BasicBlock *recalculatePlacementRec(GepNode *Node, NodeChildrenMap &NCM, 113 NodeToValueMap &Loc); 114 bool isInvariantIn(Value *Val, Loop *L); 115 bool isInvariantIn(GepNode *Node, Loop *L); 116 bool isInMainPath(BasicBlock *B, Loop *L); 117 BasicBlock *adjustForInvariance(GepNode *Node, NodeChildrenMap &NCM, 118 NodeToValueMap &Loc); 119 void separateChainForNode(GepNode *Node, Use *U, NodeToValueMap &Loc); 120 void separateConstantChains(GepNode *Node, NodeChildrenMap &NCM, 121 NodeToValueMap &Loc); 122 void computeNodePlacement(NodeToValueMap &Loc); 123 124 Value *fabricateGEP(NodeVect &NA, BasicBlock::iterator At, 125 BasicBlock *LocB); 126 void getAllUsersForNode(GepNode *Node, ValueVect &Values, 127 NodeChildrenMap &NCM); 128 void materialize(NodeToValueMap &Loc); 129 130 void removeDeadCode(); 131 132 NodeVect Nodes; 133 NodeToUsesMap Uses; 134 NodeOrdering NodeOrder; // Node ordering, for deterministic behavior. 135 SpecificBumpPtrAllocator<GepNode> *Mem; 136 LLVMContext *Ctx; 137 LoopInfo *LI; 138 DominatorTree *DT; 139 PostDominatorTree *PDT; 140 Function *Fn; 141 }; 142 } 143 144 145 char HexagonCommonGEP::ID = 0; 146 INITIALIZE_PASS_BEGIN(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP", 147 false, false) 148 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 149 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 150 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 151 INITIALIZE_PASS_END(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP", 152 false, false) 153 154 namespace { 155 struct GepNode { 156 enum { 157 None = 0, 158 Root = 0x01, 159 Internal = 0x02, 160 Used = 0x04 161 }; 162 163 uint32_t Flags; 164 union { 165 GepNode *Parent; 166 Value *BaseVal; 167 }; 168 Value *Idx; 169 Type *PTy; // Type of the pointer operand. 170 171 GepNode() : Flags(0), Parent(0), Idx(0), PTy(0) {} 172 GepNode(const GepNode *N) : Flags(N->Flags), Idx(N->Idx), PTy(N->PTy) { 173 if (Flags & Root) 174 BaseVal = N->BaseVal; 175 else 176 Parent = N->Parent; 177 } 178 friend raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN); 179 }; 180 181 182 Type *next_type(Type *Ty, Value *Idx) { 183 // Advance the type. 184 if (!Ty->isStructTy()) { 185 Type *NexTy = cast<SequentialType>(Ty)->getElementType(); 186 return NexTy; 187 } 188 // Otherwise it is a struct type. 189 ConstantInt *CI = dyn_cast<ConstantInt>(Idx); 190 assert(CI && "Struct type with non-constant index"); 191 int64_t i = CI->getValue().getSExtValue(); 192 Type *NextTy = cast<StructType>(Ty)->getElementType(i); 193 return NextTy; 194 } 195 196 197 raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN) { 198 OS << "{ {"; 199 bool Comma = false; 200 if (GN.Flags & GepNode::Root) { 201 OS << "root"; 202 Comma = true; 203 } 204 if (GN.Flags & GepNode::Internal) { 205 if (Comma) 206 OS << ','; 207 OS << "internal"; 208 Comma = true; 209 } 210 if (GN.Flags & GepNode::Used) { 211 if (Comma) 212 OS << ','; 213 OS << "used"; 214 } 215 OS << "} "; 216 if (GN.Flags & GepNode::Root) 217 OS << "BaseVal:" << GN.BaseVal->getName() << '(' << GN.BaseVal << ')'; 218 else 219 OS << "Parent:" << GN.Parent; 220 221 OS << " Idx:"; 222 if (ConstantInt *CI = dyn_cast<ConstantInt>(GN.Idx)) 223 OS << CI->getValue().getSExtValue(); 224 else if (GN.Idx->hasName()) 225 OS << GN.Idx->getName(); 226 else 227 OS << "<anon> =" << *GN.Idx; 228 229 OS << " PTy:"; 230 if (GN.PTy->isStructTy()) { 231 StructType *STy = cast<StructType>(GN.PTy); 232 if (!STy->isLiteral()) 233 OS << GN.PTy->getStructName(); 234 else 235 OS << "<anon-struct>:" << *STy; 236 } 237 else 238 OS << *GN.PTy; 239 OS << " }"; 240 return OS; 241 } 242 243 244 template <typename NodeContainer> 245 void dump_node_container(raw_ostream &OS, const NodeContainer &S) { 246 typedef typename NodeContainer::const_iterator const_iterator; 247 for (const_iterator I = S.begin(), E = S.end(); I != E; ++I) 248 OS << *I << ' ' << **I << '\n'; 249 } 250 251 raw_ostream &operator<< (raw_ostream &OS, 252 const NodeVect &S) LLVM_ATTRIBUTE_UNUSED; 253 raw_ostream &operator<< (raw_ostream &OS, const NodeVect &S) { 254 dump_node_container(OS, S); 255 return OS; 256 } 257 258 259 raw_ostream &operator<< (raw_ostream &OS, 260 const NodeToUsesMap &M) LLVM_ATTRIBUTE_UNUSED; 261 raw_ostream &operator<< (raw_ostream &OS, const NodeToUsesMap &M){ 262 typedef NodeToUsesMap::const_iterator const_iterator; 263 for (const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 264 const UseSet &Us = I->second; 265 OS << I->first << " -> #" << Us.size() << '{'; 266 for (UseSet::const_iterator J = Us.begin(), F = Us.end(); J != F; ++J) { 267 User *R = (*J)->getUser(); 268 if (R->hasName()) 269 OS << ' ' << R->getName(); 270 else 271 OS << " <?>(" << *R << ')'; 272 } 273 OS << " }\n"; 274 } 275 return OS; 276 } 277 278 279 struct in_set { 280 in_set(const NodeSet &S) : NS(S) {} 281 bool operator() (GepNode *N) const { 282 return NS.find(N) != NS.end(); 283 } 284 private: 285 const NodeSet &NS; 286 }; 287 } 288 289 290 inline void *operator new(size_t, SpecificBumpPtrAllocator<GepNode> &A) { 291 return A.Allocate(); 292 } 293 294 295 void HexagonCommonGEP::getBlockTraversalOrder(BasicBlock *Root, 296 ValueVect &Order) { 297 // Compute block ordering for a typical DT-based traversal of the flow 298 // graph: "before visiting a block, all of its dominators must have been 299 // visited". 300 301 Order.push_back(Root); 302 DomTreeNode *DTN = DT->getNode(Root); 303 typedef GraphTraits<DomTreeNode*> GTN; 304 typedef GTN::ChildIteratorType Iter; 305 for (Iter I = GTN::child_begin(DTN), E = GTN::child_end(DTN); I != E; ++I) 306 getBlockTraversalOrder((*I)->getBlock(), Order); 307 } 308 309 310 bool HexagonCommonGEP::isHandledGepForm(GetElementPtrInst *GepI) { 311 // No vector GEPs. 312 if (!GepI->getType()->isPointerTy()) 313 return false; 314 // No GEPs without any indices. (Is this possible?) 315 if (GepI->idx_begin() == GepI->idx_end()) 316 return false; 317 return true; 318 } 319 320 321 void HexagonCommonGEP::processGepInst(GetElementPtrInst *GepI, 322 ValueToNodeMap &NM) { 323 DEBUG(dbgs() << "Visiting GEP: " << *GepI << '\n'); 324 GepNode *N = new (*Mem) GepNode; 325 Value *PtrOp = GepI->getPointerOperand(); 326 ValueToNodeMap::iterator F = NM.find(PtrOp); 327 if (F == NM.end()) { 328 N->BaseVal = PtrOp; 329 N->Flags |= GepNode::Root; 330 } else { 331 // If PtrOp was a GEP instruction, it must have already been processed. 332 // The ValueToNodeMap entry for it is the last gep node in the generated 333 // chain. Link to it here. 334 N->Parent = F->second; 335 } 336 N->PTy = PtrOp->getType(); 337 N->Idx = *GepI->idx_begin(); 338 339 // Collect the list of users of this GEP instruction. Will add it to the 340 // last node created for it. 341 UseSet Us; 342 for (Value::user_iterator UI = GepI->user_begin(), UE = GepI->user_end(); 343 UI != UE; ++UI) { 344 // Check if this gep is used by anything other than other geps that 345 // we will process. 346 if (isa<GetElementPtrInst>(*UI)) { 347 GetElementPtrInst *UserG = cast<GetElementPtrInst>(*UI); 348 if (isHandledGepForm(UserG)) 349 continue; 350 } 351 Us.insert(&UI.getUse()); 352 } 353 Nodes.push_back(N); 354 NodeOrder.insert(N); 355 356 // Skip the first index operand, since we only handle 0. This dereferences 357 // the pointer operand. 358 GepNode *PN = N; 359 Type *PtrTy = cast<PointerType>(PtrOp->getType())->getElementType(); 360 for (User::op_iterator OI = GepI->idx_begin()+1, OE = GepI->idx_end(); 361 OI != OE; ++OI) { 362 Value *Op = *OI; 363 GepNode *Nx = new (*Mem) GepNode; 364 Nx->Parent = PN; // Link Nx to the previous node. 365 Nx->Flags |= GepNode::Internal; 366 Nx->PTy = PtrTy; 367 Nx->Idx = Op; 368 Nodes.push_back(Nx); 369 NodeOrder.insert(Nx); 370 PN = Nx; 371 372 PtrTy = next_type(PtrTy, Op); 373 } 374 375 // After last node has been created, update the use information. 376 if (!Us.empty()) { 377 PN->Flags |= GepNode::Used; 378 Uses[PN].insert(Us.begin(), Us.end()); 379 } 380 381 // Link the last node with the originating GEP instruction. This is to 382 // help with linking chained GEP instructions. 383 NM.insert(std::make_pair(GepI, PN)); 384 } 385 386 387 void HexagonCommonGEP::collect() { 388 // Establish depth-first traversal order of the dominator tree. 389 ValueVect BO; 390 getBlockTraversalOrder(&Fn->front(), BO); 391 392 // The creation of gep nodes requires DT-traversal. When processing a GEP 393 // instruction that uses another GEP instruction as the base pointer, the 394 // gep node for the base pointer should already exist. 395 ValueToNodeMap NM; 396 for (ValueVect::iterator I = BO.begin(), E = BO.end(); I != E; ++I) { 397 BasicBlock *B = cast<BasicBlock>(*I); 398 for (BasicBlock::iterator J = B->begin(), F = B->end(); J != F; ++J) { 399 if (!isa<GetElementPtrInst>(J)) 400 continue; 401 GetElementPtrInst *GepI = cast<GetElementPtrInst>(J); 402 if (isHandledGepForm(GepI)) 403 processGepInst(GepI, NM); 404 } 405 } 406 407 DEBUG(dbgs() << "Gep nodes after initial collection:\n" << Nodes); 408 } 409 410 411 namespace { 412 void invert_find_roots(const NodeVect &Nodes, NodeChildrenMap &NCM, 413 NodeVect &Roots) { 414 typedef NodeVect::const_iterator const_iterator; 415 for (const_iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) { 416 GepNode *N = *I; 417 if (N->Flags & GepNode::Root) { 418 Roots.push_back(N); 419 continue; 420 } 421 GepNode *PN = N->Parent; 422 NCM[PN].push_back(N); 423 } 424 } 425 426 void nodes_for_root(GepNode *Root, NodeChildrenMap &NCM, NodeSet &Nodes) { 427 NodeVect Work; 428 Work.push_back(Root); 429 Nodes.insert(Root); 430 431 while (!Work.empty()) { 432 NodeVect::iterator First = Work.begin(); 433 GepNode *N = *First; 434 Work.erase(First); 435 NodeChildrenMap::iterator CF = NCM.find(N); 436 if (CF != NCM.end()) { 437 Work.insert(Work.end(), CF->second.begin(), CF->second.end()); 438 Nodes.insert(CF->second.begin(), CF->second.end()); 439 } 440 } 441 } 442 } 443 444 445 namespace { 446 typedef std::set<NodeSet> NodeSymRel; 447 typedef std::pair<GepNode*,GepNode*> NodePair; 448 typedef std::set<NodePair> NodePairSet; 449 450 const NodeSet *node_class(GepNode *N, NodeSymRel &Rel) { 451 for (NodeSymRel::iterator I = Rel.begin(), E = Rel.end(); I != E; ++I) 452 if (I->count(N)) 453 return &*I; 454 return 0; 455 } 456 457 // Create an ordered pair of GepNode pointers. The pair will be used in 458 // determining equality. The only purpose of the ordering is to eliminate 459 // duplication due to the commutativity of equality/non-equality. 460 NodePair node_pair(GepNode *N1, GepNode *N2) { 461 uintptr_t P1 = uintptr_t(N1), P2 = uintptr_t(N2); 462 if (P1 <= P2) 463 return std::make_pair(N1, N2); 464 return std::make_pair(N2, N1); 465 } 466 467 unsigned node_hash(GepNode *N) { 468 // Include everything except flags and parent. 469 FoldingSetNodeID ID; 470 ID.AddPointer(N->Idx); 471 ID.AddPointer(N->PTy); 472 return ID.ComputeHash(); 473 } 474 475 bool node_eq(GepNode *N1, GepNode *N2, NodePairSet &Eq, NodePairSet &Ne) { 476 // Don't cache the result for nodes with different hashes. The hash 477 // comparison is fast enough. 478 if (node_hash(N1) != node_hash(N2)) 479 return false; 480 481 NodePair NP = node_pair(N1, N2); 482 NodePairSet::iterator FEq = Eq.find(NP); 483 if (FEq != Eq.end()) 484 return true; 485 NodePairSet::iterator FNe = Ne.find(NP); 486 if (FNe != Ne.end()) 487 return false; 488 // Not previously compared. 489 bool Root1 = N1->Flags & GepNode::Root; 490 bool Root2 = N2->Flags & GepNode::Root; 491 NodePair P = node_pair(N1, N2); 492 // If the Root flag has different values, the nodes are different. 493 // If both nodes are root nodes, but their base pointers differ, 494 // they are different. 495 if (Root1 != Root2 || (Root1 && N1->BaseVal != N2->BaseVal)) { 496 Ne.insert(P); 497 return false; 498 } 499 // Here the root flags are identical, and for root nodes the 500 // base pointers are equal, so the root nodes are equal. 501 // For non-root nodes, compare their parent nodes. 502 if (Root1 || node_eq(N1->Parent, N2->Parent, Eq, Ne)) { 503 Eq.insert(P); 504 return true; 505 } 506 return false; 507 } 508 } 509 510 511 void HexagonCommonGEP::common() { 512 // The essence of this commoning is finding gep nodes that are equal. 513 // To do this we need to compare all pairs of nodes. To save time, 514 // first, partition the set of all nodes into sets of potentially equal 515 // nodes, and then compare pairs from within each partition. 516 typedef std::map<unsigned,NodeSet> NodeSetMap; 517 NodeSetMap MaybeEq; 518 519 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) { 520 GepNode *N = *I; 521 unsigned H = node_hash(N); 522 MaybeEq[H].insert(N); 523 } 524 525 // Compute the equivalence relation for the gep nodes. Use two caches, 526 // one for equality and the other for non-equality. 527 NodeSymRel EqRel; // Equality relation (as set of equivalence classes). 528 NodePairSet Eq, Ne; // Caches. 529 for (NodeSetMap::iterator I = MaybeEq.begin(), E = MaybeEq.end(); 530 I != E; ++I) { 531 NodeSet &S = I->second; 532 for (NodeSet::iterator NI = S.begin(), NE = S.end(); NI != NE; ++NI) { 533 GepNode *N = *NI; 534 // If node already has a class, then the class must have been created 535 // in a prior iteration of this loop. Since equality is transitive, 536 // nothing more will be added to that class, so skip it. 537 if (node_class(N, EqRel)) 538 continue; 539 540 // Create a new class candidate now. 541 NodeSet C; 542 for (NodeSet::iterator NJ = std::next(NI); NJ != NE; ++NJ) 543 if (node_eq(N, *NJ, Eq, Ne)) 544 C.insert(*NJ); 545 // If Tmp is empty, N would be the only element in it. Don't bother 546 // creating a class for it then. 547 if (!C.empty()) { 548 C.insert(N); // Finalize the set before adding it to the relation. 549 std::pair<NodeSymRel::iterator, bool> Ins = EqRel.insert(C); 550 (void)Ins; 551 assert(Ins.second && "Cannot add a class"); 552 } 553 } 554 } 555 556 DEBUG({ 557 dbgs() << "Gep node equality:\n"; 558 for (NodePairSet::iterator I = Eq.begin(), E = Eq.end(); I != E; ++I) 559 dbgs() << "{ " << I->first << ", " << I->second << " }\n"; 560 561 dbgs() << "Gep equivalence classes:\n"; 562 for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) { 563 dbgs() << '{'; 564 const NodeSet &S = *I; 565 for (NodeSet::const_iterator J = S.begin(), F = S.end(); J != F; ++J) { 566 if (J != S.begin()) 567 dbgs() << ','; 568 dbgs() << ' ' << *J; 569 } 570 dbgs() << " }\n"; 571 } 572 }); 573 574 575 // Create a projection from a NodeSet to the minimal element in it. 576 typedef std::map<const NodeSet*,GepNode*> ProjMap; 577 ProjMap PM; 578 for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) { 579 const NodeSet &S = *I; 580 GepNode *Min = *std::min_element(S.begin(), S.end(), NodeOrder); 581 std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min)); 582 (void)Ins; 583 assert(Ins.second && "Cannot add minimal element"); 584 585 // Update the min element's flags, and user list. 586 uint32_t Flags = 0; 587 UseSet &MinUs = Uses[Min]; 588 for (NodeSet::iterator J = S.begin(), F = S.end(); J != F; ++J) { 589 GepNode *N = *J; 590 uint32_t NF = N->Flags; 591 // If N is used, append all original values of N to the list of 592 // original values of Min. 593 if (NF & GepNode::Used) 594 MinUs.insert(Uses[N].begin(), Uses[N].end()); 595 Flags |= NF; 596 } 597 if (MinUs.empty()) 598 Uses.erase(Min); 599 600 // The collected flags should include all the flags from the min element. 601 assert((Min->Flags & Flags) == Min->Flags); 602 Min->Flags = Flags; 603 } 604 605 // Commoning: for each non-root gep node, replace "Parent" with the 606 // selected (minimum) node from the corresponding equivalence class. 607 // If a given parent does not have an equivalence class, leave it 608 // unchanged (it means that it's the only element in its class). 609 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) { 610 GepNode *N = *I; 611 if (N->Flags & GepNode::Root) 612 continue; 613 const NodeSet *PC = node_class(N->Parent, EqRel); 614 if (!PC) 615 continue; 616 ProjMap::iterator F = PM.find(PC); 617 if (F == PM.end()) 618 continue; 619 // Found a replacement, use it. 620 GepNode *Rep = F->second; 621 N->Parent = Rep; 622 } 623 624 DEBUG(dbgs() << "Gep nodes after commoning:\n" << Nodes); 625 626 // Finally, erase the nodes that are no longer used. 627 NodeSet Erase; 628 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) { 629 GepNode *N = *I; 630 const NodeSet *PC = node_class(N, EqRel); 631 if (!PC) 632 continue; 633 ProjMap::iterator F = PM.find(PC); 634 if (F == PM.end()) 635 continue; 636 if (N == F->second) 637 continue; 638 // Node for removal. 639 Erase.insert(*I); 640 } 641 NodeVect::iterator NewE = remove_if(Nodes, in_set(Erase)); 642 Nodes.resize(std::distance(Nodes.begin(), NewE)); 643 644 DEBUG(dbgs() << "Gep nodes after post-commoning cleanup:\n" << Nodes); 645 } 646 647 648 namespace { 649 template <typename T> 650 BasicBlock *nearest_common_dominator(DominatorTree *DT, T &Blocks) { 651 DEBUG({ 652 dbgs() << "NCD of {"; 653 for (typename T::iterator I = Blocks.begin(), E = Blocks.end(); 654 I != E; ++I) { 655 if (!*I) 656 continue; 657 BasicBlock *B = cast<BasicBlock>(*I); 658 dbgs() << ' ' << B->getName(); 659 } 660 dbgs() << " }\n"; 661 }); 662 663 // Allow null basic blocks in Blocks. In such cases, return 0. 664 typename T::iterator I = Blocks.begin(), E = Blocks.end(); 665 if (I == E || !*I) 666 return 0; 667 BasicBlock *Dom = cast<BasicBlock>(*I); 668 while (++I != E) { 669 BasicBlock *B = cast_or_null<BasicBlock>(*I); 670 Dom = B ? DT->findNearestCommonDominator(Dom, B) : 0; 671 if (!Dom) 672 return 0; 673 } 674 DEBUG(dbgs() << "computed:" << Dom->getName() << '\n'); 675 return Dom; 676 } 677 678 template <typename T> 679 BasicBlock *nearest_common_dominatee(DominatorTree *DT, T &Blocks) { 680 // If two blocks, A and B, dominate a block C, then A dominates B, 681 // or B dominates A. 682 typename T::iterator I = Blocks.begin(), E = Blocks.end(); 683 // Find the first non-null block. 684 while (I != E && !*I) 685 ++I; 686 if (I == E) 687 return DT->getRoot(); 688 BasicBlock *DomB = cast<BasicBlock>(*I); 689 while (++I != E) { 690 if (!*I) 691 continue; 692 BasicBlock *B = cast<BasicBlock>(*I); 693 if (DT->dominates(B, DomB)) 694 continue; 695 if (!DT->dominates(DomB, B)) 696 return 0; 697 DomB = B; 698 } 699 return DomB; 700 } 701 702 // Find the first use in B of any value from Values. If no such use, 703 // return B->end(). 704 template <typename T> 705 BasicBlock::iterator first_use_of_in_block(T &Values, BasicBlock *B) { 706 BasicBlock::iterator FirstUse = B->end(), BEnd = B->end(); 707 typedef typename T::iterator iterator; 708 for (iterator I = Values.begin(), E = Values.end(); I != E; ++I) { 709 Value *V = *I; 710 // If V is used in a PHI node, the use belongs to the incoming block, 711 // not the block with the PHI node. In the incoming block, the use 712 // would be considered as being at the end of it, so it cannot 713 // influence the position of the first use (which is assumed to be 714 // at the end to start with). 715 if (isa<PHINode>(V)) 716 continue; 717 if (!isa<Instruction>(V)) 718 continue; 719 Instruction *In = cast<Instruction>(V); 720 if (In->getParent() != B) 721 continue; 722 BasicBlock::iterator It = In->getIterator(); 723 if (std::distance(FirstUse, BEnd) < std::distance(It, BEnd)) 724 FirstUse = It; 725 } 726 return FirstUse; 727 } 728 729 bool is_empty(const BasicBlock *B) { 730 return B->empty() || (&*B->begin() == B->getTerminator()); 731 } 732 } 733 734 735 BasicBlock *HexagonCommonGEP::recalculatePlacement(GepNode *Node, 736 NodeChildrenMap &NCM, NodeToValueMap &Loc) { 737 DEBUG(dbgs() << "Loc for node:" << Node << '\n'); 738 // Recalculate the placement for Node, assuming that the locations of 739 // its children in Loc are valid. 740 // Return 0 if there is no valid placement for Node (for example, it 741 // uses an index value that is not available at the location required 742 // to dominate all children, etc.). 743 744 // Find the nearest common dominator for: 745 // - all users, if the node is used, and 746 // - all children. 747 ValueVect Bs; 748 if (Node->Flags & GepNode::Used) { 749 // Append all blocks with uses of the original values to the 750 // block vector Bs. 751 NodeToUsesMap::iterator UF = Uses.find(Node); 752 assert(UF != Uses.end() && "Used node with no use information"); 753 UseSet &Us = UF->second; 754 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) { 755 Use *U = *I; 756 User *R = U->getUser(); 757 if (!isa<Instruction>(R)) 758 continue; 759 BasicBlock *PB = isa<PHINode>(R) 760 ? cast<PHINode>(R)->getIncomingBlock(*U) 761 : cast<Instruction>(R)->getParent(); 762 Bs.push_back(PB); 763 } 764 } 765 // Append the location of each child. 766 NodeChildrenMap::iterator CF = NCM.find(Node); 767 if (CF != NCM.end()) { 768 NodeVect &Cs = CF->second; 769 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) { 770 GepNode *CN = *I; 771 NodeToValueMap::iterator LF = Loc.find(CN); 772 // If the child is only used in GEP instructions (i.e. is not used in 773 // non-GEP instructions), the nearest dominator computed for it may 774 // have been null. In such case it won't have a location available. 775 if (LF == Loc.end()) 776 continue; 777 Bs.push_back(LF->second); 778 } 779 } 780 781 BasicBlock *DomB = nearest_common_dominator(DT, Bs); 782 if (!DomB) 783 return 0; 784 // Check if the index used by Node dominates the computed dominator. 785 Instruction *IdxI = dyn_cast<Instruction>(Node->Idx); 786 if (IdxI && !DT->dominates(IdxI->getParent(), DomB)) 787 return 0; 788 789 // Avoid putting nodes into empty blocks. 790 while (is_empty(DomB)) { 791 DomTreeNode *N = (*DT)[DomB]->getIDom(); 792 if (!N) 793 break; 794 DomB = N->getBlock(); 795 } 796 797 // Otherwise, DomB is fine. Update the location map. 798 Loc[Node] = DomB; 799 return DomB; 800 } 801 802 803 BasicBlock *HexagonCommonGEP::recalculatePlacementRec(GepNode *Node, 804 NodeChildrenMap &NCM, NodeToValueMap &Loc) { 805 DEBUG(dbgs() << "LocRec begin for node:" << Node << '\n'); 806 // Recalculate the placement of Node, after recursively recalculating the 807 // placements of all its children. 808 NodeChildrenMap::iterator CF = NCM.find(Node); 809 if (CF != NCM.end()) { 810 NodeVect &Cs = CF->second; 811 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) 812 recalculatePlacementRec(*I, NCM, Loc); 813 } 814 BasicBlock *LB = recalculatePlacement(Node, NCM, Loc); 815 DEBUG(dbgs() << "LocRec end for node:" << Node << '\n'); 816 return LB; 817 } 818 819 820 bool HexagonCommonGEP::isInvariantIn(Value *Val, Loop *L) { 821 if (isa<Constant>(Val) || isa<Argument>(Val)) 822 return true; 823 Instruction *In = dyn_cast<Instruction>(Val); 824 if (!In) 825 return false; 826 BasicBlock *HdrB = L->getHeader(), *DefB = In->getParent(); 827 return DT->properlyDominates(DefB, HdrB); 828 } 829 830 831 bool HexagonCommonGEP::isInvariantIn(GepNode *Node, Loop *L) { 832 if (Node->Flags & GepNode::Root) 833 if (!isInvariantIn(Node->BaseVal, L)) 834 return false; 835 return isInvariantIn(Node->Idx, L); 836 } 837 838 839 bool HexagonCommonGEP::isInMainPath(BasicBlock *B, Loop *L) { 840 BasicBlock *HB = L->getHeader(); 841 BasicBlock *LB = L->getLoopLatch(); 842 // B must post-dominate the loop header or dominate the loop latch. 843 if (PDT->dominates(B, HB)) 844 return true; 845 if (LB && DT->dominates(B, LB)) 846 return true; 847 return false; 848 } 849 850 851 namespace { 852 BasicBlock *preheader(DominatorTree *DT, Loop *L) { 853 if (BasicBlock *PH = L->getLoopPreheader()) 854 return PH; 855 if (!OptSpeculate) 856 return 0; 857 DomTreeNode *DN = DT->getNode(L->getHeader()); 858 if (!DN) 859 return 0; 860 return DN->getIDom()->getBlock(); 861 } 862 } 863 864 865 BasicBlock *HexagonCommonGEP::adjustForInvariance(GepNode *Node, 866 NodeChildrenMap &NCM, NodeToValueMap &Loc) { 867 // Find the "topmost" location for Node: it must be dominated by both, 868 // its parent (or the BaseVal, if it's a root node), and by the index 869 // value. 870 ValueVect Bs; 871 if (Node->Flags & GepNode::Root) { 872 if (Instruction *PIn = dyn_cast<Instruction>(Node->BaseVal)) 873 Bs.push_back(PIn->getParent()); 874 } else { 875 Bs.push_back(Loc[Node->Parent]); 876 } 877 if (Instruction *IIn = dyn_cast<Instruction>(Node->Idx)) 878 Bs.push_back(IIn->getParent()); 879 BasicBlock *TopB = nearest_common_dominatee(DT, Bs); 880 881 // Traverse the loop nest upwards until we find a loop in which Node 882 // is no longer invariant, or until we get to the upper limit of Node's 883 // placement. The traversal will also stop when a suitable "preheader" 884 // cannot be found for a given loop. The "preheader" may actually be 885 // a regular block outside of the loop (i.e. not guarded), in which case 886 // the Node will be speculated. 887 // For nodes that are not in the main path of the containing loop (i.e. 888 // are not executed in each iteration), do not move them out of the loop. 889 BasicBlock *LocB = cast_or_null<BasicBlock>(Loc[Node]); 890 if (LocB) { 891 Loop *Lp = LI->getLoopFor(LocB); 892 while (Lp) { 893 if (!isInvariantIn(Node, Lp) || !isInMainPath(LocB, Lp)) 894 break; 895 BasicBlock *NewLoc = preheader(DT, Lp); 896 if (!NewLoc || !DT->dominates(TopB, NewLoc)) 897 break; 898 Lp = Lp->getParentLoop(); 899 LocB = NewLoc; 900 } 901 } 902 Loc[Node] = LocB; 903 904 // Recursively compute the locations of all children nodes. 905 NodeChildrenMap::iterator CF = NCM.find(Node); 906 if (CF != NCM.end()) { 907 NodeVect &Cs = CF->second; 908 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) 909 adjustForInvariance(*I, NCM, Loc); 910 } 911 return LocB; 912 } 913 914 915 namespace { 916 struct LocationAsBlock { 917 LocationAsBlock(const NodeToValueMap &L) : Map(L) {} 918 const NodeToValueMap ⤅ 919 }; 920 921 raw_ostream &operator<< (raw_ostream &OS, 922 const LocationAsBlock &Loc) LLVM_ATTRIBUTE_UNUSED ; 923 raw_ostream &operator<< (raw_ostream &OS, const LocationAsBlock &Loc) { 924 for (NodeToValueMap::const_iterator I = Loc.Map.begin(), E = Loc.Map.end(); 925 I != E; ++I) { 926 OS << I->first << " -> "; 927 BasicBlock *B = cast<BasicBlock>(I->second); 928 OS << B->getName() << '(' << B << ')'; 929 OS << '\n'; 930 } 931 return OS; 932 } 933 934 inline bool is_constant(GepNode *N) { 935 return isa<ConstantInt>(N->Idx); 936 } 937 } 938 939 940 void HexagonCommonGEP::separateChainForNode(GepNode *Node, Use *U, 941 NodeToValueMap &Loc) { 942 User *R = U->getUser(); 943 DEBUG(dbgs() << "Separating chain for node (" << Node << ") user: " 944 << *R << '\n'); 945 BasicBlock *PB = cast<Instruction>(R)->getParent(); 946 947 GepNode *N = Node; 948 GepNode *C = 0, *NewNode = 0; 949 while (is_constant(N) && !(N->Flags & GepNode::Root)) { 950 // XXX if (single-use) dont-replicate; 951 GepNode *NewN = new (*Mem) GepNode(N); 952 Nodes.push_back(NewN); 953 Loc[NewN] = PB; 954 955 if (N == Node) 956 NewNode = NewN; 957 NewN->Flags &= ~GepNode::Used; 958 if (C) 959 C->Parent = NewN; 960 C = NewN; 961 N = N->Parent; 962 } 963 if (!NewNode) 964 return; 965 966 // Move over all uses that share the same user as U from Node to NewNode. 967 NodeToUsesMap::iterator UF = Uses.find(Node); 968 assert(UF != Uses.end()); 969 UseSet &Us = UF->second; 970 UseSet NewUs; 971 for (UseSet::iterator I = Us.begin(); I != Us.end(); ) { 972 User *S = (*I)->getUser(); 973 UseSet::iterator Nx = std::next(I); 974 if (S == R) { 975 NewUs.insert(*I); 976 Us.erase(I); 977 } 978 I = Nx; 979 } 980 if (Us.empty()) { 981 Node->Flags &= ~GepNode::Used; 982 Uses.erase(UF); 983 } 984 985 // Should at least have U in NewUs. 986 NewNode->Flags |= GepNode::Used; 987 DEBUG(dbgs() << "new node: " << NewNode << " " << *NewNode << '\n'); 988 assert(!NewUs.empty()); 989 Uses[NewNode] = NewUs; 990 } 991 992 993 void HexagonCommonGEP::separateConstantChains(GepNode *Node, 994 NodeChildrenMap &NCM, NodeToValueMap &Loc) { 995 // First approximation: extract all chains. 996 NodeSet Ns; 997 nodes_for_root(Node, NCM, Ns); 998 999 DEBUG(dbgs() << "Separating constant chains for node: " << Node << '\n'); 1000 // Collect all used nodes together with the uses from loads and stores, 1001 // where the GEP node could be folded into the load/store instruction. 1002 NodeToUsesMap FNs; // Foldable nodes. 1003 for (NodeSet::iterator I = Ns.begin(), E = Ns.end(); I != E; ++I) { 1004 GepNode *N = *I; 1005 if (!(N->Flags & GepNode::Used)) 1006 continue; 1007 NodeToUsesMap::iterator UF = Uses.find(N); 1008 assert(UF != Uses.end()); 1009 UseSet &Us = UF->second; 1010 // Loads/stores that use the node N. 1011 UseSet LSs; 1012 for (UseSet::iterator J = Us.begin(), F = Us.end(); J != F; ++J) { 1013 Use *U = *J; 1014 User *R = U->getUser(); 1015 // We're interested in uses that provide the address. It can happen 1016 // that the value may also be provided via GEP, but we won't handle 1017 // those cases here for now. 1018 if (LoadInst *Ld = dyn_cast<LoadInst>(R)) { 1019 unsigned PtrX = LoadInst::getPointerOperandIndex(); 1020 if (&Ld->getOperandUse(PtrX) == U) 1021 LSs.insert(U); 1022 } else if (StoreInst *St = dyn_cast<StoreInst>(R)) { 1023 unsigned PtrX = StoreInst::getPointerOperandIndex(); 1024 if (&St->getOperandUse(PtrX) == U) 1025 LSs.insert(U); 1026 } 1027 } 1028 // Even if the total use count is 1, separating the chain may still be 1029 // beneficial, since the constant chain may be longer than the GEP alone 1030 // would be (e.g. if the parent node has a constant index and also has 1031 // other children). 1032 if (!LSs.empty()) 1033 FNs.insert(std::make_pair(N, LSs)); 1034 } 1035 1036 DEBUG(dbgs() << "Nodes with foldable users:\n" << FNs); 1037 1038 for (NodeToUsesMap::iterator I = FNs.begin(), E = FNs.end(); I != E; ++I) { 1039 GepNode *N = I->first; 1040 UseSet &Us = I->second; 1041 for (UseSet::iterator J = Us.begin(), F = Us.end(); J != F; ++J) 1042 separateChainForNode(N, *J, Loc); 1043 } 1044 } 1045 1046 1047 void HexagonCommonGEP::computeNodePlacement(NodeToValueMap &Loc) { 1048 // Compute the inverse of the Node.Parent links. Also, collect the set 1049 // of root nodes. 1050 NodeChildrenMap NCM; 1051 NodeVect Roots; 1052 invert_find_roots(Nodes, NCM, Roots); 1053 1054 // Compute the initial placement determined by the users' locations, and 1055 // the locations of the child nodes. 1056 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I) 1057 recalculatePlacementRec(*I, NCM, Loc); 1058 1059 DEBUG(dbgs() << "Initial node placement:\n" << LocationAsBlock(Loc)); 1060 1061 if (OptEnableInv) { 1062 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I) 1063 adjustForInvariance(*I, NCM, Loc); 1064 1065 DEBUG(dbgs() << "Node placement after adjustment for invariance:\n" 1066 << LocationAsBlock(Loc)); 1067 } 1068 if (OptEnableConst) { 1069 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I) 1070 separateConstantChains(*I, NCM, Loc); 1071 } 1072 DEBUG(dbgs() << "Node use information:\n" << Uses); 1073 1074 // At the moment, there is no further refinement of the initial placement. 1075 // Such a refinement could include splitting the nodes if they are placed 1076 // too far from some of its users. 1077 1078 DEBUG(dbgs() << "Final node placement:\n" << LocationAsBlock(Loc)); 1079 } 1080 1081 1082 Value *HexagonCommonGEP::fabricateGEP(NodeVect &NA, BasicBlock::iterator At, 1083 BasicBlock *LocB) { 1084 DEBUG(dbgs() << "Fabricating GEP in " << LocB->getName() 1085 << " for nodes:\n" << NA); 1086 unsigned Num = NA.size(); 1087 GepNode *RN = NA[0]; 1088 assert((RN->Flags & GepNode::Root) && "Creating GEP for non-root"); 1089 1090 Value *NewInst = 0; 1091 Value *Input = RN->BaseVal; 1092 Value **IdxList = new Value*[Num+1]; 1093 unsigned nax = 0; 1094 do { 1095 unsigned IdxC = 0; 1096 // If the type of the input of the first node is not a pointer, 1097 // we need to add an artificial i32 0 to the indices (because the 1098 // actual input in the IR will be a pointer). 1099 if (!NA[nax]->PTy->isPointerTy()) { 1100 Type *Int32Ty = Type::getInt32Ty(*Ctx); 1101 IdxList[IdxC++] = ConstantInt::get(Int32Ty, 0); 1102 } 1103 1104 // Keep adding indices from NA until we have to stop and generate 1105 // an "intermediate" GEP. 1106 while (++nax <= Num) { 1107 GepNode *N = NA[nax-1]; 1108 IdxList[IdxC++] = N->Idx; 1109 if (nax < Num) { 1110 // We have to stop, if the expected type of the output of this node 1111 // is not the same as the input type of the next node. 1112 Type *NextTy = next_type(N->PTy, N->Idx); 1113 if (NextTy != NA[nax]->PTy) 1114 break; 1115 } 1116 } 1117 ArrayRef<Value*> A(IdxList, IdxC); 1118 Type *InpTy = Input->getType(); 1119 Type *ElTy = cast<PointerType>(InpTy->getScalarType())->getElementType(); 1120 NewInst = GetElementPtrInst::Create(ElTy, Input, A, "cgep", &*At); 1121 DEBUG(dbgs() << "new GEP: " << *NewInst << '\n'); 1122 Input = NewInst; 1123 } while (nax <= Num); 1124 1125 delete[] IdxList; 1126 return NewInst; 1127 } 1128 1129 1130 void HexagonCommonGEP::getAllUsersForNode(GepNode *Node, ValueVect &Values, 1131 NodeChildrenMap &NCM) { 1132 NodeVect Work; 1133 Work.push_back(Node); 1134 1135 while (!Work.empty()) { 1136 NodeVect::iterator First = Work.begin(); 1137 GepNode *N = *First; 1138 Work.erase(First); 1139 if (N->Flags & GepNode::Used) { 1140 NodeToUsesMap::iterator UF = Uses.find(N); 1141 assert(UF != Uses.end() && "No use information for used node"); 1142 UseSet &Us = UF->second; 1143 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) 1144 Values.push_back((*I)->getUser()); 1145 } 1146 NodeChildrenMap::iterator CF = NCM.find(N); 1147 if (CF != NCM.end()) { 1148 NodeVect &Cs = CF->second; 1149 Work.insert(Work.end(), Cs.begin(), Cs.end()); 1150 } 1151 } 1152 } 1153 1154 1155 void HexagonCommonGEP::materialize(NodeToValueMap &Loc) { 1156 DEBUG(dbgs() << "Nodes before materialization:\n" << Nodes << '\n'); 1157 NodeChildrenMap NCM; 1158 NodeVect Roots; 1159 // Compute the inversion again, since computing placement could alter 1160 // "parent" relation between nodes. 1161 invert_find_roots(Nodes, NCM, Roots); 1162 1163 while (!Roots.empty()) { 1164 NodeVect::iterator First = Roots.begin(); 1165 GepNode *Root = *First, *Last = *First; 1166 Roots.erase(First); 1167 1168 NodeVect NA; // Nodes to assemble. 1169 // Append to NA all child nodes up to (and including) the first child 1170 // that: 1171 // (1) has more than 1 child, or 1172 // (2) is used, or 1173 // (3) has a child located in a different block. 1174 bool LastUsed = false; 1175 unsigned LastCN = 0; 1176 // The location may be null if the computation failed (it can legitimately 1177 // happen for nodes created from dead GEPs). 1178 Value *LocV = Loc[Last]; 1179 if (!LocV) 1180 continue; 1181 BasicBlock *LastB = cast<BasicBlock>(LocV); 1182 do { 1183 NA.push_back(Last); 1184 LastUsed = (Last->Flags & GepNode::Used); 1185 if (LastUsed) 1186 break; 1187 NodeChildrenMap::iterator CF = NCM.find(Last); 1188 LastCN = (CF != NCM.end()) ? CF->second.size() : 0; 1189 if (LastCN != 1) 1190 break; 1191 GepNode *Child = CF->second.front(); 1192 BasicBlock *ChildB = cast_or_null<BasicBlock>(Loc[Child]); 1193 if (ChildB != 0 && LastB != ChildB) 1194 break; 1195 Last = Child; 1196 } while (true); 1197 1198 BasicBlock::iterator InsertAt = LastB->getTerminator()->getIterator(); 1199 if (LastUsed || LastCN > 0) { 1200 ValueVect Urs; 1201 getAllUsersForNode(Root, Urs, NCM); 1202 BasicBlock::iterator FirstUse = first_use_of_in_block(Urs, LastB); 1203 if (FirstUse != LastB->end()) 1204 InsertAt = FirstUse; 1205 } 1206 1207 // Generate a new instruction for NA. 1208 Value *NewInst = fabricateGEP(NA, InsertAt, LastB); 1209 1210 // Convert all the children of Last node into roots, and append them 1211 // to the Roots list. 1212 if (LastCN > 0) { 1213 NodeVect &Cs = NCM[Last]; 1214 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) { 1215 GepNode *CN = *I; 1216 CN->Flags &= ~GepNode::Internal; 1217 CN->Flags |= GepNode::Root; 1218 CN->BaseVal = NewInst; 1219 Roots.push_back(CN); 1220 } 1221 } 1222 1223 // Lastly, if the Last node was used, replace all uses with the new GEP. 1224 // The uses reference the original GEP values. 1225 if (LastUsed) { 1226 NodeToUsesMap::iterator UF = Uses.find(Last); 1227 assert(UF != Uses.end() && "No use information found"); 1228 UseSet &Us = UF->second; 1229 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) { 1230 Use *U = *I; 1231 U->set(NewInst); 1232 } 1233 } 1234 } 1235 } 1236 1237 1238 void HexagonCommonGEP::removeDeadCode() { 1239 ValueVect BO; 1240 BO.push_back(&Fn->front()); 1241 1242 for (unsigned i = 0; i < BO.size(); ++i) { 1243 BasicBlock *B = cast<BasicBlock>(BO[i]); 1244 DomTreeNode *N = DT->getNode(B); 1245 typedef GraphTraits<DomTreeNode*> GTN; 1246 typedef GTN::ChildIteratorType Iter; 1247 for (Iter I = GTN::child_begin(N), E = GTN::child_end(N); I != E; ++I) 1248 BO.push_back((*I)->getBlock()); 1249 } 1250 1251 for (unsigned i = BO.size(); i > 0; --i) { 1252 BasicBlock *B = cast<BasicBlock>(BO[i-1]); 1253 BasicBlock::InstListType &IL = B->getInstList(); 1254 typedef BasicBlock::InstListType::reverse_iterator reverse_iterator; 1255 ValueVect Ins; 1256 for (reverse_iterator I = IL.rbegin(), E = IL.rend(); I != E; ++I) 1257 Ins.push_back(&*I); 1258 for (ValueVect::iterator I = Ins.begin(), E = Ins.end(); I != E; ++I) { 1259 Instruction *In = cast<Instruction>(*I); 1260 if (isInstructionTriviallyDead(In)) 1261 In->eraseFromParent(); 1262 } 1263 } 1264 } 1265 1266 1267 bool HexagonCommonGEP::runOnFunction(Function &F) { 1268 if (skipFunction(F)) 1269 return false; 1270 1271 // For now bail out on C++ exception handling. 1272 for (Function::iterator A = F.begin(), Z = F.end(); A != Z; ++A) 1273 for (BasicBlock::iterator I = A->begin(), E = A->end(); I != E; ++I) 1274 if (isa<InvokeInst>(I) || isa<LandingPadInst>(I)) 1275 return false; 1276 1277 Fn = &F; 1278 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1279 PDT = &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1280 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1281 Ctx = &F.getContext(); 1282 1283 Nodes.clear(); 1284 Uses.clear(); 1285 NodeOrder.clear(); 1286 1287 SpecificBumpPtrAllocator<GepNode> Allocator; 1288 Mem = &Allocator; 1289 1290 collect(); 1291 common(); 1292 1293 NodeToValueMap Loc; 1294 computeNodePlacement(Loc); 1295 materialize(Loc); 1296 removeDeadCode(); 1297 1298 #ifdef EXPENSIVE_CHECKS 1299 // Run this only when expensive checks are enabled. 1300 verifyFunction(F); 1301 #endif 1302 return true; 1303 } 1304 1305 1306 namespace llvm { 1307 FunctionPass *createHexagonCommonGEP() { 1308 return new HexagonCommonGEP(); 1309 } 1310 } 1311