blob: 826efe9f6934d7e8d34eee15edebbe3fefb5136e [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
Sam Parker481cdab2018-09-17 13:57:39 +0000168 if (isa<SExtInst>(V))
169 return true;
170
Sam Parker3828c6f2018-07-23 12:27:47 +0000171 unsigned Opc = cast<Instruction>(V)->getOpcode();
172 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
173 Opc == Instruction::SRem;
174}
175
176/// Some instructions can use 8- and 16-bit operands, and we don't need to
177/// promote anything larger. We disallow booleans to make life easier when
178/// dealing with icmps but allow any other integer that is <= 16 bits. Void
179/// types are accepted so we can handle switches.
180static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000181 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000182
183 // Allow voids and pointers, these won't be promoted.
184 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000185 return true;
186
Sam Parker8c4b9642018-08-10 13:57:13 +0000187 if (auto *Ld = dyn_cast<LoadInst>(V))
188 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
189
190 const IntegerType *IntTy = dyn_cast<IntegerType>(Ty);
Sam Parkeraaec3c62018-09-13 15:14:12 +0000191 if (!IntTy)
Sam Parker3828c6f2018-07-23 12:27:47 +0000192 return false;
193
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 Parker481cdab2018-09-17 13:57:39 +0000207 else if (isa<Argument>(V) || isa<LoadInst>(V) || isa<CallInst>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000208 return true;
Sam Parker481cdab2018-09-17 13:57:39 +0000209 else if (isa<CastInst>(V))
210 return isSupportedType(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000211 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000212}
213
214/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000215/// the IR to remain valid. We can't mutate the value type of these
216/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000217static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000218 // TODO The truncate also isn't actually necessary because we would already
219 // proved that the data value is kept within the range of the original data
220 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000221 auto UsesNarrowValue = [](Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000222 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
Sam Parker3828c6f2018-07-23 12:27:47 +0000223 };
224
225 if (auto *Store = dyn_cast<StoreInst>(V))
226 return UsesNarrowValue(Store->getValueOperand());
227 if (auto *Return = dyn_cast<ReturnInst>(V))
228 return UsesNarrowValue(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000229 if (auto *Trunc = dyn_cast<TruncInst>(V))
230 return UsesNarrowValue(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000231 if (auto *ZExt = dyn_cast<ZExtInst>(V))
232 return UsesNarrowValue(ZExt->getOperand(0));
Sam Parker13567db2018-08-16 10:05:39 +0000233 if (auto *ICmp = dyn_cast<ICmpInst>(V))
234 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000235
236 return isa<CallInst>(V);
237}
238
Sam Parker3828c6f2018-07-23 12:27:47 +0000239/// Return whether the instruction can be promoted within any modifications to
240/// it's operands or result.
241static bool isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000242 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000243 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
244 return true;
245
246 unsigned Opc = I->getOpcode();
247 if (Opc == Instruction::Add || Opc == Instruction::Sub) {
248 // We don't care if the add or sub could wrap if the value is decreasing
249 // and is only being used by an unsigned compare.
250 if (!I->hasOneUse() ||
251 !isa<ICmpInst>(*I->user_begin()) ||
252 !isa<ConstantInt>(I->getOperand(1)))
253 return false;
254
255 auto *CI = cast<ICmpInst>(*I->user_begin());
Sam Parker76d25d72018-09-17 13:48:25 +0000256
257 // Don't support an icmp that deals with sign bits, including negative
258 // immediates
Sam Parker3828c6f2018-07-23 12:27:47 +0000259 if (CI->isSigned())
260 return false;
261
Sam Parker76d25d72018-09-17 13:48:25 +0000262 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
263 if (Const->isNegative())
264 return false;
265
266 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
267 if (Const->isNegative())
268 return false;
269
Sam Parker3828c6f2018-07-23 12:27:47 +0000270 bool NegImm = cast<ConstantInt>(I->getOperand(1))->isNegative();
271 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
272 ((Opc == Instruction::Add) && NegImm);
273 if (!IsDecreasing)
274 return false;
275
276 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
277 return true;
278 }
279
Sam Parker3828c6f2018-07-23 12:27:47 +0000280 return false;
281}
282
283static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000284 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000285 return false;
286
287 if (isSource(V))
288 return true;
289
Sam Parker3828c6f2018-07-23 12:27:47 +0000290 auto *I = dyn_cast<Instruction>(V);
291 if (!I)
292 return false;
293
Sam Parker8c4b9642018-08-10 13:57:13 +0000294 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000295 return false;
296
Sam Parker3828c6f2018-07-23 12:27:47 +0000297 return true;
298}
299
300/// Return whether we can safely mutate V's type to ExtTy without having to be
301/// concerned with zero extending or truncation.
302static bool isPromotedResultSafe(Value *V) {
303 if (!isa<Instruction>(V))
304 return true;
305
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000306 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000307 return false;
308
309 // If I is only being used by something that will require its value to be
310 // truncated, then we don't care about the promoted result.
311 auto *I = cast<Instruction>(V);
312 if (I->hasOneUse() && isSink(*I->use_begin()))
313 return true;
314
315 if (isa<OverflowingBinaryOperator>(I))
316 return isSafeOverflow(I);
317 return true;
318}
319
320/// Return the intrinsic for the instruction that can perform the same
321/// operation but on a narrow type. This is using the parallel dsp intrinsics
322/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000323static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000324 // Whether we use the signed or unsigned versions of these intrinsics
325 // doesn't matter because we're not using the GE bits that they set in
326 // the APSR.
327 switch(I->getOpcode()) {
328 default:
329 break;
330 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000331 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000332 Intrinsic::arm_uadd8;
333 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000334 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000335 Intrinsic::arm_usub8;
336 }
337 llvm_unreachable("unhandled opcode for narrow intrinsic");
338}
339
340void IRPromoter::Mutate(Type *OrigTy,
341 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000342 SmallPtrSetImpl<Value*> &Sources,
343 SmallPtrSetImpl<Instruction*> &Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000344 IRBuilder<> Builder{Ctx};
345 Type *ExtTy = Type::getInt32Ty(M->getContext());
Sam Parker3828c6f2018-07-23 12:27:47 +0000346 SmallPtrSet<Value*, 8> Promoted;
Sam Parker8c4b9642018-08-10 13:57:13 +0000347 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
348 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000349
Sam Parker13567db2018-08-16 10:05:39 +0000350 // Cache original types.
351 DenseMap<Value*, Type*> TruncTysMap;
352 for (auto *V : Visited)
353 TruncTysMap[V] = V->getType();
354
Sam Parker3828c6f2018-07-23 12:27:47 +0000355 auto ReplaceAllUsersOfWith = [&](Value *From, Value *To) {
356 SmallVector<Instruction*, 4> Users;
357 Instruction *InstTo = dyn_cast<Instruction>(To);
358 for (Use &U : From->uses()) {
359 auto *User = cast<Instruction>(U.getUser());
360 if (InstTo && User->isIdenticalTo(InstTo))
361 continue;
362 Users.push_back(User);
363 }
364
Sam Parkeraaec3c62018-09-13 15:14:12 +0000365 for (auto *U : Users)
Sam Parker3828c6f2018-07-23 12:27:47 +0000366 U->replaceUsesOfWith(From, To);
367 };
368
369 auto FixConst = [&](ConstantInt *Const, Instruction *I) {
Sam Parker96f77f12018-09-13 14:48:10 +0000370 Constant *NewConst = isSafeOverflow(I) && Const->isNegative() ?
371 ConstantExpr::getSExt(Const, ExtTy) :
372 ConstantExpr::getZExt(Const, ExtTy);
Sam Parker3828c6f2018-07-23 12:27:47 +0000373 I->replaceUsesOfWith(Const, NewConst);
374 };
375
376 auto InsertDSPIntrinsic = [&](Instruction *I) {
377 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
378 << *I << "\n");
379 Function *DSPInst =
Sam Parker8c4b9642018-08-10 13:57:13 +0000380 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
Sam Parker3828c6f2018-07-23 12:27:47 +0000381 Builder.SetInsertPoint(I);
382 Builder.SetCurrentDebugLocation(I->getDebugLoc());
383 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
384 CallInst *Call = Builder.CreateCall(DSPInst, Args);
385 ReplaceAllUsersOfWith(I, Call);
386 InstsToRemove.push_back(I);
387 NewInsts.insert(Call);
Sam Parker13567db2018-08-16 10:05:39 +0000388 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000389 };
390
391 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
392 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
393 Builder.SetInsertPoint(InsertPt);
394 if (auto *I = dyn_cast<Instruction>(V))
395 Builder.SetCurrentDebugLocation(I->getDebugLoc());
396 auto *ZExt = cast<Instruction>(Builder.CreateZExt(V, ExtTy));
397 if (isa<Argument>(V))
398 ZExt->moveBefore(InsertPt);
399 else
400 ZExt->moveAfter(InsertPt);
401 ReplaceAllUsersOfWith(V, ZExt);
402 NewInsts.insert(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000403 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000404 };
405
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000406 // First, insert extending instructions between the sources and their users.
407 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
408 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000409 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000410 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000411 InsertZExt(I, I);
412 else if (auto *Arg = dyn_cast<Argument>(V)) {
413 BasicBlock &BB = Arg->getParent()->front();
414 InsertZExt(Arg, &*BB.getFirstInsertionPt());
415 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000416 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000417 }
418 Promoted.insert(V);
419 }
420
421 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
422 // Then mutate the types of the instructions within the tree. Here we handle
423 // constant operands.
424 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000425 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000426 continue;
427
Sam Parker3828c6f2018-07-23 12:27:47 +0000428 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000429 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000430 continue;
431
Sam Parker7def86b2018-08-15 07:52:35 +0000432 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
433 Value *Op = I->getOperand(i);
434 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000435 continue;
436
Sam Parker7def86b2018-08-15 07:52:35 +0000437 if (auto *Const = dyn_cast<ConstantInt>(Op))
Sam Parker3828c6f2018-07-23 12:27:47 +0000438 FixConst(Const, I);
Sam Parker7def86b2018-08-15 07:52:35 +0000439 else if (isa<UndefValue>(Op))
440 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000441 }
442
443 if (shouldPromote(I)) {
444 I->mutateType(ExtTy);
445 Promoted.insert(I);
446 }
447 }
448
449 // Now we need to remove any zexts that have become unnecessary, as well
450 // as insert any intrinsics.
451 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000452 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000453 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000454
Sam Parker3828c6f2018-07-23 12:27:47 +0000455 if (!shouldPromote(V) || isPromotedResultSafe(V))
456 continue;
457
458 // Replace unsafe instructions with appropriate intrinsic calls.
459 InsertDSPIntrinsic(cast<Instruction>(V));
460 }
461
Sam Parker13567db2018-08-16 10:05:39 +0000462 auto InsertTrunc = [&](Value *V) -> Instruction* {
463 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
464 return nullptr;
465
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000466 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000467 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000468 return nullptr;
469
470 Type *TruncTy = TruncTysMap[V];
471 if (TruncTy == ExtTy)
472 return nullptr;
473
474 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
475 << *V << "\n");
476 Builder.SetInsertPoint(cast<Instruction>(V));
477 auto *Trunc = cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
478 NewInsts.insert(Trunc);
479 return Trunc;
480 };
481
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000482 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000483 // Fix up any stores or returns that use the results of the promoted
484 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000485 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000486 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000487
488 // Handle calls separately as we need to iterate over arg operands.
489 if (auto *Call = dyn_cast<CallInst>(I)) {
490 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
491 Value *Arg = Call->getArgOperand(i);
492 if (Instruction *Trunc = InsertTrunc(Arg)) {
493 Trunc->moveBefore(Call);
494 Call->setArgOperand(i, Trunc);
495 }
496 }
497 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000498 }
499
Sam Parker13567db2018-08-16 10:05:39 +0000500 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000501 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000502 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
503 Trunc->moveBefore(I);
504 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000505 }
506 }
507 }
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000508 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete:\n");
Sam Parkeraaec3c62018-09-13 15:14:12 +0000509 LLVM_DEBUG(dbgs();
510 for (auto *V : Sources)
511 V->dump();
512 for (auto *I : NewInsts)
513 I->dump();
514 for (auto *V : Visited) {
515 if (!Sources.count(V))
516 V->dump();
517 });
Sam Parker3828c6f2018-07-23 12:27:47 +0000518}
519
Sam Parker8c4b9642018-08-10 13:57:13 +0000520/// We accept most instructions, as well as Arguments and ConstantInsts. We
521/// Disallow casts other than zext and truncs and only allow calls if their
522/// return value is zeroext. We don't allow opcodes that can introduce sign
523/// bits.
524bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker481cdab2018-09-17 13:57:39 +0000525 if (generateSignBits(V))
526 return false;
527
528 // Disallow for simplicity.
529 if (isa<ConstantExpr>(V))
530 return false;
531
532 // Special case because they generate an i1, which we don't generally
533 // support.
Sam Parker13567db2018-08-16 10:05:39 +0000534 if (isa<ICmpInst>(V))
535 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000536
Sam Parker481cdab2018-09-17 13:57:39 +0000537 // Both ZExts and Truncs can be either sources and sinks. BitCasts are also
538 // sources and SExts are disallowed through their sign bit generation.
539 if (auto *Cast = dyn_cast<CastInst>(V))
540 return isSupportedType(Cast) || isSupportedType(Cast->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000541
Sam Parker8c4b9642018-08-10 13:57:13 +0000542 // Special cases for calls as we need to check for zeroext
543 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000544 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000545 if (auto *Call = dyn_cast<CallInst>(V))
546 return isSupportedType(Call) &&
547 Call->hasRetAttr(Attribute::AttrKind::ZExt);
548
Sam Parker481cdab2018-09-17 13:57:39 +0000549 return isSupportedType(V);
Sam Parker8c4b9642018-08-10 13:57:13 +0000550}
551
552/// Check that the type of V would be promoted and that the original type is
553/// smaller than the targeted promoted type. Check that we're not trying to
554/// promote something larger than our base 'TypeSize' type.
555bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
556 if (isPromotedResultSafe(V))
557 return true;
558
559 auto *I = dyn_cast<Instruction>(V);
560 if (!I)
561 return false;
562
563 // If promotion is not safe, can we use a DSP instruction to natively
564 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000565 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
566 return false;
567
568 if (ST->isThumb() && !ST->hasThumb2())
569 return false;
570
571 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
572 return false;
573
574 // TODO
575 // Would it be profitable? For Thumb code, these parallel DSP instructions
576 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
577 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
578 // halved. They also do not take immediates as operands.
579 for (auto &Op : I->operands()) {
580 if (isa<Constant>(Op)) {
581 if (!EnableDSPWithImms)
582 return false;
583 }
584 }
585 return true;
586}
587
Sam Parker3828c6f2018-07-23 12:27:47 +0000588bool ARMCodeGenPrepare::TryToPromote(Value *V) {
589 OrigTy = V->getType();
590 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000591 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000592 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000593
594 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
595 return false;
596
Sam Parker8c4b9642018-08-10 13:57:13 +0000597 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
598 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000599
600 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000601 SmallPtrSet<Value*, 8> Sources;
602 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000603 WorkList.insert(V);
604 SmallPtrSet<Value*, 16> CurrentVisited;
605 CurrentVisited.clear();
606
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000607 // Return true if V was added to the worklist as a supported instruction,
608 // if it was already visited, or if we don't need to explore it (e.g.
609 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000610 auto AddLegalInst = [&](Value *V) {
611 if (CurrentVisited.count(V))
612 return true;
613
Sam Parker0d511972018-08-16 12:24:40 +0000614 // Ignore GEPs because they don't need promoting and the constant indices
615 // will prevent the transformation.
616 if (isa<GetElementPtrInst>(V))
617 return true;
618
Sam Parker3828c6f2018-07-23 12:27:47 +0000619 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
620 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
621 return false;
622 }
623
624 WorkList.insert(V);
625 return true;
626 };
627
628 // Iterate through, and add to, a tree of operands and users in the use-def.
629 while (!WorkList.empty()) {
630 Value *V = WorkList.back();
631 WorkList.pop_back();
632 if (CurrentVisited.count(V))
633 continue;
634
Sam Parker7def86b2018-08-15 07:52:35 +0000635 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000636 if (!isa<Instruction>(V) && !isSource(V))
637 continue;
638
639 // If we've already visited this value from somewhere, bail now because
640 // the tree has already been explored.
641 // TODO: This could limit the transform, ie if we try to promote something
642 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000643 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000644 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000645
646 CurrentVisited.insert(V);
647 AllVisited.insert(V);
648
649 // Calls can be both sources and sinks.
650 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000651 Sinks.insert(cast<Instruction>(V));
Sam Parker3828c6f2018-07-23 12:27:47 +0000652 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000653 Sources.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000654 else if (auto *I = dyn_cast<Instruction>(V)) {
655 // Visit operands of any instruction visited.
656 for (auto &U : I->operands()) {
657 if (!AddLegalInst(U))
658 return false;
659 }
660 }
661
662 // Don't visit users of a node which isn't going to be mutated unless its a
663 // source.
664 if (isSource(V) || shouldPromote(V)) {
665 for (Use &U : V->uses()) {
666 if (!AddLegalInst(U.getUser()))
667 return false;
668 }
669 }
670 }
671
Sam Parker3828c6f2018-07-23 12:27:47 +0000672 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
673 for (auto *I : CurrentVisited)
674 I->dump();
675 );
Sam Parker7def86b2018-08-15 07:52:35 +0000676 unsigned ToPromote = 0;
677 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000678 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000679 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000680 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000681 continue;
682 ++ToPromote;
683 }
684
685 if (ToPromote < 2)
686 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000687
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000688 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000689 return true;
690}
691
692bool ARMCodeGenPrepare::doInitialization(Module &M) {
693 Promoter = new IRPromoter(&M);
694 return false;
695}
696
697bool ARMCodeGenPrepare::runOnFunction(Function &F) {
698 if (skipFunction(F) || DisableCGP)
699 return false;
700
701 auto *TPC = &getAnalysis<TargetPassConfig>();
702 if (!TPC)
703 return false;
704
705 const TargetMachine &TM = TPC->getTM<TargetMachine>();
706 ST = &TM.getSubtarget<ARMSubtarget>(F);
707 bool MadeChange = false;
708 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
709
710 // Search up from icmps to try to promote their operands.
711 for (BasicBlock &BB : F) {
712 auto &Insts = BB.getInstList();
713 for (auto &I : Insts) {
714 if (AllVisited.count(&I))
715 continue;
716
717 if (isa<ICmpInst>(I)) {
718 auto &CI = cast<ICmpInst>(I);
719
720 // Skip signed or pointer compares
721 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
722 continue;
723
Sam Parker3828c6f2018-07-23 12:27:47 +0000724 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000725 if (auto *I = dyn_cast<Instruction>(Op))
726 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000727 }
728 }
729 }
730 Promoter->Cleanup();
731 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
732 dbgs();
733 report_fatal_error("Broken function after type promotion");
734 });
735 }
736 if (MadeChange)
737 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
738
739 return MadeChange;
740}
741
Matt Morehousea70685f2018-07-23 17:00:45 +0000742bool ARMCodeGenPrepare::doFinalization(Module &M) {
743 delete Promoter;
744 return false;
745}
746
Sam Parker3828c6f2018-07-23 12:27:47 +0000747INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
748 "ARM IR optimizations", false, false)
749INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
750 false, false)
751
752char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +0000753unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +0000754
755FunctionPass *llvm::createARMCodeGenPreparePass() {
756 return new ARMCodeGenPrepare();
757}