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