LLVM 24.0.0git
MVELaneInterleavingPass.cpp
Go to the documentation of this file.
1//===- MVELaneInterleaving.cpp - Inverleave for MVE instructions ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass interleaves around sext/zext/trunc instructions. MVE does not have
10// a single sext/zext or trunc instruction that takes the bottom half of a
11// vector and extends to a full width, like NEON has with MOVL. Instead it is
12// expected that this happens through top/bottom instructions. So the MVE
13// equivalent VMOVLT/B instructions take either the even or odd elements of the
14// input and extend them to the larger type, producing a vector with half the
15// number of elements each of double the bitwidth. As there is no simple
16// instruction, we often have to turn sext/zext/trunc into a series of lane
17// moves (or stack loads/stores, which we do not do yet).
18//
19// This pass takes vector code that starts at truncs, looks for interconnected
20// blobs of operations that end with sext/zext (or constants/splats) of the
21// form:
22// %sa = sext v8i16 %a to v8i32
23// %sb = sext v8i16 %b to v8i32
24// %add = add v8i32 %sa, %sb
25// %r = trunc %add to v8i16
26// And adds shuffles to allow the use of VMOVL/VMOVN instructions:
27// %sha = shuffle v8i16 %a, undef, <0, 2, 4, 6, 1, 3, 5, 7>
28// %sa = sext v8i16 %sha to v8i32
29// %shb = shuffle v8i16 %b, undef, <0, 2, 4, 6, 1, 3, 5, 7>
30// %sb = sext v8i16 %shb to v8i32
31// %add = add v8i32 %sa, %sb
32// %r = trunc %add to v8i16
33// %shr = shuffle v8i16 %r, undef, <0, 4, 1, 5, 2, 6, 3, 7>
34// Which can then be split and lowered to MVE instructions efficiently:
35// %sa_b = VMOVLB.s16 %a
36// %sa_t = VMOVLT.s16 %a
37// %sb_b = VMOVLB.s16 %b
38// %sb_t = VMOVLT.s16 %b
39// %add_b = VADD.i32 %sa_b, %sb_b
40// %add_t = VADD.i32 %sa_t, %sb_t
41// %r = VMOVNT.i16 %add_b, %add_t
42//
43//===----------------------------------------------------------------------===//
44
45#include "ARM.h"
46#include "ARMBaseInstrInfo.h"
47#include "ARMSubtarget.h"
48#include "llvm/ADT/SetVector.h"
52#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/Function.h"
55#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Value.h"
65#include "llvm/Pass.h"
67#include <cassert>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "mve-laneinterleave"
72
73namespace {
74
75class MVELaneInterleaving : public FunctionPass {
76public:
77 static char ID; // Pass identification, replacement for typeid
78
79 explicit MVELaneInterleaving() : FunctionPass(ID) {
81 }
82
83 bool runOnFunction(Function &F) override;
84
85 StringRef getPassName() const override { return "MVE lane interleaving"; }
86
87 void getAnalysisUsage(AnalysisUsage &AU) const override {
88 AU.setPreservesCFG();
91 }
92};
93
94} // end anonymous namespace
95
96char MVELaneInterleaving::ID = 0;
97
98INITIALIZE_PASS(MVELaneInterleaving, DEBUG_TYPE, "MVE lane interleaving", false,
99 false)
100
102 return new MVELaneInterleaving();
103}
104
107 // This is not always beneficial to transform. Exts can be incorporated into
108 // loads, Truncs can be folded into stores.
109 // Truncs are usually the same number of instructions,
110 // VSTRH.32(A);VSTRH.32(B) vs VSTRH.16(VMOVNT A, B) with interleaving
111 // Exts are unfortunately more instructions in the general case:
112 // A=VLDRH.32; B=VLDRH.32;
113 // vs with interleaving:
114 // T=VLDRH.16; A=VMOVNB T; B=VMOVNT T
115 // But those VMOVL may be folded into a VMULL.
116
117 // But expensive extends/truncs are always good to remove. FPExts always
118 // involve extra VCVT's so are always considered to be beneficial to convert.
119 for (auto *E : Exts) {
120 if (isa<FPExtInst>(E) || !isa<LoadInst>(E->getOperand(0))) {
121 LLVM_DEBUG(dbgs() << "Beneficial due to " << *E << "\n");
122 return true;
123 }
124 }
125 for (auto *T : Truncs) {
126 if (T->hasOneUse() && !isa<StoreInst>(*T->user_begin())) {
127 LLVM_DEBUG(dbgs() << "Beneficial due to " << *T << "\n");
128 return true;
129 }
130 }
131
132 // Otherwise, we know we have a load(ext), see if any of the Extends are a
133 // vmull. This is a simple heuristic and certainly not perfect.
134 for (auto *E : Exts) {
135 if (!E->hasOneUse() ||
136 (*E->user_begin())->getOpcode() != Instruction::Mul) {
137 LLVM_DEBUG(dbgs() << "Not beneficial due to " << *E << "\n");
138 return false;
139 }
140 }
141 return true;
142}
143
144static bool tryInterleave(Instruction *Start,
146 LLVM_DEBUG(dbgs() << "tryInterleave from " << *Start << "\n");
147
148 if (!isa<Instruction>(Start->getOperand(0)))
149 return false;
150
151 // Look for connected operations starting from Ext's, terminating at Truncs.
152 std::vector<Instruction *> Worklist;
153 Worklist.push_back(Start);
154 Worklist.push_back(cast<Instruction>(Start->getOperand(0)));
155
159 SmallSetVector<Use *, 4> OtherLeafs;
161
162 while (!Worklist.empty()) {
163 Instruction *I = Worklist.back();
164 Worklist.pop_back();
165
166 switch (I->getOpcode()) {
167 // Truncs
168 case Instruction::Trunc:
169 case Instruction::FPTrunc:
170 if (!Truncs.insert(I))
171 continue;
172 Visited.insert(I);
173 break;
174
175 // Extend leaves
176 case Instruction::SExt:
177 case Instruction::ZExt:
178 case Instruction::FPExt:
179 if (Exts.count(I))
180 continue;
181 for (Instruction *Use : I->users())
182 Worklist.push_back(Use);
183 Exts.insert(I);
184 break;
185
186 case Instruction::Call: {
188 if (!II)
189 return false;
190
191 if (II->getIntrinsicID() == Intrinsic::vector_reduce_add) {
192 if (!Reducts.insert(I))
193 continue;
194 Visited.insert(I);
195 break;
196 }
197
198 switch (II->getIntrinsicID()) {
199 case Intrinsic::abs:
200 case Intrinsic::smin:
201 case Intrinsic::smax:
202 case Intrinsic::umin:
203 case Intrinsic::umax:
204 case Intrinsic::sadd_sat:
205 case Intrinsic::ssub_sat:
206 case Intrinsic::uadd_sat:
207 case Intrinsic::usub_sat:
208 case Intrinsic::minnum:
209 case Intrinsic::maxnum:
210 case Intrinsic::fabs:
211 case Intrinsic::fma:
212 case Intrinsic::ceil:
213 case Intrinsic::floor:
214 case Intrinsic::rint:
215 case Intrinsic::round:
216 case Intrinsic::trunc:
217 break;
218 default:
219 return false;
220 }
221 [[fallthrough]]; // Fall through to treating these like an operator below.
222 }
223 // Binary/tertiary ops
224 case Instruction::Add:
225 case Instruction::Sub:
226 case Instruction::Mul:
227 case Instruction::AShr:
228 case Instruction::LShr:
229 case Instruction::Shl:
230 case Instruction::ICmp:
231 case Instruction::FCmp:
232 case Instruction::FAdd:
233 case Instruction::FMul:
234 case Instruction::Select:
235 if (!Ops.insert(I))
236 continue;
237
238 for (Use &Op : I->operands()) {
239 if (!isa<FixedVectorType>(Op->getType()))
240 continue;
241 if (isa<Instruction>(Op))
242 Worklist.push_back(cast<Instruction>(&Op));
243 else
244 OtherLeafs.insert(&Op);
245 }
246
247 for (Instruction *Use : I->users())
248 Worklist.push_back(Use);
249 break;
250
251 case Instruction::ShuffleVector:
252 // A shuffle of a splat is a splat.
253 if (cast<ShuffleVectorInst>(I)->isZeroEltSplat())
254 continue;
255 [[fallthrough]];
256
257 default:
258 LLVM_DEBUG(dbgs() << " Unhandled instruction: " << *I << "\n");
259 return false;
260 }
261 }
262
263 if (Exts.empty() && OtherLeafs.empty())
264 return false;
265
266 LLVM_DEBUG({
267 dbgs() << "Found group:\n Exts:\n";
268 for (auto *I : Exts)
269 dbgs() << " " << *I << "\n";
270 dbgs() << " Ops:\n";
271 for (auto *I : Ops)
272 dbgs() << " " << *I << "\n";
273 dbgs() << " OtherLeafs:\n";
274 for (auto *I : OtherLeafs)
275 dbgs() << " " << *I->get() << " of " << *I->getUser() << "\n";
276 dbgs() << " Truncs:\n";
277 for (auto *I : Truncs)
278 dbgs() << " " << *I << "\n";
279 dbgs() << " Reducts:\n";
280 for (auto *I : Reducts)
281 dbgs() << " " << *I << "\n";
282 });
283
284 assert((!Truncs.empty() || !Reducts.empty()) &&
285 "Expected some truncs or reductions");
286 if (Truncs.empty() && Exts.empty())
287 return false;
288
289 auto *VT = !Truncs.empty()
290 ? cast<FixedVectorType>(Truncs[0]->getType())
291 : cast<FixedVectorType>(Exts[0]->getOperand(0)->getType());
292 LLVM_DEBUG(dbgs() << "Using VT:" << *VT << "\n");
293
294 // Check types
295 unsigned NumElts = VT->getNumElements();
296 unsigned BaseElts = VT->getScalarSizeInBits() == 16
297 ? 8
298 : (VT->getScalarSizeInBits() == 8 ? 16 : 0);
299 if (BaseElts == 0 || NumElts % BaseElts != 0) {
300 LLVM_DEBUG(dbgs() << " Type is unsupported\n");
301 return false;
302 }
303 if (Start->getOperand(0)->getType()->getScalarSizeInBits() !=
304 VT->getScalarSizeInBits() * 2) {
305 LLVM_DEBUG(dbgs() << " Type not double sized\n");
306 return false;
307 }
308 for (Instruction *I : Exts)
309 if (I->getOperand(0)->getType() != VT) {
310 LLVM_DEBUG(dbgs() << " Wrong type on " << *I << "\n");
311 return false;
312 }
313 for (Instruction *I : Truncs)
314 if (I->getType() != VT) {
315 LLVM_DEBUG(dbgs() << " Wrong type on " << *I << "\n");
316 return false;
317 }
318
319 // Check that it looks beneficial
320 if (!isProfitableToInterleave(Exts, Truncs))
321 return false;
322 if (!Reducts.empty() && (Ops.empty() || all_of(Ops, [](Instruction *I) {
323 return I->getOpcode() == Instruction::Mul ||
324 I->getOpcode() == Instruction::Select ||
325 I->getOpcode() == Instruction::ICmp;
326 }))) {
327 LLVM_DEBUG(dbgs() << "Reduction does not look profitable\n");
328 return false;
329 }
330
331 // Create new shuffles around the extends / truncs / other leaves.
332 IRBuilder<> Builder(Start);
333
334 SmallVector<int, 16> LeafMask;
335 SmallVector<int, 16> TruncMask;
336 // LeafMask : 0, 2, 4, 6, 1, 3, 5, 7 8, 10, 12, 14, 9, 11, 13, 15
337 // TruncMask: 0, 4, 1, 5, 2, 6, 3, 7 8, 12, 9, 13, 10, 14, 11, 15
338 for (unsigned Base = 0; Base < NumElts; Base += BaseElts) {
339 for (unsigned i = 0; i < BaseElts / 2; i++)
340 LeafMask.push_back(Base + i * 2);
341 for (unsigned i = 0; i < BaseElts / 2; i++)
342 LeafMask.push_back(Base + i * 2 + 1);
343 }
344 for (unsigned Base = 0; Base < NumElts; Base += BaseElts) {
345 for (unsigned i = 0; i < BaseElts / 2; i++) {
346 TruncMask.push_back(Base + i);
347 TruncMask.push_back(Base + i + BaseElts / 2);
348 }
349 }
350
351 for (Instruction *I : Exts) {
352 LLVM_DEBUG(dbgs() << "Replacing ext " << *I << "\n");
353 Builder.SetInsertPoint(I);
354 Value *Shuffle = Builder.CreateShuffleVector(I->getOperand(0), LeafMask);
355 bool FPext = isa<FPExtInst>(I);
356 bool Sext = isa<SExtInst>(I);
357 Value *Ext = FPext ? Builder.CreateFPExt(Shuffle, I->getType())
358 : Sext ? Builder.CreateSExt(Shuffle, I->getType())
359 : Builder.CreateZExt(Shuffle, I->getType());
360 I->replaceAllUsesWith(Ext);
361 LLVM_DEBUG(dbgs() << " with " << *Shuffle << "\n");
362 }
363
364 for (Use *I : OtherLeafs) {
365 LLVM_DEBUG(dbgs() << "Replacing leaf " << *I << "\n");
366 Builder.SetInsertPoint(cast<Instruction>(I->getUser()));
367 Value *Shuffle = Builder.CreateShuffleVector(I->get(), LeafMask);
368 I->getUser()->setOperand(I->getOperandNo(), Shuffle);
369 LLVM_DEBUG(dbgs() << " with " << *Shuffle << "\n");
370 }
371
372 for (Instruction *I : Truncs) {
373 LLVM_DEBUG(dbgs() << "Replacing trunc " << *I << "\n");
374
375 Builder.SetInsertPoint(++I->getIterator());
376 Value *Shuf = Builder.CreateShuffleVector(I, TruncMask);
377 I->replaceAllUsesWith(Shuf);
378 cast<Instruction>(Shuf)->setOperand(0, I);
379
380 LLVM_DEBUG(dbgs() << " with " << *Shuf << "\n");
381 }
382
383 return true;
384}
385
386// Add reductions are fairly common and associative, meaning we can start the
387// interleaving from them and don't need to emit a shuffle.
389 if (auto *II = dyn_cast<IntrinsicInst>(&I))
390 return II->getIntrinsicID() == Intrinsic::vector_reduce_add;
391 return false;
392}
393
394bool MVELaneInterleaving::runOnFunction(Function &F) {
395 auto &TPC = getAnalysis<TargetPassConfig>();
396 auto &TM = TPC.getTM<TargetMachine>();
397 auto *ST = &TM.getSubtarget<ARMSubtarget>(F);
398 if (!ST->getCLOpts().mve_interleave || !ST->hasMVEIntegerOps())
399 return false;
400
401 bool Changed = false;
402
403 SmallPtrSet<Instruction *, 16> Visited;
404 for (Instruction &I : reverse(instructions(F))) {
405 if (((I.getType()->isVectorTy() &&
407 isAddReduction(I)) &&
408 !Visited.count(&I))
409 Changed |= tryInterleave(&I, Visited);
410 }
411
412 return Changed;
413}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isProfitableToInterleave(SmallSetVector< Instruction *, 4 > &Exts, SmallSetVector< Instruction *, 4 > &Truncs)
static bool tryInterleave(Instruction *Start, SmallPtrSetImpl< Instruction * > &Visited)
static bool isAddReduction(Instruction &I)
#define T
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file implements a set that has insertion order iteration characteristics.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
A wrapper class for inspecting calls to intrinsic functions.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:114
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Target-Independent Code Generator Pass Configuration Options.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Pass * createMVELaneInterleavingPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void initializeMVELaneInterleavingPass(PassRegistry &)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559