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