blob: a6a218c89700c2f591fa7cf37400d4aa8fd6c454 [file] [log] [blame]
Sjoerd Meijerc89ca552018-06-28 12:55:29 +00001//===- ParallelDSP.cpp - Parallel DSP Pass --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Armv6 introduced instructions to perform 32-bit SIMD operations. The
12/// purpose of this pass is do some IR pattern matching to create ACLE
13/// DSP intrinsics, which map on these 32-bit SIMD operations.
Sjoerd Meijer53449da2018-07-11 12:36:25 +000014/// This pass runs only when unaligned accesses is supported/enabled.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000015//
16//===----------------------------------------------------------------------===//
17
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000018#include "llvm/ADT/Statistic.h"
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/LoopAccessAnalysis.h"
22#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/NoFolder.h"
26#include "llvm/Transforms/Scalar.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/LoopUtils.h"
29#include "llvm/Pass.h"
30#include "llvm/PassRegistry.h"
31#include "llvm/PassSupport.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/IR/PatternMatch.h"
34#include "llvm/CodeGen/TargetPassConfig.h"
35#include "ARM.h"
36#include "ARMSubtarget.h"
37
38using namespace llvm;
39using namespace PatternMatch;
40
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +000041#define DEBUG_TYPE "arm-parallel-dsp"
42
43STATISTIC(NumSMLAD , "Number of smlad instructions generated");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000044
Sjoerd Meijer3c859b32018-08-14 07:43:49 +000045static cl::opt<bool>
46DisableParallelDSP("disable-arm-parallel-dsp", cl::Hidden, cl::init(false),
47 cl::desc("Disable the ARM Parallel DSP pass"));
48
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000049namespace {
Sam Parker89a37992018-07-23 15:25:59 +000050 struct OpChain;
51 struct BinOpChain;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000052 struct Reduction;
53
Fangrui Song58407ca2018-07-23 17:43:21 +000054 using OpChainList = SmallVector<std::unique_ptr<OpChain>, 8>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000055 using ReductionList = SmallVector<Reduction, 8>;
56 using ValueList = SmallVector<Value*, 8>;
Sam Parkerffc16812018-07-03 12:44:16 +000057 using MemInstList = SmallVector<Instruction*, 8>;
Sam Parker89a37992018-07-23 15:25:59 +000058 using PMACPair = std::pair<BinOpChain*,BinOpChain*>;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000059 using PMACPairList = SmallVector<PMACPair, 8>;
60 using Instructions = SmallVector<Instruction*,16>;
61 using MemLocList = SmallVector<MemoryLocation, 4>;
62
Sam Parker89a37992018-07-23 15:25:59 +000063 struct OpChain {
64 Instruction *Root;
65 ValueList AllValues;
66 MemInstList VecLd; // List of all load instructions.
67 MemLocList MemLocs; // All memory locations read by this tree.
68 bool ReadOnly = true;
69
70 OpChain(Instruction *I, ValueList &vl) : Root(I), AllValues(vl) { }
Jordan Rupprechte5daf612018-07-23 17:38:05 +000071 virtual ~OpChain() = default;
Sam Parker89a37992018-07-23 15:25:59 +000072
73 void SetMemoryLocations() {
74 const auto Size = MemoryLocation::UnknownSize;
75 for (auto *V : AllValues) {
76 if (auto *I = dyn_cast<Instruction>(V)) {
77 if (I->mayWriteToMemory())
78 ReadOnly = false;
79 if (auto *Ld = dyn_cast<LoadInst>(V))
80 MemLocs.push_back(MemoryLocation(Ld->getPointerOperand(), Size));
81 }
82 }
83 }
84
85 unsigned size() const { return AllValues.size(); }
86 };
87
88 // 'BinOpChain' and 'Reduction' are just some bookkeeping data structures.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000089 // 'Reduction' contains the phi-node and accumulator statement from where we
Sam Parker89a37992018-07-23 15:25:59 +000090 // start pattern matching, and 'BinOpChain' the multiplication
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000091 // instructions that are candidates for parallel execution.
Sam Parker89a37992018-07-23 15:25:59 +000092 struct BinOpChain : public OpChain {
93 ValueList LHS; // List of all (narrow) left hand operands.
94 ValueList RHS; // List of all (narrow) right hand operands.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000095
Sam Parker89a37992018-07-23 15:25:59 +000096 BinOpChain(Instruction *I, ValueList &lhs, ValueList &rhs) :
97 OpChain(I, lhs), LHS(lhs), RHS(rhs) {
98 for (auto *V : RHS)
99 AllValues.push_back(V);
100 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000101 };
102
103 struct Reduction {
104 PHINode *Phi; // The Phi-node from where we start
105 // pattern matching.
106 Instruction *AccIntAdd; // The accumulating integer add statement,
107 // i.e, the reduction statement.
108
Sam Parker89a37992018-07-23 15:25:59 +0000109 OpChainList MACCandidates; // The MAC candidates associated with
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000110 // this reduction statement.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000111 Reduction (PHINode *P, Instruction *Acc) : Phi(P), AccIntAdd(Acc) { };
112 };
113
114 class ARMParallelDSP : public LoopPass {
115 ScalarEvolution *SE;
116 AliasAnalysis *AA;
117 TargetLibraryInfo *TLI;
118 DominatorTree *DT;
119 LoopInfo *LI;
120 Loop *L;
121 const DataLayout *DL;
122 Module *M;
123
124 bool InsertParallelMACs(Reduction &Reduction, PMACPairList &PMACPairs);
Fangrui Song68169342018-07-03 19:12:27 +0000125 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
Sam Parker89a37992018-07-23 15:25:59 +0000126 PMACPairList CreateParallelMACPairs(OpChainList &Candidates);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000127 Instruction *CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
128 Instruction *Acc, Instruction *InsertAfter);
129
130 /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
131 /// Dual performs two signed 16x16-bit multiplications. It adds the
132 /// products to a 32-bit accumulate operand. Optionally, the instruction can
133 /// exchange the halfwords of the second operand before performing the
134 /// arithmetic.
135 bool MatchSMLAD(Function &F);
136
137 public:
138 static char ID;
139
140 ARMParallelDSP() : LoopPass(ID) { }
141
142 void getAnalysisUsage(AnalysisUsage &AU) const override {
143 LoopPass::getAnalysisUsage(AU);
144 AU.addRequired<AssumptionCacheTracker>();
145 AU.addRequired<ScalarEvolutionWrapperPass>();
146 AU.addRequired<AAResultsWrapperPass>();
147 AU.addRequired<TargetLibraryInfoWrapperPass>();
148 AU.addRequired<LoopInfoWrapperPass>();
149 AU.addRequired<DominatorTreeWrapperPass>();
150 AU.addRequired<TargetPassConfig>();
151 AU.addPreserved<LoopInfoWrapperPass>();
152 AU.setPreservesCFG();
153 }
154
155 bool runOnLoop(Loop *TheLoop, LPPassManager &) override {
Sjoerd Meijer3c859b32018-08-14 07:43:49 +0000156 if (DisableParallelDSP)
157 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000158 L = TheLoop;
159 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
160 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
161 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
162 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
163 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
164 auto &TPC = getAnalysis<TargetPassConfig>();
165
166 BasicBlock *Header = TheLoop->getHeader();
167 if (!Header)
168 return false;
169
170 // TODO: We assume the loop header and latch to be the same block.
171 // This is not a fundamental restriction, but lifting this would just
172 // require more work to do the transformation and then patch up the CFG.
173 if (Header != TheLoop->getLoopLatch()) {
174 LLVM_DEBUG(dbgs() << "The loop header is not the loop latch: not "
175 "running pass ARMParallelDSP\n");
176 return false;
177 }
178
179 Function &F = *Header->getParent();
180 M = F.getParent();
181 DL = &M->getDataLayout();
182
183 auto &TM = TPC.getTM<TargetMachine>();
184 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
185
186 if (!ST->allowsUnalignedMem()) {
187 LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
188 "running pass ARMParallelDSP\n");
189 return false;
190 }
191
192 if (!ST->hasDSP()) {
193 LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
194 "ARMParallelDSP\n");
195 return false;
196 }
197
198 LoopAccessInfo LAI(L, SE, TLI, AA, DT, LI);
199 bool Changes = false;
200
201 LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n\n");
202 Changes = MatchSMLAD(F);
203 return Changes;
204 }
205 };
206}
207
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000208// MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
209// instructions, which is set to 16. So here we should collect all i8 and i16
210// narrow operations.
211// TODO: we currently only collect i16, and will support i8 later, so that's
212// why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
213template<unsigned MaxBitWidth>
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000214static bool IsNarrowSequence(Value *V, ValueList &VL) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000215 LLVM_DEBUG(dbgs() << "Is narrow sequence? "; V->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000216 ConstantInt *CInt;
217
218 if (match(V, m_ConstantInt(CInt))) {
219 // TODO: if a constant is used, it needs to fit within the bit width.
220 return false;
221 }
222
223 auto *I = dyn_cast<Instruction>(V);
224 if (!I)
225 return false;
226
227 Value *Val, *LHS, *RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000228 if (match(V, m_Trunc(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000229 if (cast<TruncInst>(I)->getDestTy()->getIntegerBitWidth() == MaxBitWidth)
230 return IsNarrowSequence<MaxBitWidth>(Val, VL);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000231 } else if (match(V, m_Add(m_Value(LHS), m_Value(RHS)))) {
232 // TODO: we need to implement sadd16/sadd8 for this, which enables to
233 // also do the rewrite for smlad8.ll, but it is unsupported for now.
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000234 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
235 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000236 } else if (match(V, m_ZExtOrSExt(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000237 if (cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() != MaxBitWidth) {
238 LLVM_DEBUG(dbgs() << "No, wrong SrcTy size: " <<
239 cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() << "\n");
240 return false;
241 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000242
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000243 if (match(Val, m_Load(m_Value()))) {
244 LLVM_DEBUG(dbgs() << "Yes, found narrow Load:\t"; Val->dump());
245 VL.push_back(Val);
246 VL.push_back(I);
247 return true;
248 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000249 }
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000250 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
251 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000252}
253
254// Element-by-element comparison of Value lists returning true if they are
255// instructions with the same opcode or constants with the same value.
256static bool AreSymmetrical(const ValueList &VL0,
257 const ValueList &VL1) {
258 if (VL0.size() != VL1.size()) {
259 LLVM_DEBUG(dbgs() << "Muls are mismatching operand list lengths: "
260 << VL0.size() << " != " << VL1.size() << "\n");
261 return false;
262 }
263
264 const unsigned Pairs = VL0.size();
265 LLVM_DEBUG(dbgs() << "Number of operand pairs: " << Pairs << "\n");
266
267 for (unsigned i = 0; i < Pairs; ++i) {
268 const Value *V0 = VL0[i];
269 const Value *V1 = VL1[i];
270 const auto *Inst0 = dyn_cast<Instruction>(V0);
271 const auto *Inst1 = dyn_cast<Instruction>(V1);
272
273 LLVM_DEBUG(dbgs() << "Pair " << i << ":\n";
274 dbgs() << "mul1: "; V0->dump();
275 dbgs() << "mul2: "; V1->dump());
276
277 if (!Inst0 || !Inst1)
278 return false;
279
280 if (Inst0->isSameOperationAs(Inst1)) {
281 LLVM_DEBUG(dbgs() << "OK: same operation found!\n");
282 continue;
283 }
284
285 const APInt *C0, *C1;
286 if (!(match(V0, m_APInt(C0)) && match(V1, m_APInt(C1)) && C0 == C1))
287 return false;
288 }
289
290 LLVM_DEBUG(dbgs() << "OK: found symmetrical operand lists.\n");
291 return true;
292}
293
Sam Parkerffc16812018-07-03 12:44:16 +0000294template<typename MemInst>
295static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
296 MemInstList &VecMem, const DataLayout &DL,
297 ScalarEvolution &SE) {
298 if (!MemOp0->isSimple() || !MemOp1->isSimple()) {
299 LLVM_DEBUG(dbgs() << "No, not touching volatile access\n");
300 return false;
301 }
302 if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE)) {
303 VecMem.push_back(MemOp0);
304 VecMem.push_back(MemOp1);
305 LLVM_DEBUG(dbgs() << "OK: accesses are consecutive.\n");
306 return true;
307 }
308 LLVM_DEBUG(dbgs() << "No, accesses aren't consecutive.\n");
309 return false;
310}
311
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000312bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
Sam Parkerffc16812018-07-03 12:44:16 +0000313 MemInstList &VecMem) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000314 if (!Ld0 || !Ld1)
315 return false;
316
317 LLVM_DEBUG(dbgs() << "Are consecutive loads:\n";
318 dbgs() << "Ld0:"; Ld0->dump();
319 dbgs() << "Ld1:"; Ld1->dump();
320 );
321
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000322 if (!Ld0->hasOneUse() || !Ld1->hasOneUse()) {
323 LLVM_DEBUG(dbgs() << "No, load has more than one use.\n");
324 return false;
325 }
Sam Parkerffc16812018-07-03 12:44:16 +0000326
327 return AreSequentialAccesses<LoadInst>(Ld0, Ld1, VecMem, *DL, *SE);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000328}
329
330PMACPairList
Sam Parker89a37992018-07-23 15:25:59 +0000331ARMParallelDSP::CreateParallelMACPairs(OpChainList &Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000332 const unsigned Elems = Candidates.size();
333 PMACPairList PMACPairs;
334
335 if (Elems < 2)
336 return PMACPairs;
337
338 // TODO: for now we simply try to match consecutive pairs i and i+1.
339 // We can compare all elements, but then we need to compare and evaluate
340 // different solutions.
341 for(unsigned i=0; i<Elems-1; i+=2) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000342 BinOpChain *PMul0 = static_cast<BinOpChain*>(Candidates[i].get());
343 BinOpChain *PMul1 = static_cast<BinOpChain*>(Candidates[i+1].get());
Sam Parker89a37992018-07-23 15:25:59 +0000344 const Instruction *Mul0 = PMul0->Root;
345 const Instruction *Mul1 = PMul1->Root;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000346
347 if (Mul0 == Mul1)
348 continue;
349
350 LLVM_DEBUG(dbgs() << "\nCheck parallel muls:\n";
351 dbgs() << "- "; Mul0->dump();
352 dbgs() << "- "; Mul1->dump());
353
Sam Parker89a37992018-07-23 15:25:59 +0000354 const ValueList &Mul0_LHS = PMul0->LHS;
355 const ValueList &Mul0_RHS = PMul0->RHS;
356 const ValueList &Mul1_LHS = PMul1->LHS;
357 const ValueList &Mul1_RHS = PMul1->RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000358
Sam Parker89a37992018-07-23 15:25:59 +0000359 if (!AreSymmetrical(Mul0_LHS, Mul1_LHS) ||
360 !AreSymmetrical(Mul0_RHS, Mul1_RHS))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000361 continue;
362
363 LLVM_DEBUG(dbgs() << "OK: mul operands list match:\n");
364 // The first elements of each vector should be loads with sexts. If we find
365 // that its two pairs of consecutive loads, then these can be transformed
366 // into two wider loads and the users can be replaced with DSP
367 // intrinsics.
Sam Parker89a37992018-07-23 15:25:59 +0000368 for (unsigned x = 0; x < Mul0_LHS.size(); x += 2) {
369 auto *Ld0 = dyn_cast<LoadInst>(Mul0_LHS[x]);
370 auto *Ld1 = dyn_cast<LoadInst>(Mul1_LHS[x]);
371 auto *Ld2 = dyn_cast<LoadInst>(Mul0_RHS[x]);
372 auto *Ld3 = dyn_cast<LoadInst>(Mul1_RHS[x]);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000373
374 LLVM_DEBUG(dbgs() << "Looking at operands " << x << ":\n";
Sam Parker89a37992018-07-23 15:25:59 +0000375 dbgs() << "\t mul1: "; Mul0_LHS[x]->dump();
376 dbgs() << "\t mul2: "; Mul1_LHS[x]->dump();
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000377 dbgs() << "and operands " << x + 2 << ":\n";
Sam Parker89a37992018-07-23 15:25:59 +0000378 dbgs() << "\t mul1: "; Mul0_RHS[x]->dump();
379 dbgs() << "\t mul2: "; Mul1_RHS[x]->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000380
Sam Parker89a37992018-07-23 15:25:59 +0000381 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd) &&
382 AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000383 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
Sam Parker89a37992018-07-23 15:25:59 +0000384 PMACPairs.push_back(std::make_pair(PMul0, PMul1));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000385 }
386 }
387 }
388 return PMACPairs;
389}
390
391bool ARMParallelDSP::InsertParallelMACs(Reduction &Reduction,
392 PMACPairList &PMACPairs) {
393 Instruction *Acc = Reduction.Phi;
394 Instruction *InsertAfter = Reduction.AccIntAdd;
395
396 for (auto &Pair : PMACPairs) {
397 LLVM_DEBUG(dbgs() << "Found parallel MACs!!\n";
Sam Parker89a37992018-07-23 15:25:59 +0000398 dbgs() << "- "; Pair.first->Root->dump();
399 dbgs() << "- "; Pair.second->Root->dump());
Sam Parkerffc16812018-07-03 12:44:16 +0000400 auto *VecLd0 = cast<LoadInst>(Pair.first->VecLd[0]);
401 auto *VecLd1 = cast<LoadInst>(Pair.second->VecLd[0]);
402 Acc = CreateSMLADCall(VecLd0, VecLd1, Acc, InsertAfter);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000403 InsertAfter = Acc;
404 }
405
406 if (Acc != Reduction.Phi) {
407 LLVM_DEBUG(dbgs() << "Replace Accumulate: "; Acc->dump());
408 Reduction.AccIntAdd->replaceAllUsesWith(Acc);
409 return true;
410 }
411 return false;
412}
413
Sam Parker89a37992018-07-23 15:25:59 +0000414static void MatchReductions(Function &F, Loop *TheLoop, BasicBlock *Header,
415 ReductionList &Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000416 RecurrenceDescriptor RecDesc;
417 const bool HasFnNoNaNAttr =
418 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
419 const BasicBlock *Latch = TheLoop->getLoopLatch();
420
421 // We need a preheader as getIncomingValueForBlock assumes there is one.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000422 if (!TheLoop->getLoopPreheader()) {
423 LLVM_DEBUG(dbgs() << "No preheader found, bailing out\n");
Sam Parker89a37992018-07-23 15:25:59 +0000424 return;
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000425 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000426
427 for (PHINode &Phi : Header->phis()) {
428 const auto *Ty = Phi.getType();
Sam Parker01db2982018-09-11 14:01:22 +0000429 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000430 continue;
431
432 const bool IsReduction =
433 RecurrenceDescriptor::AddReductionVar(&Phi,
434 RecurrenceDescriptor::RK_IntegerAdd,
435 TheLoop, HasFnNoNaNAttr, RecDesc);
436 if (!IsReduction)
437 continue;
438
439 Instruction *Acc = dyn_cast<Instruction>(Phi.getIncomingValueForBlock(Latch));
440 if (!Acc)
441 continue;
442
443 Reductions.push_back(Reduction(&Phi, Acc));
444 }
445
446 LLVM_DEBUG(
447 dbgs() << "\nAccumulating integer additions (reductions) found:\n";
Sam Parker89a37992018-07-23 15:25:59 +0000448 for (auto &R : Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000449 dbgs() << "- "; R.Phi->dump();
450 dbgs() << "-> "; R.AccIntAdd->dump();
451 }
452 );
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000453}
454
Sam Parker89a37992018-07-23 15:25:59 +0000455static void AddMACCandidate(OpChainList &Candidates,
456 const Instruction *Acc,
Sam Parker01db2982018-09-11 14:01:22 +0000457 Instruction *Mul,
458 Value *MulOp0, Value *MulOp1) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000459 LLVM_DEBUG(dbgs() << "OK, found acc mul:\t"; Mul->dump());
Sam Parker01db2982018-09-11 14:01:22 +0000460 assert(Mul->getOpcode() == Instruction::Mul &&
461 "expected mul instruction");
Sam Parker89a37992018-07-23 15:25:59 +0000462 ValueList LHS;
463 ValueList RHS;
464 if (IsNarrowSequence<16>(MulOp0, LHS) &&
465 IsNarrowSequence<16>(MulOp1, RHS)) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000466 LLVM_DEBUG(dbgs() << "OK, found narrow mul: "; Mul->dump());
Fangrui Song58407ca2018-07-23 17:43:21 +0000467 Candidates.push_back(make_unique<BinOpChain>(Mul, LHS, RHS));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000468 }
469}
470
Sam Parker89a37992018-07-23 15:25:59 +0000471static void MatchParallelMACSequences(Reduction &R,
472 OpChainList &Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000473 const Instruction *Acc = R.AccIntAdd;
474 Value *A, *MulOp0, *MulOp1;
475 LLVM_DEBUG(dbgs() << "\n- Analysing:\t"; Acc->dump());
476
477 // Pattern 1: the accumulator is the RHS of the mul.
478 while(match(Acc, m_Add(m_Mul(m_Value(MulOp0), m_Value(MulOp1)),
479 m_Value(A)))){
Sam Parker01db2982018-09-11 14:01:22 +0000480 Instruction *Mul = cast<Instruction>(Acc->getOperand(0));
481 AddMACCandidate(Candidates, Acc, Mul, MulOp0, MulOp1);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000482 Acc = dyn_cast<Instruction>(A);
483 }
484 // Pattern 2: the accumulator is the LHS of the mul.
485 while(match(Acc, m_Add(m_Value(A),
486 m_Mul(m_Value(MulOp0), m_Value(MulOp1))))) {
Sam Parker01db2982018-09-11 14:01:22 +0000487 Instruction *Mul = cast<Instruction>(Acc->getOperand(1));
488 AddMACCandidate(Candidates, Acc, Mul, MulOp0, MulOp1);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000489 Acc = dyn_cast<Instruction>(A);
490 }
491
492 // The last mul in the chain has a slightly different pattern:
493 // the mul is the first operand
494 if (match(Acc, m_Add(m_Mul(m_Value(MulOp0), m_Value(MulOp1)), m_Value(A))))
Sam Parker01db2982018-09-11 14:01:22 +0000495 AddMACCandidate(Candidates, Acc, cast<Instruction>(Acc->getOperand(0)),
496 MulOp0, MulOp1);
497
498 // Same as above, but SMLALD may perform 32-bit muls, sext the results and
499 // then accumulate.
500 while(match(Acc, m_Add(m_SExt(m_Mul(m_Value(MulOp0), m_Value(MulOp1))),
501 m_Value(A)))) {
502 Value *Mul = cast<Instruction>(Acc->getOperand(0))->getOperand(0);
503 AddMACCandidate(Candidates, Acc, cast<Instruction>(Mul), MulOp0, MulOp1);
504 Acc = dyn_cast<Instruction>(A);
505 }
506 while(match(Acc, m_Add(m_Value(A),
507 m_SExt(m_Mul(m_Value(MulOp0), m_Value(MulOp1)))))) {
508 Value *Mul = cast<Instruction>(Acc->getOperand(1))->getOperand(0);
509 AddMACCandidate(Candidates, Acc, cast<Instruction>(Mul), MulOp0, MulOp1);
510 Acc = dyn_cast<Instruction>(A);
511 }
512 if (match(Acc, m_Add(m_SExt(m_Mul(m_Value(MulOp0), m_Value(MulOp1))),
513 m_Value(A)))) {
514 Value *Mul = cast<Instruction>(
515 cast<Instruction>(Acc)->getOperand(0))->getOperand(0);
516 AddMACCandidate(Candidates, Acc, cast<Instruction>(Mul), MulOp0, MulOp1);
517 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000518
519 // Because we start at the bottom of the chain, and we work our way up,
520 // the muls are added in reverse program order to the list.
521 std::reverse(Candidates.begin(), Candidates.end());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000522}
523
524// Collects all instructions that are not part of the MAC chains, which is the
525// set of instructions that can potentially alias with the MAC operands.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000526static void AliasCandidates(BasicBlock *Header, Instructions &Reads,
527 Instructions &Writes) {
528 for (auto &I : *Header) {
529 if (I.mayReadFromMemory())
530 Reads.push_back(&I);
531 if (I.mayWriteToMemory())
532 Writes.push_back(&I);
533 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000534}
535
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000536// Check whether statements in the basic block that write to memory alias with
537// the memory locations accessed by the MAC-chains.
538// TODO: we need the read statements when we accept more complicated chains.
539static bool AreAliased(AliasAnalysis *AA, Instructions &Reads,
Sam Parker89a37992018-07-23 15:25:59 +0000540 Instructions &Writes, OpChainList &MACCandidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000541 LLVM_DEBUG(dbgs() << "Alias checks:\n");
Fangrui Song58407ca2018-07-23 17:43:21 +0000542 for (auto &MAC : MACCandidates) {
Sam Parker89a37992018-07-23 15:25:59 +0000543 LLVM_DEBUG(dbgs() << "mul: "; MAC->Root->dump());
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000544
545 // At the moment, we allow only simple chains that only consist of reads,
546 // accumulate their result with an integer add, and thus that don't write
547 // memory, and simply bail if they do.
Sam Parker89a37992018-07-23 15:25:59 +0000548 if (!MAC->ReadOnly)
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000549 return true;
550
551 // Now for all writes in the basic block, check that they don't alias with
552 // the memory locations accessed by our MAC-chain:
553 for (auto *I : Writes) {
554 LLVM_DEBUG(dbgs() << "- "; I->dump());
Sam Parker89a37992018-07-23 15:25:59 +0000555 assert(MAC->MemLocs.size() >= 2 && "expecting at least 2 memlocs");
556 for (auto &MemLoc : MAC->MemLocs) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000557 if (isModOrRefSet(intersectModRef(AA->getModRefInfo(I, MemLoc),
558 ModRefInfo::ModRef))) {
559 LLVM_DEBUG(dbgs() << "Yes, aliases found\n");
560 return true;
561 }
562 }
563 }
564 }
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000565
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000566 LLVM_DEBUG(dbgs() << "OK: no aliases found!\n");
567 return false;
568}
569
Sam Parker89a37992018-07-23 15:25:59 +0000570static bool CheckMACMemory(OpChainList &Candidates) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000571 for (auto &C : Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000572 // A mul has 2 operands, and a narrow op consist of sext and a load; thus
573 // we expect at least 4 items in this operand value list.
Sam Parker89a37992018-07-23 15:25:59 +0000574 if (C->size() < 4) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000575 LLVM_DEBUG(dbgs() << "Operand list too short.\n");
576 return false;
577 }
Sam Parker89a37992018-07-23 15:25:59 +0000578 C->SetMemoryLocations();
Fangrui Song58407ca2018-07-23 17:43:21 +0000579 ValueList &LHS = static_cast<BinOpChain*>(C.get())->LHS;
580 ValueList &RHS = static_cast<BinOpChain*>(C.get())->RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000581
Sam Parker89a37992018-07-23 15:25:59 +0000582 // Use +=2 to skip over the expected extend instructions.
583 for (unsigned i = 0, e = LHS.size(); i < e; i += 2) {
584 if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000585 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000586 }
587 }
588 return true;
589}
590
591// Loop Pass that needs to identify integer add/sub reductions of 16-bit vector
592// multiplications.
593// To use SMLAD:
594// 1) we first need to find integer add reduction PHIs,
595// 2) then from the PHI, look for this pattern:
596//
597// acc0 = phi i32 [0, %entry], [%acc1, %loop.body]
598// ld0 = load i16
599// sext0 = sext i16 %ld0 to i32
600// ld1 = load i16
601// sext1 = sext i16 %ld1 to i32
602// mul0 = mul %sext0, %sext1
603// ld2 = load i16
604// sext2 = sext i16 %ld2 to i32
605// ld3 = load i16
606// sext3 = sext i16 %ld3 to i32
607// mul1 = mul i32 %sext2, %sext3
608// add0 = add i32 %mul0, %acc0
609// acc1 = add i32 %add0, %mul1
610//
611// Which can be selected to:
612//
613// ldr.h r0
614// ldr.h r1
615// smlad r2, r0, r1, r2
616//
617// If constants are used instead of loads, these will need to be hoisted
618// out and into a register.
619//
620// If loop invariants are used instead of loads, these need to be packed
621// before the loop begins.
622//
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000623bool ARMParallelDSP::MatchSMLAD(Function &F) {
624 BasicBlock *Header = L->getHeader();
625 LLVM_DEBUG(dbgs() << "= Matching SMLAD =\n";
626 dbgs() << "Header block:\n"; Header->dump();
627 dbgs() << "Loop info:\n\n"; L->dump());
628
629 bool Changed = false;
Sam Parker89a37992018-07-23 15:25:59 +0000630 ReductionList Reductions;
631 MatchReductions(F, L, Header, Reductions);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000632
633 for (auto &R : Reductions) {
Sam Parker89a37992018-07-23 15:25:59 +0000634 OpChainList MACCandidates;
635 MatchParallelMACSequences(R, MACCandidates);
636 if (!CheckMACMemory(MACCandidates))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000637 continue;
Sam Parker89a37992018-07-23 15:25:59 +0000638
Fangrui Song58407ca2018-07-23 17:43:21 +0000639 R.MACCandidates = std::move(MACCandidates);
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000640
641 LLVM_DEBUG(dbgs() << "MAC candidates:\n";
642 for (auto &M : R.MACCandidates)
Sam Parker89a37992018-07-23 15:25:59 +0000643 M->Root->dump();
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000644 dbgs() << "\n";);
645 }
646
647 // Collect all instructions that may read or write memory. Our alias
648 // analysis checks bail out if any of these instructions aliases with an
649 // instruction from the MAC-chain.
650 Instructions Reads, Writes;
651 AliasCandidates(Header, Reads, Writes);
652
653 for (auto &R : Reductions) {
654 if (AreAliased(AA, Reads, Writes, R.MACCandidates))
655 return false;
656 PMACPairList PMACPairs = CreateParallelMACPairs(R.MACCandidates);
657 Changed |= InsertParallelMACs(R, PMACPairs);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000658 }
659
660 LLVM_DEBUG(if (Changed) dbgs() << "Header block:\n"; Header->dump(););
661 return Changed;
662}
663
Sam Parker01db2982018-09-11 14:01:22 +0000664static void CreateLoadIns(IRBuilder<NoFolder> &IRB, LoadInst **VecLd,
665 const Type *LoadTy) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000666 const unsigned AddrSpace = (*VecLd)->getPointerAddressSpace();
667
668 Value *VecPtr = IRB.CreateBitCast((*VecLd)->getPointerOperand(),
Sam Parker01db2982018-09-11 14:01:22 +0000669 LoadTy->getPointerTo(AddrSpace));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000670 *VecLd = IRB.CreateAlignedLoad(VecPtr, (*VecLd)->getAlignment());
671}
672
673Instruction *ARMParallelDSP::CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
674 Instruction *Acc,
675 Instruction *InsertAfter) {
676 LLVM_DEBUG(dbgs() << "Create SMLAD intrinsic using:\n";
677 dbgs() << "- "; VecLd0->dump();
678 dbgs() << "- "; VecLd1->dump();
679 dbgs() << "- "; Acc->dump());
680
681 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
682 ++BasicBlock::iterator(InsertAfter));
683
684 // Replace the reduction chain with an intrinsic call
Sam Parker01db2982018-09-11 14:01:22 +0000685 const Type *Ty = IntegerType::get(M->getContext(), 32);
686 CreateLoadIns(Builder, &VecLd0, Ty);
687 CreateLoadIns(Builder, &VecLd1, Ty);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000688 Value* Args[] = { VecLd0, VecLd1, Acc };
Sam Parker01db2982018-09-11 14:01:22 +0000689 Function *SMLAD = Acc->getType()->isIntegerTy(32) ?
690 Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
691 Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000692 CallInst *Call = Builder.CreateCall(SMLAD, Args);
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000693 NumSMLAD++;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000694 return Call;
695}
696
697Pass *llvm::createARMParallelDSPPass() {
698 return new ARMParallelDSP();
699}
700
701char ARMParallelDSP::ID = 0;
702
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000703INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000704 "Transform loops to use DSP intrinsics", false, false)
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000705INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000706 "Transform loops to use DSP intrinsics", false, false)