blob: 28bb482a3be847035f3179280d5bfb385e523597 [file] [log] [blame]
Sam Parker3828c6f2018-07-23 12:27:47 +00001//===----- ARMCodeGenPrepare.cpp ------------------------------------------===//
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/// This pass inserts intrinsics to handle small types that would otherwise be
12/// promoted during legalization. Here we can manually promote types or insert
13/// intrinsics which can handle narrow types that aren't supported by the
14/// register classes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "ARM.h"
19#include "ARMSubtarget.h"
20#include "ARMTargetMachine.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/CodeGen/TargetPassConfig.h"
24#include "llvm/IR/Attributes.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
35#include "llvm/IR/Verifier.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/CommandLine.h"
39
40#define DEBUG_TYPE "arm-codegenprepare"
41
42using namespace llvm;
43
44static cl::opt<bool>
Sam Parker945604d2018-09-11 12:45:43 +000045DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(false),
Sam Parker3828c6f2018-07-23 12:27:47 +000046 cl::desc("Disable ARM specific CodeGenPrepare pass"));
47
48static cl::opt<bool>
49EnableDSP("arm-enable-scalar-dsp", cl::Hidden, cl::init(false),
50 cl::desc("Use DSP instructions for scalar operations"));
51
52static cl::opt<bool>
53EnableDSPWithImms("arm-enable-scalar-dsp-imms", cl::Hidden, cl::init(false),
54 cl::desc("Use DSP instructions for scalar operations\
55 with immediate operands"));
56
Sjoerd Meijer31239a42018-08-17 07:34:01 +000057// The goal of this pass is to enable more efficient code generation for
58// operations on narrow types (i.e. types with < 32-bits) and this is a
59// motivating IR code example:
60//
61// define hidden i32 @cmp(i8 zeroext) {
62// %2 = add i8 %0, -49
63// %3 = icmp ult i8 %2, 3
64// ..
65// }
66//
67// The issue here is that i8 is type-legalized to i32 because i8 is not a
68// legal type. Thus, arithmetic is done in integer-precision, but then the
69// byte value is masked out as follows:
70//
71// t19: i32 = add t4, Constant:i32<-49>
72// t24: i32 = and t19, Constant:i32<255>
73//
74// Consequently, we generate code like this:
75//
76// subs r0, #49
77// uxtb r1, r0
78// cmp r1, #3
79//
80// This shows that masking out the byte value results in generation of
81// the UXTB instruction. This is not optimal as r0 already contains the byte
82// value we need, and so instead we can just generate:
83//
84// sub.w r1, r0, #49
85// cmp r1, #3
86//
87// We achieve this by type promoting the IR to i32 like so for this example:
88//
89// define i32 @cmp(i8 zeroext %c) {
90// %0 = zext i8 %c to i32
91// %c.off = add i32 %0, -49
92// %1 = icmp ult i32 %c.off, 3
93// ..
94// }
95//
96// For this to be valid and legal, we need to prove that the i32 add is
97// producing the same value as the i8 addition, and that e.g. no overflow
98// happens.
99//
100// A brief sketch of the algorithm and some terminology.
101// We pattern match interesting IR patterns:
102// - which have "sources": instructions producing narrow values (i8, i16), and
103// - they have "sinks": instructions consuming these narrow values.
104//
105// We collect all instruction connecting sources and sinks in a worklist, so
106// that we can mutate these instruction and perform type promotion when it is
107// legal to do so.
Sam Parker3828c6f2018-07-23 12:27:47 +0000108
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000109namespace {
Sam Parker3828c6f2018-07-23 12:27:47 +0000110class IRPromoter {
111 SmallPtrSet<Value*, 8> NewInsts;
112 SmallVector<Instruction*, 4> InstsToRemove;
113 Module *M = nullptr;
114 LLVMContext &Ctx;
115
116public:
117 IRPromoter(Module *M) : M(M), Ctx(M->getContext()) { }
118
119 void Cleanup() {
120 for (auto *I : InstsToRemove) {
121 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
122 I->dropAllReferences();
123 I->eraseFromParent();
124 }
125 InstsToRemove.clear();
126 NewInsts.clear();
127 }
128
129 void Mutate(Type *OrigTy,
130 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000131 SmallPtrSetImpl<Value*> &Sources,
132 SmallPtrSetImpl<Instruction*> &Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000133};
134
135class ARMCodeGenPrepare : public FunctionPass {
136 const ARMSubtarget *ST = nullptr;
137 IRPromoter *Promoter = nullptr;
138 std::set<Value*> AllVisited;
Sam Parker3828c6f2018-07-23 12:27:47 +0000139
Sam Parker3828c6f2018-07-23 12:27:47 +0000140 bool isSupportedValue(Value *V);
141 bool isLegalToPromote(Value *V);
142 bool TryToPromote(Value *V);
143
144public:
145 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000146 static unsigned TypeSize;
147 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000148
149 ARMCodeGenPrepare() : FunctionPass(ID) {}
150
Sam Parker3828c6f2018-07-23 12:27:47 +0000151 void getAnalysisUsage(AnalysisUsage &AU) const override {
152 AU.addRequired<TargetPassConfig>();
153 }
154
155 StringRef getPassName() const override { return "ARM IR optimizations"; }
156
157 bool doInitialization(Module &M) override;
158 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000159 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000160};
161
162}
163
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000164static bool generateSignBits(Value *V) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000165 if (!isa<Instruction>(V))
166 return false;
167
168 unsigned Opc = cast<Instruction>(V)->getOpcode();
169 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
170 Opc == Instruction::SRem;
171}
172
173/// Some instructions can use 8- and 16-bit operands, and we don't need to
174/// promote anything larger. We disallow booleans to make life easier when
175/// dealing with icmps but allow any other integer that is <= 16 bits. Void
176/// types are accepted so we can handle switches.
177static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000178 LLVM_DEBUG(dbgs() << "ARM CGP: isSupportedType: " << *V << "\n");
179 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000180
181 // Allow voids and pointers, these won't be promoted.
182 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000183 return true;
184
Sam Parker8c4b9642018-08-10 13:57:13 +0000185 if (auto *Ld = dyn_cast<LoadInst>(V))
186 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
187
188 const IntegerType *IntTy = dyn_cast<IntegerType>(Ty);
189 if (!IntTy) {
190 LLVM_DEBUG(dbgs() << "ARM CGP: No, not an integer.\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000191 return false;
Sam Parker8c4b9642018-08-10 13:57:13 +0000192 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000193
Sam Parker8c4b9642018-08-10 13:57:13 +0000194 return IntTy->getBitWidth() == ARMCodeGenPrepare::TypeSize;
195}
Sam Parker3828c6f2018-07-23 12:27:47 +0000196
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000197/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000198/// a narrow (i8, i16) value. These values will be zext to start the promotion
199/// of the tree to i32. We guarantee that these won't populate the upper bits
200/// of the register. ZExt on the loads will be free, and the same for call
201/// return values because we only accept ones that guarantee a zeroext ret val.
202/// Many arguments will have the zeroext attribute too, so those would be free
203/// too.
204static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000205 if (!isa<IntegerType>(V->getType()))
206 return false;
Sam Parker8c4b9642018-08-10 13:57:13 +0000207 // TODO Allow truncs and zext to be sources.
208 if (isa<Argument>(V))
209 return true;
210 else if (isa<LoadInst>(V))
211 return true;
Sam Parker569b2452018-09-12 09:11:48 +0000212 else if (isa<BitCastInst>(V))
213 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000214 else if (auto *Call = dyn_cast<CallInst>(V))
215 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
216 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000217}
218
219/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000220/// the IR to remain valid. We can't mutate the value type of these
221/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000222static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000223 // TODO The truncate also isn't actually necessary because we would already
224 // proved that the data value is kept within the range of the original data
225 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000226 auto UsesNarrowValue = [](Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000227 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
Sam Parker3828c6f2018-07-23 12:27:47 +0000228 };
229
230 if (auto *Store = dyn_cast<StoreInst>(V))
231 return UsesNarrowValue(Store->getValueOperand());
232 if (auto *Return = dyn_cast<ReturnInst>(V))
233 return UsesNarrowValue(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000234 if (auto *Trunc = dyn_cast<TruncInst>(V))
235 return UsesNarrowValue(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000236 if (auto *ZExt = dyn_cast<ZExtInst>(V))
237 return UsesNarrowValue(ZExt->getOperand(0));
Sam Parker13567db2018-08-16 10:05:39 +0000238 if (auto *ICmp = dyn_cast<ICmpInst>(V))
239 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000240
241 return isa<CallInst>(V);
242}
243
Sam Parker3828c6f2018-07-23 12:27:47 +0000244/// Return whether the instruction can be promoted within any modifications to
245/// it's operands or result.
246static bool isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000247 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000248 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
249 return true;
250
251 unsigned Opc = I->getOpcode();
252 if (Opc == Instruction::Add || Opc == Instruction::Sub) {
253 // We don't care if the add or sub could wrap if the value is decreasing
254 // and is only being used by an unsigned compare.
255 if (!I->hasOneUse() ||
256 !isa<ICmpInst>(*I->user_begin()) ||
257 !isa<ConstantInt>(I->getOperand(1)))
258 return false;
259
260 auto *CI = cast<ICmpInst>(*I->user_begin());
261 if (CI->isSigned())
262 return false;
263
264 bool NegImm = cast<ConstantInt>(I->getOperand(1))->isNegative();
265 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
266 ((Opc == Instruction::Add) && NegImm);
267 if (!IsDecreasing)
268 return false;
269
270 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
271 return true;
272 }
273
Sam Parker3828c6f2018-07-23 12:27:47 +0000274 return false;
275}
276
277static bool shouldPromote(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000278 if (!isa<IntegerType>(V->getType()) || isSink(V)) {
279 LLVM_DEBUG(dbgs() << "ARM CGP: Don't need to promote: " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000280 return false;
Sam Parker7def86b2018-08-15 07:52:35 +0000281 }
Sam Parker8c4b9642018-08-10 13:57:13 +0000282
283 if (isSource(V))
284 return true;
285
Sam Parker3828c6f2018-07-23 12:27:47 +0000286 auto *I = dyn_cast<Instruction>(V);
287 if (!I)
288 return false;
289
Sam Parker8c4b9642018-08-10 13:57:13 +0000290 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000291 return false;
292
Sam Parker3828c6f2018-07-23 12:27:47 +0000293 return true;
294}
295
296/// Return whether we can safely mutate V's type to ExtTy without having to be
297/// concerned with zero extending or truncation.
298static bool isPromotedResultSafe(Value *V) {
299 if (!isa<Instruction>(V))
300 return true;
301
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000302 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000303 return false;
304
305 // If I is only being used by something that will require its value to be
306 // truncated, then we don't care about the promoted result.
307 auto *I = cast<Instruction>(V);
308 if (I->hasOneUse() && isSink(*I->use_begin()))
309 return true;
310
311 if (isa<OverflowingBinaryOperator>(I))
312 return isSafeOverflow(I);
313 return true;
314}
315
316/// Return the intrinsic for the instruction that can perform the same
317/// operation but on a narrow type. This is using the parallel dsp intrinsics
318/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000319static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000320 // Whether we use the signed or unsigned versions of these intrinsics
321 // doesn't matter because we're not using the GE bits that they set in
322 // the APSR.
323 switch(I->getOpcode()) {
324 default:
325 break;
326 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000327 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000328 Intrinsic::arm_uadd8;
329 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000330 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000331 Intrinsic::arm_usub8;
332 }
333 llvm_unreachable("unhandled opcode for narrow intrinsic");
334}
335
336void IRPromoter::Mutate(Type *OrigTy,
337 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000338 SmallPtrSetImpl<Value*> &Sources,
339 SmallPtrSetImpl<Instruction*> &Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000340 IRBuilder<> Builder{Ctx};
341 Type *ExtTy = Type::getInt32Ty(M->getContext());
Sam Parker3828c6f2018-07-23 12:27:47 +0000342 SmallPtrSet<Value*, 8> Promoted;
Sam Parker8c4b9642018-08-10 13:57:13 +0000343 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
344 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000345
Sam Parker13567db2018-08-16 10:05:39 +0000346 // Cache original types.
347 DenseMap<Value*, Type*> TruncTysMap;
348 for (auto *V : Visited)
349 TruncTysMap[V] = V->getType();
350
Sam Parker3828c6f2018-07-23 12:27:47 +0000351 auto ReplaceAllUsersOfWith = [&](Value *From, Value *To) {
352 SmallVector<Instruction*, 4> Users;
353 Instruction *InstTo = dyn_cast<Instruction>(To);
354 for (Use &U : From->uses()) {
355 auto *User = cast<Instruction>(U.getUser());
356 if (InstTo && User->isIdenticalTo(InstTo))
357 continue;
358 Users.push_back(User);
359 }
360
361 for (auto &U : Users)
362 U->replaceUsesOfWith(From, To);
363 };
364
365 auto FixConst = [&](ConstantInt *Const, Instruction *I) {
Sam Parker96f77f12018-09-13 14:48:10 +0000366 Constant *NewConst = isSafeOverflow(I) && Const->isNegative() ?
367 ConstantExpr::getSExt(Const, ExtTy) :
368 ConstantExpr::getZExt(Const, ExtTy);
Sam Parker3828c6f2018-07-23 12:27:47 +0000369 I->replaceUsesOfWith(Const, NewConst);
370 };
371
372 auto InsertDSPIntrinsic = [&](Instruction *I) {
373 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
374 << *I << "\n");
375 Function *DSPInst =
Sam Parker8c4b9642018-08-10 13:57:13 +0000376 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
Sam Parker3828c6f2018-07-23 12:27:47 +0000377 Builder.SetInsertPoint(I);
378 Builder.SetCurrentDebugLocation(I->getDebugLoc());
379 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
380 CallInst *Call = Builder.CreateCall(DSPInst, Args);
381 ReplaceAllUsersOfWith(I, Call);
382 InstsToRemove.push_back(I);
383 NewInsts.insert(Call);
Sam Parker13567db2018-08-16 10:05:39 +0000384 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000385 };
386
387 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
388 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
389 Builder.SetInsertPoint(InsertPt);
390 if (auto *I = dyn_cast<Instruction>(V))
391 Builder.SetCurrentDebugLocation(I->getDebugLoc());
392 auto *ZExt = cast<Instruction>(Builder.CreateZExt(V, ExtTy));
393 if (isa<Argument>(V))
394 ZExt->moveBefore(InsertPt);
395 else
396 ZExt->moveAfter(InsertPt);
397 ReplaceAllUsersOfWith(V, ZExt);
398 NewInsts.insert(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000399 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000400 };
401
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000402 // First, insert extending instructions between the sources and their users.
403 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
404 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000405 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000406 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000407 InsertZExt(I, I);
408 else if (auto *Arg = dyn_cast<Argument>(V)) {
409 BasicBlock &BB = Arg->getParent()->front();
410 InsertZExt(Arg, &*BB.getFirstInsertionPt());
411 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000412 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000413 }
414 Promoted.insert(V);
415 }
416
417 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
418 // Then mutate the types of the instructions within the tree. Here we handle
419 // constant operands.
420 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000421 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000422 continue;
423
Sam Parker3828c6f2018-07-23 12:27:47 +0000424 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000425 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000426 continue;
427
Sam Parker7def86b2018-08-15 07:52:35 +0000428 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
429 Value *Op = I->getOperand(i);
430 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000431 continue;
432
Sam Parker7def86b2018-08-15 07:52:35 +0000433 if (auto *Const = dyn_cast<ConstantInt>(Op))
Sam Parker3828c6f2018-07-23 12:27:47 +0000434 FixConst(Const, I);
Sam Parker7def86b2018-08-15 07:52:35 +0000435 else if (isa<UndefValue>(Op))
436 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000437 }
438
439 if (shouldPromote(I)) {
440 I->mutateType(ExtTy);
441 Promoted.insert(I);
442 }
443 }
444
445 // Now we need to remove any zexts that have become unnecessary, as well
446 // as insert any intrinsics.
447 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000448 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000449 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000450
Sam Parker3828c6f2018-07-23 12:27:47 +0000451 if (!shouldPromote(V) || isPromotedResultSafe(V))
452 continue;
453
454 // Replace unsafe instructions with appropriate intrinsic calls.
455 InsertDSPIntrinsic(cast<Instruction>(V));
456 }
457
Sam Parker13567db2018-08-16 10:05:39 +0000458 auto InsertTrunc = [&](Value *V) -> Instruction* {
459 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
460 return nullptr;
461
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000462 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000463 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000464 return nullptr;
465
466 Type *TruncTy = TruncTysMap[V];
467 if (TruncTy == ExtTy)
468 return nullptr;
469
470 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
471 << *V << "\n");
472 Builder.SetInsertPoint(cast<Instruction>(V));
473 auto *Trunc = cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
474 NewInsts.insert(Trunc);
475 return Trunc;
476 };
477
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000478 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000479 // Fix up any stores or returns that use the results of the promoted
480 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000481 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000482 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000483
484 // Handle calls separately as we need to iterate over arg operands.
485 if (auto *Call = dyn_cast<CallInst>(I)) {
486 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
487 Value *Arg = Call->getArgOperand(i);
488 if (Instruction *Trunc = InsertTrunc(Arg)) {
489 Trunc->moveBefore(Call);
490 Call->setArgOperand(i, Trunc);
491 }
492 }
493 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000494 }
495
Sam Parker13567db2018-08-16 10:05:39 +0000496 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000497 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000498 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
499 Trunc->moveBefore(I);
500 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000501 }
502 }
503 }
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000504 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete:\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000505}
506
Sam Parker8c4b9642018-08-10 13:57:13 +0000507/// We accept most instructions, as well as Arguments and ConstantInsts. We
508/// Disallow casts other than zext and truncs and only allow calls if their
509/// return value is zeroext. We don't allow opcodes that can introduce sign
510/// bits.
511bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
512 LLVM_DEBUG(dbgs() << "ARM CGP: Is " << *V << " supported?\n");
513
Sam Parker13567db2018-08-16 10:05:39 +0000514 if (isa<ICmpInst>(V))
515 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000516
517 // Memory instructions
518 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
519 return true;
520
521 // Branches and targets.
522 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
523 return true;
524
525 // Non-instruction values that we can handle.
Sam Parker7def86b2018-08-15 07:52:35 +0000526 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000527 return isSupportedType(V);
528
529 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
530 isa<LoadInst>(V))
531 return isSupportedType(V);
532
Sam Parker569b2452018-09-12 09:11:48 +0000533 if (isa<CastInst>(V) && !isa<SExtInst>(V))
534 return isSupportedType(cast<CastInst>(V)->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000535
Sam Parker8c4b9642018-08-10 13:57:13 +0000536 // Special cases for calls as we need to check for zeroext
537 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000538 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000539 if (auto *Call = dyn_cast<CallInst>(V))
540 return isSupportedType(Call) &&
541 Call->hasRetAttr(Attribute::AttrKind::ZExt);
542
543 if (!isa<BinaryOperator>(V)) {
544 LLVM_DEBUG(dbgs() << "ARM CGP: No, not a binary operator.\n");
545 return false;
546 }
547 if (!isSupportedType(V))
548 return false;
549
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000550 if (generateSignBits(V)) {
551 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
552 return false;
553 }
554 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000555}
556
557/// Check that the type of V would be promoted and that the original type is
558/// smaller than the targeted promoted type. Check that we're not trying to
559/// promote something larger than our base 'TypeSize' type.
560bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
561 if (isPromotedResultSafe(V))
562 return true;
563
564 auto *I = dyn_cast<Instruction>(V);
565 if (!I)
566 return false;
567
568 // If promotion is not safe, can we use a DSP instruction to natively
569 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000570 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
571 return false;
572
573 if (ST->isThumb() && !ST->hasThumb2())
574 return false;
575
576 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
577 return false;
578
579 // TODO
580 // Would it be profitable? For Thumb code, these parallel DSP instructions
581 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
582 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
583 // halved. They also do not take immediates as operands.
584 for (auto &Op : I->operands()) {
585 if (isa<Constant>(Op)) {
586 if (!EnableDSPWithImms)
587 return false;
588 }
589 }
590 return true;
591}
592
Sam Parker3828c6f2018-07-23 12:27:47 +0000593bool ARMCodeGenPrepare::TryToPromote(Value *V) {
594 OrigTy = V->getType();
595 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000596 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000597 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000598
599 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
600 return false;
601
Sam Parker8c4b9642018-08-10 13:57:13 +0000602 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
603 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000604
605 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000606 SmallPtrSet<Value*, 8> Sources;
607 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000608 WorkList.insert(V);
609 SmallPtrSet<Value*, 16> CurrentVisited;
610 CurrentVisited.clear();
611
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000612 // Return true if V was added to the worklist as a supported instruction,
613 // if it was already visited, or if we don't need to explore it (e.g.
614 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000615 auto AddLegalInst = [&](Value *V) {
616 if (CurrentVisited.count(V))
617 return true;
618
Sam Parker0d511972018-08-16 12:24:40 +0000619 // Ignore GEPs because they don't need promoting and the constant indices
620 // will prevent the transformation.
621 if (isa<GetElementPtrInst>(V))
622 return true;
623
Sam Parker3828c6f2018-07-23 12:27:47 +0000624 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
625 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
626 return false;
627 }
628
629 WorkList.insert(V);
630 return true;
631 };
632
633 // Iterate through, and add to, a tree of operands and users in the use-def.
634 while (!WorkList.empty()) {
635 Value *V = WorkList.back();
636 WorkList.pop_back();
637 if (CurrentVisited.count(V))
638 continue;
639
Sam Parker7def86b2018-08-15 07:52:35 +0000640 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000641 if (!isa<Instruction>(V) && !isSource(V))
642 continue;
643
644 // If we've already visited this value from somewhere, bail now because
645 // the tree has already been explored.
646 // TODO: This could limit the transform, ie if we try to promote something
647 // from an i8 and fail first, before trying an i16.
648 if (AllVisited.count(V)) {
649 LLVM_DEBUG(dbgs() << "ARM CGP: Already visited this: " << *V << "\n");
650 return false;
651 }
652
653 CurrentVisited.insert(V);
654 AllVisited.insert(V);
655
656 // Calls can be both sources and sinks.
657 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000658 Sinks.insert(cast<Instruction>(V));
Sam Parker3828c6f2018-07-23 12:27:47 +0000659 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000660 Sources.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000661 else if (auto *I = dyn_cast<Instruction>(V)) {
662 // Visit operands of any instruction visited.
663 for (auto &U : I->operands()) {
664 if (!AddLegalInst(U))
665 return false;
666 }
667 }
668
669 // Don't visit users of a node which isn't going to be mutated unless its a
670 // source.
671 if (isSource(V) || shouldPromote(V)) {
672 for (Use &U : V->uses()) {
673 if (!AddLegalInst(U.getUser()))
674 return false;
675 }
676 }
677 }
678
Sam Parker3828c6f2018-07-23 12:27:47 +0000679 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
680 for (auto *I : CurrentVisited)
681 I->dump();
682 );
Sam Parker7def86b2018-08-15 07:52:35 +0000683 unsigned ToPromote = 0;
684 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000685 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000686 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000687 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000688 continue;
689 ++ToPromote;
690 }
691
692 if (ToPromote < 2)
693 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000694
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000695 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000696 return true;
697}
698
699bool ARMCodeGenPrepare::doInitialization(Module &M) {
700 Promoter = new IRPromoter(&M);
701 return false;
702}
703
704bool ARMCodeGenPrepare::runOnFunction(Function &F) {
705 if (skipFunction(F) || DisableCGP)
706 return false;
707
708 auto *TPC = &getAnalysis<TargetPassConfig>();
709 if (!TPC)
710 return false;
711
712 const TargetMachine &TM = TPC->getTM<TargetMachine>();
713 ST = &TM.getSubtarget<ARMSubtarget>(F);
714 bool MadeChange = false;
715 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
716
717 // Search up from icmps to try to promote their operands.
718 for (BasicBlock &BB : F) {
719 auto &Insts = BB.getInstList();
720 for (auto &I : Insts) {
721 if (AllVisited.count(&I))
722 continue;
723
724 if (isa<ICmpInst>(I)) {
725 auto &CI = cast<ICmpInst>(I);
726
727 // Skip signed or pointer compares
728 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
729 continue;
730
731 LLVM_DEBUG(dbgs() << "ARM CGP: Searching from: " << CI << "\n");
732 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000733 if (auto *I = dyn_cast<Instruction>(Op))
734 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000735 }
736 }
737 }
738 Promoter->Cleanup();
739 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
740 dbgs();
741 report_fatal_error("Broken function after type promotion");
742 });
743 }
744 if (MadeChange)
745 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
746
747 return MadeChange;
748}
749
Matt Morehousea70685f2018-07-23 17:00:45 +0000750bool ARMCodeGenPrepare::doFinalization(Module &M) {
751 delete Promoter;
752 return false;
753}
754
Sam Parker3828c6f2018-07-23 12:27:47 +0000755INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
756 "ARM IR optimizations", false, false)
757INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
758 false, false)
759
760char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +0000761unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +0000762
763FunctionPass *llvm::createARMCodeGenPreparePass() {
764 return new ARMCodeGenPrepare();
765}