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