LLVM 24.0.0git
HexagonLoopIdiomRecognition.cpp
Go to the documentation of this file.
1//===- HexagonLoopIdiomRecognition.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "Hexagon.h"
11#include "llvm/ADT/APInt.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/Attributes.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DebugLoc.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Instruction.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/IntrinsicsHexagon.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/PassManager.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/User.h"
49#include "llvm/IR/Value.h"
51#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <array>
66#include <cassert>
67#include <cstdint>
68#include <cstdlib>
69#include <deque>
70#include <functional>
71#include <iterator>
72#include <map>
73#include <set>
74#include <utility>
75#include <vector>
76
77#define DEBUG_TYPE "hexagon-lir"
78
79using namespace llvm;
80
81static cl::opt<bool> DisableMemcpyIdiom("disable-memcpy-idiom",
82 cl::Hidden, cl::init(false),
83 cl::desc("Disable generation of memcpy in loop idiom recognition"));
84
85static cl::opt<bool> DisableMemmoveIdiom("disable-memmove-idiom",
86 cl::Hidden, cl::init(false),
87 cl::desc("Disable generation of memmove in loop idiom recognition"));
88
89static cl::opt<unsigned> RuntimeMemSizeThreshold("runtime-mem-idiom-threshold",
90 cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime "
91 "check guarding the memmove."));
92
94 "compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64),
95 cl::desc("Threshold (in bytes) to perform the transformation, if the "
96 "runtime loop count (mem transfer size) is known at compile-time."));
97
98static cl::opt<bool> OnlyNonNestedMemmove("only-nonnested-memmove-idiom",
99 cl::Hidden, cl::init(true),
100 cl::desc("Only enable generating memmove in non-nested loops"));
101
103 "disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false),
104 cl::desc("Enable Hexagon-specific memcpy for volatile destination."));
105
106static cl::opt<unsigned> SimplifyLimit("hlir-simplify-limit", cl::init(10000),
107 cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"));
108
109namespace {
110
111class HexagonLoopIdiomRecognize {
112public:
113 explicit HexagonLoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
114 LoopInfo *LF, const TargetLibraryInfo *TLI,
115 ScalarEvolution *SE,
117 : AA(AA), DT(DT), LF(LF), TLI(TLI), SE(SE), ORE(ORE) {}
118
119 bool run(Loop *L);
120
121private:
122 int getSCEVStride(const SCEVAddRecExpr *StoreEv);
123 bool isLegalStore(Loop *CurLoop, StoreInst *SI);
124 void collectStores(Loop *CurLoop, BasicBlock *BB,
125 SmallVectorImpl<StoreInst *> &Stores);
126 bool processCopyingStore(Loop *CurLoop, StoreInst *SI, const SCEV *BECount);
127 bool coverLoop(Loop *L, SmallVectorImpl<Instruction *> &Insts) const;
128 bool runOnLoopBlock(Loop *CurLoop, BasicBlock *BB, const SCEV *BECount,
129 SmallVectorImpl<BasicBlock *> &ExitBlocks);
130 bool runOnCountableLoop(Loop *L);
131
132 AliasAnalysis *AA;
133 const DataLayout *DL;
134 DominatorTree *DT;
135 LoopInfo *LF;
136 const TargetLibraryInfo *TLI;
137 ScalarEvolution *SE;
138 OptimizationRemarkEmitter &ORE;
139 bool HasMemcpy, HasMemmove;
140};
141
142class HexagonLoopIdiomRecognizeLegacyPass : public LoopPass {
143public:
144 static char ID;
145
146 explicit HexagonLoopIdiomRecognizeLegacyPass() : LoopPass(ID) {}
147
148 StringRef getPassName() const override {
149 return "Recognize Hexagon-specific loop idioms";
150 }
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addRequired<LoopInfoWrapperPass>();
156 AU.addRequired<AAResultsWrapperPass>();
157 AU.addRequired<ScalarEvolutionWrapperPass>();
158 AU.addRequired<DominatorTreeWrapperPass>();
159 AU.addRequired<TargetLibraryInfoWrapperPass>();
160 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
161 AU.addPreserved<TargetLibraryInfoWrapperPass>();
162 }
163
164 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
165};
166
167struct Simplifier {
168 struct Rule {
169 using FuncType = std::function<Value *(Instruction *, Module &)>;
170 Rule(StringRef N, FuncType F) : Name(N), Fn(F) {}
171 StringRef Name; // For debugging.
172 FuncType Fn;
173 };
174
175 void addRule(StringRef N, const Rule::FuncType &F) {
176 Rules.push_back(Rule(N, F));
177 }
178
179private:
180 struct WorkListType {
181 WorkListType() = default;
182
183 void push_back(Value *V) {
184 // Do not push back duplicates.
185 if (S.insert(V).second)
186 Q.push_back(V);
187 }
188
189 Value *pop_front_val() {
190 Value *V = Q.front();
191 Q.pop_front();
192 S.erase(V);
193 return V;
194 }
195
196 bool empty() const { return Q.empty(); }
197
198 private:
199 std::deque<Value *> Q;
200 std::set<Value *> S;
201 };
202
203 using ValueSetType = std::set<Value *>;
204
205 std::vector<Rule> Rules;
206
207public:
208 struct Context {
209 using ValueMapType = DenseMap<Value *, Value *>;
210
211 Value *Root;
212 ValueSetType Used; // The set of all cloned values used by Root.
213 ValueSetType Clones; // The set of all cloned values.
214 Module &M;
215
216 Context(Instruction *Exp) : M(*Exp->getModule()) { initialize(Exp); }
217
218 ~Context() { cleanup(); }
219
220 void print(raw_ostream &OS, const Value *V) const;
221 Value *materialize(BasicBlock *B, BasicBlock::iterator At);
222
223 private:
224 friend struct Simplifier;
225
226 void initialize(Instruction *Exp);
227 void cleanup();
228
229 template <typename FuncT> void traverse(Value *V, FuncT F);
230 void record(Value *V);
231 void use(Value *V);
232 void unuse(Value *V);
233
234 bool equal(const Instruction *I, const Instruction *J) const;
235 Value *find(Value *Tree, Value *Sub) const;
236 Value *subst(Value *Tree, Value *OldV, Value *NewV);
237 void replace(Value *OldV, Value *NewV);
238 void link(Instruction *I, BasicBlock *B, BasicBlock::iterator At);
239 };
240
241 Value *simplify(Context &C);
242};
243
244 struct PE {
245 PE(const Simplifier::Context &c, Value *v = nullptr) : C(c), V(v) {}
246
247 const Simplifier::Context &C;
248 const Value *V;
249 };
250
252 raw_ostream &operator<<(raw_ostream &OS, const PE &P) {
253 P.C.print(OS, P.V ? P.V : P.C.Root);
254 return OS;
255 }
256
257} // end anonymous namespace
258
259char HexagonLoopIdiomRecognizeLegacyPass::ID = 0;
260
261INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom",
262 "Recognize Hexagon-specific loop idioms", false, false)
264INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
265INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
271INITIALIZE_PASS_END(HexagonLoopIdiomRecognizeLegacyPass, "hexagon-loop-idiom",
272 "Recognize Hexagon-specific loop idioms", false, false)
273
274template <typename FuncT>
275void Simplifier::Context::traverse(Value *V, FuncT F) {
276 WorkListType Q;
277 Q.push_back(V);
278
279 while (!Q.empty()) {
280 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
281 if (!U || U->getParent())
282 continue;
283 if (!F(U))
284 continue;
285 for (Value *Op : U->operands())
286 Q.push_back(Op);
287 }
288}
289
290void Simplifier::Context::print(raw_ostream &OS, const Value *V) const {
291 const auto *U = dyn_cast<const Instruction>(V);
292 if (!U) {
293 OS << V << '(' << *V << ')';
294 return;
295 }
296
297 if (U->getParent()) {
298 OS << U << '(';
299 U->printAsOperand(OS, true);
300 OS << ')';
301 return;
302 }
303
304 unsigned N = U->getNumOperands();
305 if (N != 0)
306 OS << U << '(';
307 OS << U->getOpcodeName();
308 for (const Value *Op : U->operands()) {
309 OS << ' ';
310 print(OS, Op);
311 }
312 if (N != 0)
313 OS << ')';
314}
315
316void Simplifier::Context::initialize(Instruction *Exp) {
317 // Perform a deep clone of the expression, set Root to the root
318 // of the clone, and build a map from the cloned values to the
319 // original ones.
320 ValueMapType M;
321 BasicBlock *Block = Exp->getParent();
322 WorkListType Q;
323 Q.push_back(Exp);
324
325 while (!Q.empty()) {
326 Value *V = Q.pop_front_val();
327 if (M.contains(V))
328 continue;
329 if (Instruction *U = dyn_cast<Instruction>(V)) {
330 if (isa<PHINode>(U) || U->getParent() != Block)
331 continue;
332 for (Value *Op : U->operands())
333 Q.push_back(Op);
334 M.insert({U, U->clone()});
335 }
336 }
337
338 for (std::pair<Value*,Value*> P : M) {
339 Instruction *U = cast<Instruction>(P.second);
340 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
341 auto F = M.find(U->getOperand(i));
342 if (F != M.end())
343 U->setOperand(i, F->second);
344 }
345 }
346
347 auto R = M.find(Exp);
348 assert(R != M.end());
349 Root = R->second;
350
351 record(Root);
352 use(Root);
353}
354
355void Simplifier::Context::record(Value *V) {
356 auto Record = [this](Instruction *U) -> bool {
357 Clones.insert(U);
358 return true;
359 };
360 traverse(V, Record);
361}
362
363void Simplifier::Context::use(Value *V) {
364 auto Use = [this](Instruction *U) -> bool {
365 Used.insert(U);
366 return true;
367 };
368 traverse(V, Use);
369}
370
371void Simplifier::Context::unuse(Value *V) {
372 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != nullptr)
373 return;
374
375 auto Unuse = [this](Instruction *U) -> bool {
376 if (!U->use_empty())
377 return false;
378 Used.erase(U);
379 return true;
380 };
381 traverse(V, Unuse);
382}
383
384Value *Simplifier::Context::subst(Value *Tree, Value *OldV, Value *NewV) {
385 if (Tree == OldV)
386 return NewV;
387 if (OldV == NewV)
388 return Tree;
389
390 WorkListType Q;
391 Q.push_back(Tree);
392 while (!Q.empty()) {
393 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
394 // If U is not an instruction, or it's not a clone, skip it.
395 if (!U || U->getParent())
396 continue;
397 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i) {
398 Value *Op = U->getOperand(i);
399 if (Op == OldV) {
400 U->setOperand(i, NewV);
401 unuse(OldV);
402 } else {
403 Q.push_back(Op);
404 }
405 }
406 }
407 return Tree;
408}
409
410void Simplifier::Context::replace(Value *OldV, Value *NewV) {
411 if (Root == OldV) {
412 Root = NewV;
413 use(Root);
414 return;
415 }
416
417 // NewV may be a complex tree that has just been created by one of the
418 // transformation rules. We need to make sure that it is commoned with
419 // the existing Root to the maximum extent possible.
420 // Identify all subtrees of NewV (including NewV itself) that have
421 // equivalent counterparts in Root, and replace those subtrees with
422 // these counterparts.
423 WorkListType Q;
424 Q.push_back(NewV);
425 while (!Q.empty()) {
426 Value *V = Q.pop_front_val();
428 if (!U || U->getParent())
429 continue;
430 if (Value *DupV = find(Root, V)) {
431 if (DupV != V)
432 NewV = subst(NewV, V, DupV);
433 } else {
434 for (Value *Op : U->operands())
435 Q.push_back(Op);
436 }
437 }
438
439 // Now, simply replace OldV with NewV in Root.
440 Root = subst(Root, OldV, NewV);
441 use(Root);
442}
443
444void Simplifier::Context::cleanup() {
445 for (Value *V : Clones) {
447 if (!U->getParent())
448 U->dropAllReferences();
449 }
450
451 for (Value *V : Clones) {
453 if (!U->getParent())
454 U->deleteValue();
455 }
456}
457
458bool Simplifier::Context::equal(const Instruction *I,
459 const Instruction *J) const {
460 if (I == J)
461 return true;
462 if (!I->isSameOperationAs(J))
463 return false;
464 if (isa<PHINode>(I))
465 return I->isIdenticalTo(J);
466
467 for (unsigned i = 0, n = I->getNumOperands(); i != n; ++i) {
468 Value *OpI = I->getOperand(i), *OpJ = J->getOperand(i);
469 if (OpI == OpJ)
470 continue;
471 auto *InI = dyn_cast<const Instruction>(OpI);
472 auto *InJ = dyn_cast<const Instruction>(OpJ);
473 if (InI && InJ) {
474 if (!equal(InI, InJ))
475 return false;
476 } else if (InI != InJ || !InI)
477 return false;
478 }
479 return true;
480}
481
482Value *Simplifier::Context::find(Value *Tree, Value *Sub) const {
484 WorkListType Q;
485 Q.push_back(Tree);
486
487 while (!Q.empty()) {
488 Value *V = Q.pop_front_val();
489 if (V == Sub)
490 return V;
492 if (!U || U->getParent())
493 continue;
494 if (SubI && equal(SubI, U))
495 return U;
496 assert(!isa<PHINode>(U));
497 for (Value *Op : U->operands())
498 Q.push_back(Op);
499 }
500 return nullptr;
501}
502
503void Simplifier::Context::link(Instruction *I, BasicBlock *B,
505 if (I->getParent())
506 return;
507
508 for (Value *Op : I->operands()) {
509 if (Instruction *OpI = dyn_cast<Instruction>(Op))
510 link(OpI, B, At);
511 }
512
513 I->insertInto(B, At);
514}
515
516Value *Simplifier::Context::materialize(BasicBlock *B,
518 if (Instruction *RootI = dyn_cast<Instruction>(Root))
519 link(RootI, B, At);
520 return Root;
521}
522
523Value *Simplifier::simplify(Context &C) {
524 WorkListType Q;
525 Q.push_back(C.Root);
526 unsigned Count = 0;
527 const unsigned Limit = SimplifyLimit;
528
529 while (!Q.empty()) {
530 if (Count++ >= Limit)
531 break;
532 Instruction *U = dyn_cast<Instruction>(Q.pop_front_val());
533 if (!U || U->getParent() || !C.Used.count(U))
534 continue;
535 bool Changed = false;
536 for (Rule &R : Rules) {
537 Value *W = R.Fn(U, C.M);
538 if (!W)
539 continue;
540 Changed = true;
541 C.record(W);
542 C.replace(U, W);
543 Q.push_back(C.Root);
544 break;
545 }
546 if (!Changed) {
547 for (Value *Op : U->operands())
548 Q.push_back(Op);
549 }
550 }
551 return Count < Limit ? C.Root : nullptr;
552}
553
554//===----------------------------------------------------------------------===//
555//
556// Implementation of PolynomialMultiplyRecognize
557//
558//===----------------------------------------------------------------------===//
559
560namespace {
561
562 class PolynomialMultiplyRecognize {
563 public:
564 explicit PolynomialMultiplyRecognize(Loop *loop, const DataLayout &dl,
565 const DominatorTree &dt, const TargetLibraryInfo &tli,
566 ScalarEvolution &se)
567 : CurLoop(loop), DL(dl), DT(dt), TLI(tli), SE(se) {}
568
569 bool recognize();
570
571 private:
572 using ValueSeq = SetVector<Value *>;
573
574 IntegerType *getPmpyType() const {
575 LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
576 return IntegerType::get(Ctx, 32);
577 }
578
579 bool isPromotableTo(Value *V, IntegerType *Ty);
580 void promoteTo(Instruction *In, IntegerType *DestTy, BasicBlock *LoopB);
581 bool promoteTypes(BasicBlock *LoopB, BasicBlock *ExitB);
582
583 Value *getCountIV(BasicBlock *BB);
584 bool findCycle(Value *Out, Value *In, ValueSeq &Cycle);
585 void classifyCycle(Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
586 ValueSeq &Late);
587 bool classifyInst(Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
588 bool commutesWithShift(Instruction *I);
589 bool highBitsAreZero(Value *V, unsigned IterCount);
590 bool keepsHighBitsZero(Value *V, unsigned IterCount);
591 bool isOperandShifted(Instruction *I, Value *Op);
592 bool convertShiftsToLeft(BasicBlock *LoopB, BasicBlock *ExitB,
593 unsigned IterCount);
594 void cleanupLoopBody(BasicBlock *LoopB);
595
596 struct ParsedValues {
597 ParsedValues() = default;
598
599 Value *M = nullptr;
600 Value *P = nullptr;
601 Value *Q = nullptr;
602 Value *R = nullptr;
603 Value *X = nullptr;
604 Instruction *Res = nullptr;
605 unsigned IterCount = 0;
606 bool Left = false;
607 bool Inv = false;
608 };
609
610 bool matchLeftShift(SelectInst *SelI, Value *CIV, ParsedValues &PV);
611 bool matchRightShift(SelectInst *SelI, ParsedValues &PV);
612 bool scanSelect(SelectInst *SI, BasicBlock *LoopB, BasicBlock *PrehB,
613 Value *CIV, ParsedValues &PV, bool PreScan);
614 unsigned getInverseMxN(unsigned QP);
615 Value *generate(BasicBlock::iterator At, ParsedValues &PV);
616
617 void setupPreSimplifier(Simplifier &S);
618 void setupPostSimplifier(Simplifier &S);
619
620 Loop *CurLoop;
621 const DataLayout &DL;
622 const DominatorTree &DT;
623 const TargetLibraryInfo &TLI;
624 ScalarEvolution &SE;
625 };
626
627} // end anonymous namespace
628
629Value *PolynomialMultiplyRecognize::getCountIV(BasicBlock *BB) {
630 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
631 if (std::distance(PI, PE) != 2)
632 return nullptr;
633 BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
634
635 for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
636 auto *PN = cast<PHINode>(I);
637 Value *InitV = PN->getIncomingValueForBlock(PB);
638 if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->isZero())
639 continue;
640 Value *IterV = PN->getIncomingValueForBlock(BB);
641 auto *BO = dyn_cast<BinaryOperator>(IterV);
642 if (!BO)
643 continue;
644 if (BO->getOpcode() != Instruction::Add)
645 continue;
646 Value *IncV = nullptr;
647 if (BO->getOperand(0) == PN)
648 IncV = BO->getOperand(1);
649 else if (BO->getOperand(1) == PN)
650 IncV = BO->getOperand(0);
651 if (IncV == nullptr)
652 continue;
653
654 if (auto *T = dyn_cast<ConstantInt>(IncV))
655 if (T->isOne())
656 return PN;
657 }
658 return nullptr;
659}
660
662 for (auto UI = I->user_begin(), UE = I->user_end(); UI != UE;) {
663 Use &TheUse = UI.getUse();
664 ++UI;
665 if (auto *II = dyn_cast<Instruction>(TheUse.getUser()))
666 if (BB == II->getParent())
667 II->replaceUsesOfWith(I, J);
668 }
669}
670
671bool PolynomialMultiplyRecognize::matchLeftShift(SelectInst *SelI,
672 Value *CIV, ParsedValues &PV) {
673 // Match the following:
674 // select (X & (1 << i)) != 0 ? R ^ (Q << i) : R
675 // select (X & (1 << i)) == 0 ? R : R ^ (Q << i)
676 // The condition may also check for equality with the masked value, i.e
677 // select (X & (1 << i)) == (1 << i) ? R ^ (Q << i) : R
678 // select (X & (1 << i)) != (1 << i) ? R : R ^ (Q << i);
679
680 Value *CondV = SelI->getCondition();
681 Value *TrueV = SelI->getTrueValue();
682 Value *FalseV = SelI->getFalseValue();
683
684 using namespace PatternMatch;
685
686 CmpPredicate P;
687 Value *A = nullptr, *B = nullptr, *C = nullptr;
688
689 if (!match(CondV, m_ICmp(P, m_And(m_Value(A), m_Value(B)), m_Value(C))) &&
690 !match(CondV, m_ICmp(P, m_Value(C), m_And(m_Value(A), m_Value(B)))))
691 return false;
693 return false;
694 // Matched: select (A & B) == C ? ... : ...
695 // select (A & B) != C ? ... : ...
696
697 Value *X = nullptr, *Sh1 = nullptr;
698 // Check (A & B) for (X & (1 << i)):
699 if (match(A, m_Shl(m_One(), m_Specific(CIV)))) {
700 Sh1 = A;
701 X = B;
702 } else if (match(B, m_Shl(m_One(), m_Specific(CIV)))) {
703 Sh1 = B;
704 X = A;
705 } else {
706 // TODO: Could also check for an induction variable containing single
707 // bit shifted left by 1 in each iteration.
708 return false;
709 }
710
711 bool TrueIfZero;
712
713 // Check C against the possible values for comparison: 0 and (1 << i):
714 if (match(C, m_Zero()))
715 TrueIfZero = (P == CmpInst::ICMP_EQ);
716 else if (C == Sh1)
717 TrueIfZero = (P == CmpInst::ICMP_NE);
718 else
719 return false;
720
721 // So far, matched:
722 // select (X & (1 << i)) ? ... : ...
723 // including variations of the check against zero/non-zero value.
724
725 Value *ShouldSameV = nullptr, *ShouldXoredV = nullptr;
726 if (TrueIfZero) {
727 ShouldSameV = TrueV;
728 ShouldXoredV = FalseV;
729 } else {
730 ShouldSameV = FalseV;
731 ShouldXoredV = TrueV;
732 }
733
734 Value *Q = nullptr, *R = nullptr, *Y = nullptr, *Z = nullptr;
735 Value *T = nullptr;
736 if (match(ShouldXoredV, m_Xor(m_Value(Y), m_Value(Z)))) {
737 // Matched: select +++ ? ... : Y ^ Z
738 // select +++ ? Y ^ Z : ...
739 // where +++ denotes previously checked matches.
740 if (ShouldSameV == Y)
741 T = Z;
742 else if (ShouldSameV == Z)
743 T = Y;
744 else
745 return false;
746 R = ShouldSameV;
747 // Matched: select +++ ? R : R ^ T
748 // select +++ ? R ^ T : R
749 // depending on TrueIfZero.
750
751 } else if (match(ShouldSameV, m_Zero())) {
752 // Matched: select +++ ? 0 : ...
753 // select +++ ? ... : 0
754 if (!SelI->hasOneUse())
755 return false;
756 T = ShouldXoredV;
757 // Matched: select +++ ? 0 : T
758 // select +++ ? T : 0
759
760 Value *U = *SelI->user_begin();
761 if (!match(U, m_c_Xor(m_Specific(SelI), m_Value(R))))
762 return false;
763 // Matched: xor (select +++ ? 0 : T), R
764 // xor (select +++ ? T : 0), R
765 } else
766 return false;
767
768 // The xor input value T is isolated into its own match so that it could
769 // be checked against an induction variable containing a shifted bit
770 // (todo).
771 // For now, check against (Q << i).
772 if (!match(T, m_Shl(m_Value(Q), m_Specific(CIV))) &&
773 !match(T, m_Shl(m_ZExt(m_Value(Q)), m_ZExt(m_Specific(CIV)))))
774 return false;
775 // Matched: select +++ ? R : R ^ (Q << i)
776 // select +++ ? R ^ (Q << i) : R
777
778 PV.X = X;
779 PV.Q = Q;
780 PV.R = R;
781 PV.Left = true;
782 return true;
783}
784
785bool PolynomialMultiplyRecognize::matchRightShift(SelectInst *SelI,
786 ParsedValues &PV) {
787 // Match the following:
788 // select (X & 1) != 0 ? (R >> 1) ^ Q : (R >> 1)
789 // select (X & 1) == 0 ? (R >> 1) : (R >> 1) ^ Q
790 // The condition may also check for equality with the masked value, i.e
791 // select (X & 1) == 1 ? (R >> 1) ^ Q : (R >> 1)
792 // select (X & 1) != 1 ? (R >> 1) : (R >> 1) ^ Q
793
794 Value *CondV = SelI->getCondition();
795 Value *TrueV = SelI->getTrueValue();
796 Value *FalseV = SelI->getFalseValue();
797
798 using namespace PatternMatch;
799
800 Value *C = nullptr;
801 CmpPredicate P;
802 bool TrueIfZero;
803
804 if (match(CondV, m_c_ICmp(P, m_Value(C), m_Zero()))) {
806 return false;
807 // Matched: select C == 0 ? ... : ...
808 // select C != 0 ? ... : ...
809 TrueIfZero = (P == CmpInst::ICMP_EQ);
810 } else if (match(CondV, m_c_ICmp(P, m_Value(C), m_One()))) {
812 return false;
813 // Matched: select C == 1 ? ... : ...
814 // select C != 1 ? ... : ...
815 TrueIfZero = (P == CmpInst::ICMP_NE);
816 } else
817 return false;
818
819 Value *X = nullptr;
820 if (!match(C, m_And(m_Value(X), m_One())))
821 return false;
822 // Matched: select (X & 1) == +++ ? ... : ...
823 // select (X & 1) != +++ ? ... : ...
824
825 Value *R = nullptr, *Q = nullptr;
826 if (TrueIfZero) {
827 // The select's condition is true if the tested bit is 0.
828 // TrueV must be the shift, FalseV must be the xor.
829 if (!match(TrueV, m_LShr(m_Value(R), m_One())))
830 return false;
831 // Matched: select +++ ? (R >> 1) : ...
832 if (!match(FalseV, m_c_Xor(m_Specific(TrueV), m_Value(Q))))
833 return false;
834 // Matched: select +++ ? (R >> 1) : (R >> 1) ^ Q
835 // with commuting ^.
836 } else {
837 // The select's condition is true if the tested bit is 1.
838 // TrueV must be the xor, FalseV must be the shift.
839 if (!match(FalseV, m_LShr(m_Value(R), m_One())))
840 return false;
841 // Matched: select +++ ? ... : (R >> 1)
842 if (!match(TrueV, m_c_Xor(m_Specific(FalseV), m_Value(Q))))
843 return false;
844 // Matched: select +++ ? (R >> 1) ^ Q : (R >> 1)
845 // with commuting ^.
846 }
847
848 PV.X = X;
849 PV.Q = Q;
850 PV.R = R;
851 PV.Left = false;
852 return true;
853}
854
855bool PolynomialMultiplyRecognize::scanSelect(SelectInst *SelI,
856 BasicBlock *LoopB, BasicBlock *PrehB, Value *CIV, ParsedValues &PV,
857 bool PreScan) {
858 using namespace PatternMatch;
859
860 // The basic pattern for R = P.Q is:
861 // for i = 0..31
862 // R = phi (0, R')
863 // if (P & (1 << i)) ; test-bit(P, i)
864 // R' = R ^ (Q << i)
865 //
866 // Similarly, the basic pattern for R = (P/Q).Q - P
867 // for i = 0..31
868 // R = phi(P, R')
869 // if (R & (1 << i))
870 // R' = R ^ (Q << i)
871
872 // There exist idioms, where instead of Q being shifted left, P is shifted
873 // right. This produces a result that is shifted right by 32 bits (the
874 // non-shifted result is 64-bit).
875 //
876 // For R = P.Q, this would be:
877 // for i = 0..31
878 // R = phi (0, R')
879 // if ((P >> i) & 1)
880 // R' = (R >> 1) ^ Q ; R is cycled through the loop, so it must
881 // else ; be shifted by 1, not i.
882 // R' = R >> 1
883 //
884 // And for the inverse:
885 // for i = 0..31
886 // R = phi (P, R')
887 // if (R & 1)
888 // R' = (R >> 1) ^ Q
889 // else
890 // R' = R >> 1
891
892 // The left-shifting idioms share the same pattern:
893 // select (X & (1 << i)) ? R ^ (Q << i) : R
894 // Similarly for right-shifting idioms:
895 // select (X & 1) ? (R >> 1) ^ Q
896
897 if (matchLeftShift(SelI, CIV, PV)) {
898 // If this is a pre-scan, getting this far is sufficient.
899 if (PreScan)
900 return true;
901
902 // Need to make sure that the SelI goes back into R.
903 auto *RPhi = dyn_cast<PHINode>(PV.R);
904 if (!RPhi)
905 return false;
906 if (SelI != RPhi->getIncomingValueForBlock(LoopB))
907 return false;
908 PV.Res = SelI;
909
910 // If X is loop invariant, it must be the input polynomial, and the
911 // idiom is the basic polynomial multiply.
912 if (CurLoop->isLoopInvariant(PV.X)) {
913 PV.P = PV.X;
914 PV.Inv = false;
915 } else {
916 // X is not loop invariant. If X == R, this is the inverse pmpy.
917 // Otherwise, check for an xor with an invariant value. If the
918 // variable argument to the xor is R, then this is still a valid
919 // inverse pmpy.
920 PV.Inv = true;
921 if (PV.X != PV.R) {
922 Value *Var = nullptr, *Inv = nullptr, *X1 = nullptr, *X2 = nullptr;
923 if (!match(PV.X, m_Xor(m_Value(X1), m_Value(X2))))
924 return false;
925 auto *I1 = dyn_cast<Instruction>(X1);
926 auto *I2 = dyn_cast<Instruction>(X2);
927 if (!I1 || I1->getParent() != LoopB) {
928 Var = X2;
929 Inv = X1;
930 } else if (!I2 || I2->getParent() != LoopB) {
931 Var = X1;
932 Inv = X2;
933 } else
934 return false;
935 if (Var != PV.R)
936 return false;
937 PV.M = Inv;
938 }
939 // The input polynomial P still needs to be determined. It will be
940 // the entry value of R.
941 Value *EntryP = RPhi->getIncomingValueForBlock(PrehB);
942 PV.P = EntryP;
943 }
944
945 return true;
946 }
947
948 if (matchRightShift(SelI, PV)) {
949 // If this is an inverse pattern, the Q polynomial must be known at
950 // compile time.
951 if (PV.Inv && !isa<ConstantInt>(PV.Q))
952 return false;
953 if (PreScan)
954 return true;
955 // There is no exact matching of right-shift pmpy.
956 return false;
957 }
958
959 return false;
960}
961
962bool PolynomialMultiplyRecognize::isPromotableTo(Value *Val,
963 IntegerType *DestTy) {
964 IntegerType *T = dyn_cast<IntegerType>(Val->getType());
965 if (!T || T->getBitWidth() > DestTy->getBitWidth())
966 return false;
967 if (T->getBitWidth() == DestTy->getBitWidth())
968 return true;
969 // Non-instructions are promotable. The reason why an instruction may not
970 // be promotable is that it may produce a different result if its operands
971 // and the result are promoted, for example, it may produce more non-zero
972 // bits. While it would still be possible to represent the proper result
973 // in a wider type, it may require adding additional instructions (which
974 // we don't want to do).
976 if (!In)
977 return true;
978 // The bitwidth of the source type is smaller than the destination.
979 // Check if the individual operation can be promoted.
980 switch (In->getOpcode()) {
981 case Instruction::PHI:
982 case Instruction::ZExt:
983 case Instruction::And:
984 case Instruction::Or:
985 case Instruction::Xor:
986 case Instruction::LShr: // Shift right is ok.
987 case Instruction::Select:
988 case Instruction::Trunc:
989 return true;
990 case Instruction::ICmp:
991 if (CmpInst *CI = cast<CmpInst>(In))
992 return CI->isEquality() || CI->isUnsigned();
993 llvm_unreachable("Cast failed unexpectedly");
994 case Instruction::Add:
995 return In->hasNoSignedWrap() && In->hasNoUnsignedWrap();
996 }
997 return false;
998}
999
1000void PolynomialMultiplyRecognize::promoteTo(Instruction *In,
1001 IntegerType *DestTy, BasicBlock *LoopB) {
1002 Type *OrigTy = In->getType();
1003 assert(!OrigTy->isVoidTy() && "Invalid instruction to promote");
1004
1005 // Leave boolean values alone.
1006 if (!In->getType()->isIntegerTy(1))
1007 In->mutateType(DestTy);
1008 unsigned DestBW = DestTy->getBitWidth();
1009
1010 // Handle PHIs.
1011 if (PHINode *P = dyn_cast<PHINode>(In)) {
1012 unsigned N = P->getNumIncomingValues();
1013 for (unsigned i = 0; i != N; ++i) {
1014 BasicBlock *InB = P->getIncomingBlock(i);
1015 if (InB == LoopB)
1016 continue;
1017 Value *InV = P->getIncomingValue(i);
1018 IntegerType *Ty = cast<IntegerType>(InV->getType());
1019 // Do not promote values in PHI nodes of type i1.
1020 if (Ty != P->getType()) {
1021 // If the value type does not match the PHI type, the PHI type
1022 // must have been promoted.
1023 assert(Ty->getBitWidth() < DestBW);
1024 InV = IRBuilder<>(InB->getTerminator()).CreateZExt(InV, DestTy);
1025 P->setIncomingValue(i, InV);
1026 }
1027 }
1028 } else if (ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
1029 Value *Op = Z->getOperand(0);
1030 if (Op->getType() == Z->getType())
1031 Z->replaceAllUsesWith(Op);
1032 Z->eraseFromParent();
1033 return;
1034 }
1035 if (TruncInst *T = dyn_cast<TruncInst>(In)) {
1036 IntegerType *TruncTy = cast<IntegerType>(OrigTy);
1037 Value *Mask = ConstantInt::get(DestTy, (1u << TruncTy->getBitWidth()) - 1);
1038 Value *And = IRBuilder<>(In).CreateAnd(T->getOperand(0), Mask);
1039 T->replaceAllUsesWith(And);
1040 T->eraseFromParent();
1041 return;
1042 }
1043
1044 // Promote immediates.
1045 for (unsigned i = 0, n = In->getNumOperands(); i != n; ++i) {
1046 if (ConstantInt *CI = dyn_cast<ConstantInt>(In->getOperand(i)))
1047 if (CI->getBitWidth() < DestBW)
1048 In->setOperand(i, ConstantInt::get(DestTy, CI->getZExtValue()));
1049 }
1050}
1051
1052bool PolynomialMultiplyRecognize::promoteTypes(BasicBlock *LoopB,
1053 BasicBlock *ExitB) {
1054 assert(LoopB);
1055 // Skip loops where the exit block has more than one predecessor. The values
1056 // coming from the loop block will be promoted to another type, and so the
1057 // values coming into the exit block from other predecessors would also have
1058 // to be promoted.
1059 if (!ExitB || (ExitB->getSinglePredecessor() != LoopB))
1060 return false;
1061 IntegerType *DestTy = getPmpyType();
1062 // Check if the exit values have types that are no wider than the type
1063 // that we want to promote to.
1064 unsigned DestBW = DestTy->getBitWidth();
1065 for (PHINode &P : ExitB->phis()) {
1066 if (P.getNumIncomingValues() != 1)
1067 return false;
1068 assert(P.getIncomingBlock(0) == LoopB);
1069 IntegerType *T = dyn_cast<IntegerType>(P.getType());
1070 if (!T || T->getBitWidth() > DestBW)
1071 return false;
1072 }
1073
1074 // Check all instructions in the loop.
1075 for (Instruction &In : *LoopB)
1076 if (!In.isTerminator() && !isPromotableTo(&In, DestTy))
1077 return false;
1078
1079 // Perform the promotion.
1080 SmallVector<Instruction *> LoopIns(llvm::make_pointer_range(*LoopB));
1081 for (Instruction *In : LoopIns)
1082 if (!In->isTerminator())
1083 promoteTo(In, DestTy, LoopB);
1084
1085 // Fix up the PHI nodes in the exit block.
1087 for (auto I = ExitB->begin(); I != End; ++I) {
1088 PHINode *P = dyn_cast<PHINode>(I);
1089 if (!P)
1090 break;
1091 Type *Ty0 = P->getIncomingValue(0)->getType();
1092 Type *PTy = P->getType();
1093 if (PTy != Ty0) {
1094 assert(Ty0 == DestTy);
1095 // In order to create the trunc, P must have the promoted type.
1096 P->mutateType(Ty0);
1097 Value *T = IRBuilder<>(End).CreateTrunc(P, PTy);
1098 // In order for the RAUW to work, the types of P and T must match.
1099 P->mutateType(PTy);
1100 P->replaceAllUsesWith(T);
1101 // Final update of the P's type.
1102 P->mutateType(Ty0);
1103 cast<Instruction>(T)->setOperand(0, P);
1104 }
1105 }
1106
1107 return true;
1108}
1109
1110bool PolynomialMultiplyRecognize::findCycle(Value *Out, Value *In,
1111 ValueSeq &Cycle) {
1112 // Out = ..., In, ...
1113 if (Out == In)
1114 return true;
1115
1116 auto *BB = cast<Instruction>(Out)->getParent();
1117 bool HadPhi = false;
1118
1119 for (auto *U : Out->users()) {
1120 auto *I = dyn_cast<Instruction>(&*U);
1121 if (I == nullptr || I->getParent() != BB)
1122 continue;
1123 // Make sure that there are no multi-iteration cycles, e.g.
1124 // p1 = phi(p2)
1125 // p2 = phi(p1)
1126 // The cycle p1->p2->p1 would span two loop iterations.
1127 // Check that there is only one phi in the cycle.
1128 bool IsPhi = isa<PHINode>(I);
1129 if (IsPhi && HadPhi)
1130 return false;
1131 HadPhi |= IsPhi;
1132 if (!Cycle.insert(I))
1133 return false;
1134 if (findCycle(I, In, Cycle))
1135 break;
1136 Cycle.remove(I);
1137 }
1138 return !Cycle.empty();
1139}
1140
1141void PolynomialMultiplyRecognize::classifyCycle(Instruction *DivI,
1142 ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
1143 // All the values in the cycle that are between the phi node and the
1144 // divider instruction will be classified as "early", all other values
1145 // will be "late".
1146
1147 bool IsE = true;
1148 unsigned I, N = Cycle.size();
1149 for (I = 0; I < N; ++I) {
1150 Value *V = Cycle[I];
1151 if (DivI == V)
1152 IsE = false;
1153 else if (!isa<PHINode>(V))
1154 continue;
1155 // Stop if found either.
1156 break;
1157 }
1158 // "I" is the index of either DivI or the phi node, whichever was first.
1159 // "E" is "false" or "true" respectively.
1160 ValueSeq &First = !IsE ? Early : Late;
1161 for (unsigned J = 0; J < I; ++J)
1162 First.insert(Cycle[J]);
1163
1164 ValueSeq &Second = IsE ? Early : Late;
1165 Second.insert(Cycle[I]);
1166 for (++I; I < N; ++I) {
1167 Value *V = Cycle[I];
1168 if (DivI == V || isa<PHINode>(V))
1169 break;
1170 Second.insert(V);
1171 }
1172
1173 for (; I < N; ++I)
1174 First.insert(Cycle[I]);
1175}
1176
1177bool PolynomialMultiplyRecognize::classifyInst(Instruction *UseI,
1178 ValueSeq &Early, ValueSeq &Late) {
1179 // Select is an exception, since the condition value does not have to be
1180 // classified in the same way as the true/false values. The true/false
1181 // values do have to be both early or both late.
1182 if (UseI->getOpcode() == Instruction::Select) {
1183 Value *TV = UseI->getOperand(1), *FV = UseI->getOperand(2);
1184 if (Early.count(TV) || Early.count(FV)) {
1185 if (Late.count(TV) || Late.count(FV))
1186 return false;
1187 Early.insert(UseI);
1188 } else if (Late.count(TV) || Late.count(FV)) {
1189 if (Early.count(TV) || Early.count(FV))
1190 return false;
1191 Late.insert(UseI);
1192 }
1193 return true;
1194 }
1195
1196 // Not sure what would be the example of this, but the code below relies
1197 // on having at least one operand.
1198 if (UseI->getNumOperands() == 0)
1199 return true;
1200
1201 bool AE = true, AL = true;
1202 for (auto &I : UseI->operands()) {
1203 if (Early.count(&*I))
1204 AL = false;
1205 else if (Late.count(&*I))
1206 AE = false;
1207 }
1208 // If the operands appear "all early" and "all late" at the same time,
1209 // then it means that none of them are actually classified as either.
1210 // This is harmless.
1211 if (AE && AL)
1212 return true;
1213 // Conversely, if they are neither "all early" nor "all late", then
1214 // we have a mixture of early and late operands that is not a known
1215 // exception.
1216 if (!AE && !AL)
1217 return false;
1218
1219 // Check that we have covered the two special cases.
1220 assert(AE != AL);
1221
1222 if (AE)
1223 Early.insert(UseI);
1224 else
1225 Late.insert(UseI);
1226 return true;
1227}
1228
1229bool PolynomialMultiplyRecognize::commutesWithShift(Instruction *I) {
1230 switch (I->getOpcode()) {
1231 case Instruction::And:
1232 case Instruction::Or:
1233 case Instruction::Xor:
1234 case Instruction::LShr:
1235 case Instruction::Shl:
1236 case Instruction::Select:
1237 case Instruction::ICmp:
1238 case Instruction::PHI:
1239 break;
1240 default:
1241 return false;
1242 }
1243 return true;
1244}
1245
1246bool PolynomialMultiplyRecognize::highBitsAreZero(Value *V,
1247 unsigned IterCount) {
1248 auto *T = dyn_cast<IntegerType>(V->getType());
1249 if (!T)
1250 return false;
1251
1252 KnownBits Known(T->getBitWidth());
1254 return Known.countMinLeadingZeros() >= IterCount;
1255}
1256
1257bool PolynomialMultiplyRecognize::keepsHighBitsZero(Value *V,
1258 unsigned IterCount) {
1259 // Assume that all inputs to the value have the high bits zero.
1260 // Check if the value itself preserves the zeros in the high bits.
1261 if (auto *C = dyn_cast<ConstantInt>(V))
1262 return C->getValue().countl_zero() >= IterCount;
1263
1264 if (auto *I = dyn_cast<Instruction>(V)) {
1265 switch (I->getOpcode()) {
1266 case Instruction::And:
1267 case Instruction::Or:
1268 case Instruction::Xor:
1269 case Instruction::LShr:
1270 case Instruction::Select:
1271 case Instruction::ICmp:
1272 case Instruction::PHI:
1273 case Instruction::ZExt:
1274 return true;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281bool PolynomialMultiplyRecognize::isOperandShifted(Instruction *I, Value *Op) {
1282 unsigned Opc = I->getOpcode();
1283 if (Opc == Instruction::Shl || Opc == Instruction::LShr)
1284 return Op != I->getOperand(1);
1285 return true;
1286}
1287
1288bool PolynomialMultiplyRecognize::convertShiftsToLeft(BasicBlock *LoopB,
1289 BasicBlock *ExitB, unsigned IterCount) {
1290 Value *CIV = getCountIV(LoopB);
1291 if (CIV == nullptr)
1292 return false;
1293 auto *CIVTy = dyn_cast<IntegerType>(CIV->getType());
1294 if (CIVTy == nullptr)
1295 return false;
1296
1297 ValueSeq RShifts;
1298 ValueSeq Early, Late, Cycled;
1299
1300 // Find all value cycles that contain logical right shifts by 1.
1301 for (Instruction &I : *LoopB) {
1302 using namespace PatternMatch;
1303
1304 Value *V = nullptr;
1305 if (!match(&I, m_LShr(m_Value(V), m_One())))
1306 continue;
1307 ValueSeq C;
1308 if (!findCycle(&I, V, C))
1309 continue;
1310
1311 // Found a cycle.
1312 C.insert(&I);
1313 classifyCycle(&I, C, Early, Late);
1314 Cycled.insert_range(C);
1315 RShifts.insert(&I);
1316 }
1317
1318 // Find the set of all values affected by the shift cycles, i.e. all
1319 // cycled values, and (recursively) all their users.
1320 ValueSeq Users(llvm::from_range, Cycled);
1321 for (unsigned i = 0; i < Users.size(); ++i) {
1322 Value *V = Users[i];
1323 if (!isa<IntegerType>(V->getType()))
1324 return false;
1325 auto *R = cast<Instruction>(V);
1326 // If the instruction does not commute with shifts, the loop cannot
1327 // be unshifted.
1328 if (!commutesWithShift(R))
1329 return false;
1330 for (Instruction *T : R->users()) {
1331 // Skip users from outside of the loop. They will be handled later.
1332 // Also, skip the right-shifts and phi nodes, since they mix early
1333 // and late values.
1334 if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(T))
1335 continue;
1336
1337 Users.insert(T);
1338 if (!classifyInst(T, Early, Late))
1339 return false;
1340 }
1341 }
1342
1343 if (Users.empty())
1344 return false;
1345
1346 // Verify that high bits remain zero.
1347 ValueSeq Internal(llvm::from_range, Users);
1348 ValueSeq Inputs;
1349 for (unsigned i = 0; i < Internal.size(); ++i) {
1350 auto *R = dyn_cast<Instruction>(Internal[i]);
1351 if (!R)
1352 continue;
1353 for (Value *Op : R->operands()) {
1354 auto *T = dyn_cast<Instruction>(Op);
1355 if (T && T->getParent() != LoopB)
1356 Inputs.insert(Op);
1357 else
1358 Internal.insert(Op);
1359 }
1360 }
1361 for (Value *V : Inputs)
1362 if (!highBitsAreZero(V, IterCount))
1363 return false;
1364 for (Value *V : Internal)
1365 if (!keepsHighBitsZero(V, IterCount))
1366 return false;
1367
1368 // Finally, the work can be done. Unshift each user.
1369 IRBuilder<> IRB(LoopB);
1370 std::map<Value*,Value*> ShiftMap;
1371
1372 using CastMapType = std::map<std::pair<Value *, Type *>, Value *>;
1373
1374 CastMapType CastMap;
1375
1376 auto upcast = [](CastMapType &CM, IRBuilder<> &IRB, Value *V,
1377 IntegerType *Ty) -> Value * {
1378 auto [H, Inserted] = CM.try_emplace(std::make_pair(V, Ty));
1379 if (Inserted)
1380 H->second = IRB.CreateIntCast(V, Ty, false);
1381 return H->second;
1382 };
1383
1384 for (auto I = LoopB->begin(), E = LoopB->end(); I != E; ++I) {
1385 using namespace PatternMatch;
1386
1387 if (isa<PHINode>(I) || !Users.count(&*I))
1388 continue;
1389
1390 // Match lshr x, 1.
1391 Value *V = nullptr;
1392 if (match(&*I, m_LShr(m_Value(V), m_One()))) {
1393 replaceAllUsesOfWithIn(&*I, V, LoopB);
1394 continue;
1395 }
1396 // For each non-cycled operand, replace it with the corresponding
1397 // value shifted left.
1398 for (auto &J : I->operands()) {
1399 Value *Op = J.get();
1400 if (!isOperandShifted(&*I, Op))
1401 continue;
1402 if (Users.count(Op))
1403 continue;
1404 // Skip shifting zeros.
1406 continue;
1407 // Check if we have already generated a shift for this value.
1408 auto F = ShiftMap.find(Op);
1409 Value *W = (F != ShiftMap.end()) ? F->second : nullptr;
1410 if (W == nullptr) {
1411 IRB.SetInsertPoint(&*I);
1412 // First, the shift amount will be CIV or CIV+1, depending on
1413 // whether the value is early or late. Instead of creating CIV+1,
1414 // do a single shift of the value.
1415 Value *ShAmt = CIV, *ShVal = Op;
1416 auto *VTy = cast<IntegerType>(ShVal->getType());
1417 auto *ATy = cast<IntegerType>(ShAmt->getType());
1418 if (Late.count(&*I))
1419 ShVal = IRB.CreateShl(Op, ConstantInt::get(VTy, 1));
1420 // Second, the types of the shifted value and the shift amount
1421 // must match.
1422 if (VTy != ATy) {
1423 if (VTy->getBitWidth() < ATy->getBitWidth())
1424 ShVal = upcast(CastMap, IRB, ShVal, ATy);
1425 else
1426 ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
1427 }
1428 // Ready to generate the shift and memoize it.
1429 W = IRB.CreateShl(ShVal, ShAmt);
1430 ShiftMap.insert(std::make_pair(Op, W));
1431 }
1432 I->replaceUsesOfWith(Op, W);
1433 }
1434 }
1435
1436 // Update the users outside of the loop to account for having left
1437 // shifts. They would normally be shifted right in the loop, so shift
1438 // them right after the loop exit.
1439 // Take advantage of the loop-closed SSA form, which has all the post-
1440 // loop values in phi nodes.
1441 IRB.SetInsertPoint(ExitB->getFirstInsertionPt());
1442 for (auto P = ExitB->begin(), Q = ExitB->end(); P != Q; ++P) {
1443 if (!isa<PHINode>(P))
1444 break;
1445 auto *PN = cast<PHINode>(P);
1446 Value *U = PN->getIncomingValueForBlock(LoopB);
1447 if (!Users.count(U))
1448 continue;
1449 Value *S = IRB.CreateLShr(PN, ConstantInt::get(PN->getType(), IterCount));
1450 PN->replaceAllUsesWith(S);
1451 // The above RAUW will create
1452 // S = lshr S, IterCount
1453 // so we need to fix it back into
1454 // S = lshr PN, IterCount
1455 cast<User>(S)->replaceUsesOfWith(S, PN);
1456 }
1457
1458 return true;
1459}
1460
1461void PolynomialMultiplyRecognize::cleanupLoopBody(BasicBlock *LoopB) {
1462 for (auto &I : *LoopB)
1463 if (Value *SV = simplifyInstruction(&I, {DL, &TLI, &DT}))
1464 I.replaceAllUsesWith(SV);
1465
1466 for (Instruction &I : llvm::make_early_inc_range(*LoopB))
1468}
1469
1470unsigned PolynomialMultiplyRecognize::getInverseMxN(unsigned QP) {
1471 // Arrays of coefficients of Q and the inverse, C.
1472 // Q[i] = coefficient at x^i.
1473 std::array<char,32> Q, C;
1474
1475 for (unsigned i = 0; i < 32; ++i) {
1476 Q[i] = QP & 1;
1477 QP >>= 1;
1478 }
1479 assert(Q[0] == 1);
1480
1481 // Find C, such that
1482 // (Q[n]*x^n + ... + Q[1]*x + Q[0]) * (C[n]*x^n + ... + C[1]*x + C[0]) = 1
1483 //
1484 // For it to have a solution, Q[0] must be 1. Since this is Z2[x], the
1485 // operations * and + are & and ^ respectively.
1486 //
1487 // Find C[i] recursively, by comparing i-th coefficient in the product
1488 // with 0 (or 1 for i=0).
1489 //
1490 // C[0] = 1, since C[0] = Q[0], and Q[0] = 1.
1491 C[0] = 1;
1492 for (unsigned i = 1; i < 32; ++i) {
1493 // Solve for C[i] in:
1494 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i]Q[0] = 0
1495 // This is equivalent to
1496 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] ^ C[i] = 0
1497 // which is
1498 // C[0]Q[i] ^ C[1]Q[i-1] ^ ... ^ C[i-1]Q[1] = C[i]
1499 unsigned T = 0;
1500 for (unsigned j = 0; j < i; ++j)
1501 T = T ^ (C[j] & Q[i-j]);
1502 C[i] = T;
1503 }
1504
1505 unsigned QV = 0;
1506 for (unsigned i = 0; i < 32; ++i)
1507 if (C[i])
1508 QV |= (1 << i);
1509
1510 return QV;
1511}
1512
1513Value *PolynomialMultiplyRecognize::generate(BasicBlock::iterator At,
1514 ParsedValues &PV) {
1515 IRBuilder<> B(&*At);
1516 Module *M = At->getParent()->getParent()->getParent();
1517 Function *PMF =
1518 Intrinsic::getOrInsertDeclaration(M, Intrinsic::hexagon_M4_pmpyw);
1519
1520 Value *P = PV.P, *Q = PV.Q, *P0 = P;
1521 unsigned IC = PV.IterCount;
1522
1523 if (PV.M != nullptr)
1524 P0 = P = B.CreateXor(P, PV.M);
1525
1526 // Create a bit mask to clear the high bits beyond IterCount.
1527 auto *BMI = ConstantInt::get(P->getType(), APInt::getLowBitsSet(32, IC));
1528
1529 if (PV.IterCount != 32)
1530 P = B.CreateAnd(P, BMI);
1531
1532 if (PV.Inv) {
1533 auto *QI = dyn_cast<ConstantInt>(PV.Q);
1534 assert(QI && QI->getBitWidth() <= 32);
1535
1536 // Again, clearing bits beyond IterCount.
1537 unsigned M = (1 << PV.IterCount) - 1;
1538 unsigned Tmp = (QI->getZExtValue() | 1) & M;
1539 unsigned QV = getInverseMxN(Tmp) & M;
1540 auto *QVI = ConstantInt::get(QI->getType(), QV);
1541 P = B.CreateCall(PMF, {P, QVI});
1542 P = B.CreateTrunc(P, QI->getType());
1543 if (IC != 32)
1544 P = B.CreateAnd(P, BMI);
1545 }
1546
1547 Value *R = B.CreateCall(PMF, {P, Q});
1548
1549 if (PV.M != nullptr)
1550 R = B.CreateXor(R, B.CreateIntCast(P0, R->getType(), false));
1551
1552 return R;
1553}
1554
1555static bool hasZeroSignBit(const Value *V) {
1556 if (const auto *CI = dyn_cast<const ConstantInt>(V))
1557 return CI->getValue().isNonNegative();
1559 if (!I)
1560 return false;
1561 switch (I->getOpcode()) {
1562 case Instruction::LShr:
1563 if (const auto SI = dyn_cast<const ConstantInt>(I->getOperand(1)))
1564 return SI->getZExtValue() > 0;
1565 return false;
1566 case Instruction::Or:
1567 case Instruction::Xor:
1568 return hasZeroSignBit(I->getOperand(0)) &&
1569 hasZeroSignBit(I->getOperand(1));
1570 case Instruction::And:
1571 return hasZeroSignBit(I->getOperand(0)) ||
1572 hasZeroSignBit(I->getOperand(1));
1573 }
1574 return false;
1575}
1576
1577void PolynomialMultiplyRecognize::setupPreSimplifier(Simplifier &S) {
1578 S.addRule("sink-zext",
1579 // Sink zext past bitwise operations.
1580 [](Instruction *I, Module &M) -> Value * {
1581 if (I->getOpcode() != Instruction::ZExt)
1582 return nullptr;
1583 Instruction *T = dyn_cast<Instruction>(I->getOperand(0));
1584 if (!T)
1585 return nullptr;
1586 switch (T->getOpcode()) {
1587 case Instruction::And:
1588 case Instruction::Or:
1589 case Instruction::Xor:
1590 break;
1591 default:
1592 return nullptr;
1593 }
1594 IRBuilder<> B(M);
1595 return B.CreateBinOp(
1597 B.CreateZExt(T->getOperand(0), I->getType()),
1598 B.CreateZExt(T->getOperand(1), I->getType()));
1599 });
1600 S.addRule("xor/and -> and/xor",
1601 // (xor (and x a) (and y a)) -> (and (xor x y) a)
1602 [](Instruction *I, Module &M) -> Value * {
1603 if (I->getOpcode() != Instruction::Xor)
1604 return nullptr;
1605 Instruction *And0 = dyn_cast<Instruction>(I->getOperand(0));
1606 Instruction *And1 = dyn_cast<Instruction>(I->getOperand(1));
1607 if (!And0 || !And1)
1608 return nullptr;
1609 if (And0->getOpcode() != Instruction::And ||
1610 And1->getOpcode() != Instruction::And)
1611 return nullptr;
1612 if (And0->getOperand(1) != And1->getOperand(1))
1613 return nullptr;
1614 IRBuilder<> B(M);
1615 return B.CreateAnd(
1616 B.CreateXor(And0->getOperand(0), And1->getOperand(0)),
1617 And0->getOperand(1));
1618 });
1619 S.addRule(
1620 "sink binop into select",
1621 // (Op (select c x y) z) -> (select c (Op x z) (Op y z))
1622 // (Op x (select c y z)) -> (select c (Op x y) (Op x z))
1623 [](Instruction *I, Module &M) -> Value * {
1624 BinaryOperator *BO = dyn_cast<BinaryOperator>(I);
1625 if (!BO)
1626 return nullptr;
1628 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(0))) {
1629 IRBuilder<> B(M);
1630 Value *X = Sel->getTrueValue(), *Y = Sel->getFalseValue();
1631 Value *Z = BO->getOperand(1);
1632 return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Z),
1633 B.CreateBinOp(Op, Y, Z));
1634 }
1635 if (SelectInst *Sel = dyn_cast<SelectInst>(BO->getOperand(1))) {
1636 IRBuilder<> B(M);
1637 Value *X = BO->getOperand(0);
1638 Value *Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1639 return B.CreateSelect(Sel->getCondition(), B.CreateBinOp(Op, X, Y),
1640 B.CreateBinOp(Op, X, Z));
1641 }
1642 return nullptr;
1643 });
1644 S.addRule(
1645 "fold select-select",
1646 // (select c (select c x y) z) -> (select c x z)
1647 // (select c x (select c y z)) -> (select c x z)
1648 [](Instruction *I, Module &M) -> Value * {
1649 SelectInst *Sel = dyn_cast<SelectInst>(I);
1650 if (!Sel)
1651 return nullptr;
1652 IRBuilder<> B(M);
1653 Value *C = Sel->getCondition();
1654 if (SelectInst *Sel0 = dyn_cast<SelectInst>(Sel->getTrueValue())) {
1655 if (Sel0->getCondition() == C)
1656 return B.CreateSelect(C, Sel0->getTrueValue(),
1657 Sel->getFalseValue());
1658 }
1659 if (SelectInst *Sel1 = dyn_cast<SelectInst>(Sel->getFalseValue())) {
1660 if (Sel1->getCondition() == C)
1661 return B.CreateSelect(C, Sel->getTrueValue(),
1662 Sel1->getFalseValue());
1663 }
1664 return nullptr;
1665 });
1666 S.addRule("or-signbit -> xor-signbit",
1667 // (or (lshr x 1) 0x800.0) -> (xor (lshr x 1) 0x800.0)
1668 [](Instruction *I, Module &M) -> Value * {
1669 if (I->getOpcode() != Instruction::Or)
1670 return nullptr;
1671 ConstantInt *Msb = dyn_cast<ConstantInt>(I->getOperand(1));
1672 if (!Msb || !Msb->getValue().isSignMask())
1673 return nullptr;
1674 if (!hasZeroSignBit(I->getOperand(0)))
1675 return nullptr;
1676 return IRBuilder<>(M).CreateXor(I->getOperand(0), Msb);
1677 });
1678 S.addRule("sink lshr into binop",
1679 // (lshr (BitOp x y) c) -> (BitOp (lshr x c) (lshr y c))
1680 [](Instruction *I, Module &M) -> Value * {
1681 if (I->getOpcode() != Instruction::LShr)
1682 return nullptr;
1683 BinaryOperator *BitOp =
1684 dyn_cast<BinaryOperator>(I->getOperand(0));
1685 if (!BitOp)
1686 return nullptr;
1687 switch (BitOp->getOpcode()) {
1688 case Instruction::And:
1689 case Instruction::Or:
1690 case Instruction::Xor:
1691 break;
1692 default:
1693 return nullptr;
1694 }
1695 IRBuilder<> B(M);
1696 Value *S = I->getOperand(1);
1697 return B.CreateBinOp(BitOp->getOpcode(),
1698 B.CreateLShr(BitOp->getOperand(0), S),
1699 B.CreateLShr(BitOp->getOperand(1), S));
1700 });
1701 S.addRule("expose bitop-const",
1702 // (BitOp1 (BitOp2 x a) b) -> (BitOp2 x (BitOp1 a b))
1703 [](Instruction *I, Module &M) -> Value * {
1704 auto IsBitOp = [](unsigned Op) -> bool {
1705 switch (Op) {
1706 case Instruction::And:
1707 case Instruction::Or:
1708 case Instruction::Xor:
1709 return true;
1710 }
1711 return false;
1712 };
1713 BinaryOperator *BitOp1 = dyn_cast<BinaryOperator>(I);
1714 if (!BitOp1 || !IsBitOp(BitOp1->getOpcode()))
1715 return nullptr;
1716 BinaryOperator *BitOp2 =
1718 if (!BitOp2 || !IsBitOp(BitOp2->getOpcode()))
1719 return nullptr;
1720 ConstantInt *CA = dyn_cast<ConstantInt>(BitOp2->getOperand(1));
1721 ConstantInt *CB = dyn_cast<ConstantInt>(BitOp1->getOperand(1));
1722 if (!CA || !CB)
1723 return nullptr;
1724 IRBuilder<> B(M);
1725 Value *X = BitOp2->getOperand(0);
1726 return B.CreateBinOp(BitOp2->getOpcode(), X,
1727 B.CreateBinOp(BitOp1->getOpcode(), CA, CB));
1728 });
1729 S.addRule("select with trunc cond to select with icmp cond",
1730 // select (trunc x to i1) -> select (icmp ne (and x, 1), 0)
1731 // select (xor (trunc x to i1) 1) -> select (icmp eq (and x, 1), 0)
1732 [](Instruction *I, Module &M) -> Value * {
1733 SelectInst *Sel = dyn_cast<SelectInst>(I);
1734 if (!Sel)
1735 return nullptr;
1736 Value *C = Sel->getCondition();
1737 Value *X;
1738 using namespace PatternMatch;
1739 if (!(match(C, m_Trunc(m_Value(X))) ||
1740 match(C, m_Not(m_Trunc(m_Value(X))))))
1741 return nullptr;
1742
1743 IRBuilder<> B(M);
1744 Type *Ty = X->getType();
1745 Value *And = B.CreateAnd(X, ConstantInt::get(Ty, 1));
1746 Value *Icmp = B.CreateICmp(isa<TruncInst>(C) ? ICmpInst::ICMP_NE
1747 : ICmpInst::ICMP_EQ,
1748 And, ConstantInt::get(Ty, 0));
1749 return B.CreateSelect(Icmp, Sel->getTrueValue(),
1750 Sel->getFalseValue());
1751 });
1752}
1753
1754void PolynomialMultiplyRecognize::setupPostSimplifier(Simplifier &S) {
1755 S.addRule("(and (xor (and x a) y) b) -> (and (xor x y) b), if b == b&a",
1756 [](Instruction *I, Module &M) -> Value * {
1757 if (I->getOpcode() != Instruction::And)
1758 return nullptr;
1759 Instruction *Xor = dyn_cast<Instruction>(I->getOperand(0));
1760 ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(1));
1761 if (!Xor || !C0)
1762 return nullptr;
1763 if (Xor->getOpcode() != Instruction::Xor)
1764 return nullptr;
1765 Instruction *And0 = dyn_cast<Instruction>(Xor->getOperand(0));
1766 Instruction *And1 = dyn_cast<Instruction>(Xor->getOperand(1));
1767 // Pick the first non-null and.
1768 if (!And0 || And0->getOpcode() != Instruction::And)
1769 std::swap(And0, And1);
1770 ConstantInt *C1 = dyn_cast<ConstantInt>(And0->getOperand(1));
1771 if (!C1)
1772 return nullptr;
1773 uint32_t V0 = C0->getZExtValue();
1774 uint32_t V1 = C1->getZExtValue();
1775 if (V0 != (V0 & V1))
1776 return nullptr;
1777 IRBuilder<> B(M);
1778 return B.CreateAnd(B.CreateXor(And0->getOperand(0), And1), C0);
1779 });
1780}
1781
1782bool PolynomialMultiplyRecognize::recognize() {
1783 LLVM_DEBUG(dbgs() << "Starting PolynomialMultiplyRecognize on loop\n"
1784 << *CurLoop << '\n');
1785 // Restrictions:
1786 // - The loop must consist of a single block.
1787 // - The iteration count must be known at compile-time.
1788 // - The loop must have an induction variable starting from 0, and
1789 // incremented in each iteration of the loop.
1790 BasicBlock *LoopB = CurLoop->getHeader();
1791 LLVM_DEBUG(dbgs() << "Loop header:\n" << *LoopB);
1792
1793 if (LoopB != CurLoop->getLoopLatch())
1794 return false;
1795 BasicBlock *ExitB = CurLoop->getExitBlock();
1796 if (ExitB == nullptr)
1797 return false;
1798 BasicBlock *EntryB = CurLoop->getLoopPreheader();
1799 if (EntryB == nullptr)
1800 return false;
1801
1802 unsigned IterCount = 0;
1803 const SCEV *CT = SE.getBackedgeTakenCount(CurLoop);
1805 return false;
1806 if (auto *CV = dyn_cast<SCEVConstant>(CT))
1807 IterCount = CV->getValue()->getZExtValue() + 1;
1808
1809 Value *CIV = getCountIV(LoopB);
1810 if (CIV == nullptr)
1811 return false;
1812 ParsedValues PV;
1813 Simplifier PreSimp;
1814 PV.IterCount = IterCount;
1815 LLVM_DEBUG(dbgs() << "Loop IV: " << *CIV << "\nIterCount: " << IterCount
1816 << '\n');
1817
1818 setupPreSimplifier(PreSimp);
1819
1820 // Perform a preliminary scan of select instructions to see if any of them
1821 // looks like a generator of the polynomial multiply steps. Assume that a
1822 // loop can only contain a single transformable operation, so stop the
1823 // traversal after the first reasonable candidate was found.
1824 // XXX: Currently this approach can modify the loop before being 100% sure
1825 // that the transformation can be carried out.
1826 bool FoundPreScan = false;
1827 auto FeedsPHI = [LoopB](const Value *V) -> bool {
1828 for (const Value *U : V->users()) {
1829 if (const auto *P = dyn_cast<const PHINode>(U))
1830 if (P->getParent() == LoopB)
1831 return true;
1832 }
1833 return false;
1834 };
1835 for (Instruction &In : *LoopB) {
1836 SelectInst *SI = dyn_cast<SelectInst>(&In);
1837 if (!SI || !FeedsPHI(SI))
1838 continue;
1839
1840 Simplifier::Context C(SI);
1841 Value *T = PreSimp.simplify(C);
1842 SelectInst *SelI = (T && isa<SelectInst>(T)) ? cast<SelectInst>(T) : SI;
1843 LLVM_DEBUG(dbgs() << "scanSelect(pre-scan): " << PE(C, SelI) << '\n');
1844 if (scanSelect(SelI, LoopB, EntryB, CIV, PV, true)) {
1845 FoundPreScan = true;
1846 if (SelI != SI) {
1847 Value *NewSel = C.materialize(LoopB, SI->getIterator());
1848 SI->replaceAllUsesWith(NewSel);
1850 }
1851 break;
1852 }
1853 }
1854
1855 if (!FoundPreScan) {
1856 LLVM_DEBUG(dbgs() << "Have not found candidates for pmpy\n");
1857 return false;
1858 }
1859
1860 if (!PV.Left) {
1861 // The right shift version actually only returns the higher bits of
1862 // the result (each iteration discards the LSB). If we want to convert it
1863 // to a left-shifting loop, the working data type must be at least as
1864 // wide as the target's pmpy instruction.
1865 if (!promoteTypes(LoopB, ExitB))
1866 return false;
1867 // Run post-promotion simplifications.
1868 Simplifier PostSimp;
1869 setupPostSimplifier(PostSimp);
1870 for (Instruction &In : *LoopB) {
1871 SelectInst *SI = dyn_cast<SelectInst>(&In);
1872 if (!SI || !FeedsPHI(SI))
1873 continue;
1874 Simplifier::Context C(SI);
1875 Value *T = PostSimp.simplify(C);
1876 SelectInst *SelI = dyn_cast_or_null<SelectInst>(T);
1877 if (SelI != SI) {
1878 Value *NewSel = C.materialize(LoopB, SI->getIterator());
1879 SI->replaceAllUsesWith(NewSel);
1881 }
1882 break;
1883 }
1884
1885 if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
1886 return false;
1887 cleanupLoopBody(LoopB);
1888 }
1889
1890 // Scan the loop again, find the generating select instruction.
1891 bool FoundScan = false;
1892 for (Instruction &In : *LoopB) {
1893 SelectInst *SelI = dyn_cast<SelectInst>(&In);
1894 if (!SelI)
1895 continue;
1896 LLVM_DEBUG(dbgs() << "scanSelect: " << *SelI << '\n');
1897 FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV, false);
1898 if (FoundScan)
1899 break;
1900 }
1901 assert(FoundScan);
1902
1903 LLVM_DEBUG({
1904 StringRef PP = (PV.M ? "(P+M)" : "P");
1905 if (!PV.Inv)
1906 dbgs() << "Found pmpy idiom: R = " << PP << ".Q\n";
1907 else
1908 dbgs() << "Found inverse pmpy idiom: R = (" << PP << "/Q).Q) + "
1909 << PP << "\n";
1910 dbgs() << " Res:" << *PV.Res << "\n P:" << *PV.P << "\n";
1911 if (PV.M)
1912 dbgs() << " M:" << *PV.M << "\n";
1913 dbgs() << " Q:" << *PV.Q << "\n";
1914 dbgs() << " Iteration count:" << PV.IterCount << "\n";
1915 });
1916
1917 BasicBlock::iterator At(EntryB->getTerminator());
1918 Value *PM = generate(At, PV);
1919 if (PM == nullptr)
1920 return false;
1921
1922 if (PM->getType() != PV.Res->getType())
1923 PM = IRBuilder<>(&*At).CreateIntCast(PM, PV.Res->getType(), false);
1924
1925 PV.Res->replaceAllUsesWith(PM);
1926 PV.Res->eraseFromParent();
1927 return true;
1928}
1929
1930int HexagonLoopIdiomRecognize::getSCEVStride(const SCEVAddRecExpr *S) {
1931 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1932 return SC->getAPInt().getSExtValue();
1933 return 0;
1934}
1935
1936bool HexagonLoopIdiomRecognize::isLegalStore(Loop *CurLoop, StoreInst *SI) {
1937 // Allow volatile stores if HexagonVolatileMemcpy is enabled.
1938 if (!(SI->isVolatile() && HexagonVolatileMemcpy) && !SI->isSimple())
1939 return false;
1940
1941 Value *StoredVal = SI->getValueOperand();
1942 Value *StorePtr = SI->getPointerOperand();
1943
1944 // Reject stores that are so large that they overflow an unsigned.
1945 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
1946 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
1947 return false;
1948
1949 // See if the pointer expression is an AddRec like {base,+,1} on the current
1950 // loop, which indicates a strided store. If we have something else, it's a
1951 // random store we can't handle.
1952 auto *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1953 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine()) {
1954 ORE.emit([&]() {
1955 return OptimizationRemarkMissed(DEBUG_TYPE, "NonAffineStorePtr",
1956 SI->getDebugLoc(), SI->getParent())
1957 << "store pointer is not an affine AddRec";
1958 });
1959 return false;
1960 }
1961
1962 // Check to see if the stride matches the size of the store. If so, then we
1963 // know that every byte is touched in the loop.
1964 int Stride = getSCEVStride(StoreEv);
1965 if (Stride == 0)
1966 return false;
1967 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1968 if (StoreSize != unsigned(std::abs(Stride))) {
1969 ORE.emit([&]() {
1970 return OptimizationRemarkMissed(DEBUG_TYPE, "StrideSizeMismatch",
1971 SI->getDebugLoc(), SI->getParent())
1972 << "stride does not match store size";
1973 });
1974 return false;
1975 }
1976
1977 // The store must be feeding a non-volatile load.
1978 LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
1979 if (!LI || !LI->isSimple()) {
1980 ORE.emit([&]() {
1981 return OptimizationRemarkMissed(DEBUG_TYPE, "StoreNotFeedingLoad",
1982 SI->getDebugLoc(), SI->getParent())
1983 << "store value is not a simple load";
1984 });
1985 return false;
1986 }
1987
1988 // See if the pointer expression is an AddRec like {base,+,1} on the current
1989 // loop, which indicates a strided load. If we have something else, it's a
1990 // random load we can't handle.
1991 Value *LoadPtr = LI->getPointerOperand();
1992 auto *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1993 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine()) {
1994 ORE.emit([&]() {
1995 return OptimizationRemarkMissed(DEBUG_TYPE, "NonAffineLoadPtr",
1996 LI->getDebugLoc(), LI->getParent())
1997 << "load pointer is not an affine AddRec";
1998 });
1999 return false;
2000 }
2001
2002 // The store and load must share the same stride.
2003 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
2004 return false;
2005
2006 // Success. This store can be converted into a memcpy.
2007 return true;
2008}
2009
2010/// mayLoopAccessLocation - Return true if the specified loop might access the
2011/// specified pointer location, which is a loop-strided access. The 'Access'
2012/// argument specifies what the verboten forms of access are (read or write).
2013static bool
2015 const SCEV *BECount, unsigned StoreSize,
2018 // Get the location that may be stored across the loop. Since the access
2019 // is strided positively through memory, we say that the modified location
2020 // starts at the pointer and has infinite size.
2022
2023 // If the loop iterates a fixed number of times, we can refine the access
2024 // size to be exactly the size of the memset, which is (BECount+1)*StoreSize
2025 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
2026 AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
2027 StoreSize);
2028
2029 // TODO: For this to be really effective, we have to dive into the pointer
2030 // operand in the store. Store to &A[i] of 100 will always return may alias
2031 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
2032 // which will then no-alias a store to &A[100].
2033 MemoryLocation StoreLoc(Ptr, AccessSize);
2034
2035 for (auto *B : L->blocks())
2036 for (auto &I : *B)
2037 if (Ignored.count(&I) == 0 &&
2038 isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access))
2039 return true;
2040
2041 return false;
2042}
2043
2044void HexagonLoopIdiomRecognize::collectStores(Loop *CurLoop, BasicBlock *BB,
2045 SmallVectorImpl<StoreInst*> &Stores) {
2046 Stores.clear();
2047 for (Instruction &I : *BB)
2048 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2049 if (isLegalStore(CurLoop, SI))
2050 Stores.push_back(SI);
2051}
2052
2053bool HexagonLoopIdiomRecognize::processCopyingStore(Loop *CurLoop,
2054 StoreInst *SI, const SCEV *BECount) {
2055 assert((SI->isSimple() || (SI->isVolatile() && HexagonVolatileMemcpy)) &&
2056 "Expected only non-volatile stores, or Hexagon-specific memcpy"
2057 "to volatile destination.");
2058
2059 Value *StorePtr = SI->getPointerOperand();
2060 auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
2061 unsigned Stride = getSCEVStride(StoreEv);
2062 unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
2063 if (Stride != StoreSize)
2064 return false;
2065
2066 // See if the pointer expression is an AddRec like {base,+,1} on the current
2067 // loop, which indicates a strided load. If we have something else, it's a
2068 // random load we can't handle.
2069 auto *LI = cast<LoadInst>(SI->getValueOperand());
2070 auto *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
2071
2072 // The trip count of the loop and the base pointer of the addrec SCEV is
2073 // guaranteed to be loop invariant, which means that it should dominate the
2074 // header. This allows us to insert code for it in the preheader.
2075 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2076 Instruction *ExpPt = Preheader->getTerminator();
2077 IRBuilder<> Builder(ExpPt);
2078 SCEVExpander Expander(*SE, "hexagon-loop-idiom");
2079
2080 Type *IntPtrTy = Builder.getIntPtrTy(*DL, SI->getPointerAddressSpace());
2081
2082 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
2083 // this into a memcpy/memmove in the loop preheader now if we want. However,
2084 // this would be unsafe to do if there is anything else in the loop that may
2085 // read or write the memory region we're storing to. For memcpy, this
2086 // includes the load that feeds the stores. Check for an alias by generating
2087 // the base address and checking everything.
2088 Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(),
2089 Builder.getPtrTy(SI->getPointerAddressSpace()), ExpPt);
2090 Value *LoadBasePtr = nullptr;
2091
2092 bool Overlap = false;
2093 bool DestVolatile = SI->isVolatile();
2094 Type *BECountTy = BECount->getType();
2095
2096 if (DestVolatile) {
2097 // The trip count must fit in i32, since it is the type of the "num_words"
2098 // argument to hexagon_memcpy_forward_vp4cp4n2.
2099 if (StoreSize != 4 || DL->getTypeSizeInBits(BECountTy) > 32) {
2100CleanupAndExit:
2101 // If we generated new code for the base pointer, clean up.
2102 Expander.clear();
2103 if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
2105 StoreBasePtr = nullptr;
2106 }
2107 if (LoadBasePtr) {
2109 LoadBasePtr = nullptr;
2110 }
2111 return false;
2112 }
2113 }
2114
2115 SmallPtrSet<Instruction*, 2> Ignore1;
2116 Ignore1.insert(SI);
2117 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
2118 StoreSize, *AA, Ignore1)) {
2119 // Check if the load is the offending instruction.
2120 Ignore1.insert(LI);
2121 if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
2122 BECount, StoreSize, *AA, Ignore1)) {
2123 // Still bad. Nothing we can do.
2124 ORE.emit([&]() {
2125 return OptimizationRemarkMissed(DEBUG_TYPE, "MemoryAlias",
2126 SI->getDebugLoc(), SI->getParent())
2127 << "memory aliasing prevents memcpy/memmove";
2128 });
2129 goto CleanupAndExit;
2130 }
2131 // It worked with the load ignored.
2132 Overlap = true;
2133 }
2134
2135 if (!Overlap) {
2136 if (DisableMemcpyIdiom || !HasMemcpy) {
2137 ORE.emit([&]() {
2138 return OptimizationRemarkMissed(DEBUG_TYPE, "MemcpyDisabled",
2139 SI->getDebugLoc(), SI->getParent())
2140 << "memcpy idiom is disabled or unavailable";
2141 });
2142 goto CleanupAndExit;
2143 }
2144 } else {
2145 // Don't generate memmove if this function will be inlined. This is
2146 // because the caller will undergo this transformation after inlining.
2147 Function *Func = CurLoop->getHeader()->getParent();
2148 if (Func->hasFnAttribute(Attribute::AlwaysInline))
2149 goto CleanupAndExit;
2150
2151 // In case of a memmove, the call to memmove will be executed instead
2152 // of the loop, so we need to make sure that there is nothing else in
2153 // the loop than the load, store and instructions that these two depend
2154 // on.
2155 SmallVector<Instruction*,2> Insts;
2156 Insts.push_back(SI);
2157 Insts.push_back(LI);
2158 if (!coverLoop(CurLoop, Insts)) {
2159 ORE.emit([&]() {
2160 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtraLoopInstructions",
2161 SI->getDebugLoc(), SI->getParent())
2162 << "loop contains instructions beyond load/store pair";
2163 });
2164 goto CleanupAndExit;
2165 }
2166
2167 if (DisableMemmoveIdiom || !HasMemmove) {
2168 ORE.emit([&]() {
2169 return OptimizationRemarkMissed(DEBUG_TYPE, "MemmoveDisabled",
2170 SI->getDebugLoc(), SI->getParent())
2171 << "memmove idiom is disabled or unavailable";
2172 });
2173 goto CleanupAndExit;
2174 }
2175 bool IsNested = CurLoop->getParentLoop() != nullptr;
2176 if (IsNested && OnlyNonNestedMemmove) {
2177 ORE.emit([&]() {
2178 return OptimizationRemarkMissed(DEBUG_TYPE, "NestedLoop",
2179 SI->getDebugLoc(), SI->getParent())
2180 << "memmove skipped for nested loop";
2181 });
2182 goto CleanupAndExit;
2183 }
2184 }
2185
2186 // For a memcpy, we have to make sure that the input array is not being
2187 // mutated by the loop.
2188 LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(),
2189 Builder.getPtrTy(LI->getPointerAddressSpace()), ExpPt);
2190
2191 SmallPtrSet<Instruction*, 2> Ignore2;
2192 Ignore2.insert(SI);
2193 if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
2194 StoreSize, *AA, Ignore2))
2195 goto CleanupAndExit;
2196
2197 // Check the stride.
2198 bool StridePos = getSCEVStride(LoadEv) >= 0;
2199
2200 // Currently, the volatile memcpy only emulates traversing memory forward.
2201 if (!StridePos && DestVolatile)
2202 goto CleanupAndExit;
2203
2204 bool RuntimeCheck = (Overlap || DestVolatile);
2205
2206 BasicBlock *ExitB;
2207 if (RuntimeCheck) {
2208 // The runtime check needs a single exit block.
2209 SmallVector<BasicBlock*, 8> ExitBlocks;
2210 CurLoop->getUniqueExitBlocks(ExitBlocks);
2211 if (ExitBlocks.size() != 1)
2212 goto CleanupAndExit;
2213 ExitB = ExitBlocks[0];
2214 }
2215
2216 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
2217 // pointer size if it isn't already.
2218 LLVMContext &Ctx = SI->getContext();
2219 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
2220 DebugLoc DLoc = SI->getDebugLoc();
2221
2222 const SCEV *NumBytesS =
2223 SE->getAddExpr(BECount, SE->getOne(IntPtrTy), SCEV::FlagNUW);
2224 if (StoreSize != 1)
2225 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
2227 Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
2228 if (Instruction *In = dyn_cast<Instruction>(NumBytes))
2229 if (Value *Simp = simplifyInstruction(In, {*DL, TLI, DT}))
2230 NumBytes = Simp;
2231
2232 CallInst *NewCall;
2233
2234 if (RuntimeCheck) {
2235 unsigned Threshold = RuntimeMemSizeThreshold;
2236 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) {
2237 uint64_t C = CI->getZExtValue();
2238 if (Threshold != 0 && C < Threshold)
2239 goto CleanupAndExit;
2241 goto CleanupAndExit;
2242 }
2243
2244 BasicBlock *Header = CurLoop->getHeader();
2245 Function *Func = Header->getParent();
2246 Loop *ParentL = LF->getLoopFor(Preheader);
2247 StringRef HeaderName = Header->getName();
2248
2249 // Create a new (empty) preheader, and update the PHI nodes in the
2250 // header to use the new preheader.
2251 BasicBlock *NewPreheader = BasicBlock::Create(Ctx, HeaderName+".rtli.ph",
2252 Func, Header);
2253 if (ParentL)
2254 ParentL->addBasicBlockToLoop(NewPreheader, *LF);
2255 IRBuilder<>(NewPreheader).CreateBr(Header);
2256 for (auto &In : *Header) {
2257 PHINode *PN = dyn_cast<PHINode>(&In);
2258 if (!PN)
2259 break;
2260 int bx = PN->getBasicBlockIndex(Preheader);
2261 if (bx >= 0)
2262 PN->setIncomingBlock(bx, NewPreheader);
2263 }
2264 DT->addNewBlock(NewPreheader, Preheader);
2265 DT->changeImmediateDominator(Header, NewPreheader);
2266
2267 // Check for safe conditions to execute memmove.
2268 // If stride is positive, copying things from higher to lower addresses
2269 // is equivalent to memmove. For negative stride, it's the other way
2270 // around. Copying forward in memory with positive stride may not be
2271 // same as memmove since we may be copying values that we just stored
2272 // in some previous iteration.
2273 Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy);
2274 Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
2275 Value *LowA = StridePos ? SA : LA;
2276 Value *HighA = StridePos ? LA : SA;
2277 Value *CmpA = Builder.CreateICmpULT(LowA, HighA);
2278 Value *Cond = CmpA;
2279
2280 // Check for distance between pointers. Since the case LowA < HighA
2281 // is checked for above, assume LowA >= HighA.
2282 Value *Dist = Builder.CreateSub(LowA, HighA);
2283 Value *CmpD = Builder.CreateICmpSLE(NumBytes, Dist);
2284 Value *CmpEither = Builder.CreateOr(Cond, CmpD);
2285 Cond = CmpEither;
2286
2287 if (Threshold != 0) {
2288 Type *Ty = NumBytes->getType();
2289 Value *Thr = ConstantInt::get(Ty, Threshold);
2290 Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
2291 Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
2292 Cond = CmpBoth;
2293 }
2294 BasicBlock *MemmoveB = BasicBlock::Create(Ctx, Header->getName()+".rtli",
2295 Func, NewPreheader);
2296 if (ParentL)
2297 ParentL->addBasicBlockToLoop(MemmoveB, *LF);
2298 Instruction *OldT = Preheader->getTerminator();
2299 Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
2300 OldT->eraseFromParent();
2301 Preheader->setName(Preheader->getName()+".old");
2302 DT->addNewBlock(MemmoveB, Preheader);
2303 // Find the new immediate dominator of the exit block.
2304 BasicBlock *ExitD = Preheader;
2305 for (BasicBlock *PB : predecessors(ExitB)) {
2306 ExitD = DT->findNearestCommonDominator(ExitD, PB);
2307 if (!ExitD)
2308 break;
2309 }
2310 // If the prior immediate dominator of ExitB was dominated by the
2311 // old preheader, then the old preheader becomes the new immediate
2312 // dominator. Otherwise don't change anything (because the newly
2313 // added blocks are dominated by the old preheader).
2314 if (ExitD && DT->dominates(Preheader, ExitD)) {
2315 DomTreeNode *BN = DT->getNode(ExitB);
2316 DomTreeNode *DN = DT->getNode(ExitD);
2317 BN->setIDom(DN);
2318 }
2319
2320 // Add a call to memmove to the conditional block.
2321 IRBuilder<> CondBuilder(MemmoveB);
2322 CondBuilder.CreateBr(ExitB);
2323 CondBuilder.SetInsertPoint(MemmoveB->getTerminator());
2324
2325 if (DestVolatile) {
2326 Type *Int32Ty = Type::getInt32Ty(Ctx);
2327 Type *PtrTy = PointerType::get(Ctx, 0);
2328 Type *VoidTy = Type::getVoidTy(Ctx);
2329 Module *M = Func->getParent();
2330
2331 // FIXME: This should check if the call is supported
2332 StringRef HexagonVolatileMemcpyName =
2334 RTLIB::impl_hexagon_memcpy_forward_vp4cp4n2);
2335 FunctionCallee Fn = M->getOrInsertFunction(
2336 HexagonVolatileMemcpyName, VoidTy, PtrTy, PtrTy, Int32Ty);
2337
2338 const SCEV *OneS = SE->getConstant(Int32Ty, 1);
2339 const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
2340 const SCEV *NumWordsS = SE->getAddExpr(BECount32, OneS, SCEV::FlagNUW);
2341 Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
2342 MemmoveB->getTerminator());
2343 if (Instruction *In = dyn_cast<Instruction>(NumWords))
2344 if (Value *Simp = simplifyInstruction(In, {*DL, TLI, DT}))
2345 NumWords = Simp;
2346
2347 NewCall = CondBuilder.CreateCall(Fn,
2348 {StoreBasePtr, LoadBasePtr, NumWords});
2349 } else {
2350 NewCall = CondBuilder.CreateMemMove(
2351 StoreBasePtr, SI->getAlign(), LoadBasePtr, LI->getAlign(), NumBytes);
2352 }
2353 } else {
2354 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlign(), LoadBasePtr,
2355 LI->getAlign(), NumBytes);
2356 // Okay, the memcpy has been formed. Zap the original store and
2357 // anything that feeds into it.
2359 }
2360
2361 NewCall->setDebugLoc(DLoc);
2362
2363 LLVM_DEBUG(dbgs() << " Formed " << (Overlap ? "memmove: " : "memcpy: ")
2364 << *NewCall << "\n"
2365 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
2366 << " from store ptr=" << *StoreEv << " at: " << *SI
2367 << "\n");
2368
2369 if (Overlap) {
2370 ORE.emit([&]() {
2371 return OptimizationRemark(DEBUG_TYPE, "LoopToMemmove", DLoc,
2372 CurLoop->getHeader())
2373 << "converted loop to memmove";
2374 });
2375 } else {
2376 ORE.emit([&]() {
2377 return OptimizationRemark(DEBUG_TYPE, "LoopToMemcpy", DLoc,
2378 CurLoop->getHeader())
2379 << "converted loop to memcpy";
2380 });
2381 }
2382
2383 return true;
2384}
2385
2386// Check if the instructions in Insts, together with their dependencies
2387// cover the loop in the sense that the loop could be safely eliminated once
2388// the instructions in Insts are removed.
2389bool HexagonLoopIdiomRecognize::coverLoop(Loop *L,
2390 SmallVectorImpl<Instruction*> &Insts) const {
2391 SmallPtrSet<BasicBlock *, 8> LoopBlocks;
2392 LoopBlocks.insert_range(L->blocks());
2393
2394 SetVector<Instruction *> Worklist(llvm::from_range, Insts);
2395
2396 // Collect all instructions from the loop that the instructions in Insts
2397 // depend on (plus their dependencies, etc.). These instructions will
2398 // constitute the expression trees that feed those in Insts, but the trees
2399 // will be limited only to instructions contained in the loop.
2400 for (unsigned i = 0; i < Worklist.size(); ++i) {
2401 Instruction *In = Worklist[i];
2402 for (auto I = In->op_begin(), E = In->op_end(); I != E; ++I) {
2404 if (!OpI)
2405 continue;
2406 BasicBlock *PB = OpI->getParent();
2407 if (!LoopBlocks.count(PB))
2408 continue;
2409 Worklist.insert(OpI);
2410 }
2411 }
2412
2413 // Scan all instructions in the loop, if any of them have a user outside
2414 // of the loop, or outside of the expressions collected above, then either
2415 // the loop has a side-effect visible outside of it, or there are
2416 // instructions in it that are not involved in the original set Insts.
2417 for (auto *B : L->blocks()) {
2418 for (auto &In : *B) {
2420 continue;
2421 if (!Worklist.count(&In) && In.mayHaveSideEffects())
2422 return false;
2423 for (Instruction *UseI : In.users()) {
2424 BasicBlock *UseB = UseI->getParent();
2425 if (LF->getLoopFor(UseB) != L)
2426 return false;
2427 }
2428 }
2429 }
2430
2431 return true;
2432}
2433
2434/// runOnLoopBlock - Process the specified block, which lives in a counted loop
2435/// with the specified backedge count. This block is known to be in the current
2436/// loop and not in any subloops.
2437bool HexagonLoopIdiomRecognize::runOnLoopBlock(Loop *CurLoop, BasicBlock *BB,
2438 const SCEV *BECount, SmallVectorImpl<BasicBlock*> &ExitBlocks) {
2439 // We can only promote stores in this block if they are unconditionally
2440 // executed in the loop. For a block to be unconditionally executed, it has
2441 // to dominate all the exit blocks of the loop. Verify this now.
2442 auto DominatedByBB = [this,BB] (BasicBlock *EB) -> bool {
2443 return DT->dominates(BB, EB);
2444 };
2445 if (!all_of(ExitBlocks, DominatedByBB))
2446 return false;
2447
2448 bool MadeChange = false;
2449 // Look for store instructions, which may be optimized to memset/memcpy.
2450 SmallVector<StoreInst*,8> Stores;
2451 collectStores(CurLoop, BB, Stores);
2452
2453 // Optimize the store into a memcpy, if it feeds an similarly strided load.
2454 for (auto &SI : Stores)
2455 MadeChange |= processCopyingStore(CurLoop, SI, BECount);
2456
2457 return MadeChange;
2458}
2459
2460bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
2461 PolynomialMultiplyRecognize PMR(L, *DL, *DT, *TLI, *SE);
2462 if (PMR.recognize()) {
2463 ORE.emit([&]() {
2464 return OptimizationRemark(DEBUG_TYPE, "PolynomialMultiply",
2465 L->getStartLoc(), L->getHeader())
2466 << "recognized polynomial multiply idiom";
2467 });
2468 return true;
2469 }
2470
2471 if (!HasMemcpy && !HasMemmove)
2472 return false;
2473
2474 const SCEV *BECount = SE->getBackedgeTakenCount(L);
2475 assert(!isa<SCEVCouldNotCompute>(BECount) &&
2476 "runOnCountableLoop() called on a loop without a predictable"
2477 "backedge-taken count");
2478
2479 SmallVector<BasicBlock *, 8> ExitBlocks;
2480 L->getUniqueExitBlocks(ExitBlocks);
2481
2482 bool Changed = false;
2483
2484 // Scan all the blocks in the loop that are not in subloops.
2485 for (auto *BB : L->getBlocks()) {
2486 // Ignore blocks in subloops.
2487 if (LF->getLoopFor(BB) != L)
2488 continue;
2489 Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks);
2490 }
2491
2492 return Changed;
2493}
2494
2495bool HexagonLoopIdiomRecognize::run(Loop *L) {
2496 const Module &M = *L->getHeader()->getParent()->getParent();
2497 if (M.getTargetTriple().getArch() != Triple::hexagon)
2498 return false;
2499
2500 // If the loop could not be converted to canonical form, it must have an
2501 // indirectbr in it, just give up.
2502 if (!L->getLoopPreheader()) {
2503 ORE.emit([&]() {
2504 return OptimizationRemarkMissed(DEBUG_TYPE, "NoPreheader",
2505 L->getStartLoc(), L->getHeader())
2506 << "loop not in canonical form (no preheader)";
2507 });
2508 return false;
2509 }
2510
2511 // Disable loop idiom recognition if the function's name is a common idiom.
2512 StringRef Name = L->getHeader()->getParent()->getName();
2513 if (Name == "memset" || Name == "memcpy" || Name == "memmove")
2514 return false;
2515
2516 DL = &L->getHeader()->getDataLayout();
2517
2518 HasMemcpy = TLI->has(LibFunc_memcpy);
2519 HasMemmove = TLI->has(LibFunc_memmove);
2520
2521 if (SE->hasLoopInvariantBackedgeTakenCount(L))
2522 return runOnCountableLoop(L);
2523
2524 ORE.emit([&]() {
2525 return OptimizationRemarkMissed(DEBUG_TYPE, "NonCountableLoop",
2526 L->getStartLoc(), L->getHeader())
2527 << "backedge-taken count is not loop-invariant";
2528 });
2529 return false;
2530}
2531
2532bool HexagonLoopIdiomRecognizeLegacyPass::runOnLoop(Loop *L,
2533 LPPassManager &LPM) {
2534 if (skipLoop(L))
2535 return false;
2536
2537 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2538 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2539 auto *LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2540 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
2541 *L->getHeader()->getParent());
2542 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2543 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2544 return HexagonLoopIdiomRecognize(AA, DT, LF, TLI, SE, ORE).run(L);
2545}
2546
2548 return new HexagonLoopIdiomRecognizeLegacyPass();
2549}
2550
2554 LPMUpdater &U) {
2555 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
2556 return HexagonLoopIdiomRecognize(&AR.AA, &AR.DT, &AR.LI, &AR.TLI, &AR.SE, ORE)
2557 .run(&L)
2560}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ATTRIBUTE_USED
Definition Compiler.h:234
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
This file defines the DenseMap class.
#define DEBUG_TYPE
hexagon bit simplify
static cl::opt< unsigned > SimplifyLimit("hlir-simplify-limit", cl::init(10000), cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"))
static cl::opt< bool > DisableMemcpyIdiom("disable-memcpy-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memcpy in loop idiom recognition"))
static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB)
static cl::opt< unsigned > RuntimeMemSizeThreshold("runtime-mem-idiom-threshold", cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime " "check guarding the memmove."))
static cl::opt< bool > HexagonVolatileMemcpy("disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false), cl::desc("Enable Hexagon-specific memcpy for volatile destination."))
static cl::opt< bool > DisableMemmoveIdiom("disable-memmove-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memmove in loop idiom recognition"))
static cl::opt< unsigned > CompileTimeMemSizeThreshold("compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64), cl::desc("Threshold (in bytes) to perform the transformation, if the " "runtime loop count (mem transfer size) is known at compile-time."))
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Ignored)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
static bool hasZeroSignBit(const Value *V)
static cl::opt< bool > OnlyNonNestedMemmove("only-nonnested-memmove-idiom", cl::Hidden, cl::init(true), cl::desc("Only enable generating memmove in non-nested loops"))
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
Move duplicate certain instructions close to their use
Definition Localizer.cpp:78
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
This header provides classes for managing per-loop analyses.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file provides utility analysis objects describing memory locations.
#define T
uint64_t IntrinsicInst * II
#define P(N)
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
int64_t C1
int64_t C0
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
Definition Pass.cpp:294
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BinaryOps getOpcode() const
Definition InstrTypes.h:409
@ ICMP_NE
not equal
Definition InstrTypes.h:762
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
void setIDom(DomTreeNodeBase *NewIDom)
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
bool empty() const
Definition Function.h:853
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
void setIncomingBlock(unsigned i, BasicBlock *BB)
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
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
This class represents a constant integer value.
SCEVUse getOperand(unsigned i) const
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
Provides information about what library functions are available for the current target.
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
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
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
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
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
@ Known
Known to have no common set bits.
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
Pass * createHexagonLoopIdiomPass()
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI char & LCSSAID
Definition LCSSA.cpp:545
LLVM_ABI char & LoopSimplifyID
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
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
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.