1 //===----- TypePromotion.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This is an opcode based type promotion pass for small types that would
11 /// otherwise be promoted during legalisation. This works around the limitations
12 /// of selection dag for cyclic regions. The search begins from icmp
13 /// instructions operands where a tree, consisting of non-wrapping or safe
14 /// wrapping instructions, is built, checked and promoted if possible.
15 ///
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Target/TargetMachine.h"
41 
42 #define DEBUG_TYPE "type-promotion"
43 #define PASS_NAME "Type Promotion"
44 
45 using namespace llvm;
46 
47 static cl::opt<bool>
48 DisablePromotion("disable-type-promotion", cl::Hidden, cl::init(false),
49                  cl::desc("Disable type promotion pass"));
50 
51 // The goal of this pass is to enable more efficient code generation for
52 // operations on narrow types (i.e. types with < 32-bits) and this is a
53 // motivating IR code example:
54 //
55 //   define hidden i32 @cmp(i8 zeroext) {
56 //     %2 = add i8 %0, -49
57 //     %3 = icmp ult i8 %2, 3
58 //     ..
59 //   }
60 //
61 // The issue here is that i8 is type-legalized to i32 because i8 is not a
62 // legal type. Thus, arithmetic is done in integer-precision, but then the
63 // byte value is masked out as follows:
64 //
65 //   t19: i32 = add t4, Constant:i32<-49>
66 //     t24: i32 = and t19, Constant:i32<255>
67 //
68 // Consequently, we generate code like this:
69 //
70 //   subs  r0, #49
71 //   uxtb  r1, r0
72 //   cmp r1, #3
73 //
74 // This shows that masking out the byte value results in generation of
75 // the UXTB instruction. This is not optimal as r0 already contains the byte
76 // value we need, and so instead we can just generate:
77 //
78 //   sub.w r1, r0, #49
79 //   cmp r1, #3
80 //
81 // We achieve this by type promoting the IR to i32 like so for this example:
82 //
83 //   define i32 @cmp(i8 zeroext %c) {
84 //     %0 = zext i8 %c to i32
85 //     %c.off = add i32 %0, -49
86 //     %1 = icmp ult i32 %c.off, 3
87 //     ..
88 //   }
89 //
90 // For this to be valid and legal, we need to prove that the i32 add is
91 // producing the same value as the i8 addition, and that e.g. no overflow
92 // happens.
93 //
94 // A brief sketch of the algorithm and some terminology.
95 // We pattern match interesting IR patterns:
96 // - which have "sources": instructions producing narrow values (i8, i16), and
97 // - they have "sinks": instructions consuming these narrow values.
98 //
99 // We collect all instruction connecting sources and sinks in a worklist, so
100 // that we can mutate these instruction and perform type promotion when it is
101 // legal to do so.
102 
103 namespace {
104 class IRPromoter {
105   LLVMContext &Ctx;
106   IntegerType *OrigTy = nullptr;
107   unsigned PromotedWidth = 0;
108   SetVector<Value*> &Visited;
109   SetVector<Value*> &Sources;
110   SetVector<Instruction*> &Sinks;
111   SmallVectorImpl<Instruction*> &SafeWrap;
112   IntegerType *ExtTy = nullptr;
113   SmallPtrSet<Value*, 8> NewInsts;
114   SmallPtrSet<Instruction*, 4> InstsToRemove;
115   DenseMap<Value*, SmallVector<Type*, 4>> TruncTysMap;
116   SmallPtrSet<Value*, 8> Promoted;
117 
118   void ReplaceAllUsersOfWith(Value *From, Value *To);
119   void PrepareWrappingAdds(void);
120   void ExtendSources(void);
121   void ConvertTruncs(void);
122   void PromoteTree(void);
123   void TruncateSinks(void);
124   void Cleanup(void);
125 
126 public:
127   IRPromoter(LLVMContext &C, IntegerType *Ty, unsigned Width,
128              SetVector<Value*> &visited, SetVector<Value*> &sources,
129              SetVector<Instruction*> &sinks,
130              SmallVectorImpl<Instruction*> &wrap) :
131     Ctx(C), OrigTy(Ty), PromotedWidth(Width), Visited(visited),
132     Sources(sources), Sinks(sinks), SafeWrap(wrap) {
133     ExtTy = IntegerType::get(Ctx, PromotedWidth);
134     assert(OrigTy->getPrimitiveSizeInBits().getFixedSize() <
135                ExtTy->getPrimitiveSizeInBits().getFixedSize() &&
136            "Original type not smaller than extended type");
137   }
138 
139   void Mutate();
140 };
141 
142 class TypePromotion : public FunctionPass {
143   unsigned TypeSize = 0;
144   LLVMContext *Ctx = nullptr;
145   unsigned RegisterBitWidth = 0;
146   SmallPtrSet<Value*, 16> AllVisited;
147   SmallPtrSet<Instruction*, 8> SafeToPromote;
148   SmallVector<Instruction*, 4> SafeWrap;
149 
150   // Does V have the same size result type as TypeSize.
151   bool EqualTypeSize(Value *V);
152   // Does V have the same size, or narrower, result type as TypeSize.
153   bool LessOrEqualTypeSize(Value *V);
154   // Does V have a result type that is wider than TypeSize.
155   bool GreaterThanTypeSize(Value *V);
156   // Does V have a result type that is narrower than TypeSize.
157   bool LessThanTypeSize(Value *V);
158   // Should V be a leaf in the promote tree?
159   bool isSource(Value *V);
160   // Should V be a root in the promotion tree?
161   bool isSink(Value *V);
162   // Should we change the result type of V? It will result in the users of V
163   // being visited.
164   bool shouldPromote(Value *V);
165   // Is I an add or a sub, which isn't marked as nuw, but where a wrapping
166   // result won't affect the computation?
167   bool isSafeWrap(Instruction *I);
168   // Can V have its integer type promoted, or can the type be ignored.
169   bool isSupportedType(Value *V);
170   // Is V an instruction with a supported opcode or another value that we can
171   // handle, such as constants and basic blocks.
172   bool isSupportedValue(Value *V);
173   // Is V an instruction thats result can trivially promoted, or has safe
174   // wrapping.
175   bool isLegalToPromote(Value *V);
176   bool TryToPromote(Value *V, unsigned PromotedWidth);
177 
178 public:
179   static char ID;
180 
181   TypePromotion() : FunctionPass(ID) {}
182 
183   void getAnalysisUsage(AnalysisUsage &AU) const override {
184     AU.addRequired<TargetTransformInfoWrapperPass>();
185     AU.addRequired<TargetPassConfig>();
186     AU.setPreservesCFG();
187   }
188 
189   StringRef getPassName() const override { return PASS_NAME; }
190 
191   bool runOnFunction(Function &F) override;
192 };
193 
194 }
195 
196 static bool GenerateSignBits(Instruction *I) {
197   unsigned Opc = I->getOpcode();
198   return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
199          Opc == Instruction::SRem || Opc == Instruction::SExt;
200 }
201 
202 bool TypePromotion::EqualTypeSize(Value *V) {
203   return V->getType()->getScalarSizeInBits() == TypeSize;
204 }
205 
206 bool TypePromotion::LessOrEqualTypeSize(Value *V) {
207   return V->getType()->getScalarSizeInBits() <= TypeSize;
208 }
209 
210 bool TypePromotion::GreaterThanTypeSize(Value *V) {
211   return V->getType()->getScalarSizeInBits() > TypeSize;
212 }
213 
214 bool TypePromotion::LessThanTypeSize(Value *V) {
215   return V->getType()->getScalarSizeInBits() < TypeSize;
216 }
217 
218 /// Return true if the given value is a source in the use-def chain, producing
219 /// a narrow 'TypeSize' value. These values will be zext to start the promotion
220 /// of the tree to i32. We guarantee that these won't populate the upper bits
221 /// of the register. ZExt on the loads will be free, and the same for call
222 /// return values because we only accept ones that guarantee a zeroext ret val.
223 /// Many arguments will have the zeroext attribute too, so those would be free
224 /// too.
225 bool TypePromotion::isSource(Value *V) {
226   if (!isa<IntegerType>(V->getType()))
227     return false;
228 
229   // TODO Allow zext to be sources.
230   if (isa<Argument>(V))
231     return true;
232   else if (isa<LoadInst>(V))
233     return true;
234   else if (isa<BitCastInst>(V))
235     return true;
236   else if (auto *Call = dyn_cast<CallInst>(V))
237     return Call->hasRetAttr(Attribute::AttrKind::ZExt);
238   else if (auto *Trunc = dyn_cast<TruncInst>(V))
239     return EqualTypeSize(Trunc);
240   return false;
241 }
242 
243 /// Return true if V will require any promoted values to be truncated for the
244 /// the IR to remain valid. We can't mutate the value type of these
245 /// instructions.
246 bool TypePromotion::isSink(Value *V) {
247   // TODO The truncate also isn't actually necessary because we would already
248   // proved that the data value is kept within the range of the original data
249   // type.
250 
251   // Sinks are:
252   // - points where the value in the register is being observed, such as an
253   //   icmp, switch or store.
254   // - points where value types have to match, such as calls and returns.
255   // - zext are included to ease the transformation and are generally removed
256   //   later on.
257   if (auto *Store = dyn_cast<StoreInst>(V))
258     return LessOrEqualTypeSize(Store->getValueOperand());
259   if (auto *Return = dyn_cast<ReturnInst>(V))
260     return LessOrEqualTypeSize(Return->getReturnValue());
261   if (auto *ZExt = dyn_cast<ZExtInst>(V))
262     return GreaterThanTypeSize(ZExt);
263   if (auto *Switch = dyn_cast<SwitchInst>(V))
264     return LessThanTypeSize(Switch->getCondition());
265   if (auto *ICmp = dyn_cast<ICmpInst>(V))
266     return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
267 
268   return isa<CallInst>(V);
269 }
270 
271 /// Return whether this instruction can safely wrap.
272 bool TypePromotion::isSafeWrap(Instruction *I) {
273   // We can support a, potentially, wrapping instruction (I) if:
274   // - It is only used by an unsigned icmp.
275   // - The icmp uses a constant.
276   // - The wrapping value (I) is decreasing, i.e would underflow - wrapping
277   //   around zero to become a larger number than before.
278   // - The wrapping instruction (I) also uses a constant.
279   //
280   // We can then use the two constants to calculate whether the result would
281   // wrap in respect to itself in the original bitwidth. If it doesn't wrap,
282   // just underflows the range, the icmp would give the same result whether the
283   // result has been truncated or not. We calculate this by:
284   // - Zero extending both constants, if needed, to RegisterBitWidth.
285   // - Take the absolute value of I's constant, adding this to the icmp const.
286   // - Check that this value is not out of range for small type. If it is, it
287   //   means that it has underflowed enough to wrap around the icmp constant.
288   //
289   // For example:
290   //
291   // %sub = sub i8 %a, 2
292   // %cmp = icmp ule i8 %sub, 254
293   //
294   // If %a = 0, %sub = -2 == FE == 254
295   // But if this is evalulated as a i32
296   // %sub = -2 == FF FF FF FE == 4294967294
297   // So the unsigned compares (i8 and i32) would not yield the same result.
298   //
299   // Another way to look at it is:
300   // %a - 2 <= 254
301   // %a + 2 <= 254 + 2
302   // %a <= 256
303   // And we can't represent 256 in the i8 format, so we don't support it.
304   //
305   // Whereas:
306   //
307   // %sub i8 %a, 1
308   // %cmp = icmp ule i8 %sub, 254
309   //
310   // If %a = 0, %sub = -1 == FF == 255
311   // As i32:
312   // %sub = -1 == FF FF FF FF == 4294967295
313   //
314   // In this case, the unsigned compare results would be the same and this
315   // would also be true for ult, uge and ugt:
316   // - (255 < 254) == (0xFFFFFFFF < 254) == false
317   // - (255 <= 254) == (0xFFFFFFFF <= 254) == false
318   // - (255 > 254) == (0xFFFFFFFF > 254) == true
319   // - (255 >= 254) == (0xFFFFFFFF >= 254) == true
320   //
321   // To demonstrate why we can't handle increasing values:
322   //
323   // %add = add i8 %a, 2
324   // %cmp = icmp ult i8 %add, 127
325   //
326   // If %a = 254, %add = 256 == (i8 1)
327   // As i32:
328   // %add = 256
329   //
330   // (1 < 127) != (256 < 127)
331 
332   unsigned Opc = I->getOpcode();
333   if (Opc != Instruction::Add && Opc != Instruction::Sub)
334     return false;
335 
336   if (!I->hasOneUse() ||
337       !isa<ICmpInst>(*I->user_begin()) ||
338       !isa<ConstantInt>(I->getOperand(1)))
339     return false;
340 
341   ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1));
342   bool NegImm = OverflowConst->isNegative();
343   bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
344                        ((Opc == Instruction::Add) && NegImm);
345   if (!IsDecreasing)
346     return false;
347 
348   // Don't support an icmp that deals with sign bits.
349   auto *CI = cast<ICmpInst>(*I->user_begin());
350   if (CI->isSigned() || CI->isEquality())
351     return false;
352 
353   ConstantInt *ICmpConst = nullptr;
354   if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
355     ICmpConst = Const;
356   else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
357     ICmpConst = Const;
358   else
359     return false;
360 
361   // Now check that the result can't wrap on itself.
362   APInt Total = ICmpConst->getValue().zextOrSelf(RegisterBitWidth);
363   Total += OverflowConst->getValue().abs().zextOrSelf(RegisterBitWidth);
364 
365   APInt Max = APInt::getAllOnes(TypeSize).zextOrSelf(RegisterBitWidth);
366 
367   if (Total.ugt(Max))
368     return false;
369 
370   LLVM_DEBUG(dbgs() << "IR Promotion: Allowing safe overflow for " << *I
371                     << "\n");
372   SafeWrap.push_back(I);
373   return true;
374 }
375 
376 bool TypePromotion::shouldPromote(Value *V) {
377   if (!isa<IntegerType>(V->getType()) || isSink(V))
378     return false;
379 
380   if (isSource(V))
381     return true;
382 
383   auto *I = dyn_cast<Instruction>(V);
384   if (!I)
385     return false;
386 
387   if (isa<ICmpInst>(I))
388     return false;
389 
390   return true;
391 }
392 
393 /// Return whether we can safely mutate V's type to ExtTy without having to be
394 /// concerned with zero extending or truncation.
395 static bool isPromotedResultSafe(Instruction *I) {
396   if (GenerateSignBits(I))
397     return false;
398 
399   if (!isa<OverflowingBinaryOperator>(I))
400     return true;
401 
402   return I->hasNoUnsignedWrap();
403 }
404 
405 void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) {
406   SmallVector<Instruction*, 4> Users;
407   Instruction *InstTo = dyn_cast<Instruction>(To);
408   bool ReplacedAll = true;
409 
410   LLVM_DEBUG(dbgs() << "IR Promotion: Replacing " << *From << " with " << *To
411              << "\n");
412 
413   for (Use &U : From->uses()) {
414     auto *User = cast<Instruction>(U.getUser());
415     if (InstTo && User->isIdenticalTo(InstTo)) {
416       ReplacedAll = false;
417       continue;
418     }
419     Users.push_back(User);
420   }
421 
422   for (auto *U : Users)
423     U->replaceUsesOfWith(From, To);
424 
425   if (ReplacedAll)
426     if (auto *I = dyn_cast<Instruction>(From))
427       InstsToRemove.insert(I);
428 }
429 
430 void IRPromoter::PrepareWrappingAdds() {
431   LLVM_DEBUG(dbgs() << "IR Promotion: Prepare wrapping adds.\n");
432   IRBuilder<> Builder{Ctx};
433 
434   // For adds that safely wrap and use a negative immediate as operand 1, we
435   // create an equivalent instruction using a positive immediate.
436   // That positive immediate can then be zext along with all the other
437   // immediates later.
438   for (auto *I : SafeWrap) {
439     if (I->getOpcode() != Instruction::Add)
440       continue;
441 
442     LLVM_DEBUG(dbgs() << "IR Promotion: Adjusting " << *I << "\n");
443     assert((isa<ConstantInt>(I->getOperand(1)) &&
444             cast<ConstantInt>(I->getOperand(1))->isNegative()) &&
445            "Wrapping should have a negative immediate as the second operand");
446 
447     auto Const = cast<ConstantInt>(I->getOperand(1));
448     auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs());
449     Builder.SetInsertPoint(I);
450     Value *NewVal = Builder.CreateSub(I->getOperand(0), NewConst);
451     if (auto *NewInst = dyn_cast<Instruction>(NewVal)) {
452       NewInst->copyIRFlags(I);
453       NewInsts.insert(NewInst);
454     }
455     InstsToRemove.insert(I);
456     I->replaceAllUsesWith(NewVal);
457     LLVM_DEBUG(dbgs() << "IR Promotion: New equivalent: " << *NewVal << "\n");
458   }
459   for (auto *I : NewInsts)
460     Visited.insert(I);
461 }
462 
463 void IRPromoter::ExtendSources() {
464   IRBuilder<> Builder{Ctx};
465 
466   auto InsertZExt = [&](Value *V, Instruction *InsertPt) {
467     assert(V->getType() != ExtTy && "zext already extends to i32");
468     LLVM_DEBUG(dbgs() << "IR Promotion: Inserting ZExt for " << *V << "\n");
469     Builder.SetInsertPoint(InsertPt);
470     if (auto *I = dyn_cast<Instruction>(V))
471       Builder.SetCurrentDebugLocation(I->getDebugLoc());
472 
473     Value *ZExt = Builder.CreateZExt(V, ExtTy);
474     if (auto *I = dyn_cast<Instruction>(ZExt)) {
475       if (isa<Argument>(V))
476         I->moveBefore(InsertPt);
477       else
478         I->moveAfter(InsertPt);
479       NewInsts.insert(I);
480     }
481 
482     ReplaceAllUsersOfWith(V, ZExt);
483   };
484 
485   // Now, insert extending instructions between the sources and their users.
486   LLVM_DEBUG(dbgs() << "IR Promotion: Promoting sources:\n");
487   for (auto V : Sources) {
488     LLVM_DEBUG(dbgs() << " - " << *V << "\n");
489     if (auto *I = dyn_cast<Instruction>(V))
490       InsertZExt(I, I);
491     else if (auto *Arg = dyn_cast<Argument>(V)) {
492       BasicBlock &BB = Arg->getParent()->front();
493       InsertZExt(Arg, &*BB.getFirstInsertionPt());
494     } else {
495       llvm_unreachable("unhandled source that needs extending");
496     }
497     Promoted.insert(V);
498   }
499 }
500 
501 void IRPromoter::PromoteTree() {
502   LLVM_DEBUG(dbgs() << "IR Promotion: Mutating the tree..\n");
503 
504   // Mutate the types of the instructions within the tree. Here we handle
505   // constant operands.
506   for (auto *V : Visited) {
507     if (Sources.count(V))
508       continue;
509 
510     auto *I = cast<Instruction>(V);
511     if (Sinks.count(I))
512       continue;
513 
514     for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
515       Value *Op = I->getOperand(i);
516       if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType()))
517         continue;
518 
519       if (auto *Const = dyn_cast<ConstantInt>(Op)) {
520         Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy);
521         I->setOperand(i, NewConst);
522       } else if (isa<UndefValue>(Op))
523         I->setOperand(i, UndefValue::get(ExtTy));
524     }
525 
526     // Mutate the result type, unless this is an icmp or switch.
527     if (!isa<ICmpInst>(I) && !isa<SwitchInst>(I)) {
528       I->mutateType(ExtTy);
529       Promoted.insert(I);
530     }
531   }
532 }
533 
534 void IRPromoter::TruncateSinks() {
535   LLVM_DEBUG(dbgs() << "IR Promotion: Fixing up the sinks:\n");
536 
537   IRBuilder<> Builder{Ctx};
538 
539   auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction* {
540     if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType()))
541       return nullptr;
542 
543     if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources.count(V))
544       return nullptr;
545 
546     LLVM_DEBUG(dbgs() << "IR Promotion: Creating " << *TruncTy << " Trunc for "
547                << *V << "\n");
548     Builder.SetInsertPoint(cast<Instruction>(V));
549     auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy));
550     if (Trunc)
551       NewInsts.insert(Trunc);
552     return Trunc;
553   };
554 
555   // Fix up any stores or returns that use the results of the promoted
556   // chain.
557   for (auto I : Sinks) {
558     LLVM_DEBUG(dbgs() << "IR Promotion: For Sink: " << *I << "\n");
559 
560     // Handle calls separately as we need to iterate over arg operands.
561     if (auto *Call = dyn_cast<CallInst>(I)) {
562       for (unsigned i = 0; i < Call->arg_size(); ++i) {
563         Value *Arg = Call->getArgOperand(i);
564         Type *Ty = TruncTysMap[Call][i];
565         if (Instruction *Trunc = InsertTrunc(Arg, Ty)) {
566           Trunc->moveBefore(Call);
567           Call->setArgOperand(i, Trunc);
568         }
569       }
570       continue;
571     }
572 
573     // Special case switches because we need to truncate the condition.
574     if (auto *Switch = dyn_cast<SwitchInst>(I)) {
575       Type *Ty = TruncTysMap[Switch][0];
576       if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
577         Trunc->moveBefore(Switch);
578         Switch->setCondition(Trunc);
579       }
580       continue;
581     }
582 
583     // Now handle the others.
584     for (unsigned i = 0; i < I->getNumOperands(); ++i) {
585       Type *Ty = TruncTysMap[I][i];
586       if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) {
587         Trunc->moveBefore(I);
588         I->setOperand(i, Trunc);
589       }
590     }
591   }
592 }
593 
594 void IRPromoter::Cleanup() {
595   LLVM_DEBUG(dbgs() << "IR Promotion: Cleanup..\n");
596   // Some zexts will now have become redundant, along with their trunc
597   // operands, so remove them
598   for (auto V : Visited) {
599     if (!isa<ZExtInst>(V))
600       continue;
601 
602     auto ZExt = cast<ZExtInst>(V);
603     if (ZExt->getDestTy() != ExtTy)
604       continue;
605 
606     Value *Src = ZExt->getOperand(0);
607     if (ZExt->getSrcTy() == ZExt->getDestTy()) {
608       LLVM_DEBUG(dbgs() << "IR Promotion: Removing unnecessary cast: " << *ZExt
609                  << "\n");
610       ReplaceAllUsersOfWith(ZExt, Src);
611       continue;
612     }
613 
614     // Unless they produce a value that is narrower than ExtTy, we can
615     // replace the result of the zext with the input of a newly inserted
616     // trunc.
617     if (NewInsts.count(Src) && isa<TruncInst>(Src) &&
618         Src->getType() == OrigTy) {
619       auto *Trunc = cast<TruncInst>(Src);
620       assert(Trunc->getOperand(0)->getType() == ExtTy &&
621              "expected inserted trunc to be operating on i32");
622       ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
623     }
624   }
625 
626   for (auto *I : InstsToRemove) {
627     LLVM_DEBUG(dbgs() << "IR Promotion: Removing " << *I << "\n");
628     I->dropAllReferences();
629     I->eraseFromParent();
630   }
631 }
632 
633 void IRPromoter::ConvertTruncs() {
634   LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n");
635   IRBuilder<> Builder{Ctx};
636 
637   for (auto *V : Visited) {
638     if (!isa<TruncInst>(V) || Sources.count(V))
639       continue;
640 
641     auto *Trunc = cast<TruncInst>(V);
642     Builder.SetInsertPoint(Trunc);
643     IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
644     IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
645 
646     unsigned NumBits = DestTy->getScalarSizeInBits();
647     ConstantInt *Mask =
648       ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue());
649     Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask);
650 
651     if (auto *I = dyn_cast<Instruction>(Masked))
652       NewInsts.insert(I);
653 
654     ReplaceAllUsersOfWith(Trunc, Masked);
655   }
656 }
657 
658 void IRPromoter::Mutate() {
659   LLVM_DEBUG(dbgs() << "IR Promotion: Promoting use-def chains from "
660              << OrigTy->getBitWidth() << " to " << PromotedWidth << "-bits\n");
661 
662   // Cache original types of the values that will likely need truncating
663   for (auto *I : Sinks) {
664     if (auto *Call = dyn_cast<CallInst>(I)) {
665       for (Value *Arg : Call->args())
666         TruncTysMap[Call].push_back(Arg->getType());
667     } else if (auto *Switch = dyn_cast<SwitchInst>(I))
668       TruncTysMap[I].push_back(Switch->getCondition()->getType());
669     else {
670       for (unsigned i = 0; i < I->getNumOperands(); ++i)
671         TruncTysMap[I].push_back(I->getOperand(i)->getType());
672     }
673   }
674   for (auto *V : Visited) {
675     if (!isa<TruncInst>(V) || Sources.count(V))
676       continue;
677     auto *Trunc = cast<TruncInst>(V);
678     TruncTysMap[Trunc].push_back(Trunc->getDestTy());
679   }
680 
681   // Convert adds using negative immediates to equivalent instructions that use
682   // positive constants.
683   PrepareWrappingAdds();
684 
685   // Insert zext instructions between sources and their users.
686   ExtendSources();
687 
688   // Promote visited instructions, mutating their types in place.
689   PromoteTree();
690 
691   // Convert any truncs, that aren't sources, into AND masks.
692   ConvertTruncs();
693 
694   // Insert trunc instructions for use by calls, stores etc...
695   TruncateSinks();
696 
697   // Finally, remove unecessary zexts and truncs, delete old instructions and
698   // clear the data structures.
699   Cleanup();
700 
701   LLVM_DEBUG(dbgs() << "IR Promotion: Mutation complete\n");
702 }
703 
704 /// We disallow booleans to make life easier when dealing with icmps but allow
705 /// any other integer that fits in a scalar register. Void types are accepted
706 /// so we can handle switches.
707 bool TypePromotion::isSupportedType(Value *V) {
708   Type *Ty = V->getType();
709 
710   // Allow voids and pointers, these won't be promoted.
711   if (Ty->isVoidTy() || Ty->isPointerTy())
712     return true;
713 
714   if (!isa<IntegerType>(Ty) ||
715       cast<IntegerType>(Ty)->getBitWidth() == 1 ||
716       cast<IntegerType>(Ty)->getBitWidth() > RegisterBitWidth)
717     return false;
718 
719   return LessOrEqualTypeSize(V);
720 }
721 
722 /// We accept most instructions, as well as Arguments and ConstantInsts. We
723 /// Disallow casts other than zext and truncs and only allow calls if their
724 /// return value is zeroext. We don't allow opcodes that can introduce sign
725 /// bits.
726 bool TypePromotion::isSupportedValue(Value *V) {
727   if (auto *I = dyn_cast<Instruction>(V)) {
728     switch (I->getOpcode()) {
729     default:
730       return isa<BinaryOperator>(I) && isSupportedType(I) &&
731              !GenerateSignBits(I);
732     case Instruction::GetElementPtr:
733     case Instruction::Store:
734     case Instruction::Br:
735     case Instruction::Switch:
736       return true;
737     case Instruction::PHI:
738     case Instruction::Select:
739     case Instruction::Ret:
740     case Instruction::Load:
741     case Instruction::Trunc:
742     case Instruction::BitCast:
743       return isSupportedType(I);
744     case Instruction::ZExt:
745       return isSupportedType(I->getOperand(0));
746     case Instruction::ICmp:
747       // Now that we allow small types than TypeSize, only allow icmp of
748       // TypeSize because they will require a trunc to be legalised.
749       // TODO: Allow icmp of smaller types, and calculate at the end
750       // whether the transform would be beneficial.
751       if (isa<PointerType>(I->getOperand(0)->getType()))
752         return true;
753       return EqualTypeSize(I->getOperand(0));
754     case Instruction::Call: {
755       // Special cases for calls as we need to check for zeroext
756       // TODO We should accept calls even if they don't have zeroext, as they
757       // can still be sinks.
758       auto *Call = cast<CallInst>(I);
759       return isSupportedType(Call) &&
760              Call->hasRetAttr(Attribute::AttrKind::ZExt);
761     }
762     }
763   } else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) {
764     return isSupportedType(V);
765   } else if (isa<Argument>(V))
766     return isSupportedType(V);
767 
768   return isa<BasicBlock>(V);
769 }
770 
771 /// Check that the type of V would be promoted and that the original type is
772 /// smaller than the targeted promoted type. Check that we're not trying to
773 /// promote something larger than our base 'TypeSize' type.
774 bool TypePromotion::isLegalToPromote(Value *V) {
775 
776   auto *I = dyn_cast<Instruction>(V);
777   if (!I)
778     return true;
779 
780   if (SafeToPromote.count(I))
781    return true;
782 
783   if (isPromotedResultSafe(I) || isSafeWrap(I)) {
784     SafeToPromote.insert(I);
785     return true;
786   }
787   return false;
788 }
789 
790 bool TypePromotion::TryToPromote(Value *V, unsigned PromotedWidth) {
791   Type *OrigTy = V->getType();
792   TypeSize = OrigTy->getPrimitiveSizeInBits().getFixedSize();
793   SafeToPromote.clear();
794   SafeWrap.clear();
795 
796   if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V))
797     return false;
798 
799   LLVM_DEBUG(dbgs() << "IR Promotion: TryToPromote: " << *V << ", from "
800              << TypeSize << " bits to " << PromotedWidth << "\n");
801 
802   SetVector<Value*> WorkList;
803   SetVector<Value*> Sources;
804   SetVector<Instruction*> Sinks;
805   SetVector<Value*> CurrentVisited;
806   WorkList.insert(V);
807 
808   // Return true if V was added to the worklist as a supported instruction,
809   // if it was already visited, or if we don't need to explore it (e.g.
810   // pointer values and GEPs), and false otherwise.
811   auto AddLegalInst = [&](Value *V) {
812     if (CurrentVisited.count(V))
813       return true;
814 
815     // Ignore GEPs because they don't need promoting and the constant indices
816     // will prevent the transformation.
817     if (isa<GetElementPtrInst>(V))
818       return true;
819 
820     if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) {
821       LLVM_DEBUG(dbgs() << "IR Promotion: Can't handle: " << *V << "\n");
822       return false;
823     }
824 
825     WorkList.insert(V);
826     return true;
827   };
828 
829   // Iterate through, and add to, a tree of operands and users in the use-def.
830   while (!WorkList.empty()) {
831     Value *V = WorkList.pop_back_val();
832     if (CurrentVisited.count(V))
833       continue;
834 
835     // Ignore non-instructions, other than arguments.
836     if (!isa<Instruction>(V) && !isSource(V))
837       continue;
838 
839     // If we've already visited this value from somewhere, bail now because
840     // the tree has already been explored.
841     // TODO: This could limit the transform, ie if we try to promote something
842     // from an i8 and fail first, before trying an i16.
843     if (AllVisited.count(V))
844       return false;
845 
846     CurrentVisited.insert(V);
847     AllVisited.insert(V);
848 
849     // Calls can be both sources and sinks.
850     if (isSink(V))
851       Sinks.insert(cast<Instruction>(V));
852 
853     if (isSource(V))
854       Sources.insert(V);
855 
856     if (!isSink(V) && !isSource(V)) {
857       if (auto *I = dyn_cast<Instruction>(V)) {
858         // Visit operands of any instruction visited.
859         for (auto &U : I->operands()) {
860           if (!AddLegalInst(U))
861             return false;
862         }
863       }
864     }
865 
866     // Don't visit users of a node which isn't going to be mutated unless its a
867     // source.
868     if (isSource(V) || shouldPromote(V)) {
869       for (Use &U : V->uses()) {
870         if (!AddLegalInst(U.getUser()))
871           return false;
872       }
873     }
874   }
875 
876   LLVM_DEBUG(dbgs() << "IR Promotion: Visited nodes:\n";
877              for (auto *I : CurrentVisited)
878                I->dump();
879              );
880 
881   unsigned ToPromote = 0;
882   unsigned NonFreeArgs = 0;
883   SmallPtrSet<BasicBlock*, 4> Blocks;
884   for (auto *V : CurrentVisited) {
885     if (auto *I = dyn_cast<Instruction>(V))
886       Blocks.insert(I->getParent());
887 
888     if (Sources.count(V)) {
889       if (auto *Arg = dyn_cast<Argument>(V))
890         if (!Arg->hasZExtAttr() && !Arg->hasSExtAttr())
891           ++NonFreeArgs;
892       continue;
893     }
894 
895     if (Sinks.count(cast<Instruction>(V)))
896       continue;
897      ++ToPromote;
898    }
899 
900   // DAG optimizations should be able to handle these cases better, especially
901   // for function arguments.
902   if (ToPromote < 2 || (Blocks.size() == 1 && (NonFreeArgs > SafeWrap.size())))
903     return false;
904 
905   IRPromoter Promoter(*Ctx, cast<IntegerType>(OrigTy), PromotedWidth,
906                       CurrentVisited, Sources, Sinks, SafeWrap);
907   Promoter.Mutate();
908   return true;
909 }
910 
911 bool TypePromotion::runOnFunction(Function &F) {
912   if (skipFunction(F) || DisablePromotion)
913     return false;
914 
915   LLVM_DEBUG(dbgs() << "IR Promotion: Running on " << F.getName() << "\n");
916 
917   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
918   if (!TPC)
919     return false;
920 
921   AllVisited.clear();
922   SafeToPromote.clear();
923   SafeWrap.clear();
924   bool MadeChange = false;
925   const DataLayout &DL = F.getParent()->getDataLayout();
926   const TargetMachine &TM = TPC->getTM<TargetMachine>();
927   const TargetSubtargetInfo *SubtargetInfo = TM.getSubtargetImpl(F);
928   const TargetLowering *TLI = SubtargetInfo->getTargetLowering();
929   const TargetTransformInfo &TII =
930     getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
931   RegisterBitWidth =
932       TII.getRegisterBitWidth(TargetTransformInfo::RGK_Scalar).getFixedSize();
933   Ctx = &F.getParent()->getContext();
934 
935   // Search up from icmps to try to promote their operands.
936   for (BasicBlock &BB : F) {
937     for (auto &I : BB) {
938       if (AllVisited.count(&I))
939         continue;
940 
941       if (!isa<ICmpInst>(&I))
942         continue;
943 
944       auto *ICmp = cast<ICmpInst>(&I);
945       // Skip signed or pointer compares
946       if (ICmp->isSigned() ||
947           !isa<IntegerType>(ICmp->getOperand(0)->getType()))
948         continue;
949 
950       LLVM_DEBUG(dbgs() << "IR Promotion: Searching from: " << *ICmp << "\n");
951 
952       for (auto &Op : ICmp->operands()) {
953         if (auto *I = dyn_cast<Instruction>(Op)) {
954           EVT SrcVT = TLI->getValueType(DL, I->getType());
955           if (SrcVT.isSimple() && TLI->isTypeLegal(SrcVT.getSimpleVT()))
956             break;
957 
958           if (TLI->getTypeAction(ICmp->getContext(), SrcVT) !=
959               TargetLowering::TypePromoteInteger)
960             break;
961           EVT PromotedVT = TLI->getTypeToTransformTo(ICmp->getContext(), SrcVT);
962           if (RegisterBitWidth < PromotedVT.getFixedSizeInBits()) {
963             LLVM_DEBUG(dbgs() << "IR Promotion: Couldn't find target register "
964                        << "for promoted type\n");
965             break;
966           }
967 
968           MadeChange |= TryToPromote(I, PromotedVT.getFixedSizeInBits());
969           break;
970         }
971       }
972     }
973     LLVM_DEBUG(if (verifyFunction(F, &dbgs())) {
974                 dbgs() << F;
975                 report_fatal_error("Broken function after type promotion");
976                });
977   }
978   if (MadeChange)
979     LLVM_DEBUG(dbgs() << "After TypePromotion: " << F << "\n");
980 
981   AllVisited.clear();
982   SafeToPromote.clear();
983   SafeWrap.clear();
984 
985   return MadeChange;
986 }
987 
988 INITIALIZE_PASS_BEGIN(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
989 INITIALIZE_PASS_END(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false)
990 
991 char TypePromotion::ID = 0;
992 
993 FunctionPass *llvm::createTypePromotionPass() {
994   return new TypePromotion();
995 }
996