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