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