blob: 2403b9e1327ad17011ca44f3769bffde336af421 [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>
Hans Wennborg5555c002018-09-24 11:40:07 +000045DisableCGP("arm-disable-cgp", cl::Hidden, cl::init(true),
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;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000113 DenseMap<Value*, Type*> TruncTysMap;
114 SmallPtrSet<Value*, 8> Promoted;
Sam Parker3828c6f2018-07-23 12:27:47 +0000115 Module *M = nullptr;
116 LLVMContext &Ctx;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000117 Type *ExtTy = nullptr;
118 Type *OrigTy = nullptr;
119
120 void PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
121 SmallPtrSetImpl<Instruction*> &SafeToPromote);
122 void ExtendSources(SmallPtrSetImpl<Value*> &Sources);
123 void PromoteTree(SmallPtrSetImpl<Value*> &Visited,
124 SmallPtrSetImpl<Value*> &Sources,
125 SmallPtrSetImpl<Instruction*> &Sinks,
126 SmallPtrSetImpl<Instruction*> &SafeToPromote);
127 void TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
128 SmallPtrSetImpl<Instruction*> &Sinks);
Sam Parker3828c6f2018-07-23 12:27:47 +0000129
130public:
Sam Parker84a2f8b2018-11-01 15:23:42 +0000131 IRPromoter(Module *M) : M(M), Ctx(M->getContext()),
132 ExtTy(Type::getInt32Ty(Ctx)) { }
Sam Parker3828c6f2018-07-23 12:27:47 +0000133
134 void Cleanup() {
135 for (auto *I : InstsToRemove) {
136 LLVM_DEBUG(dbgs() << "ARM CGP: Removing " << *I << "\n");
137 I->dropAllReferences();
138 I->eraseFromParent();
139 }
140 InstsToRemove.clear();
141 NewInsts.clear();
142 }
143
144 void Mutate(Type *OrigTy,
145 SmallPtrSetImpl<Value*> &Visited,
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000146 SmallPtrSetImpl<Value*> &Sources,
Sam Parker84a2f8b2018-11-01 15:23:42 +0000147 SmallPtrSetImpl<Instruction*> &Sinks,
148 SmallPtrSetImpl<Instruction*> &SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000149};
150
151class ARMCodeGenPrepare : public FunctionPass {
152 const ARMSubtarget *ST = nullptr;
153 IRPromoter *Promoter = nullptr;
154 std::set<Value*> AllVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000155 SmallPtrSet<Instruction*, 8> SafeToPromote;
Sam Parker3828c6f2018-07-23 12:27:47 +0000156
Sam Parker84a2f8b2018-11-01 15:23:42 +0000157 bool isSafeOverflow(Instruction *I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000158 bool isSupportedValue(Value *V);
159 bool isLegalToPromote(Value *V);
160 bool TryToPromote(Value *V);
161
162public:
163 static char ID;
Sam Parker8c4b9642018-08-10 13:57:13 +0000164 static unsigned TypeSize;
165 Type *OrigTy = nullptr;
Sam Parker3828c6f2018-07-23 12:27:47 +0000166
167 ARMCodeGenPrepare() : FunctionPass(ID) {}
168
Sam Parker3828c6f2018-07-23 12:27:47 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
170 AU.addRequired<TargetPassConfig>();
171 }
172
173 StringRef getPassName() const override { return "ARM IR optimizations"; }
174
175 bool doInitialization(Module &M) override;
176 bool runOnFunction(Function &F) override;
Matt Morehousea70685f2018-07-23 17:00:45 +0000177 bool doFinalization(Module &M) override;
Sam Parker3828c6f2018-07-23 12:27:47 +0000178};
179
180}
181
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000182static bool generateSignBits(Value *V) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000183 if (!isa<Instruction>(V))
184 return false;
185
186 unsigned Opc = cast<Instruction>(V)->getOpcode();
187 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
188 Opc == Instruction::SRem;
189}
190
191/// Some instructions can use 8- and 16-bit operands, and we don't need to
192/// promote anything larger. We disallow booleans to make life easier when
193/// dealing with icmps but allow any other integer that is <= 16 bits. Void
194/// types are accepted so we can handle switches.
195static bool isSupportedType(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000196 Type *Ty = V->getType();
Sam Parker7def86b2018-08-15 07:52:35 +0000197
198 // Allow voids and pointers, these won't be promoted.
199 if (Ty->isVoidTy() || Ty->isPointerTy())
Sam Parker3828c6f2018-07-23 12:27:47 +0000200 return true;
201
Sam Parker8c4b9642018-08-10 13:57:13 +0000202 if (auto *Ld = dyn_cast<LoadInst>(V))
203 Ty = cast<PointerType>(Ld->getPointerOperandType())->getElementType();
204
205 const IntegerType *IntTy = dyn_cast<IntegerType>(Ty);
Sam Parkeraaec3c62018-09-13 15:14:12 +0000206 if (!IntTy)
Sam Parker3828c6f2018-07-23 12:27:47 +0000207 return false;
208
Sam Parker8c4b9642018-08-10 13:57:13 +0000209 return IntTy->getBitWidth() == ARMCodeGenPrepare::TypeSize;
210}
Sam Parker3828c6f2018-07-23 12:27:47 +0000211
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000212/// Return true if the given value is a source in the use-def chain, producing
Sam Parker8c4b9642018-08-10 13:57:13 +0000213/// a narrow (i8, i16) value. These values will be zext to start the promotion
214/// of the tree to i32. We guarantee that these won't populate the upper bits
215/// of the register. ZExt on the loads will be free, and the same for call
216/// return values because we only accept ones that guarantee a zeroext ret val.
217/// Many arguments will have the zeroext attribute too, so those would be free
218/// too.
219static bool isSource(Value *V) {
Sam Parker7def86b2018-08-15 07:52:35 +0000220 if (!isa<IntegerType>(V->getType()))
221 return false;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000222 // TODO Allow zext to be sources.
223 if (isa<Argument>(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000224 return true;
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000225 else if (isa<LoadInst>(V))
226 return true;
227 else if (isa<BitCastInst>(V))
228 return true;
229 else if (auto *Call = dyn_cast<CallInst>(V))
230 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
231 else if (auto *Trunc = dyn_cast<TruncInst>(V))
232 return isSupportedType(Trunc);
Sam Parker8c4b9642018-08-10 13:57:13 +0000233 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000234}
235
236/// Return true if V will require any promoted values to be truncated for the
Sam Parker8c4b9642018-08-10 13:57:13 +0000237/// the IR to remain valid. We can't mutate the value type of these
238/// instructions.
Sam Parker3828c6f2018-07-23 12:27:47 +0000239static bool isSink(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000240 // TODO The truncate also isn't actually necessary because we would already
241 // proved that the data value is kept within the range of the original data
242 // type.
Sam Parker3828c6f2018-07-23 12:27:47 +0000243 auto UsesNarrowValue = [](Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000244 return V->getType()->getScalarSizeInBits() == ARMCodeGenPrepare::TypeSize;
Sam Parker3828c6f2018-07-23 12:27:47 +0000245 };
246
247 if (auto *Store = dyn_cast<StoreInst>(V))
248 return UsesNarrowValue(Store->getValueOperand());
249 if (auto *Return = dyn_cast<ReturnInst>(V))
250 return UsesNarrowValue(Return->getReturnValue());
Sam Parker8c4b9642018-08-10 13:57:13 +0000251 if (auto *Trunc = dyn_cast<TruncInst>(V))
252 return UsesNarrowValue(Trunc->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000253 if (auto *ZExt = dyn_cast<ZExtInst>(V))
254 return UsesNarrowValue(ZExt->getOperand(0));
Sam Parker13567db2018-08-16 10:05:39 +0000255 if (auto *ICmp = dyn_cast<ICmpInst>(V))
256 return ICmp->isSigned();
Sam Parker3828c6f2018-07-23 12:27:47 +0000257
258 return isa<CallInst>(V);
259}
260
Sam Parker3828c6f2018-07-23 12:27:47 +0000261/// Return whether the instruction can be promoted within any modifications to
Sam Parker84a2f8b2018-11-01 15:23:42 +0000262/// its operands or result.
263bool ARMCodeGenPrepare::isSafeOverflow(Instruction *I) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000264 // FIXME Do we need NSW too?
Sam Parker3828c6f2018-07-23 12:27:47 +0000265 if (isa<OverflowingBinaryOperator>(I) && I->hasNoUnsignedWrap())
266 return true;
267
Sam Parker75aca942018-09-26 10:56:00 +0000268 // We can support a, potentially, overflowing instruction (I) if:
269 // - It is only used by an unsigned icmp.
270 // - The icmp uses a constant.
271 // - The overflowing value (I) is decreasing, i.e would underflow - wrapping
272 // around zero to become a larger number than before.
273 // - The underflowing instruction (I) also uses a constant.
274 //
275 // We can then use the two constants to calculate whether the result would
276 // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
277 // just underflows the range, the icmp would give the same result whether the
278 // result has been truncated or not. We calculate this by:
279 // - Zero extending both constants, if needed, to 32-bits.
280 // - Take the absolute value of I's constant, adding this to the icmp const.
281 // - Check that this value is not out of range for small type. If it is, it
282 // means that it has underflowed enough to wrap around the icmp constant.
283 //
284 // For example:
285 //
286 // %sub = sub i8 %a, 2
287 // %cmp = icmp ule i8 %sub, 254
288 //
289 // If %a = 0, %sub = -2 == FE == 254
290 // But if this is evalulated as a i32
291 // %sub = -2 == FF FF FF FE == 4294967294
292 // So the unsigned compares (i8 and i32) would not yield the same result.
293 //
294 // Another way to look at it is:
295 // %a - 2 <= 254
296 // %a + 2 <= 254 + 2
297 // %a <= 256
298 // And we can't represent 256 in the i8 format, so we don't support it.
299 //
300 // Whereas:
301 //
302 // %sub i8 %a, 1
303 // %cmp = icmp ule i8 %sub, 254
304 //
305 // If %a = 0, %sub = -1 == FF == 255
306 // As i32:
307 // %sub = -1 == FF FF FF FF == 4294967295
308 //
309 // In this case, the unsigned compare results would be the same and this
310 // would also be true for ult, uge and ugt:
311 // - (255 < 254) == (0xFFFFFFFF < 254) == false
312 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
313 // - (255 > 254) == (0xFFFFFFFF > 254) == true
314 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
315 //
316 // To demonstrate why we can't handle increasing values:
317 //
318 // %add = add i8 %a, 2
319 // %cmp = icmp ult i8 %add, 127
320 //
321 // If %a = 254, %add = 256 == (i8 1)
322 // As i32:
323 // %add = 256
324 //
325 // (1 < 127) != (256 < 127)
326
Sam Parker3828c6f2018-07-23 12:27:47 +0000327 unsigned Opc = I->getOpcode();
Sam Parker75aca942018-09-26 10:56:00 +0000328 if (Opc != Instruction::Add && Opc != Instruction::Sub)
329 return false;
330
331 if (!I->hasOneUse() ||
332 !isa<ICmpInst>(*I->user_begin()) ||
333 !isa<ConstantInt>(I->getOperand(1)))
334 return false;
335
336 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
337 bool NegImm = OverflowConst->isNegative();
338 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
339 ((Opc == Instruction::Add) && NegImm);
340 if (!IsDecreasing)
341 return false;
342
343 // Don't support an icmp that deals with sign bits.
344 auto *CI = cast<ICmpInst>(*I->user_begin());
345 if (CI->isSigned() || CI->isEquality())
346 return false;
347
348 ConstantInt *ICmpConst = nullptr;
349 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
350 ICmpConst = Const;
351 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
352 ICmpConst = Const;
353 else
354 return false;
355
356 // Now check that the result can't wrap on itself.
357 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ?
358 ICmpConst->getValue().zext(32) : ICmpConst->getValue();
359
360 Total += OverflowConst->getValue().getBitWidth() < 32 ?
361 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs();
362
363 APInt Max = APInt::getAllOnesValue(ARMCodeGenPrepare::TypeSize);
364
365 if (Total.getBitWidth() > Max.getBitWidth()) {
366 if (Total.ugt(Max.zext(Total.getBitWidth())))
Sam Parker3828c6f2018-07-23 12:27:47 +0000367 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000368 } else if (Max.getBitWidth() > Total.getBitWidth()) {
369 if (Total.zext(Max.getBitWidth()).ugt(Max))
Sam Parker3828c6f2018-07-23 12:27:47 +0000370 return false;
Sam Parker75aca942018-09-26 10:56:00 +0000371 } else if (Total.ugt(Max))
372 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000373
Sam Parker75aca942018-09-26 10:56:00 +0000374 LLVM_DEBUG(dbgs() << "ARM CGP: Allowing safe overflow for " << *I << "\n");
375 return true;
Sam Parker3828c6f2018-07-23 12:27:47 +0000376}
377
378static bool shouldPromote(Value *V) {
Sam Parkeraaec3c62018-09-13 15:14:12 +0000379 if (!isa<IntegerType>(V->getType()) || isSink(V))
Sam Parker8c4b9642018-08-10 13:57:13 +0000380 return false;
381
382 if (isSource(V))
383 return true;
384
Sam Parker3828c6f2018-07-23 12:27:47 +0000385 auto *I = dyn_cast<Instruction>(V);
386 if (!I)
387 return false;
388
Sam Parker8c4b9642018-08-10 13:57:13 +0000389 if (isa<ICmpInst>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000390 return false;
391
Sam Parker3828c6f2018-07-23 12:27:47 +0000392 return true;
393}
394
395/// Return whether we can safely mutate V's type to ExtTy without having to be
396/// concerned with zero extending or truncation.
397static bool isPromotedResultSafe(Value *V) {
398 if (!isa<Instruction>(V))
399 return true;
400
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000401 if (generateSignBits(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000402 return false;
403
404 // If I is only being used by something that will require its value to be
405 // truncated, then we don't care about the promoted result.
406 auto *I = cast<Instruction>(V);
Sam Parker84a2f8b2018-11-01 15:23:42 +0000407 if (I->hasOneUse() && isSink(*I->use_begin())) {
408 LLVM_DEBUG(dbgs() << "ARM CGP: Only use is a sink: " << *V << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000409 return true;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000410 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000411
412 if (isa<OverflowingBinaryOperator>(I))
Sam Parker84a2f8b2018-11-01 15:23:42 +0000413 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000414 return true;
415}
416
417/// Return the intrinsic for the instruction that can perform the same
418/// operation but on a narrow type. This is using the parallel dsp intrinsics
419/// on scalar values.
Sam Parker8c4b9642018-08-10 13:57:13 +0000420static Intrinsic::ID getNarrowIntrinsic(Instruction *I) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000421 // Whether we use the signed or unsigned versions of these intrinsics
422 // doesn't matter because we're not using the GE bits that they set in
423 // the APSR.
424 switch(I->getOpcode()) {
425 default:
426 break;
427 case Instruction::Add:
Sam Parker8c4b9642018-08-10 13:57:13 +0000428 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_uadd16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000429 Intrinsic::arm_uadd8;
430 case Instruction::Sub:
Sam Parker8c4b9642018-08-10 13:57:13 +0000431 return ARMCodeGenPrepare::TypeSize == 16 ? Intrinsic::arm_usub16 :
Sam Parker3828c6f2018-07-23 12:27:47 +0000432 Intrinsic::arm_usub8;
433 }
434 llvm_unreachable("unhandled opcode for narrow intrinsic");
435}
436
Sam Parker84a2f8b2018-11-01 15:23:42 +0000437static void ReplaceAllUsersOfWith(Value *From, Value *To) {
438 SmallVector<Instruction*, 4> Users;
439 Instruction *InstTo = dyn_cast<Instruction>(To);
440 for (Use &U : From->uses()) {
441 auto *User = cast<Instruction>(U.getUser());
442 if (InstTo && User->isIdenticalTo(InstTo))
443 continue;
444 Users.push_back(User);
445 }
446
447 for (auto *U : Users)
448 U->replaceUsesOfWith(From, To);
449}
450
451void
452IRPromoter::PrepareConstants(SmallPtrSetImpl<Value*> &Visited,
453 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000454 IRBuilder<> Builder{Ctx};
Sam Parker84a2f8b2018-11-01 15:23:42 +0000455 // First step is to prepare the instructions for mutation. Most constants
456 // just need to be zero extended into their new type, but complications arise
457 // because:
458 // - For nuw binary operators, negative immediates would need sign extending;
459 // however, instead we'll change them to positive and zext them. We can do
460 // this because:
461 // > The operators that can wrap are: add, sub, mul and shl.
462 // > shl interprets its second operand as unsigned and if the first operand
463 // is an immediate, it will need zext to be nuw.
464 // > I'm assuming mul cannot be nuw while using a negative immediate...
465 // > Which leaves the nuw add and sub to be handled; as with shl, if an
466 // immediate is used as operand 0, it will need zext to be nuw.
467 // - We also allow add and sub to safely overflow in certain circumstances
468 // and only when the value (operand 0) is being decreased.
469 //
470 // For adds and subs, that are either nuw or safely wrap and use a negative
471 // immediate as operand 1, we create an equivalent instruction using a
472 // positive immediate. That positive immediate can then be zext along with
473 // all the other immediates later.
474 for (auto *V : Visited) {
475 if (!isa<Instruction>(V))
476 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000477
Sam Parker84a2f8b2018-11-01 15:23:42 +0000478 auto *I = cast<Instruction>(V);
479 if (SafeToPromote.count(I)) {
Sam Parker13567db2018-08-16 10:05:39 +0000480
Sam Parker84a2f8b2018-11-01 15:23:42 +0000481 if (!isa<OverflowingBinaryOperator>(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000482 continue;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000483
484 if (auto *Const = dyn_cast<ConstantInt>(I->getOperand(1))) {
485 if (!Const->isNegative())
486 break;
487
488 unsigned Opc = I->getOpcode();
489 assert((Opc == Instruction::Add || Opc == Instruction::Sub) &&
490 "expected only an add or sub to use a negative imm");
491
492 LLVM_DEBUG(dbgs() << "ARM CGP: Adjusting " << *I << "\n");
493 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
494 Builder.SetInsertPoint(I);
495 Value *NewVal = Opc == Instruction::Sub ?
496 Builder.CreateAdd(I->getOperand(0), NewConst) :
497 Builder.CreateSub(I->getOperand(0), NewConst);
498 LLVM_DEBUG(dbgs() << "ARM CGP: New equivalent: " << *NewVal << "\n");
499
500 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
501 NewInst->copyIRFlags(I);
502 NewInsts.insert(NewInst);
503 }
504 InstsToRemove.push_back(I);
505 I->replaceAllUsesWith(NewVal);
506 }
Sam Parker3828c6f2018-07-23 12:27:47 +0000507 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000508 }
509 for (auto *I : NewInsts)
510 Visited.insert(I);
511}
Sam Parker3828c6f2018-07-23 12:27:47 +0000512
Sam Parker84a2f8b2018-11-01 15:23:42 +0000513void IRPromoter::ExtendSources(SmallPtrSetImpl<Value*> &Sources) {
514 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000515
516 auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
517 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting ZExt for " << *V << "\n");
518 Builder.SetInsertPoint(InsertPt);
519 if (auto *I = dyn_cast<Instruction>(V))
520 Builder.SetCurrentDebugLocation(I->getDebugLoc());
521 auto *ZExt = cast<Instruction>(Builder.CreateZExt(V, ExtTy));
522 if (isa<Argument>(V))
523 ZExt->moveBefore(InsertPt);
524 else
525 ZExt->moveAfter(InsertPt);
526 ReplaceAllUsersOfWith(V, ZExt);
527 NewInsts.insert(ZExt);
Sam Parker13567db2018-08-16 10:05:39 +0000528 TruncTysMap[ZExt] = TruncTysMap[V];
Sam Parker3828c6f2018-07-23 12:27:47 +0000529 };
530
Sam Parker84a2f8b2018-11-01 15:23:42 +0000531
532 // Now, insert extending instructions between the sources and their users.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000533 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting sources:\n");
534 for (auto V : Sources) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000535 LLVM_DEBUG(dbgs() << " - " << *V << "\n");
Sam Parker8c4b9642018-08-10 13:57:13 +0000536 if (auto *I = dyn_cast<Instruction>(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000537 InsertZExt(I, I);
538 else if (auto *Arg = dyn_cast<Argument>(V)) {
539 BasicBlock &BB = Arg->getParent()->front();
540 InsertZExt(Arg, &*BB.getFirstInsertionPt());
541 } else {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000542 llvm_unreachable("unhandled source that needs extending");
Sam Parker3828c6f2018-07-23 12:27:47 +0000543 }
544 Promoted.insert(V);
545 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000546}
Sam Parker3828c6f2018-07-23 12:27:47 +0000547
Sam Parker84a2f8b2018-11-01 15:23:42 +0000548void IRPromoter::PromoteTree(SmallPtrSetImpl<Value*> &Visited,
549 SmallPtrSetImpl<Value*> &Sources,
550 SmallPtrSetImpl<Instruction*> &Sinks,
551 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000552 LLVM_DEBUG(dbgs() << "ARM CGP: Mutating the tree..\n");
Sam Parker84a2f8b2018-11-01 15:23:42 +0000553
554 IRBuilder<> Builder{Ctx};
555
556 // Mutate the types of the instructions within the tree. Here we handle
Sam Parker3828c6f2018-07-23 12:27:47 +0000557 // constant operands.
558 for (auto *V : Visited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000559 if (Sources.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000560 continue;
561
Sam Parker3828c6f2018-07-23 12:27:47 +0000562 auto *I = cast<Instruction>(V);
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000563 if (Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000564 continue;
565
Sam Parker7def86b2018-08-15 07:52:35 +0000566 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
567 Value *Op = I->getOperand(i);
568 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
Sam Parker3828c6f2018-07-23 12:27:47 +0000569 continue;
570
Sam Parker84a2f8b2018-11-01 15:23:42 +0000571 if (auto *Const = dyn_cast<ConstantInt>(Op)) {
572 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
573 I->setOperand(i, NewConst);
574 } else if (isa<UndefValue>(Op))
Sam Parker7def86b2018-08-15 07:52:35 +0000575 I->setOperand(i, UndefValue::get(ExtTy));
Sam Parker3828c6f2018-07-23 12:27:47 +0000576 }
577
578 if (shouldPromote(I)) {
579 I->mutateType(ExtTy);
580 Promoted.insert(I);
581 }
582 }
583
Sam Parker84a2f8b2018-11-01 15:23:42 +0000584 // Finally, any instructions that should be promoted but haven't yet been,
585 // need to be handled using intrinsics.
Sam Parker3828c6f2018-07-23 12:27:47 +0000586 for (auto *V : Visited) {
Sam Parker84a2f8b2018-11-01 15:23:42 +0000587 auto *I = dyn_cast<Instruction>(V);
588 if (!I)
Sam Parker3828c6f2018-07-23 12:27:47 +0000589 continue;
Sam Parker8c4b9642018-08-10 13:57:13 +0000590
Sam Parker84a2f8b2018-11-01 15:23:42 +0000591 if (Sources.count(I) || Sinks.count(I))
Sam Parker3828c6f2018-07-23 12:27:47 +0000592 continue;
593
Sam Parker84a2f8b2018-11-01 15:23:42 +0000594 if (!shouldPromote(I) || SafeToPromote.count(I) || NewInsts.count(I))
595 continue;
596
Sam Parker75aca942018-09-26 10:56:00 +0000597 assert(EnableDSP && "DSP intrinisc insertion not enabled!");
598
Sam Parker3828c6f2018-07-23 12:27:47 +0000599 // Replace unsafe instructions with appropriate intrinsic calls.
Sam Parker84a2f8b2018-11-01 15:23:42 +0000600 LLVM_DEBUG(dbgs() << "ARM CGP: Inserting DSP intrinsic for "
601 << *I << "\n");
602 Function *DSPInst =
603 Intrinsic::getDeclaration(M, getNarrowIntrinsic(I));
604 Builder.SetInsertPoint(I);
605 Builder.SetCurrentDebugLocation(I->getDebugLoc());
606 Value *Args[] = { I->getOperand(0), I->getOperand(1) };
607 CallInst *Call = Builder.CreateCall(DSPInst, Args);
608 ReplaceAllUsersOfWith(I, Call);
609 InstsToRemove.push_back(I);
610 NewInsts.insert(Call);
611 TruncTysMap[Call] = OrigTy;
Sam Parker3828c6f2018-07-23 12:27:47 +0000612 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000613}
614
615void IRPromoter::TruncateSinks(SmallPtrSetImpl<Value*> &Sources,
616 SmallPtrSetImpl<Instruction*> &Sinks) {
617 LLVM_DEBUG(dbgs() << "ARM CGP: Fixing up the sinks:\n");
618
619 IRBuilder<> Builder{Ctx};
Sam Parker3828c6f2018-07-23 12:27:47 +0000620
Sam Parker13567db2018-08-16 10:05:39 +0000621 auto InsertTrunc = [&](Value *V) -> Instruction* {
622 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
623 return nullptr;
624
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000625 if ((!Promoted.count(V) && !NewInsts.count(V)) || !TruncTysMap.count(V) ||
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000626 Sources.count(V))
Sam Parker13567db2018-08-16 10:05:39 +0000627 return nullptr;
628
629 Type *TruncTy = TruncTysMap[V];
630 if (TruncTy == ExtTy)
631 return nullptr;
632
633 LLVM_DEBUG(dbgs() << "ARM CGP: Creating " << *TruncTy << " Trunc for "
634 << *V << "\n");
635 Builder.SetInsertPoint(cast<Instruction>(V));
636 auto *Trunc = cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
637 NewInsts.insert(Trunc);
638 return Trunc;
639 };
640
Sam Parker3828c6f2018-07-23 12:27:47 +0000641 // Fix up any stores or returns that use the results of the promoted
642 // chain.
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000643 for (auto I : Sinks) {
Sam Parker3828c6f2018-07-23 12:27:47 +0000644 LLVM_DEBUG(dbgs() << " - " << *I << "\n");
Sam Parker13567db2018-08-16 10:05:39 +0000645
646 // Handle calls separately as we need to iterate over arg operands.
647 if (auto *Call = dyn_cast<CallInst>(I)) {
648 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
649 Value *Arg = Call->getArgOperand(i);
650 if (Instruction *Trunc = InsertTrunc(Arg)) {
651 Trunc->moveBefore(Call);
652 Call->setArgOperand(i, Trunc);
653 }
654 }
655 continue;
Sam Parker3828c6f2018-07-23 12:27:47 +0000656 }
657
Sam Parker13567db2018-08-16 10:05:39 +0000658 // Now handle the others.
Sam Parker3828c6f2018-07-23 12:27:47 +0000659 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
Sam Parker13567db2018-08-16 10:05:39 +0000660 if (Instruction *Trunc = InsertTrunc(I->getOperand(i))) {
661 Trunc->moveBefore(I);
662 I->setOperand(i, Trunc);
Sam Parker3828c6f2018-07-23 12:27:47 +0000663 }
664 }
665 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000666}
667
668void IRPromoter::Mutate(Type *OrigTy,
669 SmallPtrSetImpl<Value*> &Visited,
670 SmallPtrSetImpl<Value*> &Sources,
671 SmallPtrSetImpl<Instruction*> &Sinks,
672 SmallPtrSetImpl<Instruction*> &SafeToPromote) {
673 LLVM_DEBUG(dbgs() << "ARM CGP: Promoting use-def chains to from "
674 << ARMCodeGenPrepare::TypeSize << " to 32-bits\n");
675 this->OrigTy = OrigTy;
676
677 // Cache original types.
678 for (auto *V : Visited)
679 TruncTysMap[V] = V->getType();
680
681 // Convert adds and subs using negative immediates to equivalent instructions
682 // that use positive constants.
683 PrepareConstants(Visited, SafeToPromote);
684
685 // Insert zext instructions between sources and their users.
686 ExtendSources(Sources);
687
688 // Promote visited instructions, mutating their types in place. Also insert
689 // DSP intrinsics, if enabled, for adds and subs which would be unsafe to
690 // promote.
691 PromoteTree(Visited, Sources, Sinks, SafeToPromote);
692
693 // Finally, insert trunc instructions for use by calls, stores etc...
694 TruncateSinks(Sources, Sinks);
695
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000696 LLVM_DEBUG(dbgs() << "ARM CGP: Mutation complete:\n");
Sam Parkeraaec3c62018-09-13 15:14:12 +0000697 LLVM_DEBUG(dbgs();
698 for (auto *V : Sources)
699 V->dump();
700 for (auto *I : NewInsts)
701 I->dump();
702 for (auto *V : Visited) {
703 if (!Sources.count(V))
704 V->dump();
705 });
Sam Parker3828c6f2018-07-23 12:27:47 +0000706}
707
Sam Parker8c4b9642018-08-10 13:57:13 +0000708/// We accept most instructions, as well as Arguments and ConstantInsts. We
709/// Disallow casts other than zext and truncs and only allow calls if their
710/// return value is zeroext. We don't allow opcodes that can introduce sign
711/// bits.
712bool ARMCodeGenPrepare::isSupportedValue(Value *V) {
Sam Parker13567db2018-08-16 10:05:39 +0000713 if (isa<ICmpInst>(V))
714 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000715
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000716 // Memory instructions
717 if (isa<StoreInst>(V) || isa<GetElementPtrInst>(V))
718 return true;
719
720 // Branches and targets.
721 if( isa<BranchInst>(V) || isa<SwitchInst>(V) || isa<BasicBlock>(V))
722 return true;
723
724 // Non-instruction values that we can handle.
725 if ((isa<Constant>(V) && !isa<ConstantExpr>(V)) || isa<Argument>(V))
726 return isSupportedType(V);
727
728 if (isa<PHINode>(V) || isa<SelectInst>(V) || isa<ReturnInst>(V) ||
729 isa<LoadInst>(V))
730 return isSupportedType(V);
731
732 // Truncs can be either sources or sinks.
733 if (auto *Trunc = dyn_cast<TruncInst>(V))
734 return isSupportedType(Trunc) || isSupportedType(Trunc->getOperand(0));
735
736 if (isa<CastInst>(V) && !isa<SExtInst>(V))
737 return isSupportedType(cast<CastInst>(V)->getOperand(0));
Sam Parker0e2f0bd2018-08-16 11:54:09 +0000738
Sam Parker8c4b9642018-08-10 13:57:13 +0000739 // Special cases for calls as we need to check for zeroext
740 // TODO We should accept calls even if they don't have zeroext, as they can
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000741 // still be sinks.
Sam Parker8c4b9642018-08-10 13:57:13 +0000742 if (auto *Call = dyn_cast<CallInst>(V))
743 return isSupportedType(Call) &&
744 Call->hasRetAttr(Attribute::AttrKind::ZExt);
745
Volodymyr Sapsai703ab842018-09-18 00:11:55 +0000746 if (!isa<BinaryOperator>(V))
747 return false;
748
749 if (!isSupportedType(V))
750 return false;
751
752 if (generateSignBits(V)) {
753 LLVM_DEBUG(dbgs() << "ARM CGP: No, instruction can generate sign bits.\n");
754 return false;
755 }
756 return true;
Sam Parker8c4b9642018-08-10 13:57:13 +0000757}
758
759/// Check that the type of V would be promoted and that the original type is
760/// smaller than the targeted promoted type. Check that we're not trying to
761/// promote something larger than our base 'TypeSize' type.
762bool ARMCodeGenPrepare::isLegalToPromote(Value *V) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000763
764 auto *I = dyn_cast<Instruction>(V);
765 if (!I)
Sam Parker84a2f8b2018-11-01 15:23:42 +0000766 return true;
767
768 if (SafeToPromote.count(I))
769 return true;
770
771 if (isPromotedResultSafe(V) || isSafeOverflow(I)) {
772 SafeToPromote.insert(I);
773 return true;
774 }
775
776 if (I->getOpcode() != Instruction::Add && I->getOpcode() != Instruction::Sub)
Sam Parker8c4b9642018-08-10 13:57:13 +0000777 return false;
778
779 // If promotion is not safe, can we use a DSP instruction to natively
780 // handle the narrow type?
Sam Parker3828c6f2018-07-23 12:27:47 +0000781 if (!ST->hasDSP() || !EnableDSP || !isSupportedType(I))
782 return false;
783
784 if (ST->isThumb() && !ST->hasThumb2())
785 return false;
786
Sam Parker3828c6f2018-07-23 12:27:47 +0000787 // TODO
788 // Would it be profitable? For Thumb code, these parallel DSP instructions
789 // are only Thumb-2, so we wouldn't be able to dual issue on Cortex-M33. For
790 // Cortex-A, specifically Cortex-A72, the latency is double and throughput is
791 // halved. They also do not take immediates as operands.
792 for (auto &Op : I->operands()) {
793 if (isa<Constant>(Op)) {
794 if (!EnableDSPWithImms)
795 return false;
796 }
797 }
Sam Parker84a2f8b2018-11-01 15:23:42 +0000798 LLVM_DEBUG(dbgs() << "ARM CGP: Will use an intrinsic for: " << *I << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000799 return true;
800}
801
Sam Parker3828c6f2018-07-23 12:27:47 +0000802bool ARMCodeGenPrepare::TryToPromote(Value *V) {
803 OrigTy = V->getType();
804 TypeSize = OrigTy->getPrimitiveSizeInBits();
Sam Parkerfabf7fe2018-08-15 13:29:50 +0000805 if (TypeSize > 16 || TypeSize < 8)
Sam Parker8c4b9642018-08-10 13:57:13 +0000806 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000807
Sam Parker84a2f8b2018-11-01 15:23:42 +0000808 SafeToPromote.clear();
809
Sam Parker3828c6f2018-07-23 12:27:47 +0000810 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
811 return false;
812
Sam Parker8c4b9642018-08-10 13:57:13 +0000813 LLVM_DEBUG(dbgs() << "ARM CGP: TryToPromote: " << *V << ", TypeSize = "
814 << TypeSize << "\n");
Sam Parker3828c6f2018-07-23 12:27:47 +0000815
816 SetVector<Value*> WorkList;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000817 SmallPtrSet<Value*, 8> Sources;
818 SmallPtrSet<Instruction*, 4> Sinks;
Sam Parker3828c6f2018-07-23 12:27:47 +0000819 SmallPtrSet<Value*, 16> CurrentVisited;
Sam Parker84a2f8b2018-11-01 15:23:42 +0000820 WorkList.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000821
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000822 // Return true if V was added to the worklist as a supported instruction,
823 // if it was already visited, or if we don't need to explore it (e.g.
824 // pointer values and GEPs), and false otherwise.
Sam Parker3828c6f2018-07-23 12:27:47 +0000825 auto AddLegalInst = [&](Value *V) {
826 if (CurrentVisited.count(V))
827 return true;
828
Sam Parker0d511972018-08-16 12:24:40 +0000829 // Ignore GEPs because they don't need promoting and the constant indices
830 // will prevent the transformation.
831 if (isa<GetElementPtrInst>(V))
832 return true;
833
Sam Parker3828c6f2018-07-23 12:27:47 +0000834 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
835 LLVM_DEBUG(dbgs() << "ARM CGP: Can't handle: " << *V << "\n");
836 return false;
837 }
838
839 WorkList.insert(V);
840 return true;
841 };
842
843 // Iterate through, and add to, a tree of operands and users in the use-def.
844 while (!WorkList.empty()) {
845 Value *V = WorkList.back();
846 WorkList.pop_back();
847 if (CurrentVisited.count(V))
848 continue;
849
Sam Parker7def86b2018-08-15 07:52:35 +0000850 // Ignore non-instructions, other than arguments.
Sam Parker3828c6f2018-07-23 12:27:47 +0000851 if (!isa<Instruction>(V) && !isSource(V))
852 continue;
853
854 // If we've already visited this value from somewhere, bail now because
855 // the tree has already been explored.
856 // TODO: This could limit the transform, ie if we try to promote something
857 // from an i8 and fail first, before trying an i16.
Sam Parkeraaec3c62018-09-13 15:14:12 +0000858 if (AllVisited.count(V))
Sam Parker3828c6f2018-07-23 12:27:47 +0000859 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000860
861 CurrentVisited.insert(V);
862 AllVisited.insert(V);
863
864 // Calls can be both sources and sinks.
865 if (isSink(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000866 Sinks.insert(cast<Instruction>(V));
Sam Parker3828c6f2018-07-23 12:27:47 +0000867 if (isSource(V))
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000868 Sources.insert(V);
Sam Parker3828c6f2018-07-23 12:27:47 +0000869 else if (auto *I = dyn_cast<Instruction>(V)) {
870 // Visit operands of any instruction visited.
871 for (auto &U : I->operands()) {
872 if (!AddLegalInst(U))
873 return false;
874 }
875 }
876
877 // Don't visit users of a node which isn't going to be mutated unless its a
878 // source.
879 if (isSource(V) || shouldPromote(V)) {
880 for (Use &U : V->uses()) {
881 if (!AddLegalInst(U.getUser()))
882 return false;
883 }
884 }
885 }
886
Sam Parker3828c6f2018-07-23 12:27:47 +0000887 LLVM_DEBUG(dbgs() << "ARM CGP: Visited nodes:\n";
888 for (auto *I : CurrentVisited)
889 I->dump();
890 );
Sam Parker7def86b2018-08-15 07:52:35 +0000891 unsigned ToPromote = 0;
892 for (auto *V : CurrentVisited) {
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000893 if (Sources.count(V))
Sam Parker7def86b2018-08-15 07:52:35 +0000894 continue;
Sjoerd Meijer31239a42018-08-17 07:34:01 +0000895 if (Sinks.count(cast<Instruction>(V)))
Sam Parker7def86b2018-08-15 07:52:35 +0000896 continue;
897 ++ToPromote;
898 }
899
900 if (ToPromote < 2)
901 return false;
Sam Parker3828c6f2018-07-23 12:27:47 +0000902
Sam Parker84a2f8b2018-11-01 15:23:42 +0000903 Promoter->Mutate(OrigTy, CurrentVisited, Sources, Sinks, SafeToPromote);
Sam Parker3828c6f2018-07-23 12:27:47 +0000904 return true;
905}
906
907bool ARMCodeGenPrepare::doInitialization(Module &M) {
908 Promoter = new IRPromoter(&M);
909 return false;
910}
911
912bool ARMCodeGenPrepare::runOnFunction(Function &F) {
913 if (skipFunction(F) || DisableCGP)
914 return false;
915
916 auto *TPC = &getAnalysis<TargetPassConfig>();
917 if (!TPC)
918 return false;
919
920 const TargetMachine &TM = TPC->getTM<TargetMachine>();
921 ST = &TM.getSubtarget<ARMSubtarget>(F);
922 bool MadeChange = false;
923 LLVM_DEBUG(dbgs() << "ARM CGP: Running on " << F.getName() << "\n");
924
925 // Search up from icmps to try to promote their operands.
926 for (BasicBlock &BB : F) {
927 auto &Insts = BB.getInstList();
928 for (auto &I : Insts) {
929 if (AllVisited.count(&I))
930 continue;
931
932 if (isa<ICmpInst>(I)) {
933 auto &CI = cast<ICmpInst>(I);
934
935 // Skip signed or pointer compares
936 if (CI.isSigned() || !isa<IntegerType>(CI.getOperand(0)->getType()))
937 continue;
938
Sam Parker3828c6f2018-07-23 12:27:47 +0000939 for (auto &Op : CI.operands()) {
Sam Parker8c4b9642018-08-10 13:57:13 +0000940 if (auto *I = dyn_cast<Instruction>(Op))
941 MadeChange |= TryToPromote(I);
Sam Parker3828c6f2018-07-23 12:27:47 +0000942 }
943 }
944 }
945 Promoter->Cleanup();
946 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
947 dbgs();
948 report_fatal_error("Broken function after type promotion");
949 });
950 }
951 if (MadeChange)
952 LLVM_DEBUG(dbgs() << "After ARMCodeGenPrepare: " << F << "\n");
953
954 return MadeChange;
955}
956
Matt Morehousea70685f2018-07-23 17:00:45 +0000957bool ARMCodeGenPrepare::doFinalization(Module &M) {
958 delete Promoter;
959 return false;
960}
961
Sam Parker3828c6f2018-07-23 12:27:47 +0000962INITIALIZE_PASS_BEGIN(ARMCodeGenPrepare, DEBUG_TYPE,
963 "ARM IR optimizations", false, false)
964INITIALIZE_PASS_END(ARMCodeGenPrepare, DEBUG_TYPE, "ARM IR optimizations",
965 false, false)
966
967char ARMCodeGenPrepare::ID = 0;
Sam Parker8c4b9642018-08-10 13:57:13 +0000968unsigned ARMCodeGenPrepare::TypeSize = 0;
Sam Parker3828c6f2018-07-23 12:27:47 +0000969
970FunctionPass *llvm::createARMCodeGenPreparePass() {
971 return new ARMCodeGenPrepare();
972}