LLVM 24.0.0git
GVNHoist.cpp
Go to the documentation of this file.
1//===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass hoists expressions from branches to a common dominator. It uses
10// GVN (global value numbering) to discover expressions computing the same
11// values. The primary goals of code-hoisting are:
12// 1. To reduce the code size.
13// 2. In some cases reduce critical path (by exposing more ILP).
14//
15// The algorithm factors out the reachability of values such that multiple
16// queries to find reachability of values are fast. This is based on finding the
17// ANTIC points in the CFG which do not change during hoisting. The ANTIC points
18// are basically the dominance-frontiers in the inverse graph. So we introduce a
19// data structure (CHI nodes) to keep track of values flowing out of a basic
20// block. We only do this for values with multiple occurrences in the function
21// as they are the potential hoistable candidates. This approach allows us to
22// hoist instructions to a basic block with more than two successors, as well as
23// deal with infinite loops in a trivial way.
24//
25// Limitations: This pass does not hoist fully redundant expressions because
26// they are already handled by GVN-PRE. It is advisable to run gvn-hoist before
27// and after gvn-pre because gvn-pre creates opportunities for more instructions
28// to be hoisted.
29//
30// Hoisting may affect the performance in some cases. To mitigate that, hoisting
31// is disabled in the following cases.
32// 1. Scalars across calls.
33// 2. geps when corresponding load/store cannot be hoisted.
34//===----------------------------------------------------------------------===//
35
37#include "ScalarOptions.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/Statistic.h"
52#include "llvm/IR/Argument.h"
53#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/CFG.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/Dominators.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Instruction.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/PassManager.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/User.h"
65#include "llvm/IR/Value.h"
67#include "llvm/Support/Debug.h"
71#include <algorithm>
72#include <cassert>
73#include <memory>
74#include <utility>
75#include <vector>
76
77using namespace llvm;
78
79#define DEBUG_TYPE "gvn-hoist"
80
81STATISTIC(NumHoisted, "Number of instructions hoisted");
82STATISTIC(NumRemoved, "Number of instructions removed");
83STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
84STATISTIC(NumLoadsRemoved, "Number of loads removed");
85STATISTIC(NumStoresHoisted, "Number of stores hoisted");
86STATISTIC(NumStoresRemoved, "Number of stores removed");
87STATISTIC(NumCallsHoisted, "Number of calls hoisted");
88STATISTIC(NumCallsRemoved, "Number of calls removed");
89
90namespace llvm {
91
94
95// Each element of a hoisting list contains the basic block where to hoist and
96// a list of instructions to be hoisted.
97using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>;
98
100
101// A map from a pair of VNs to all the instructions with those VNs.
102using VNType = std::pair<unsigned, uintptr_t>;
103
105
106// CHI keeps information about values flowing out of a basic block. It is
107// similar to PHI but in the inverse graph, and used for outgoing values on each
108// edge. For conciseness, it is computed only for instructions with multiple
109// occurrences in the CFG because they are the only hoistable candidates.
110// A (CHI[{V, B, I1}, {V, C, I2}]
111// / \
112// / \
113// B(I1) C (I2)
114// The Value number for both I1 and I2 is V, the CHI node will save the
115// instruction as well as the edge where the value is flowing to.
116struct CHIArg {
118
119 // Edge destination (shows the direction of flow), may not be where the I is.
121
122 // The instruction (VN) which uses the values flowing out of CHI.
124
125 bool operator==(const CHIArg &A) const { return VN == A.VN; }
126 bool operator!=(const CHIArg &A) const { return !(*this == A); }
127};
128
134
135// An invalid value number Used when inserting a single value number into
136// VNtoInsns.
138
139// Records all scalar instructions candidate for code hoisting.
140class InsnInfo {
141 VNtoInsns VNtoScalars;
142
143public:
144 // Inserts I and its value number in VNtoScalars.
146 // Scalar instruction.
147 unsigned V = VN.lookupOrAdd(I);
148 VNtoScalars[{V, InvalidVN}].push_back(I);
149 }
150
151 const VNtoInsns &getVNTable() const { return VNtoScalars; }
152};
153
154// Records all load instructions candidate for code hoisting.
155class LoadInfo {
156 VNtoInsns VNtoLoads;
157
158public:
159 // Insert Load and the value number of its memory address in VNtoLoads.
161 if (Load->isSimple()) {
162 unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
163 // With opaque pointers we may have loads from the same pointer with
164 // different result types, which should be disambiguated.
165 VNtoLoads[{V, (uintptr_t)Load->getType()}].push_back(Load);
166 }
167 }
168
169 const VNtoInsns &getVNTable() const { return VNtoLoads; }
170};
171
172// Records all store instructions candidate for code hoisting.
174 VNtoInsns VNtoStores;
175
176public:
177 // Insert the Store and a hash number of the store address and the stored
178 // value in VNtoStores.
180 if (!Store->isSimple())
181 return;
182 // Hash the store address and the stored value.
183 Value *Ptr = Store->getPointerOperand();
184 Value *Val = Store->getValueOperand();
185 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
186 }
187
188 const VNtoInsns &getVNTable() const { return VNtoStores; }
189};
190
191// Records all call instructions candidate for code hoisting.
192class CallInfo {
193 VNtoInsns VNtoCallsScalars;
194 VNtoInsns VNtoCallsLoads;
195 VNtoInsns VNtoCallsStores;
196
197public:
198 // Insert Call and its value numbering in one of the VNtoCalls* containers.
200 // A call that doesNotAccessMemory is handled as a Scalar,
201 // onlyReadsMemory will be handled as a Load instruction,
202 // all other calls will be handled as stores.
203 unsigned V = VN.lookupOrAdd(Call);
204 auto Entry = std::make_pair(V, InvalidVN);
205
206 if (Call->doesNotAccessMemory())
207 VNtoCallsScalars[Entry].push_back(Call);
208 else if (Call->onlyReadsMemory())
209 VNtoCallsLoads[Entry].push_back(Call);
210 else
211 VNtoCallsStores[Entry].push_back(Call);
212 }
213
214 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
215 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
216 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
217};
218
219// This pass hoists common computations across branches sharing common
220// dominator. The primary goal is to reduce the code size, and in some
221// cases reduce critical path (by exposing more ILP).
222class GVNHoist {
223public:
224 GVNHoist(const ScalarOptions &Opts, DominatorTree *DT, PostDominatorTree *PDT,
225 AliasAnalysis *AA, MemorySSA *MSSA)
226 : Opts(Opts), DT(DT), PDT(PDT), AA(AA), MSSA(MSSA),
227 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {
228 }
229
230 bool run(Function &F);
231
232 // Copied from NewGVN.cpp
233 // This function provides global ranking of operations so that we can place
234 // them in a canonical order. Note that rank alone is not necessarily enough
235 // for a complete ordering, as constants all have the same rank. However,
236 // generally, we will simplify an operation with all constants so that it
237 // doesn't matter what order they appear in.
238 unsigned int rank(const Value *V) const;
239
240private:
241 const ScalarOptions &Opts;
242 GVNValueTable VN;
243 DominatorTree *DT;
246 MemorySSA *MSSA;
247 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
249 BBSideEffectsSet BBSideEffects;
250 DenseSet<const BasicBlock *> HoistBarrier;
252 unsigned NumFuncArgs;
253 const bool HoistingGeps = false;
254
255 enum InsKind { Unknown, Scalar, Load, Store };
256
257 // Return true when there are exception handling in BB.
258 bool hasEH(const BasicBlock *BB);
259
260 // Return true when I1 appears before I2 in the instructions of BB.
261 bool firstInBB(const Instruction *I1, const Instruction *I2) {
262 assert(I1->getParent() == I2->getParent());
263 unsigned I1DFS = DFSNumber.lookup(I1);
264 unsigned I2DFS = DFSNumber.lookup(I2);
265 assert(I1DFS && I2DFS);
266 return I1DFS < I2DFS;
267 }
268
269 // Return true when there are memory uses of Def in BB.
270 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
271 const BasicBlock *BB);
272
273 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
274 int &NBBsOnAllPaths);
275
276 // Return true when there are exception handling or loads of memory Def
277 // between Def and NewPt. This function is only called for stores: Def is
278 // the MemoryDef of the store to be hoisted.
279
280 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
281 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
282 // initialized to -1 which is unlimited.
283 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
284 int &NBBsOnAllPaths);
285
286 // Return true when there are exception handling between HoistPt and BB.
287 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
288 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
289 // initialized to -1 which is unlimited.
290 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
291 int &NBBsOnAllPaths);
292
293 // Return true when it is safe to hoist a memory load or store U from OldPt
294 // to NewPt.
295 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
296 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths);
297
298 // Return true when it is safe to hoist scalar instructions from all blocks in
299 // WL to HoistBB.
300 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
301 int &NBBsOnAllPaths) {
302 return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);
303 }
304
305 // In the inverse CFG, the dominance frontier of basic block (BB) is the
306 // point where ANTIC needs to be computed for instructions which are going
307 // to be hoisted. Since this point does not change during gvn-hoist,
308 // we compute it only once (on demand).
309 // The ides is inspired from:
310 // "Partial Redundancy Elimination in SSA Form"
311 // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW
312 // They use similar idea in the forward graph to find fully redundant and
313 // partially redundant expressions, here it is used in the inverse graph to
314 // find fully anticipable instructions at merge point (post-dominator in
315 // the inverse CFG).
316 // Returns the edge via which an instruction in BB will get the values from.
317
318 // Returns true when the values are flowing out to each edge.
319 bool valueAnticipable(CHIArgs C, Instruction *TI) const;
320
321 // Check if it is safe to hoist values tracked by CHI in the range
322 // [Begin, End) and accumulate them in Safe.
323 void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
324 SmallVectorImpl<CHIArg> &Safe);
325
326 using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>;
327
328 // Push all the VNs corresponding to BB into RenameStack.
329 void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
330 RenameStackType &RenameStack);
331
332 void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
333 RenameStackType &RenameStack);
334
335 // Walk the post-dominator tree top-down and use a stack for each value to
336 // store the last value you see. When you hit a CHI from a given edge, the
337 // value to use as the argument is at the top of the stack, add the value to
338 // CHI and pop.
339 void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
340 auto Root = PDT->getNode(nullptr);
341 if (!Root)
342 return;
343 // Depth first walk on PDom tree to fill the CHIargs at each PDF.
344 for (auto *Node : depth_first(Root)) {
345 BasicBlock *BB = Node->getBlock();
346 if (!BB)
347 continue;
348
349 RenameStackType RenameStack;
350 // Collect all values in BB and push to stack.
351 fillRenameStack(BB, ValueBBs, RenameStack);
352
353 // Fill outgoing values in each CHI corresponding to BB.
354 fillChiArgs(BB, CHIBBs, RenameStack);
355 }
356 }
357
358 // Walk all the CHI-nodes to find ones which have a empty-entry and remove
359 // them Then collect all the instructions which are safe to hoist and see if
360 // they form a list of anticipable values. OutValues contains CHIs
361 // corresponding to each basic block.
362 void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
363 HoistingPointList &HPL);
364
365 // Compute insertion points for each values which can be fully anticipated at
366 // a dominator. HPL contains all such values.
367 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
368 InsKind K) {
369 // Sort VNs based on their rankings
370 std::vector<VNType> Ranks;
371 for (const auto &Entry : Map) {
372 Ranks.push_back(Entry.first);
373 }
374
375 // TODO: Remove fully-redundant expressions.
376 // Get instruction from the Map, assume that all the Instructions
377 // with same VNs have same rank (this is an approximation).
378 llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) {
379 return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin()));
380 });
381
382 // - Sort VNs according to their rank, and start with lowest ranked VN
383 // - Take a VN and for each instruction with same VN
384 // - Find the dominance frontier in the inverse graph (PDF)
385 // - Insert the chi-node at PDF
386 // - Remove the chi-nodes with missing entries
387 // - Remove values from CHI-nodes which do not truly flow out, e.g.,
388 // modified along the path.
389 // - Collect the remaining values that are still anticipable
391 ReverseIDFCalculator IDFs(*PDT);
392 OutValuesType OutValue;
393 InValuesType InValue;
394 for (const auto &R : Ranks) {
395 const SmallVecInsn &V = Map.lookup(R);
396 if (V.size() < 2)
397 continue;
398 const VNType &VN = R;
399 SmallPtrSet<BasicBlock *, 2> VNBlocks;
400 for (const auto &I : V) {
401 BasicBlock *BBI = I->getParent();
402 if (!hasEH(BBI))
403 VNBlocks.insert(BBI);
404 }
405 // Compute the Post Dominance Frontiers of each basic block
406 // The dominance frontier of a live block X in the reverse
407 // control graph is the set of blocks upon which X is control
408 // dependent. The following sequence computes the set of blocks
409 // which currently have dead terminators that are control
410 // dependence sources of a block which is in NewLiveBlocks.
411 IDFs.setDefiningBlocks(VNBlocks);
412 IDFBlocks.clear();
413 IDFs.calculate(IDFBlocks);
414
415 // Make a map of BB vs instructions to be hoisted.
416 for (unsigned i = 0; i < V.size(); ++i) {
417 InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
418 }
419 // Insert empty CHI node for this VN. This is used to factor out
420 // basic blocks where the ANTIC can potentially change.
421 CHIArg EmptyChi = {VN, nullptr, nullptr};
422 for (auto *IDFBB : IDFBlocks) {
423 for (unsigned i = 0; i < V.size(); ++i) {
424 // Ignore spurious PDFs.
425 if (DT->properlyDominates(IDFBB, V[i]->getParent())) {
426 OutValue[IDFBB].push_back(EmptyChi);
427 LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: "
428 << IDFBB->getName() << ", for Insn: " << *V[i]);
429 }
430 }
431 }
432 }
433
434 // Insert CHI args at each PDF to iterate on factored graph of
435 // control dependence.
436 insertCHI(InValue, OutValue);
437 // Using the CHI args inserted at each PDF, find fully anticipable values.
438 findHoistableCandidates(OutValue, K, HPL);
439 }
440
441 // Return true when all operands of Instr are available at insertion point
442 // HoistPt. When limiting the number of hoisted expressions, one could hoist
443 // a load without hoisting its access function. So before hoisting any
444 // expression, make sure that all its operands are available at insert point.
445 bool allOperandsAvailable(const Instruction *I,
446 const BasicBlock *HoistPt) const;
447
448 // Same as allOperandsAvailable with recursive check for GEP operands.
449 bool allGepOperandsAvailable(const Instruction *I,
450 const BasicBlock *HoistPt) const;
451
452 // Make all operands of the GEP available.
453 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
454 const SmallVecInsn &InstructionsToHoist,
455 Instruction *Gep) const;
456
457 void updateAlignment(Instruction *I, Instruction *Repl);
458
459 // Remove all the instructions in Candidates and replace their usage with
460 // Repl. Returns the number of instructions removed.
461 unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl);
462
463 // Replace all Memory PHI usage with NewMemAcc.
464 void raMPHIuw(MemoryUseOrDef *NewMemAcc);
465
466 // Remove all other instructions and replace them with Repl.
467 unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
468 BasicBlock *DestBB, bool MoveAccess);
469
470 // In the case Repl is a load or a store, we make all their GEPs
471 // available: GEPs are not hoisted by default to avoid the address
472 // computations to be hoisted without the associated load or store.
473 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
474 const SmallVecInsn &InstructionsToHoist) const;
475
476 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL);
477
478 // Hoist all expressions. Returns Number of scalars hoisted
479 // and number of non-scalars hoisted.
480 std::pair<unsigned, unsigned> hoistExpressions(Function &F);
481};
482
484 NumFuncArgs = F.arg_size();
485 VN.setDomTree(DT);
486 VN.setAliasAnalysis(AA);
487 // TODO: Is this actually needed?
488 VN.setMemorySSA(MSSA, true);
489 bool Res = false;
490 // Perform DFS Numbering of instructions.
491 unsigned BBI = 0;
492 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
493 DFSNumber[BB] = ++BBI;
494 unsigned I = 0;
495 for (const auto &Inst : *BB)
496 DFSNumber[&Inst] = ++I;
497 }
498
499 int ChainLength = 0;
500
501 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
502 while (true) {
503 if (Opts.gvn_hoist_max_chain_length != -1 &&
504 ++ChainLength >= Opts.gvn_hoist_max_chain_length)
505 return Res;
506
507 auto HoistStat = hoistExpressions(F);
508 if (HoistStat.first + HoistStat.second == 0)
509 return Res;
510
511 if (HoistStat.second > 0)
512 // To address a limitation of the current GVN, we need to rerun the
513 // hoisting after we hoisted loads or stores in order to be able to
514 // hoist all scalars dependent on the hoisted ld/st.
515 VN.clear();
516
517 Res = true;
518 }
519
520 return Res;
521}
522
523unsigned int GVNHoist::rank(const Value *V) const {
524 // Prefer constants to undef to anything else
525 // Undef is a constant, have to check it first.
526 // Prefer smaller constants to constantexprs
527 if (isa<ConstantExpr>(V))
528 return 2;
529 if (isa<UndefValue>(V))
530 return 1;
531 if (isa<Constant>(V))
532 return 0;
533 else if (auto *A = dyn_cast<Argument>(V))
534 return 3 + A->getArgNo();
535
536 // Need to shift the instruction DFS by number of arguments + 3 to account
537 // for the constant and argument ranking above.
538 auto Result = DFSNumber.lookup(V);
539 if (Result > 0)
540 return 4 + NumFuncArgs + Result;
541 // Unreachable or something else, just return a really large number.
542 return ~0;
543}
544
545bool GVNHoist::hasEH(const BasicBlock *BB) {
546 auto [It, Inserted] = BBSideEffects.try_emplace(BB);
547 if (!Inserted)
548 return It->second;
549
550 if (BB->isEHPad() || BB->hasAddressTaken()) {
551 It->second = true;
552 return true;
553 }
554
555 if (BB->getTerminator()->mayThrow()) {
556 It->second = true;
557 return true;
558 }
559
560 return false;
561}
562
563bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
564 const BasicBlock *BB) {
565 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
566 if (!Acc)
567 return false;
568
569 Instruction *OldPt = Def->getMemoryInst();
570 const BasicBlock *OldBB = OldPt->getParent();
571 const BasicBlock *NewBB = NewPt->getParent();
572 bool ReachedNewPt = false;
573
574 for (const MemoryAccess &MA : *Acc)
575 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
576 Instruction *Insn = MU->getMemoryInst();
577
578 // Do not check whether MU aliases Def when MU occurs after OldPt.
579 if (BB == OldBB && firstInBB(OldPt, Insn))
580 break;
581
582 // Do not check whether MU aliases Def when MU occurs before NewPt.
583 if (BB == NewBB) {
584 if (!ReachedNewPt) {
585 if (firstInBB(Insn, NewPt))
586 continue;
587 ReachedNewPt = true;
588 }
589 }
590 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
591 return true;
592 }
593
594 return false;
595}
596
597bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
598 int &NBBsOnAllPaths) {
599 // Stop walk once the limit is reached.
600 if (NBBsOnAllPaths == 0)
601 return true;
602
603 // Impossible to hoist with exceptions on the path.
604 if (hasEH(BB))
605 return true;
606
607 // No such instruction after HoistBarrier in a basic block was
608 // selected for hoisting so instructions selected within basic block with
609 // a hoist barrier can be hoisted.
610 if ((BB != SrcBB) && HoistBarrier.count(BB))
611 return true;
612
613 return false;
614}
615
616bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
617 int &NBBsOnAllPaths) {
618 const BasicBlock *NewBB = NewPt->getParent();
619 const BasicBlock *OldBB = Def->getBlock();
620 assert(DT->dominates(NewBB, OldBB) && "invalid path");
621
622 // Walk all basic blocks reachable in depth-first iteration on the inverse
623 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
624 // executed between the execution of NewBB and OldBB. Hoisting an expression
625 // from OldBB into NewBB has to be safe on all execution paths.
626 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
627 const BasicBlock *BB = *I;
628 if (BB == NewBB) {
629 // Stop traversal when reaching HoistPt.
630 I.skipChildren();
631 continue;
632 }
633
634 if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
635 return true;
636
637 // Check that we do not move a store past loads.
638 if (hasMemoryUse(NewPt, Def, BB))
639 return true;
640
641 // -1 is unlimited number of blocks on all paths.
642 if (NBBsOnAllPaths != -1)
643 --NBBsOnAllPaths;
644
645 ++I;
646 }
647
648 return false;
649}
650
651bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
652 int &NBBsOnAllPaths) {
653 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
654
655 // Walk all basic blocks reachable in depth-first iteration on
656 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
657 // blocks that may be executed between the execution of NewHoistPt and
658 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
659 // on all execution paths.
660 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
661 const BasicBlock *BB = *I;
662 if (BB == HoistPt) {
663 // Stop traversal when reaching NewHoistPt.
664 I.skipChildren();
665 continue;
666 }
667
668 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
669 return true;
670
671 // -1 is unlimited number of blocks on all paths.
672 if (NBBsOnAllPaths != -1)
673 --NBBsOnAllPaths;
674
675 ++I;
676 }
677
678 return false;
679}
680
681bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt,
682 const Instruction *OldPt, MemoryUseOrDef *U,
683 GVNHoist::InsKind K, int &NBBsOnAllPaths) {
684 // In place hoisting is safe.
685 if (NewPt == OldPt)
686 return true;
687
688 const BasicBlock *NewBB = NewPt->getParent();
689 const BasicBlock *OldBB = OldPt->getParent();
690 const BasicBlock *UBB = U->getBlock();
691
692 // Check for dependences on the Memory SSA.
693 MemoryAccess *D = MSSA->getWalker()->getClobberingMemoryAccess(U);
694 BasicBlock *DBB = D->getBlock();
695 if (DT->properlyDominates(NewBB, DBB))
696 // Cannot move the load or store to NewBB above its definition in DBB.
697 return false;
698
699 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
700 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
701 if (!firstInBB(UD->getMemoryInst(), NewPt))
702 // Cannot move the load or store to NewPt above its definition in D.
703 return false;
704
705 // Check for unsafe hoistings due to side effects.
706 if (K == InsKind::Store) {
707 if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths))
708 return false;
709 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
710 return false;
711
712 if (UBB == NewBB) {
713 if (DT->properlyDominates(DBB, NewBB))
714 return true;
715 assert(UBB == DBB);
716 assert(MSSA->locallyDominates(D, U));
717 }
718
719 // No side effects: it is safe to hoist.
720 return true;
721}
722
723bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const {
724 if (TI->getNumSuccessors() > (unsigned)size(C))
725 return false; // Not enough args in this CHI.
726
727 for (auto CHI : C) {
728 // Find if all the edges have values flowing out of BB.
729 if (!llvm::is_contained(successors(TI), CHI.Dest))
730 return false;
731 }
732 return true;
733}
734
735void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K,
737 int NumBBsOnAllPaths = Opts.gvn_hoist_max_bbs;
738 const Instruction *T = BB->getTerminator();
739 for (auto CHI : C) {
740 Instruction *Insn = CHI.I;
741 if (!Insn) // No instruction was inserted in this CHI.
742 continue;
743 // If the Terminator is some kind of "exotic terminator" that produces a
744 // value (such as InvokeInst, CallBrInst, or CatchSwitchInst) which the CHI
745 // uses, it is not safe to hoist the use above the def.
746 if (!T->use_empty() && is_contained(Insn->operands(), cast<const Value>(T)))
747 continue;
748 if (K == InsKind::Scalar) {
749 if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))
750 Safe.push_back(CHI);
751 } else {
752 if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn))
753 if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths))
754 Safe.push_back(CHI);
755 }
756 }
757}
758
759void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
760 GVNHoist::RenameStackType &RenameStack) {
761 auto it1 = ValueBBs.find(BB);
762 if (it1 != ValueBBs.end()) {
763 // Iterate in reverse order to keep lower ranked values on the top.
764 LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName()
765 << " for pushing instructions on stack";);
766 for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {
767 // Get the value of instruction I
768 LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
769 RenameStack[VI.first].push_back(VI.second);
770 }
771 }
772}
773
774void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
775 GVNHoist::RenameStackType &RenameStack) {
776 // For each *predecessor* (because Post-DOM) of BB check if it has a CHI
777 for (auto *Pred : predecessors(BB)) {
778 auto P = CHIBBs.find(Pred);
779 if (P == CHIBBs.end()) {
780 continue;
781 }
782 LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
783 // A CHI is found (BB -> Pred is an edge in the CFG)
784 // Pop the stack until Top(V) = Ve.
785 auto &VCHI = P->second;
786 for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
787 CHIArg &C = *It;
788 if (!C.Dest) {
789 auto si = RenameStack.find(C.VN);
790 // The Basic Block where CHI is must dominate the value we want to
791 // track in a CHI. In the PDom walk, there can be values in the
792 // stack which are not control dependent e.g., nested loop.
793 if (si != RenameStack.end() && si->second.size() &&
794 DT->properlyDominates(Pred, si->second.back()->getParent())) {
795 C.Dest = BB; // Assign the edge
796 C.I = si->second.pop_back_val(); // Assign the argument
798 << "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I
799 << ", VN: " << C.VN.first << ", " << C.VN.second);
800 }
801 // Move to next CHI of a different value
802 It = std::find_if(It, VCHI.end(), not_equal_to(*It));
803 } else
804 ++It;
805 }
806 }
807}
808
809void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs,
810 GVNHoist::InsKind K,
811 HoistingPointList &HPL) {
812 auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
813
814 // CHIArgs now have the outgoing values, so check for anticipability and
815 // accumulate hoistable candidates in HPL.
816 for (auto &A : CHIBBs) {
817 BasicBlock *BB = A.first;
818 SmallVectorImpl<CHIArg> &CHIs = A.second;
819 // Vector of PHIs contains PHIs for different instructions.
820 // Sort the args according to their VNs, such that identical
821 // instructions are together.
822 llvm::stable_sort(CHIs, cmpVN);
823 auto TI = BB->getTerminator();
824 auto B = CHIs.begin();
825 // [PreIt, PHIIt) form a range of CHIs which have identical VNs.
826 auto PHIIt = llvm::find_if(CHIs, not_equal_to(*B));
827 auto PrevIt = CHIs.begin();
828 while (PrevIt != PHIIt) {
829 // Collect values which satisfy safety checks.
831 // We check for safety first because there might be multiple values in
832 // the same path, some of which are not safe to be hoisted, but overall
833 // each edge has at least one value which can be hoisted, making the
834 // value anticipable along that path.
835 checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);
836
837 // List of safe values should be anticipable at TI.
838 if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {
839 HPL.push_back({BB, SmallVecInsn()});
840 SmallVecInsn &V = HPL.back().second;
841 for (auto B : Safe)
842 V.push_back(B.I);
843 }
844
845 // Check other VNs
846 PrevIt = PHIIt;
847 PHIIt = std::find_if(PrevIt, CHIs.end(),
848 [PrevIt](CHIArg &A) { return A != *PrevIt; });
849 }
850 }
851}
852
853bool GVNHoist::allOperandsAvailable(const Instruction *I,
854 const BasicBlock *HoistPt) const {
855 for (const Use &Op : I->operands())
856 if (const auto *Inst = dyn_cast<Instruction>(&Op))
857 if (!DT->dominates(Inst->getParent(), HoistPt))
858 return false;
859
860 return true;
861}
862
863bool GVNHoist::allGepOperandsAvailable(const Instruction *I,
864 const BasicBlock *HoistPt) const {
865 for (const Use &Op : I->operands())
866 if (const auto *Inst = dyn_cast<Instruction>(&Op))
867 if (!DT->dominates(Inst->getParent(), HoistPt)) {
868 if (const GetElementPtrInst *GepOp =
870 if (!allGepOperandsAvailable(GepOp, HoistPt))
871 return false;
872 // Gep is available if all operands of GepOp are available.
873 } else {
874 // Gep is not available if it has operands other than GEPs that are
875 // defined in blocks not dominating HoistPt.
876 return false;
877 }
878 }
879 return true;
880}
881
882void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
883 const SmallVecInsn &InstructionsToHoist,
884 Instruction *Gep) const {
885 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
886
887 Instruction *ClonedGep = Gep->clone();
888 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
889 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
890 // Check whether the operand is already available.
891 if (DT->dominates(Op->getParent(), HoistPt))
892 continue;
893
894 // As a GEP can refer to other GEPs, recursively make all the operands
895 // of this GEP available at HoistPt.
896 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
897 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
898 }
899
900 // Copy Gep and replace its uses in Repl with ClonedGep.
901 ClonedGep->insertBefore(HoistPt->getTerminator()->getIterator());
902
903 // Conservatively discard any optimization hints, they may differ on the
904 // other paths.
905 ClonedGep->dropUnknownNonDebugMetadata();
906
907 // If we have optimization hints which agree with each other along different
908 // paths, preserve them.
909 for (const Instruction *OtherInst : InstructionsToHoist) {
910 const GetElementPtrInst *OtherGep;
911 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
912 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
913 else
914 OtherGep = cast<GetElementPtrInst>(
915 cast<StoreInst>(OtherInst)->getPointerOperand());
916 ClonedGep->andIRFlags(OtherGep);
917
918 // Merge debug locations of GEPs, because the hoisted GEP replaces those
919 // in branches. When cloning, ClonedGep preserves the debug location of
920 // Gepd, so Gep is skipped to avoid merging it twice.
921 if (OtherGep != Gep) {
922 ClonedGep->applyMergedLocation(ClonedGep->getDebugLoc(),
923 OtherGep->getDebugLoc());
924 }
925 }
926
927 // Replace uses of Gep with ClonedGep in Repl.
928 Repl->replaceUsesOfWith(Gep, ClonedGep);
929}
930
931void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) {
932 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
933 ReplacementLoad->setAlignment(
934 std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign()));
935 ++NumLoadsRemoved;
936 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
937 ReplacementStore->setAlignment(
938 std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign()));
939 ++NumStoresRemoved;
940 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
941 ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(),
942 cast<AllocaInst>(I)->getAlign()));
943 } else if (isa<CallInst>(Repl)) {
944 ++NumCallsRemoved;
945 }
946}
947
948unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl) {
949 unsigned NR = 0;
950 for (Instruction *I : Candidates) {
951 if (I != Repl) {
952 ++NR;
953 updateAlignment(I, Repl);
954 if (MemoryAccess *OldMA = MSSA->getMemoryAccess(I))
955 MSSAUpdater->removeMemoryAccess(OldMA);
956
957 patchReplacementInstruction(I, Repl, /*DoesKMove=*/true);
958 I->replaceAllUsesWith(Repl);
959 I->eraseFromParent();
960 }
961 }
962 return NR;
963}
964
965void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) {
966 SmallPtrSet<MemoryPhi *, 4> UsePhis;
967 for (User *U : NewMemAcc->users())
968 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
969 UsePhis.insert(Phi);
970
971 for (MemoryPhi *Phi : UsePhis) {
972 auto In = Phi->incoming_values();
973 if (llvm::all_of(In, equal_to(NewMemAcc))) {
974 Phi->replaceAllUsesWith(NewMemAcc);
975 MSSAUpdater->removeMemoryAccess(Phi);
976 }
977 }
978}
979
980unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates,
981 Instruction *Repl, BasicBlock *DestBB,
982 bool MoveAccess) {
983 MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);
984 if (MoveAccess && NewMemAcc) {
985 // The ld/st is not moved past its clobbering access, but a store may be
986 // moved past MemoryDefs that do not alias it; moveToPlace renames those.
987 MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator);
988 }
989
990 // Replace all other instructions with Repl.
991 unsigned NR = rauw(Candidates, Repl);
992
993 // Remove MemorySSA phi nodes with the same arguments.
994 if (NewMemAcc)
995 raMPHIuw(NewMemAcc);
996 return NR;
997}
998
999bool GVNHoist::makeGepOperandsAvailable(
1000 Instruction *Repl, BasicBlock *HoistPt,
1001 const SmallVecInsn &InstructionsToHoist) const {
1002 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
1003 GetElementPtrInst *Gep = nullptr;
1004 Instruction *Val = nullptr;
1005 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
1006 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
1007 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
1008 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
1009 Val = dyn_cast<Instruction>(St->getValueOperand());
1010 // Check that the stored value is available.
1011 if (Val) {
1012 if (isa<GetElementPtrInst>(Val)) {
1013 // Check whether we can compute the GEP at HoistPt.
1014 if (!allGepOperandsAvailable(Val, HoistPt))
1015 return false;
1016 } else if (!DT->dominates(Val->getParent(), HoistPt))
1017 return false;
1018 }
1019 }
1020
1021 // Check whether we can compute the Gep at HoistPt.
1022 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
1023 return false;
1024
1025 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
1026
1027 if (Val && isa<GetElementPtrInst>(Val))
1028 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
1029
1030 return true;
1031}
1032
1033std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {
1034 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
1035 for (const HoistingPointInfo &HP : HPL) {
1036 // Find out whether we already have one of the instructions in HoistPt,
1037 // in which case we do not have to move it.
1038 BasicBlock *DestBB = HP.first;
1039 const SmallVecInsn &InstructionsToHoist = HP.second;
1040 Instruction *Repl = nullptr;
1041 for (Instruction *I : InstructionsToHoist)
1042 if (I->getParent() == DestBB)
1043 // If there are two instructions in HoistPt to be hoisted in place:
1044 // update Repl to be the first one, such that we can rename the uses
1045 // of the second based on the first.
1046 if (!Repl || firstInBB(I, Repl))
1047 Repl = I;
1048
1049 // Keep track of whether we moved the instruction so we know whether we
1050 // should move the MemoryAccess.
1051 bool MoveAccess = true;
1052 if (Repl) {
1053 // Repl is already in HoistPt: it remains in place.
1054 assert(allOperandsAvailable(Repl, DestBB) &&
1055 "instruction depends on operands that are not available");
1056 MoveAccess = false;
1057 } else {
1058 // When we do not find Repl in HoistPt, select the first in the list
1059 // and move it to HoistPt.
1060 Repl = InstructionsToHoist.front();
1061
1062 // We can move Repl in HoistPt only when all operands are available.
1063 // The order in which hoistings are done may influence the availability
1064 // of operands.
1065 if (!allOperandsAvailable(Repl, DestBB)) {
1066 // When HoistingGeps there is nothing more we can do to make the
1067 // operands available: just continue.
1068 if (HoistingGeps)
1069 continue;
1070
1071 // When not HoistingGeps we need to copy the GEPs.
1072 if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))
1073 continue;
1074 }
1075
1076 // Move the instruction at the end of HoistPt.
1077 Instruction *Last = DestBB->getTerminator();
1078 if (auto *MUD = MSSA->getMemoryAccess(Repl))
1079 MSSAUpdater->moveToPlace(MUD, DestBB, MemorySSA::BeforeTerminator);
1080 Repl->moveBefore(Last->getIterator());
1081
1082 DFSNumber[Repl] = DFSNumber[Last]++;
1083 }
1084
1085 // Drop debug location as per debug info update guide.
1086 Repl->dropLocation();
1087 NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);
1088
1089 if (isa<LoadInst>(Repl))
1090 ++NL;
1091 else if (isa<StoreInst>(Repl))
1092 ++NS;
1093 else if (isa<CallInst>(Repl))
1094 ++NC;
1095 else // Scalar
1096 ++NI;
1097 }
1098
1099 if (MSSA && VerifyMemorySSA)
1100 MSSA->verifyMemorySSA();
1101
1102 NumHoisted += NL + NS + NC + NI;
1103 NumRemoved += NR;
1104 NumLoadsHoisted += NL;
1105 NumStoresHoisted += NS;
1106 NumCallsHoisted += NC;
1107 return {NI, NL + NC + NS};
1108}
1109
1110std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) {
1111 InsnInfo II;
1112 LoadInfo LI;
1113 StoreInfo SI;
1114 CallInfo CI;
1115 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
1116 int InstructionNb = 0;
1117 for (Instruction &I1 : *BB) {
1118 // If I1 cannot guarantee progress, subsequent instructions
1119 // in BB cannot be hoisted anyways.
1121 HoistBarrier.insert(BB);
1122 break;
1123 }
1124 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
1125 // deeper may increase the register pressure and compilation time.
1126 if (Opts.gvn_hoist_max_depth != -1 &&
1127 InstructionNb++ >= Opts.gvn_hoist_max_depth)
1128 break;
1129
1130 // Do not value number terminator instructions.
1131 if (I1.isTerminator())
1132 break;
1133
1134 if (auto *Load = dyn_cast<LoadInst>(&I1))
1135 LI.insert(Load, VN);
1136 else if (auto *Store = dyn_cast<StoreInst>(&I1))
1137 SI.insert(Store, VN);
1138 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
1139 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
1140 if (Intr->getIntrinsicID() == Intrinsic::assume ||
1141 Intr->getIntrinsicID() == Intrinsic::sideeffect)
1142 continue;
1143 }
1144 if (Call->mayHaveSideEffects())
1145 break;
1146
1147 if (Call->isConvergent())
1148 break;
1149
1150 CI.insert(Call, VN);
1151 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
1152 // Do not hoist scalars past calls that may write to memory because
1153 // that could result in spills later. geps are handled separately.
1154 // TODO: We can relax this for targets like AArch64 as they have more
1155 // registers than X86.
1156 II.insert(&I1, VN);
1157 }
1158 }
1159
1161 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
1162 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
1163 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
1164 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
1165 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
1166 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
1167 return hoist(HPL);
1168}
1169
1170} // end namespace llvm
1171
1176 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1177 const ScalarOptions &Opts = getScalarOptions(F);
1178 GVNHoist G(Opts, &DT, &PDT, &AA, &MSSA);
1179 if (!G.run(F))
1180 return PreservedAnalyses::all();
1181
1185 return PA;
1186}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file provides the interface for the GVNHoist pass.
This file provides a data structure for mapping values and expressions to congruence class IDs.
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define T
uint64_t IntrinsicInst * II
#define P(N)
static void r2(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:51
static void r1(uint32_t &A, uint32_t &B, uint32_t &C, uint32_t &D, uint32_t &E, int I, uint32_t *Buf)
Definition SHA1.cpp:45
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:683
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
bool isConvergent() const
Determine if the invoke is convergent.
void insert(CallInst *Call, GVNValueTable &VN)
Definition GVNHoist.cpp:199
const VNtoInsns & getLoadVNTable() const
Definition GVNHoist.cpp:215
const VNtoInsns & getScalarVNTable() const
Definition GVNHoist.cpp:214
const VNtoInsns & getStoreVNTable() const
Definition GVNHoist.cpp:216
This class represents a function call, abstracting a target machine's calling convention.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
bool run(Function &F)
Definition GVNHoist.cpp:483
GVNHoist(const ScalarOptions &Opts, DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA, MemorySSA *MSSA)
Definition GVNHoist.cpp:224
unsigned int rank(const Value *V) const
Definition GVNHoist.cpp:523
This class holds the mapping between values and value numbers.
LLVM_ABI uint32_t lookupOrAdd(MemoryAccess *MA)
Definition GVN.cpp:909
void insert(Instruction *I, GVNValueTable &VN)
Definition GVNHoist.cpp:145
const VNtoInsns & getVNTable() const
Definition GVNHoist.cpp:151
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
const VNtoInsns & getVNTable() const
Definition GVNHoist.cpp:169
void insert(LoadInst *Load, GVNValueTable &VN)
Definition GVNHoist.cpp:160
An instruction for reading from memory.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:369
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:913
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:689
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
Definition MemorySSA.h:740
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:252
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void insert(StoreInst *Store, GVNValueTable &VN)
Definition GVNHoist.cpp:179
const VNtoInsns & getVNTable() const
Definition GVNHoist.cpp:188
An instruction for storing to memory.
op_range operands()
Definition User.h:267
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Abstract Attribute helper functions.
Definition Attributor.h:165
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
DenseMap< BasicBlock *, SmallVector< std::pair< VNType, Instruction * >, 2 > > InValuesType
Definition GVNHoist.cpp:132
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
@ InvalidVN
Definition GVNHoist.cpp:137
void stable_sort(R &&Range)
Definition STLExtras.h:2132
SmallVector< HoistingPointInfo, 4 > HoistingPointList
Definition GVNHoist.cpp:99
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
@ Unknown
Not known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const ScalarOptions & getScalarOptions(const LLVMContext &C)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
SmallVector< Instruction *, 4 > SmallVecInsn
Definition GVNHoist.cpp:93
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
SmallVectorImpl< CHIArg >::iterator CHIIt
Definition GVNHoist.cpp:129
DenseMap< VNType, SmallVector< Instruction *, 4 > > VNtoInsns
Definition GVNHoist.cpp:104
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
std::pair< unsigned, uintptr_t > VNType
Definition GVNHoist.cpp:102
IDFCalculator< true > ReverseIDFCalculator
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl, bool DoesKMove=false)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3249
std::pair< BasicBlock *, SmallVecInsn > HoistingPointInfo
Definition GVNHoist.cpp:97
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
idf_iterator< T > idf_end(const T &G)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
idf_iterator< T > idf_begin(const T &G)
DenseMap< BasicBlock *, SmallVector< CHIArg, 2 > > OutValuesType
Definition GVNHoist.cpp:131
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
iterator_range< CHIIt > CHIArgs
Definition GVNHoist.cpp:130
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
DenseMap< const BasicBlock *, bool > BBSideEffectsSet
Definition GVNHoist.cpp:92
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define NC
Definition regutils.h:42
bool operator!=(const CHIArg &A) const
Definition GVNHoist.cpp:126
BasicBlock * Dest
Definition GVNHoist.cpp:120
Instruction * I
Definition GVNHoist.cpp:123
bool operator==(const CHIArg &A) const
Definition GVNHoist.cpp:125
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.