blob: 3ab9298c1108ca00b60b5752b3b6619080e62b6d [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;
Eli Friedmanb09c7782018-10-18 19:34:30 +000066 MemInstList VecLd; // List of all load instructions.
Sam Parker89a37992018-07-23 15:25:59 +000067 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() {
George Burgess IV6ef80022018-10-10 21:28:44 +000074 const auto Size = LocationSize::unknown();
Sam Parker89a37992018-07-23 15:25:59 +000075 for (auto *V : AllValues) {
76 if (auto *I = dyn_cast<Instruction>(V)) {
77 if (I->mayWriteToMemory())
78 ReadOnly = false;
Eli Friedmanb09c7782018-10-18 19:34:30 +000079 if (auto *Ld = dyn_cast<LoadInst>(V))
Sam Parker89a37992018-07-23 15:25:59 +000080 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.
Sam Parkera023c7a2018-09-12 09:17:44 +000095 bool Exchange = false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +000096
Sam Parker89a37992018-07-23 15:25:59 +000097 BinOpChain(Instruction *I, ValueList &lhs, ValueList &rhs) :
98 OpChain(I, lhs), LHS(lhs), RHS(rhs) {
99 for (auto *V : RHS)
100 AllValues.push_back(V);
101 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000102 };
103
104 struct Reduction {
105 PHINode *Phi; // The Phi-node from where we start
106 // pattern matching.
107 Instruction *AccIntAdd; // The accumulating integer add statement,
108 // i.e, the reduction statement.
109
Sam Parker89a37992018-07-23 15:25:59 +0000110 OpChainList MACCandidates; // The MAC candidates associated with
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000111 // this reduction statement.
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000112 Reduction (PHINode *P, Instruction *Acc) : Phi(P), AccIntAdd(Acc) { };
113 };
114
115 class ARMParallelDSP : public LoopPass {
116 ScalarEvolution *SE;
117 AliasAnalysis *AA;
118 TargetLibraryInfo *TLI;
119 DominatorTree *DT;
120 LoopInfo *LI;
121 Loop *L;
122 const DataLayout *DL;
123 Module *M;
124
125 bool InsertParallelMACs(Reduction &Reduction, PMACPairList &PMACPairs);
Fangrui Song68169342018-07-03 19:12:27 +0000126 bool AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1, MemInstList &VecMem);
Sam Parker89a37992018-07-23 15:25:59 +0000127 PMACPairList CreateParallelMACPairs(OpChainList &Candidates);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000128 Instruction *CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
Sam Parkera023c7a2018-09-12 09:17:44 +0000129 Instruction *Acc, bool Exchange,
130 Instruction *InsertAfter);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000131
132 /// Try to match and generate: SMLAD, SMLADX - Signed Multiply Accumulate
133 /// Dual performs two signed 16x16-bit multiplications. It adds the
134 /// products to a 32-bit accumulate operand. Optionally, the instruction can
135 /// exchange the halfwords of the second operand before performing the
136 /// arithmetic.
137 bool MatchSMLAD(Function &F);
138
139 public:
140 static char ID;
141
142 ARMParallelDSP() : LoopPass(ID) { }
143
144 void getAnalysisUsage(AnalysisUsage &AU) const override {
145 LoopPass::getAnalysisUsage(AU);
146 AU.addRequired<AssumptionCacheTracker>();
147 AU.addRequired<ScalarEvolutionWrapperPass>();
148 AU.addRequired<AAResultsWrapperPass>();
149 AU.addRequired<TargetLibraryInfoWrapperPass>();
150 AU.addRequired<LoopInfoWrapperPass>();
151 AU.addRequired<DominatorTreeWrapperPass>();
152 AU.addRequired<TargetPassConfig>();
153 AU.addPreserved<LoopInfoWrapperPass>();
154 AU.setPreservesCFG();
155 }
156
157 bool runOnLoop(Loop *TheLoop, LPPassManager &) override {
Sjoerd Meijer3c859b32018-08-14 07:43:49 +0000158 if (DisableParallelDSP)
159 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000160 L = TheLoop;
161 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
162 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
163 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
164 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
165 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
166 auto &TPC = getAnalysis<TargetPassConfig>();
167
168 BasicBlock *Header = TheLoop->getHeader();
169 if (!Header)
170 return false;
171
172 // TODO: We assume the loop header and latch to be the same block.
173 // This is not a fundamental restriction, but lifting this would just
174 // require more work to do the transformation and then patch up the CFG.
175 if (Header != TheLoop->getLoopLatch()) {
176 LLVM_DEBUG(dbgs() << "The loop header is not the loop latch: not "
177 "running pass ARMParallelDSP\n");
178 return false;
179 }
180
181 Function &F = *Header->getParent();
182 M = F.getParent();
183 DL = &M->getDataLayout();
184
185 auto &TM = TPC.getTM<TargetMachine>();
186 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
187
188 if (!ST->allowsUnalignedMem()) {
189 LLVM_DEBUG(dbgs() << "Unaligned memory access not supported: not "
190 "running pass ARMParallelDSP\n");
191 return false;
192 }
193
194 if (!ST->hasDSP()) {
195 LLVM_DEBUG(dbgs() << "DSP extension not enabled: not running pass "
196 "ARMParallelDSP\n");
197 return false;
198 }
199
200 LoopAccessInfo LAI(L, SE, TLI, AA, DT, LI);
201 bool Changes = false;
202
Sam Parkera023c7a2018-09-12 09:17:44 +0000203 LLVM_DEBUG(dbgs() << "\n== Parallel DSP pass ==\n");
204 LLVM_DEBUG(dbgs() << " - " << F.getName() << "\n\n");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000205 Changes = MatchSMLAD(F);
206 return Changes;
207 }
208 };
209}
210
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000211// MaxBitwidth: the maximum supported bitwidth of the elements in the DSP
212// instructions, which is set to 16. So here we should collect all i8 and i16
213// narrow operations.
214// TODO: we currently only collect i16, and will support i8 later, so that's
215// why we check that types are equal to MaxBitWidth, and not <= MaxBitWidth.
216template<unsigned MaxBitWidth>
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000217static bool IsNarrowSequence(Value *V, ValueList &VL) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000218 LLVM_DEBUG(dbgs() << "Is narrow sequence? "; V->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000219 ConstantInt *CInt;
220
221 if (match(V, m_ConstantInt(CInt))) {
222 // TODO: if a constant is used, it needs to fit within the bit width.
223 return false;
224 }
225
226 auto *I = dyn_cast<Instruction>(V);
227 if (!I)
228 return false;
229
230 Value *Val, *LHS, *RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000231 if (match(V, m_Trunc(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000232 if (cast<TruncInst>(I)->getDestTy()->getIntegerBitWidth() == MaxBitWidth)
233 return IsNarrowSequence<MaxBitWidth>(Val, VL);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000234 } else if (match(V, m_Add(m_Value(LHS), m_Value(RHS)))) {
235 // TODO: we need to implement sadd16/sadd8 for this, which enables to
236 // also do the rewrite for smlad8.ll, but it is unsupported for now.
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000237 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
238 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000239 } else if (match(V, m_ZExtOrSExt(m_Value(Val)))) {
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000240 if (cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() != MaxBitWidth) {
241 LLVM_DEBUG(dbgs() << "No, wrong SrcTy size: " <<
242 cast<CastInst>(I)->getSrcTy()->getIntegerBitWidth() << "\n");
243 return false;
244 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000245
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000246 if (match(Val, m_Load(m_Value()))) {
247 LLVM_DEBUG(dbgs() << "Yes, found narrow Load:\t"; Val->dump());
248 VL.push_back(Val);
249 VL.push_back(I);
250 return true;
251 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000252 }
Sjoerd Meijer27be58b2018-07-05 08:21:40 +0000253 LLVM_DEBUG(dbgs() << "No, unsupported Op:\t"; I->dump());
254 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000255}
256
257// Element-by-element comparison of Value lists returning true if they are
258// instructions with the same opcode or constants with the same value.
259static bool AreSymmetrical(const ValueList &VL0,
260 const ValueList &VL1) {
261 if (VL0.size() != VL1.size()) {
262 LLVM_DEBUG(dbgs() << "Muls are mismatching operand list lengths: "
263 << VL0.size() << " != " << VL1.size() << "\n");
264 return false;
265 }
266
267 const unsigned Pairs = VL0.size();
268 LLVM_DEBUG(dbgs() << "Number of operand pairs: " << Pairs << "\n");
269
270 for (unsigned i = 0; i < Pairs; ++i) {
271 const Value *V0 = VL0[i];
272 const Value *V1 = VL1[i];
273 const auto *Inst0 = dyn_cast<Instruction>(V0);
274 const auto *Inst1 = dyn_cast<Instruction>(V1);
275
276 LLVM_DEBUG(dbgs() << "Pair " << i << ":\n";
277 dbgs() << "mul1: "; V0->dump();
278 dbgs() << "mul2: "; V1->dump());
279
280 if (!Inst0 || !Inst1)
281 return false;
282
283 if (Inst0->isSameOperationAs(Inst1)) {
284 LLVM_DEBUG(dbgs() << "OK: same operation found!\n");
285 continue;
286 }
287
288 const APInt *C0, *C1;
289 if (!(match(V0, m_APInt(C0)) && match(V1, m_APInt(C1)) && C0 == C1))
290 return false;
291 }
292
293 LLVM_DEBUG(dbgs() << "OK: found symmetrical operand lists.\n");
294 return true;
295}
296
Sam Parkerffc16812018-07-03 12:44:16 +0000297template<typename MemInst>
298static bool AreSequentialAccesses(MemInst *MemOp0, MemInst *MemOp1,
299 MemInstList &VecMem, const DataLayout &DL,
300 ScalarEvolution &SE) {
301 if (!MemOp0->isSimple() || !MemOp1->isSimple()) {
302 LLVM_DEBUG(dbgs() << "No, not touching volatile access\n");
303 return false;
304 }
305 if (isConsecutiveAccess(MemOp0, MemOp1, DL, SE)) {
Sam Parkera023c7a2018-09-12 09:17:44 +0000306 VecMem.clear();
Sam Parkerffc16812018-07-03 12:44:16 +0000307 VecMem.push_back(MemOp0);
308 VecMem.push_back(MemOp1);
309 LLVM_DEBUG(dbgs() << "OK: accesses are consecutive.\n");
310 return true;
311 }
312 LLVM_DEBUG(dbgs() << "No, accesses aren't consecutive.\n");
313 return false;
314}
315
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000316bool ARMParallelDSP::AreSequentialLoads(LoadInst *Ld0, LoadInst *Ld1,
Sam Parkerffc16812018-07-03 12:44:16 +0000317 MemInstList &VecMem) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000318 if (!Ld0 || !Ld1)
319 return false;
320
321 LLVM_DEBUG(dbgs() << "Are consecutive loads:\n";
322 dbgs() << "Ld0:"; Ld0->dump();
323 dbgs() << "Ld1:"; Ld1->dump();
324 );
325
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000326 if (!Ld0->hasOneUse() || !Ld1->hasOneUse()) {
327 LLVM_DEBUG(dbgs() << "No, load has more than one use.\n");
328 return false;
329 }
Sam Parkerffc16812018-07-03 12:44:16 +0000330
331 return AreSequentialAccesses<LoadInst>(Ld0, Ld1, VecMem, *DL, *SE);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000332}
333
334PMACPairList
Sam Parker89a37992018-07-23 15:25:59 +0000335ARMParallelDSP::CreateParallelMACPairs(OpChainList &Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000336 const unsigned Elems = Candidates.size();
337 PMACPairList PMACPairs;
338
339 if (Elems < 2)
340 return PMACPairs;
341
Sam Parkera023c7a2018-09-12 09:17:44 +0000342 SmallPtrSet<const Instruction*, 4> Paired;
343 for (unsigned i = 0; i < Elems; ++i) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000344 BinOpChain *PMul0 = static_cast<BinOpChain*>(Candidates[i].get());
Sam Parkera023c7a2018-09-12 09:17:44 +0000345 if (Paired.count(PMul0->Root))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000346 continue;
347
Sam Parkera023c7a2018-09-12 09:17:44 +0000348 for (unsigned j = 0; j < Elems; ++j) {
349 if (i == j)
350 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000351
Sam Parkera023c7a2018-09-12 09:17:44 +0000352 BinOpChain *PMul1 = static_cast<BinOpChain*>(Candidates[j].get());
353 if (Paired.count(PMul1->Root))
354 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000355
Sam Parkera023c7a2018-09-12 09:17:44 +0000356 const Instruction *Mul0 = PMul0->Root;
357 const Instruction *Mul1 = PMul1->Root;
358 if (Mul0 == Mul1)
359 continue;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000360
Sam Parkera023c7a2018-09-12 09:17:44 +0000361 assert(PMul0 != PMul1 && "expected different chains");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000362
Sam Parkera023c7a2018-09-12 09:17:44 +0000363 LLVM_DEBUG(dbgs() << "\nCheck parallel muls:\n";
364 dbgs() << "- "; Mul0->dump();
365 dbgs() << "- "; Mul1->dump());
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000366
Sam Parkera023c7a2018-09-12 09:17:44 +0000367 const ValueList &Mul0_LHS = PMul0->LHS;
368 const ValueList &Mul0_RHS = PMul0->RHS;
369 const ValueList &Mul1_LHS = PMul1->LHS;
370 const ValueList &Mul1_RHS = PMul1->RHS;
371
372 if (!AreSymmetrical(Mul0_LHS, Mul1_LHS) ||
373 !AreSymmetrical(Mul0_RHS, Mul1_RHS))
374 continue;
375
376 LLVM_DEBUG(dbgs() << "OK: mul operands list match:\n");
377 // The first elements of each vector should be loads with sexts. If we
378 // find that its two pairs of consecutive loads, then these can be
379 // transformed into two wider loads and the users can be replaced with
380 // DSP intrinsics.
381 bool Found = false;
382 for (unsigned x = 0; x < Mul0_LHS.size(); x += 2) {
383 auto *Ld0 = dyn_cast<LoadInst>(Mul0_LHS[x]);
384 auto *Ld1 = dyn_cast<LoadInst>(Mul1_LHS[x]);
385 auto *Ld2 = dyn_cast<LoadInst>(Mul0_RHS[x]);
386 auto *Ld3 = dyn_cast<LoadInst>(Mul1_RHS[x]);
387
388 if (!Ld0 || !Ld1 || !Ld2 || !Ld3)
389 continue;
390
391 LLVM_DEBUG(dbgs() << "Looking at operands " << x << ":\n"
392 << "\t Ld0: " << *Ld0 << "\n"
393 << "\t Ld1: " << *Ld1 << "\n"
394 << "and operands " << x + 2 << ":\n"
395 << "\t Ld2: " << *Ld2 << "\n"
396 << "\t Ld3: " << *Ld3 << "\n");
397
398 if (AreSequentialLoads(Ld0, Ld1, PMul0->VecLd)) {
399 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
400 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
401 PMACPairs.push_back(std::make_pair(PMul0, PMul1));
402 Found = true;
403 } else if (AreSequentialLoads(Ld3, Ld2, PMul1->VecLd)) {
404 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
405 LLVM_DEBUG(dbgs() << " exchanging Ld2 and Ld3\n");
406 PMul1->Exchange = true;
407 PMACPairs.push_back(std::make_pair(PMul0, PMul1));
408 Found = true;
409 }
410 } else if (AreSequentialLoads(Ld1, Ld0, PMul0->VecLd)) {
411 if (AreSequentialLoads(Ld2, Ld3, PMul1->VecLd)) {
412 LLVM_DEBUG(dbgs() << "OK: found two pairs of parallel loads!\n");
413 LLVM_DEBUG(dbgs() << " exchanging Ld0 and Ld1\n");
414 LLVM_DEBUG(dbgs() << " and swapping muls\n");
415 PMul0->Exchange = true;
416 // Only the second operand can be exchanged, so swap the muls.
417 PMACPairs.push_back(std::make_pair(PMul1, PMul0));
418 Found = true;
419 }
420 }
421 }
422 if (Found) {
423 Paired.insert(Mul0);
424 Paired.insert(Mul1);
425 break;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000426 }
427 }
428 }
429 return PMACPairs;
430}
431
432bool ARMParallelDSP::InsertParallelMACs(Reduction &Reduction,
433 PMACPairList &PMACPairs) {
434 Instruction *Acc = Reduction.Phi;
435 Instruction *InsertAfter = Reduction.AccIntAdd;
436
437 for (auto &Pair : PMACPairs) {
Sam Parkera023c7a2018-09-12 09:17:44 +0000438 BinOpChain *PMul0 = Pair.first;
439 BinOpChain *PMul1 = Pair.second;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000440 LLVM_DEBUG(dbgs() << "Found parallel MACs!!\n";
Sam Parkera023c7a2018-09-12 09:17:44 +0000441 dbgs() << "- "; PMul0->Root->dump();
442 dbgs() << "- "; PMul1->Root->dump());
443
444 auto *VecLd0 = cast<LoadInst>(PMul0->VecLd[0]);
445 auto *VecLd1 = cast<LoadInst>(PMul1->VecLd[0]);
446 Acc = CreateSMLADCall(VecLd0, VecLd1, Acc, PMul1->Exchange, InsertAfter);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000447 InsertAfter = Acc;
448 }
449
450 if (Acc != Reduction.Phi) {
451 LLVM_DEBUG(dbgs() << "Replace Accumulate: "; Acc->dump());
452 Reduction.AccIntAdd->replaceAllUsesWith(Acc);
453 return true;
454 }
455 return false;
456}
457
Sam Parker89a37992018-07-23 15:25:59 +0000458static void MatchReductions(Function &F, Loop *TheLoop, BasicBlock *Header,
459 ReductionList &Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000460 RecurrenceDescriptor RecDesc;
461 const bool HasFnNoNaNAttr =
462 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
463 const BasicBlock *Latch = TheLoop->getLoopLatch();
464
465 // We need a preheader as getIncomingValueForBlock assumes there is one.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000466 if (!TheLoop->getLoopPreheader()) {
467 LLVM_DEBUG(dbgs() << "No preheader found, bailing out\n");
Sam Parker89a37992018-07-23 15:25:59 +0000468 return;
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000469 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000470
471 for (PHINode &Phi : Header->phis()) {
472 const auto *Ty = Phi.getType();
Sam Parker01db2982018-09-11 14:01:22 +0000473 if (!Ty->isIntegerTy(32) && !Ty->isIntegerTy(64))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000474 continue;
475
476 const bool IsReduction =
477 RecurrenceDescriptor::AddReductionVar(&Phi,
478 RecurrenceDescriptor::RK_IntegerAdd,
479 TheLoop, HasFnNoNaNAttr, RecDesc);
480 if (!IsReduction)
481 continue;
482
483 Instruction *Acc = dyn_cast<Instruction>(Phi.getIncomingValueForBlock(Latch));
484 if (!Acc)
485 continue;
486
487 Reductions.push_back(Reduction(&Phi, Acc));
488 }
489
490 LLVM_DEBUG(
491 dbgs() << "\nAccumulating integer additions (reductions) found:\n";
Sam Parker89a37992018-07-23 15:25:59 +0000492 for (auto &R : Reductions) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000493 dbgs() << "- "; R.Phi->dump();
494 dbgs() << "-> "; R.AccIntAdd->dump();
495 }
496 );
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000497}
498
Eli Friedmanb09c7782018-10-18 19:34:30 +0000499static void AddMACCandidate(OpChainList &Candidates,
Sam Parker01db2982018-09-11 14:01:22 +0000500 Instruction *Mul,
501 Value *MulOp0, Value *MulOp1) {
Eli Friedmanb09c7782018-10-18 19:34:30 +0000502 LLVM_DEBUG(dbgs() << "OK, found acc mul:\t"; Mul->dump());
Sam Parker01db2982018-09-11 14:01:22 +0000503 assert(Mul->getOpcode() == Instruction::Mul &&
504 "expected mul instruction");
Sam Parker89a37992018-07-23 15:25:59 +0000505 ValueList LHS;
506 ValueList RHS;
507 if (IsNarrowSequence<16>(MulOp0, LHS) &&
508 IsNarrowSequence<16>(MulOp1, RHS)) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000509 LLVM_DEBUG(dbgs() << "OK, found narrow mul: "; Mul->dump());
Fangrui Song58407ca2018-07-23 17:43:21 +0000510 Candidates.push_back(make_unique<BinOpChain>(Mul, LHS, RHS));
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000511 }
512}
513
Sam Parker89a37992018-07-23 15:25:59 +0000514static void MatchParallelMACSequences(Reduction &R,
515 OpChainList &Candidates) {
Sam Parkera023c7a2018-09-12 09:17:44 +0000516 Instruction *Acc = R.AccIntAdd;
517 LLVM_DEBUG(dbgs() << "\n- Analysing:\t" << *Acc);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000518
Sam Parkera023c7a2018-09-12 09:17:44 +0000519 // Returns false to signal the search should be stopped.
520 std::function<bool(Value*)> Match =
521 [&Candidates, &Match](Value *V) -> bool {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000522
Sam Parkera023c7a2018-09-12 09:17:44 +0000523 auto *I = dyn_cast<Instruction>(V);
Sam Parker11879112018-09-12 09:58:56 +0000524 if (!I)
Sam Parkera023c7a2018-09-12 09:17:44 +0000525 return false;
Sam Parker01db2982018-09-11 14:01:22 +0000526
Sam Parkera023c7a2018-09-12 09:17:44 +0000527 Value *MulOp0, *MulOp1;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000528
Sam Parkera023c7a2018-09-12 09:17:44 +0000529 switch (I->getOpcode()) {
530 case Instruction::Add:
531 if (Match(I->getOperand(0)) || (Match(I->getOperand(1))))
532 return true;
533 break;
534 case Instruction::Mul:
535 if (match (I, (m_Mul(m_Value(MulOp0), m_Value(MulOp1))))) {
Eli Friedmanb09c7782018-10-18 19:34:30 +0000536 AddMACCandidate(Candidates, I, MulOp0, MulOp1);
Sam Parkera023c7a2018-09-12 09:17:44 +0000537 return false;
538 }
539 break;
540 case Instruction::SExt:
541 if (match (I, (m_SExt(m_Mul(m_Value(MulOp0), m_Value(MulOp1)))))) {
542 Instruction *Mul = cast<Instruction>(I->getOperand(0));
Eli Friedmanb09c7782018-10-18 19:34:30 +0000543 AddMACCandidate(Candidates, Mul, MulOp0, MulOp1);
Sam Parkera023c7a2018-09-12 09:17:44 +0000544 return false;
545 }
546 break;
547 }
548 return false;
549 };
550
551 while (Match (Acc));
552 LLVM_DEBUG(dbgs() << "Finished matching MAC sequences, found "
553 << Candidates.size() << " candidates.\n");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000554}
555
556// Collects all instructions that are not part of the MAC chains, which is the
557// set of instructions that can potentially alias with the MAC operands.
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000558static void AliasCandidates(BasicBlock *Header, Instructions &Reads,
559 Instructions &Writes) {
560 for (auto &I : *Header) {
561 if (I.mayReadFromMemory())
562 Reads.push_back(&I);
563 if (I.mayWriteToMemory())
564 Writes.push_back(&I);
565 }
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000566}
567
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000568// Check whether statements in the basic block that write to memory alias with
569// the memory locations accessed by the MAC-chains.
570// TODO: we need the read statements when we accept more complicated chains.
571static bool AreAliased(AliasAnalysis *AA, Instructions &Reads,
Eli Friedmanb09c7782018-10-18 19:34:30 +0000572 Instructions &Writes, OpChainList &MACCandidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000573 LLVM_DEBUG(dbgs() << "Alias checks:\n");
Eli Friedmanb09c7782018-10-18 19:34:30 +0000574 for (auto &MAC : MACCandidates) {
575 LLVM_DEBUG(dbgs() << "mul: "; MAC->Root->dump());
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000576
577 // At the moment, we allow only simple chains that only consist of reads,
578 // accumulate their result with an integer add, and thus that don't write
579 // memory, and simply bail if they do.
Eli Friedmanb09c7782018-10-18 19:34:30 +0000580 if (!MAC->ReadOnly)
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000581 return true;
582
583 // Now for all writes in the basic block, check that they don't alias with
584 // the memory locations accessed by our MAC-chain:
585 for (auto *I : Writes) {
586 LLVM_DEBUG(dbgs() << "- "; I->dump());
Eli Friedmanb09c7782018-10-18 19:34:30 +0000587 assert(MAC->MemLocs.size() >= 2 && "expecting at least 2 memlocs");
588 for (auto &MemLoc : MAC->MemLocs) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000589 if (isModOrRefSet(intersectModRef(AA->getModRefInfo(I, MemLoc),
590 ModRefInfo::ModRef))) {
591 LLVM_DEBUG(dbgs() << "Yes, aliases found\n");
592 return true;
593 }
594 }
595 }
596 }
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000597
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000598 LLVM_DEBUG(dbgs() << "OK: no aliases found!\n");
599 return false;
600}
601
Eli Friedmanb09c7782018-10-18 19:34:30 +0000602static bool CheckMACMemory(OpChainList &Candidates) {
Fangrui Song58407ca2018-07-23 17:43:21 +0000603 for (auto &C : Candidates) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000604 // A mul has 2 operands, and a narrow op consist of sext and a load; thus
605 // we expect at least 4 items in this operand value list.
Sam Parker89a37992018-07-23 15:25:59 +0000606 if (C->size() < 4) {
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000607 LLVM_DEBUG(dbgs() << "Operand list too short.\n");
608 return false;
609 }
Eli Friedmanb09c7782018-10-18 19:34:30 +0000610 C->SetMemoryLocations();
Fangrui Song58407ca2018-07-23 17:43:21 +0000611 ValueList &LHS = static_cast<BinOpChain*>(C.get())->LHS;
612 ValueList &RHS = static_cast<BinOpChain*>(C.get())->RHS;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000613
Sam Parker89a37992018-07-23 15:25:59 +0000614 // Use +=2 to skip over the expected extend instructions.
615 for (unsigned i = 0, e = LHS.size(); i < e; i += 2) {
616 if (!isa<LoadInst>(LHS[i]) || !isa<LoadInst>(RHS[i]))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000617 return false;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000618 }
619 }
620 return true;
621}
622
623// Loop Pass that needs to identify integer add/sub reductions of 16-bit vector
624// multiplications.
625// To use SMLAD:
626// 1) we first need to find integer add reduction PHIs,
627// 2) then from the PHI, look for this pattern:
628//
629// acc0 = phi i32 [0, %entry], [%acc1, %loop.body]
630// ld0 = load i16
631// sext0 = sext i16 %ld0 to i32
632// ld1 = load i16
633// sext1 = sext i16 %ld1 to i32
634// mul0 = mul %sext0, %sext1
635// ld2 = load i16
636// sext2 = sext i16 %ld2 to i32
637// ld3 = load i16
638// sext3 = sext i16 %ld3 to i32
639// mul1 = mul i32 %sext2, %sext3
640// add0 = add i32 %mul0, %acc0
641// acc1 = add i32 %add0, %mul1
642//
643// Which can be selected to:
644//
645// ldr.h r0
646// ldr.h r1
647// smlad r2, r0, r1, r2
648//
649// If constants are used instead of loads, these will need to be hoisted
650// out and into a register.
651//
652// If loop invariants are used instead of loads, these need to be packed
653// before the loop begins.
654//
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000655bool ARMParallelDSP::MatchSMLAD(Function &F) {
656 BasicBlock *Header = L->getHeader();
657 LLVM_DEBUG(dbgs() << "= Matching SMLAD =\n";
658 dbgs() << "Header block:\n"; Header->dump();
659 dbgs() << "Loop info:\n\n"; L->dump());
660
Eli Friedmanb09c7782018-10-18 19:34:30 +0000661 bool Changed = false;
Sam Parker89a37992018-07-23 15:25:59 +0000662 ReductionList Reductions;
663 MatchReductions(F, L, Header, Reductions);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000664
665 for (auto &R : Reductions) {
Sam Parker89a37992018-07-23 15:25:59 +0000666 OpChainList MACCandidates;
667 MatchParallelMACSequences(R, MACCandidates);
Eli Friedmanb09c7782018-10-18 19:34:30 +0000668 if (!CheckMACMemory(MACCandidates))
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000669 continue;
Sam Parker89a37992018-07-23 15:25:59 +0000670
Fangrui Song58407ca2018-07-23 17:43:21 +0000671 R.MACCandidates = std::move(MACCandidates);
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000672
673 LLVM_DEBUG(dbgs() << "MAC candidates:\n";
674 for (auto &M : R.MACCandidates)
Sam Parker89a37992018-07-23 15:25:59 +0000675 M->Root->dump();
Sjoerd Meijer53449da2018-07-11 12:36:25 +0000676 dbgs() << "\n";);
677 }
678
679 // Collect all instructions that may read or write memory. Our alias
680 // analysis checks bail out if any of these instructions aliases with an
681 // instruction from the MAC-chain.
682 Instructions Reads, Writes;
683 AliasCandidates(Header, Reads, Writes);
684
685 for (auto &R : Reductions) {
686 if (AreAliased(AA, Reads, Writes, R.MACCandidates))
687 return false;
688 PMACPairList PMACPairs = CreateParallelMACPairs(R.MACCandidates);
689 Changed |= InsertParallelMACs(R, PMACPairs);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000690 }
691
692 LLVM_DEBUG(if (Changed) dbgs() << "Header block:\n"; Header->dump(););
693 return Changed;
694}
695
Eli Friedmanb09c7782018-10-18 19:34:30 +0000696static LoadInst *CreateLoadIns(IRBuilder<NoFolder> &IRB, LoadInst &BaseLoad,
697 const Type *LoadTy) {
698 const unsigned AddrSpace = BaseLoad.getPointerAddressSpace();
699
700 Value *VecPtr = IRB.CreateBitCast(BaseLoad.getPointerOperand(),
701 LoadTy->getPointerTo(AddrSpace));
702 return IRB.CreateAlignedLoad(VecPtr, BaseLoad.getAlignment());
703}
704
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000705Instruction *ARMParallelDSP::CreateSMLADCall(LoadInst *VecLd0, LoadInst *VecLd1,
Sam Parkera023c7a2018-09-12 09:17:44 +0000706 Instruction *Acc, bool Exchange,
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000707 Instruction *InsertAfter) {
Sam Parkera023c7a2018-09-12 09:17:44 +0000708 LLVM_DEBUG(dbgs() << "Create SMLAD intrinsic using:\n"
709 << "- " << *VecLd0 << "\n"
710 << "- " << *VecLd1 << "\n"
711 << "- " << *Acc << "\n"
712 << "Exchange: " << Exchange << "\n");
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000713
714 IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
715 ++BasicBlock::iterator(InsertAfter));
716
717 // Replace the reduction chain with an intrinsic call
Sam Parker01db2982018-09-11 14:01:22 +0000718 const Type *Ty = IntegerType::get(M->getContext(), 32);
Eli Friedmanb09c7782018-10-18 19:34:30 +0000719 LoadInst *NewLd0 = CreateLoadIns(Builder, VecLd0[0], Ty);
720 LoadInst *NewLd1 = CreateLoadIns(Builder, VecLd1[0], Ty);
Sam Parkera023c7a2018-09-12 09:17:44 +0000721 Value* Args[] = { NewLd0, NewLd1, Acc };
722 Function *SMLAD = nullptr;
723 if (Exchange)
724 SMLAD = Acc->getType()->isIntegerTy(32) ?
725 Intrinsic::getDeclaration(M, Intrinsic::arm_smladx) :
726 Intrinsic::getDeclaration(M, Intrinsic::arm_smlaldx);
727 else
728 SMLAD = Acc->getType()->isIntegerTy(32) ?
729 Intrinsic::getDeclaration(M, Intrinsic::arm_smlad) :
730 Intrinsic::getDeclaration(M, Intrinsic::arm_smlald);
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000731 CallInst *Call = Builder.CreateCall(SMLAD, Args);
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000732 NumSMLAD++;
Sjoerd Meijerc89ca552018-06-28 12:55:29 +0000733 return Call;
734}
735
736Pass *llvm::createARMParallelDSPPass() {
737 return new ARMParallelDSP();
738}
739
740char ARMParallelDSP::ID = 0;
741
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000742INITIALIZE_PASS_BEGIN(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000743 "Transform loops to use DSP intrinsics", false, false)
Sjoerd Meijerb3e06fa2018-07-06 14:47:09 +0000744INITIALIZE_PASS_END(ARMParallelDSP, "arm-parallel-dsp",
Simon Pilgrimc09b5e32018-06-28 18:37:16 +0000745 "Transform loops to use DSP intrinsics", false, false)