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