1 //===- ParallelDSP.cpp - Parallel DSP Pass --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Armv6 introduced instructions to perform 32-bit SIMD operations. The
11 /// purpose of this pass is do some IR pattern matching to create ACLE
12 /// DSP intrinsics, which map on these 32-bit SIMD operations.
13 /// This pass runs only when unaligned accesses is supported/enabled.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/LoopAccessAnalysis.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/NoFolder.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "llvm/Transforms/Utils/LoopUtils.h"
28 #include "llvm/Pass.h"
29 #include "llvm/PassRegistry.h"
30 #include "llvm/PassSupport.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "ARM.h"
35 #include "ARMSubtarget.h"
36 
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 #define DEBUG_TYPE "arm-parallel-dsp"
41 
42 STATISTIC(NumSMLAD , "Number of smlad instructions generated");
43 
44 static cl::opt<bool>
45 DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false),
46                    cl::desc("Disable the ARM Parallel DSP pass"));
47 
48 namespace {
49   struct OpChain;
50   struct BinOpChain;
51   class Reduction;
52 
53   using OpChainList     = SmallVector<std::unique_ptr<OpChain>, 8>;
54   using ReductionList   = SmallVector<Reduction, 8>;
55   using ValueList       = SmallVector<Value*, 8>;
56   using MemInstList     = SmallVector<LoadInst*, 8>;
57   using PMACPair        = std::pair<BinOpChain*,BinOpChain*>;
58   using PMACPairList    = SmallVector<PMACPair, 8>;
59   using Instructions    = SmallVector<Instruction*,16>;
60   using MemLocList      = SmallVector<MemoryLocation, 4>;
61 
62   struct OpChain {
63     Instruction   *Root;
64     ValueList     AllValues;
65     MemInstList   VecLd;    // List of all load instructions.
66     MemInstList   Loads;
67     bool          ReadOnly = true;
68 
69     OpChain(Instruction *I, ValueList &vl) : Root(I), AllValues(vl) { }
70     virtual ~OpChain() = default;
71 
72     void PopulateLoads() {
73       for (auto *V : AllValues) {
74         if (auto *Ld = dyn_cast<LoadInst>(V))
75           Loads.push_back(Ld);
76       }
77     }
78 
79     unsigned size() const { return AllValues.size(); }
80   };
81 
82   // 'BinOpChain' holds the multiplication instructions that are candidates
83   // for parallel execution.
84   struct BinOpChain : public OpChain {
85     ValueList     LHS;      // List of all (narrow) left hand operands.
86     ValueList     RHS;      // List of all (narrow) right hand operands.
87     bool Exchange = false;
88 
89     BinOpChain(Instruction *I, ValueList &lhs, ValueList &rhs) :
90       OpChain(I, lhs), LHS(lhs), RHS(rhs) {
91         for (auto *V : RHS)
92           AllValues.push_back(V);
93       }
94 
95     bool AreSymmetrical(BinOpChain *Other);
96   };
97 
98   /// Represent a sequence of multiply-accumulate operations with the aim to
99   /// perform the multiplications in parallel.
100   class Reduction {
101     Instruction     *Root = nullptr;
102     Value           *Acc = nullptr;
103     OpChainList     Muls;
104     PMACPairList        MulPairs;
105     SmallPtrSet<Instruction*, 4> Adds;
106 
107   public:
108     Reduction() = delete;
109 
110     Reduction (Instruction *Add) : Root(Add) { }
111 
112     /// Record an Add instruction that is a part of the this reduction.
113     void InsertAdd(Instruction *I) { Adds.insert(I); }
114 
115     /// Record a BinOpChain, rooted at a Mul instruction, that is a part of
116     /// this reduction.
117     void InsertMul(Instruction *I, ValueList &LHS, ValueList &RHS) {
118       Muls.push_back(make_unique<BinOpChain>(I, LHS, RHS));
119     }
120 
121     /// Add the incoming accumulator value, returns true if a value had not
122     /// already been added. Returning false signals to the user that this
123     /// reduction already has a value to initialise the accumulator.
124     bool InsertAcc(Value *V) {
125       if (Acc)
126         return false;
127       Acc = V;
128       return true;
129     }
130 
131     /// Set two BinOpChains, rooted at muls, that can be executed as a single
132     /// parallel operation.
133     void AddMulPair(BinOpChain *Mul0, BinOpChain *Mul1) {
134       MulPairs.push_back(std::make_pair(Mul0, Mul1));
135     }
136 
137     /// Return true if enough mul operations are found that can be executed in
138     /// parallel.
139     bool CreateParallelPairs();
140 
141     /// Return the add instruction which is the root of the reduction.
142     Instruction *getRoot() { return Root; }
143 
144     /// Return the incoming value to be accumulated. This maybe null.
145     Value *getAccumulator() { return Acc; }
146 
147     /// Return the set of adds that comprise the reduction.
148     SmallPtrSetImpl<Instruction*> &getAdds() { return Adds; }
149 
150     /// Return the BinOpChain, rooted at mul instruction, that comprise the
151     /// the reduction.
152     OpChainList &getMuls() { return Muls; }
153 
154     /// Return the BinOpChain, rooted at mul instructions, that have been
155     /// paired for parallel execution.
156     PMACPairList &getMulPairs() { return MulPairs; }
157 
158     /// To finalise, replace the uses of the root with the intrinsic call.
159     void UpdateRoot(Instruction *SMLAD) {
160       Root->replaceAllUsesWith(SMLAD);
161     }
162   };
163 
164   class WidenedLoad {
165     LoadInst *NewLd = nullptr;
166     SmallVector<LoadInst*, 4> Loads;
167 
168   public:
169     WidenedLoad(SmallVectorImpl<LoadInst*> &Lds, LoadInst *Wide)
170       : NewLd(Wide) {
171       for (auto *I : Lds)
172         Loads.push_back(I);
173     }
174     LoadInst *getLoad() {
175       return NewLd;
176     }
177   };
178 
179   class ARMParallelDSP : public LoopPass {
180     ScalarEvolution   *SE;
181     AliasAnalysis     *AA;
182     TargetLibraryInfo *TLI;
183     DominatorTree     *DT;
184     LoopInfo          *LI;
185     Loop              *L;
186     const DataLayout  *DL;
187     Module            *M;
188     std::map<LoadInst*, LoadInst*> LoadPairs;
189     SmallPtrSet<LoadInst*, 4> OffsetLoads;
190     std::map<LoadInst*, std::unique_ptr<WidenedLoad>> WideLoads;
191 
192     template<unsigned>
193     bool IsNarrowSequence(Value *V, ValueList &VL);
194 
195     bool RecordMemoryOps(BasicBlock *BB);
196     void InsertParallelMACs(Reduction &Reduction);
197     bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
198     LoadInst* CreateWideLoad(SmallVectorImpl<LoadInst*> &Loads,
199                              IntegerType *LoadTy);
200     bool CreateParallelPairs(Reduction &R);
201 
202     /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
203     /// Dual performs two signed 16x16-bit multiplications. It adds the
204     /// products to a 32-bit accumulate operand. Optionally, the instruction can
205     /// exchange the halfwords of the second operand before performing the
206     /// arithmetic.
207     bool MatchSMLAD(Loop *L);
208 
209   public:
210     static char ID;
211 
212     ARMParallelDSP() : LoopPass(ID) { }
213 
214     bool doInitialization(Loop *L, LPPassManager &LPM) override {
215       LoadPairs.clear();
216       WideLoads.clear();
217       return true;
218     }
219 
220     void getAnalysisUsage(AnalysisUsage &AU) const override {
221       LoopPass::getAnalysisUsage(AU);
222       AU.addRequired<AssumptionCacheTracker>();
223       AU.addRequired<ScalarEvolutionWrapperPass>();
224       AU.addRequired<AAResultsWrapperPass>();
225       AU.addRequired<TargetLibraryInfoWrapperPass>();
226       AU.addRequired<LoopInfoWrapperPass>();
227       AU.addRequired<DominatorTreeWrapperPass>();
228       AU.addRequired<TargetPassConfig>();
229       AU.addPreserved<LoopInfoWrapperPass>();
230       AU.setPreservesCFG();
231     }
232 
233     bool runOnLoop(Loop *TheLoop, LPPassManager &) override {
234       if (DisableParallelDSP)
235         return false;
236       if (skipLoop(TheLoop))
237         return false;
238 
239       L = TheLoop;
240       SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
241       AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
242       TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
243       DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
244       LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
245       auto &TPC = getAnalysis<TargetPassConfig>();
246 
247       BasicBlock *Header = TheLoop->getHeader();
248       if (!Header)
249         return false;
250 
251       // TODO: We assume the loop header and latch to be the same block.
252       // This is not a fundamental restriction, but lifting this would just
253       // require more work to do the transformation and then patch up the CFG.
254       if (Header != TheLoop->getLoopLatch()) {
255         LLVM_DEBUG(dbgs() << "The loop header is not the loop latch: not "
256                              "running pass ARMParallelDSP\n");
257         return false;
258       }
259 
260       if (!TheLoop->getLoopPreheader())
261         InsertPreheaderForLoop(L, DT, LI, nullptr, true);
262 
263       Function &F = *Header->getParent();
264       M = F.getParent();
265       DL = &M->getDataLayout();
266 
267       auto &TM = TPC.getTM<TargetMachine>();
268       auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
269 
270       if (!ST->allowsUnalignedMem()) {
271         LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
272                              "running pass ARMParallelDSP\n");
273         return false;
274       }
275 
276       if (!ST->hasDSP()) {
277         LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
278                              "ARMParallelDSP\n");
279         return false;
280       }
281 
282       if (!ST->isLittle()) {
283         LLVM_DEBUG(dbgs() << "Only supporting little endian: not running pass "
284                           << "ARMParallelDSP\n");
285         return false;
286       }
287 
288       LoopAccessInfo LAI(L, SE, TLI, AA, DT, LI);
289 
290       LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
291       LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
292 
293       if (!RecordMemoryOps(Header)) {
294         LLVM_DEBUG(dbgs() << " - No sequential loads found.\n");
295         return false;
296       }
297 
298       bool Changes = MatchSMLAD(L);
299       return Changes;
300     }
301   };
302 }
303 
304 template<typename MemInst>
305 static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
306                                   const DataLayout &DL, ScalarEvolution &SE) {
307   if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE))
308     return true;
309   return false;
310 }
311 
312 bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
313                                         MemInstList &VecMem) {
314   if (!Ld0 || !Ld1)
315     return false;
316 
317   if (!LoadPairs.count(Ld0) || LoadPairs[Ld0] != Ld1)
318     return false;
319 
320   LLVM_DEBUG(dbgs() << "Loads are sequential and valid:\n";
321     dbgs() << "Ld0:"; Ld0->dump();
322     dbgs() << "Ld1:"; Ld1->dump();
323   );
324 
325   VecMem.clear();
326   VecMem.push_back(Ld0);
327   VecMem.push_back(Ld1);
328   return true;
329 }
330 
331 // MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
332 // instructions, which is set to 16. So here we should collect all i8 and i16
333 // narrow operations.
334 // TODO: we currently only collect i16, and will support i8 later, so that's
335 // why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
336 template<unsigned MaxBitWidth>
337 bool ARMParallelDSP::IsNarrowSequence(Value *V, ValueList &VL) {
338   if (auto *SExt = dyn_cast<SExtInst>(V)) {
339     if (SExt->getSrcTy()->getIntegerBitWidth() != MaxBitWidth)
340       return false;
341 
342     if (auto *Ld = dyn_cast<LoadInst>(SExt->getOperand(0))) {
343       // Check that these load could be paired.
344       if (!LoadPairs.count(Ld) && !OffsetLoads.count(Ld))
345         return false;
346 
347       VL.push_back(Ld);
348       VL.push_back(SExt);
349       return true;
350     }
351   }
352   return false;
353 }
354 
355 /// Iterate through the block and record base, offset pairs of loads which can
356 /// be widened into a single load.
357 bool ARMParallelDSP::RecordMemoryOps(BasicBlock *BB) {
358   SmallVector<LoadInst*, 8> Loads;
359   SmallVector<Instruction*, 8> Writes;
360 
361   // Collect loads and instruction that may write to memory. For now we only
362   // record loads which are simple, sign-extended and have a single user.
363   // TODO: Allow zero-extended loads.
364   for (auto &I : *BB) {
365     if (I.mayWriteToMemory())
366       Writes.push_back(&I);
367     auto *Ld = dyn_cast<LoadInst>(&I);
368     if (!Ld || !Ld->isSimple() ||
369         !Ld->hasOneUse() || !isa<SExtInst>(Ld->user_back()))
370       continue;
371     Loads.push_back(Ld);
372   }
373 
374   using InstSet = std::set<Instruction*>;
375   using DepMap = std::map<Instruction*, InstSet>;
376   DepMap RAWDeps;
377 
378   // Record any writes that may alias a load.
379   const auto Size = LocationSize::unknown();
380   for (auto Read : Loads) {
381     for (auto Write : Writes) {
382       MemoryLocation ReadLoc =
383         MemoryLocation(Read->getPointerOperand(), Size);
384 
385       if (!isModOrRefSet(intersectModRef(AA->getModRefInfo(Write, ReadLoc),
386           ModRefInfo::ModRef)))
387         continue;
388       if (DT->dominates(Write, Read))
389         RAWDeps[Read].insert(Write);
390     }
391   }
392 
393   // Check whether there's not a write between the two loads which would
394   // prevent them from being safely merged.
395   auto SafeToPair = [&](LoadInst *Base, LoadInst *Offset) {
396     LoadInst *Dominator = DT->dominates(Base, Offset) ? Base : Offset;
397     LoadInst *Dominated = DT->dominates(Base, Offset) ? Offset : Base;
398 
399     if (RAWDeps.count(Dominated)) {
400       InstSet &WritesBefore = RAWDeps[Dominated];
401 
402       for (auto Before : WritesBefore) {
403 
404         // We can't move the second load backward, past a write, to merge
405         // with the first load.
406         if (DT->dominates(Dominator, Before))
407           return false;
408       }
409     }
410     return true;
411   };
412 
413   // Record base, offset load pairs.
414   for (auto *Base : Loads) {
415     for (auto *Offset : Loads) {
416       if (Base == Offset)
417         continue;
418 
419       if (AreSequentialAccesses<LoadInst>(Base, Offset, *DL, *SE) &&
420           SafeToPair(Base, Offset)) {
421         LoadPairs[Base] = Offset;
422         OffsetLoads.insert(Offset);
423         break;
424       }
425     }
426   }
427 
428   LLVM_DEBUG(if (!LoadPairs.empty()) {
429                dbgs() << "Consecutive load pairs:\n";
430                for (auto &MapIt : LoadPairs) {
431                  LLVM_DEBUG(dbgs() << *MapIt.first << ", "
432                             << *MapIt.second << "\n");
433                }
434              });
435   return LoadPairs.size() > 1;
436 }
437 
438 // Loop Pass that needs to identify integer add/sub reductions of 16-bit vector
439 // multiplications.
440 // To use SMLAD:
441 // 1) we first need to find integer add then look for this pattern:
442 //
443 // acc0 = ...
444 // ld0 = load i16
445 // sext0 = sext i16 %ld0 to i32
446 // ld1 = load i16
447 // sext1 = sext i16 %ld1 to i32
448 // mul0 = mul %sext0, %sext1
449 // ld2 = load i16
450 // sext2 = sext i16 %ld2 to i32
451 // ld3 = load i16
452 // sext3 = sext i16 %ld3 to i32
453 // mul1 = mul i32 %sext2, %sext3
454 // add0 = add i32 %mul0, %acc0
455 // acc1 = add i32 %add0, %mul1
456 //
457 // Which can be selected to:
458 //
459 // ldr r0
460 // ldr r1
461 // smlad r2, r0, r1, r2
462 //
463 // If constants are used instead of loads, these will need to be hoisted
464 // out and into a register.
465 //
466 // If loop invariants are used instead of loads, these need to be packed
467 // before the loop begins.
468 //
469 bool ARMParallelDSP::MatchSMLAD(Loop *L) {
470   // Search recursively back through the operands to find a tree of values that
471   // form a multiply-accumulate chain. The search records the Add and Mul
472   // instructions that form the reduction and allows us to find a single value
473   // to be used as the initial input to the accumlator.
474   std::function<bool(Value*, Reduction&)> Search = [&]
475     (Value *V, Reduction &R) -> bool {
476 
477     // If we find a non-instruction, try to use it as the initial accumulator
478     // value. This may have already been found during the search in which case
479     // this function will return false, signaling a search fail.
480     auto *I = dyn_cast<Instruction>(V);
481     if (!I)
482       return R.InsertAcc(V);
483 
484     switch (I->getOpcode()) {
485     default:
486       break;
487     case Instruction::PHI:
488       // Could be the accumulator value.
489       return R.InsertAcc(V);
490     case Instruction::Add: {
491       // Adds should be adding together two muls, or another add and a mul to
492       // be within the mac chain. One of the operands may also be the
493       // accumulator value at which point we should stop searching.
494       bool ValidLHS = Search(I->getOperand(0), R);
495       bool ValidRHS = Search(I->getOperand(1), R);
496       if (!ValidLHS && !ValidLHS)
497         return false;
498       else if (ValidLHS && ValidRHS) {
499         R.InsertAdd(I);
500         return true;
501       } else {
502         R.InsertAdd(I);
503         return R.InsertAcc(I);
504       }
505     }
506     case Instruction::Mul: {
507       Value *MulOp0 = I->getOperand(0);
508       Value *MulOp1 = I->getOperand(1);
509       if (isa<SExtInst>(MulOp0) && isa<SExtInst>(MulOp1)) {
510         ValueList LHS;
511         ValueList RHS;
512         if (IsNarrowSequence<16>(MulOp0, LHS) &&
513             IsNarrowSequence<16>(MulOp1, RHS)) {
514           R.InsertMul(I, LHS, RHS);
515           return true;
516         }
517       }
518       return false;
519     }
520     case Instruction::SExt:
521       return Search(I->getOperand(0), R);
522     }
523     return false;
524   };
525 
526   bool Changed = false;
527   SmallPtrSet<Instruction*, 4> AllAdds;
528   BasicBlock *Latch = L->getLoopLatch();
529 
530   for (Instruction &I : reverse(*Latch)) {
531     if (I.getOpcode() != Instruction::Add)
532       continue;
533 
534     if (AllAdds.count(&I))
535       continue;
536 
537     const auto *Ty = I.getType();
538     if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
539       continue;
540 
541     Reduction R(&I);
542     if (!Search(&I, R))
543       continue;
544 
545     if (!CreateParallelPairs(R))
546       continue;
547 
548     InsertParallelMACs(R);
549     Changed = true;
550     AllAdds.insert(R.getAdds().begin(), R.getAdds().end());
551   }
552 
553   return Changed;
554 }
555 
556 bool ARMParallelDSP::CreateParallelPairs(Reduction &R) {
557 
558   // Not enough mul operations to make a pair.
559   if (R.getMuls().size() < 2)
560     return false;
561 
562   // Check that the muls operate directly upon sign extended loads.
563   for (auto &MulChain : R.getMuls()) {
564     // A mul has 2 operands, and a narrow op consist of sext and a load; thus
565     // we expect at least 4 items in this operand value list.
566     if (MulChain->size() < 4) {
567       LLVM_DEBUG(dbgs() << "Operand list too short.\n");
568       return false;
569     }
570     MulChain->PopulateLoads();
571     ValueList &LHS = static_cast<BinOpChain*>(MulChain.get())->LHS;
572     ValueList &RHS = static_cast<BinOpChain*>(MulChain.get())->RHS;
573 
574     // Use +=2 to skip over the expected extend instructions.
575     for (unsigned i = 0, e = LHS.size(); i < e; i += 2) {
576       if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
577         return false;
578     }
579   }
580 
581   auto CanPair = [&](Reduction &R, BinOpChain *PMul0, BinOpChain *PMul1) {
582     if (!PMul0->AreSymmetrical(PMul1))
583       return false;
584 
585     // The first elements of each vector should be loads with sexts. If we
586     // find that its two pairs of consecutive loads, then these can be
587     // transformed into two wider loads and the users can be replaced with
588     // DSP intrinsics.
589     for (unsigned x = 0; x < PMul0->LHS.size(); x += 2) {
590       auto *Ld0 = dyn_cast<LoadInst>(PMul0->LHS[x]);
591       auto *Ld1 = dyn_cast<LoadInst>(PMul1->LHS[x]);
592       auto *Ld2 = dyn_cast<LoadInst>(PMul0->RHS[x]);
593       auto *Ld3 = dyn_cast<LoadInst>(PMul1->RHS[x]);
594 
595       if (!Ld0 || !Ld1 || !Ld2 || !Ld3)
596         return false;
597 
598       LLVM_DEBUG(dbgs() << "Loads:\n"
599                  << " - " << *Ld0 << "\n"
600                  << " - " << *Ld1 << "\n"
601                  << " - " << *Ld2 << "\n"
602                  << " - " << *Ld3 << "\n");
603 
604       if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
605         if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
606           LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
607           R.AddMulPair(PMul0, PMul1);
608           return true;
609         } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
610           LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
611           LLVM_DEBUG(dbgs() << "    exchanging Ld2 and Ld3\n");
612           PMul1->Exchange = true;
613           R.AddMulPair(PMul0, PMul1);
614           return true;
615         }
616       } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd) &&
617                  AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
618         LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
619         LLVM_DEBUG(dbgs() << "    exchanging Ld0 and Ld1\n");
620         LLVM_DEBUG(dbgs() << "    and swapping muls\n");
621         PMul0->Exchange = true;
622         // Only the second operand can be exchanged, so swap the muls.
623         R.AddMulPair(PMul1, PMul0);
624         return true;
625       }
626     }
627     return false;
628   };
629 
630   OpChainList &Muls = R.getMuls();
631   const unsigned Elems = Muls.size();
632   SmallPtrSet<const Instruction*, 4> Paired;
633   for (unsigned i = 0; i < Elems; ++i) {
634     BinOpChain *PMul0 = static_cast<BinOpChain*>(Muls[i].get());
635     if (Paired.count(PMul0->Root))
636       continue;
637 
638     for (unsigned j = 0; j < Elems; ++j) {
639       if (i == j)
640         continue;
641 
642       BinOpChain *PMul1 = static_cast<BinOpChain*>(Muls[j].get());
643       if (Paired.count(PMul1->Root))
644         continue;
645 
646       const Instruction *Mul0 = PMul0->Root;
647       const Instruction *Mul1 = PMul1->Root;
648       if (Mul0 == Mul1)
649         continue;
650 
651       assert(PMul0 != PMul1 && "expected different chains");
652 
653       if (CanPair(R, PMul0, PMul1)) {
654         Paired.insert(Mul0);
655         Paired.insert(Mul1);
656         break;
657       }
658     }
659   }
660   return !R.getMulPairs().empty();
661 }
662 
663 
664 void ARMParallelDSP::InsertParallelMACs(Reduction &R) {
665 
666   auto CreateSMLADCall = [&](SmallVectorImpl<LoadInst*> &VecLd0,
667                              SmallVectorImpl<LoadInst*> &VecLd1,
668                              Value *Acc, bool Exchange,
669                              Instruction *InsertAfter) {
670     // Replace the reduction chain with an intrinsic call
671     IntegerType *Ty = IntegerType::get(M->getContext(), 32);
672     LoadInst *WideLd0 = WideLoads.count(VecLd0[0]) ?
673       WideLoads[VecLd0[0]]->getLoad() : CreateWideLoad(VecLd0, Ty);
674     LoadInst *WideLd1 = WideLoads.count(VecLd1[0]) ?
675       WideLoads[VecLd1[0]]->getLoad() : CreateWideLoad(VecLd1, Ty);
676 
677     Value* Args[] = { WideLd0, WideLd1, Acc };
678     Function *SMLAD = nullptr;
679     if (Exchange)
680       SMLAD = Acc->getType()->isIntegerTy(32) ?
681         Intrinsic::getDeclaration(M, Intrinsic::arm_smladx) :
682         Intrinsic::getDeclaration(M, Intrinsic::arm_smlaldx);
683     else
684       SMLAD = Acc->getType()->isIntegerTy(32) ?
685         Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
686         Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
687 
688     IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
689                                 ++BasicBlock::iterator(InsertAfter));
690     Instruction *Call = Builder.CreateCall(SMLAD, Args);
691     NumSMLAD++;
692     return Call;
693   };
694 
695   Instruction *InsertAfter = R.getRoot();
696   Value *Acc = R.getAccumulator();
697   if (!Acc)
698     Acc = ConstantInt::get(IntegerType::get(M->getContext(), 32), 0);
699 
700   LLVM_DEBUG(dbgs() << "Root: " << *InsertAfter << "\n"
701              << "Acc: " << *Acc << "\n");
702   for (auto &Pair : R.getMulPairs()) {
703     BinOpChain *PMul0 = Pair.first;
704     BinOpChain *PMul1 = Pair.second;
705     LLVM_DEBUG(dbgs() << "Muls:\n"
706                << "- " << *PMul0->Root << "\n"
707                << "- " << *PMul1->Root << "\n");
708 
709     Acc = CreateSMLADCall(PMul0->VecLd, PMul1->VecLd, Acc, PMul1->Exchange,
710                           InsertAfter);
711     InsertAfter = cast<Instruction>(Acc);
712   }
713   R.UpdateRoot(cast<Instruction>(Acc));
714 }
715 
716 LoadInst* ARMParallelDSP::CreateWideLoad(SmallVectorImpl<LoadInst*> &Loads,
717                                          IntegerType *LoadTy) {
718   assert(Loads.size() == 2 && "currently only support widening two loads");
719 
720   LoadInst *Base = Loads[0];
721   LoadInst *Offset = Loads[1];
722 
723   Instruction *BaseSExt = dyn_cast<SExtInst>(Base->user_back());
724   Instruction *OffsetSExt = dyn_cast<SExtInst>(Offset->user_back());
725 
726   assert((BaseSExt && OffsetSExt)
727          && "Loads should have a single, extending, user");
728 
729   std::function<void(Value*, Value*)> MoveBefore =
730     [&](Value *A, Value *B) -> void {
731       if (!isa<Instruction>(A) || !isa<Instruction>(B))
732         return;
733 
734       auto *Source = cast<Instruction>(A);
735       auto *Sink = cast<Instruction>(B);
736 
737       if (DT->dominates(Source, Sink) ||
738           Source->getParent() != Sink->getParent() ||
739           isa<PHINode>(Source) || isa<PHINode>(Sink))
740         return;
741 
742       Source->moveBefore(Sink);
743       for (auto &Op : Source->operands())
744         MoveBefore(Op, Source);
745     };
746 
747   // Insert the load at the point of the original dominating load.
748   LoadInst *DomLoad = DT->dominates(Base, Offset) ? Base : Offset;
749   IRBuilder<NoFolder> IRB(DomLoad->getParent(),
750                           ++BasicBlock::iterator(DomLoad));
751 
752   // Bitcast the pointer to a wider type and create the wide load, while making
753   // sure to maintain the original alignment as this prevents ldrd from being
754   // generated when it could be illegal due to memory alignment.
755   const unsigned AddrSpace = DomLoad->getPointerAddressSpace();
756   Value *VecPtr = IRB.CreateBitCast(Base->getPointerOperand(),
757                                     LoadTy->getPointerTo(AddrSpace));
758   LoadInst *WideLoad = IRB.CreateAlignedLoad(LoadTy, VecPtr,
759                                              Base->getAlignment());
760 
761   // Make sure everything is in the correct order in the basic block.
762   MoveBefore(Base->getPointerOperand(), VecPtr);
763   MoveBefore(VecPtr, WideLoad);
764 
765   // From the wide load, create two values that equal the original two loads.
766   // Loads[0] needs trunc while Loads[1] needs a lshr and trunc.
767   // TODO: Support big-endian as well.
768   Value *Bottom = IRB.CreateTrunc(WideLoad, Base->getType());
769   BaseSExt->setOperand(0, Bottom);
770 
771   IntegerType *OffsetTy = cast<IntegerType>(Offset->getType());
772   Value *ShiftVal = ConstantInt::get(LoadTy, OffsetTy->getBitWidth());
773   Value *Top = IRB.CreateLShr(WideLoad, ShiftVal);
774   Value *Trunc = IRB.CreateTrunc(Top, OffsetTy);
775   OffsetSExt->setOperand(0, Trunc);
776 
777   WideLoads.emplace(std::make_pair(Base,
778                                    make_unique<WidenedLoad>(Loads, WideLoad)));
779   return WideLoad;
780 }
781 
782 // Compare the value lists in Other to this chain.
783 bool BinOpChain::AreSymmetrical(BinOpChain *Other) {
784   // Element-by-element comparison of Value lists returning true if they are
785   // instructions with the same opcode or constants with the same value.
786   auto CompareValueList = [](const ValueList &VL0,
787                              const ValueList &VL1) {
788     if (VL0.size() != VL1.size()) {
789       LLVM_DEBUG(dbgs() << "Muls are mismatching operand list lengths: "
790                         << VL0.size() << " != " << VL1.size() << "\n");
791       return false;
792     }
793 
794     const unsigned Pairs = VL0.size();
795 
796     for (unsigned i = 0; i < Pairs; ++i) {
797       const Value *V0 = VL0[i];
798       const Value *V1 = VL1[i];
799       const auto *Inst0 = dyn_cast<Instruction>(V0);
800       const auto *Inst1 = dyn_cast<Instruction>(V1);
801 
802       if (!Inst0 || !Inst1)
803         return false;
804 
805       if (Inst0->isSameOperationAs(Inst1))
806         continue;
807 
808       const APInt *C0, *C1;
809       if (!(match(V0, m_APInt(C0)) && match(V1, m_APInt(C1)) && C0 == C1))
810         return false;
811     }
812 
813     return true;
814   };
815 
816   return CompareValueList(LHS, Other->LHS) &&
817          CompareValueList(RHS, Other->RHS);
818 }
819 
820 Pass *llvm::createARMParallelDSPPass() {
821   return new ARMParallelDSP();
822 }
823 
824 char ARMParallelDSP::ID = 0;
825 
826 INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
827                 "Transform loops to use DSP intrinsics", false, false)
828 INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
829                 "Transform loops to use DSP intrinsics", false, false)
830