InstCombinePHI.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. //===- InstCombinePHI.cpp -------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the visitPHINode function.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "instcombine"
  19. /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
  20. /// adds all have a single use, turn this into a phi and a single binop.
  21. Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
  22. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  23. assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
  24. unsigned Opc = FirstInst->getOpcode();
  25. Value *LHSVal = FirstInst->getOperand(0);
  26. Value *RHSVal = FirstInst->getOperand(1);
  27. Type *LHSType = LHSVal->getType();
  28. Type *RHSType = RHSVal->getType();
  29. bool isNUW = false, isNSW = false, isExact = false;
  30. if (OverflowingBinaryOperator *BO =
  31. dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
  32. isNUW = BO->hasNoUnsignedWrap();
  33. isNSW = BO->hasNoSignedWrap();
  34. } else if (PossiblyExactOperator *PEO =
  35. dyn_cast<PossiblyExactOperator>(FirstInst))
  36. isExact = PEO->isExact();
  37. // Scan to see if all operands are the same opcode, and all have one use.
  38. for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
  39. Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
  40. if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
  41. // Verify type of the LHS matches so we don't fold cmp's of different
  42. // types.
  43. I->getOperand(0)->getType() != LHSType ||
  44. I->getOperand(1)->getType() != RHSType)
  45. return nullptr;
  46. // If they are CmpInst instructions, check their predicates
  47. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  48. if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
  49. return nullptr;
  50. if (isNUW)
  51. isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
  52. if (isNSW)
  53. isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  54. if (isExact)
  55. isExact = cast<PossiblyExactOperator>(I)->isExact();
  56. // Keep track of which operand needs a phi node.
  57. if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
  58. if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
  59. }
  60. // If both LHS and RHS would need a PHI, don't do this transformation,
  61. // because it would increase the number of PHIs entering the block,
  62. // which leads to higher register pressure. This is especially
  63. // bad when the PHIs are in the header of a loop.
  64. if (!LHSVal && !RHSVal)
  65. return nullptr;
  66. // Otherwise, this is safe to transform!
  67. Value *InLHS = FirstInst->getOperand(0);
  68. Value *InRHS = FirstInst->getOperand(1);
  69. PHINode *NewLHS = nullptr, *NewRHS = nullptr;
  70. if (!LHSVal) {
  71. NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
  72. FirstInst->getOperand(0)->getName() + ".pn");
  73. NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
  74. InsertNewInstBefore(NewLHS, PN);
  75. LHSVal = NewLHS;
  76. }
  77. if (!RHSVal) {
  78. NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
  79. FirstInst->getOperand(1)->getName() + ".pn");
  80. NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
  81. InsertNewInstBefore(NewRHS, PN);
  82. RHSVal = NewRHS;
  83. }
  84. // Add all operands to the new PHIs.
  85. if (NewLHS || NewRHS) {
  86. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  87. Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
  88. if (NewLHS) {
  89. Value *NewInLHS = InInst->getOperand(0);
  90. NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
  91. }
  92. if (NewRHS) {
  93. Value *NewInRHS = InInst->getOperand(1);
  94. NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
  95. }
  96. }
  97. }
  98. if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
  99. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  100. LHSVal, RHSVal);
  101. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  102. return NewCI;
  103. }
  104. BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
  105. BinaryOperator *NewBinOp =
  106. BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
  107. if (isNUW) NewBinOp->setHasNoUnsignedWrap();
  108. if (isNSW) NewBinOp->setHasNoSignedWrap();
  109. if (isExact) NewBinOp->setIsExact();
  110. NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
  111. return NewBinOp;
  112. }
  113. Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
  114. GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
  115. SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
  116. FirstInst->op_end());
  117. // This is true if all GEP bases are allocas and if all indices into them are
  118. // constants.
  119. bool AllBasePointersAreAllocas = true;
  120. // We don't want to replace this phi if the replacement would require
  121. // more than one phi, which leads to higher register pressure. This is
  122. // especially bad when the PHIs are in the header of a loop.
  123. bool NeededPhi = false;
  124. bool AllInBounds = true;
  125. // Scan to see if all operands are the same opcode, and all have one use.
  126. for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
  127. GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
  128. if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
  129. GEP->getNumOperands() != FirstInst->getNumOperands())
  130. return nullptr;
  131. AllInBounds &= GEP->isInBounds();
  132. // Keep track of whether or not all GEPs are of alloca pointers.
  133. if (AllBasePointersAreAllocas &&
  134. (!isa<AllocaInst>(GEP->getOperand(0)) ||
  135. !GEP->hasAllConstantIndices()))
  136. AllBasePointersAreAllocas = false;
  137. // Compare the operand lists.
  138. for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
  139. if (FirstInst->getOperand(op) == GEP->getOperand(op))
  140. continue;
  141. // Don't merge two GEPs when two operands differ (introducing phi nodes)
  142. // if one of the PHIs has a constant for the index. The index may be
  143. // substantially cheaper to compute for the constants, so making it a
  144. // variable index could pessimize the path. This also handles the case
  145. // for struct indices, which must always be constant.
  146. if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
  147. isa<ConstantInt>(GEP->getOperand(op)))
  148. return nullptr;
  149. if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
  150. return nullptr;
  151. // If we already needed a PHI for an earlier operand, and another operand
  152. // also requires a PHI, we'd be introducing more PHIs than we're
  153. // eliminating, which increases register pressure on entry to the PHI's
  154. // block.
  155. if (NeededPhi)
  156. return nullptr;
  157. FixedOperands[op] = nullptr; // Needs a PHI.
  158. NeededPhi = true;
  159. }
  160. }
  161. // If all of the base pointers of the PHI'd GEPs are from allocas, don't
  162. // bother doing this transformation. At best, this will just save a bit of
  163. // offset calculation, but all the predecessors will have to materialize the
  164. // stack address into a register anyway. We'd actually rather *clone* the
  165. // load up into the predecessors so that we have a load of a gep of an alloca,
  166. // which can usually all be folded into the load.
  167. if (AllBasePointersAreAllocas)
  168. return nullptr;
  169. // Otherwise, this is safe to transform. Insert PHI nodes for each operand
  170. // that is variable.
  171. SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
  172. bool HasAnyPHIs = false;
  173. for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
  174. if (FixedOperands[i]) continue; // operand doesn't need a phi.
  175. Value *FirstOp = FirstInst->getOperand(i);
  176. PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
  177. FirstOp->getName()+".pn");
  178. InsertNewInstBefore(NewPN, PN);
  179. NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
  180. OperandPhis[i] = NewPN;
  181. FixedOperands[i] = NewPN;
  182. HasAnyPHIs = true;
  183. }
  184. // Add all operands to the new PHIs.
  185. if (HasAnyPHIs) {
  186. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  187. GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
  188. BasicBlock *InBB = PN.getIncomingBlock(i);
  189. for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
  190. if (PHINode *OpPhi = OperandPhis[op])
  191. OpPhi->addIncoming(InGEP->getOperand(op), InBB);
  192. }
  193. }
  194. Value *Base = FixedOperands[0];
  195. GetElementPtrInst *NewGEP =
  196. GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
  197. makeArrayRef(FixedOperands).slice(1));
  198. if (AllInBounds) NewGEP->setIsInBounds();
  199. NewGEP->setDebugLoc(FirstInst->getDebugLoc());
  200. return NewGEP;
  201. }
  202. /// Return true if we know that it is safe to sink the load out of the block
  203. /// that defines it. This means that it must be obvious the value of the load is
  204. /// not changed from the point of the load to the end of the block it is in.
  205. ///
  206. /// Finally, it is safe, but not profitable, to sink a load targeting a
  207. /// non-address-taken alloca. Doing so will cause us to not promote the alloca
  208. /// to a register.
  209. static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
  210. BasicBlock::iterator BBI = L, E = L->getParent()->end();
  211. for (++BBI; BBI != E; ++BBI)
  212. if (BBI->mayWriteToMemory())
  213. return false;
  214. // Check for non-address taken alloca. If not address-taken already, it isn't
  215. // profitable to do this xform.
  216. if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
  217. bool isAddressTaken = false;
  218. for (User *U : AI->users()) {
  219. if (isa<LoadInst>(U)) continue;
  220. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  221. // If storing TO the alloca, then the address isn't taken.
  222. if (SI->getOperand(1) == AI) continue;
  223. }
  224. isAddressTaken = true;
  225. break;
  226. }
  227. if (!isAddressTaken && AI->isStaticAlloca())
  228. return false;
  229. }
  230. // If this load is a load from a GEP with a constant offset from an alloca,
  231. // then we don't want to sink it. In its present form, it will be
  232. // load [constant stack offset]. Sinking it will cause us to have to
  233. // materialize the stack addresses in each predecessor in a register only to
  234. // do a shared load from register in the successor.
  235. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
  236. if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
  237. if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
  238. return false;
  239. return true;
  240. }
  241. Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
  242. LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
  243. // FIXME: This is overconservative; this transform is allowed in some cases
  244. // for atomic operations.
  245. if (FirstLI->isAtomic())
  246. return nullptr;
  247. // When processing loads, we need to propagate two bits of information to the
  248. // sunk load: whether it is volatile, and what its alignment is. We currently
  249. // don't sink loads when some have their alignment specified and some don't.
  250. // visitLoadInst will propagate an alignment onto the load when TD is around,
  251. // and if TD isn't around, we can't handle the mixed case.
  252. bool isVolatile = FirstLI->isVolatile();
  253. unsigned LoadAlignment = FirstLI->getAlignment();
  254. unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
  255. // HLSL Change Begin.
  256. // Do not create phi on non-default address space.
  257. if (LoadAddrSpace != 0)
  258. return nullptr;
  259. // HLSL Change End.
  260. // We can't sink the load if the loaded value could be modified between the
  261. // load and the PHI.
  262. if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
  263. !isSafeAndProfitableToSinkLoad(FirstLI))
  264. return nullptr;
  265. // If the PHI is of volatile loads and the load block has multiple
  266. // successors, sinking it would remove a load of the volatile value from
  267. // the path through the other successor.
  268. if (isVolatile &&
  269. FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
  270. return nullptr;
  271. // Check to see if all arguments are the same operation.
  272. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  273. LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
  274. if (!LI || !LI->hasOneUse())
  275. return nullptr;
  276. // We can't sink the load if the loaded value could be modified between
  277. // the load and the PHI.
  278. if (LI->isVolatile() != isVolatile ||
  279. LI->getParent() != PN.getIncomingBlock(i) ||
  280. LI->getPointerAddressSpace() != LoadAddrSpace ||
  281. !isSafeAndProfitableToSinkLoad(LI))
  282. return nullptr;
  283. // If some of the loads have an alignment specified but not all of them,
  284. // we can't do the transformation.
  285. if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
  286. return nullptr;
  287. LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
  288. // If the PHI is of volatile loads and the load block has multiple
  289. // successors, sinking it would remove a load of the volatile value from
  290. // the path through the other successor.
  291. if (isVolatile &&
  292. LI->getParent()->getTerminator()->getNumSuccessors() != 1)
  293. return nullptr;
  294. }
  295. // Okay, they are all the same operation. Create a new PHI node of the
  296. // correct type, and PHI together all of the LHS's of the instructions.
  297. PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
  298. PN.getNumIncomingValues(),
  299. PN.getName()+".in");
  300. Value *InVal = FirstLI->getOperand(0);
  301. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  302. // Add all operands to the new PHI.
  303. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  304. Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
  305. if (NewInVal != InVal)
  306. InVal = nullptr;
  307. NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
  308. }
  309. Value *PhiVal;
  310. if (InVal) {
  311. // The new PHI unions all of the same values together. This is really
  312. // common, so we handle it intelligently here for compile-time speed.
  313. PhiVal = InVal;
  314. delete NewPN;
  315. } else {
  316. InsertNewInstBefore(NewPN, PN);
  317. PhiVal = NewPN;
  318. }
  319. // If this was a volatile load that we are merging, make sure to loop through
  320. // and mark all the input loads as non-volatile. If we don't do this, we will
  321. // insert a new volatile load and the old ones will not be deletable.
  322. if (isVolatile)
  323. for (Value *IncValue : PN.incoming_values())
  324. cast<LoadInst>(IncValue)->setVolatile(false);
  325. LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
  326. NewLI->setDebugLoc(FirstLI->getDebugLoc());
  327. return NewLI;
  328. }
  329. /// If all operands to a PHI node are the same "unary" operator and they all are
  330. /// only used by the PHI, PHI together their inputs, and do the operation once,
  331. /// to the result of the PHI.
  332. Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
  333. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  334. if (isa<GetElementPtrInst>(FirstInst))
  335. return FoldPHIArgGEPIntoPHI(PN);
  336. if (isa<LoadInst>(FirstInst))
  337. return FoldPHIArgLoadIntoPHI(PN);
  338. // Scan the instruction, looking for input operations that can be folded away.
  339. // If all input operands to the phi are the same instruction (e.g. a cast from
  340. // the same type or "+42") we can pull the operation through the PHI, reducing
  341. // code size and simplifying code.
  342. Constant *ConstantOp = nullptr;
  343. Type *CastSrcTy = nullptr;
  344. bool isNUW = false, isNSW = false, isExact = false;
  345. if (isa<CastInst>(FirstInst)) {
  346. CastSrcTy = FirstInst->getOperand(0)->getType();
  347. // Be careful about transforming integer PHIs. We don't want to pessimize
  348. // the code by turning an i32 into an i1293.
  349. if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
  350. if (!ShouldChangeType(PN.getType(), CastSrcTy))
  351. return nullptr;
  352. }
  353. } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
  354. // Can fold binop, compare or shift here if the RHS is a constant,
  355. // otherwise call FoldPHIArgBinOpIntoPHI.
  356. ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
  357. if (!ConstantOp)
  358. return FoldPHIArgBinOpIntoPHI(PN);
  359. if (OverflowingBinaryOperator *BO =
  360. dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
  361. isNUW = BO->hasNoUnsignedWrap();
  362. isNSW = BO->hasNoSignedWrap();
  363. } else if (PossiblyExactOperator *PEO =
  364. dyn_cast<PossiblyExactOperator>(FirstInst))
  365. isExact = PEO->isExact();
  366. } else {
  367. return nullptr; // Cannot fold this operation.
  368. }
  369. // Check to see if all arguments are the same operation.
  370. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  371. Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
  372. if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
  373. return nullptr;
  374. if (CastSrcTy) {
  375. if (I->getOperand(0)->getType() != CastSrcTy)
  376. return nullptr; // Cast operation must match.
  377. } else if (I->getOperand(1) != ConstantOp) {
  378. return nullptr;
  379. }
  380. if (isNUW)
  381. isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
  382. if (isNSW)
  383. isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  384. if (isExact)
  385. isExact = cast<PossiblyExactOperator>(I)->isExact();
  386. }
  387. // Okay, they are all the same operation. Create a new PHI node of the
  388. // correct type, and PHI together all of the LHS's of the instructions.
  389. PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
  390. PN.getNumIncomingValues(),
  391. PN.getName()+".in");
  392. Value *InVal = FirstInst->getOperand(0);
  393. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  394. // Add all operands to the new PHI.
  395. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  396. Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
  397. if (NewInVal != InVal)
  398. InVal = nullptr;
  399. NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
  400. }
  401. Value *PhiVal;
  402. if (InVal) {
  403. // The new PHI unions all of the same values together. This is really
  404. // common, so we handle it intelligently here for compile-time speed.
  405. PhiVal = InVal;
  406. delete NewPN;
  407. } else {
  408. InsertNewInstBefore(NewPN, PN);
  409. PhiVal = NewPN;
  410. }
  411. // Insert and return the new operation.
  412. if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
  413. CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
  414. PN.getType());
  415. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  416. return NewCI;
  417. }
  418. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
  419. BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
  420. if (isNUW) BinOp->setHasNoUnsignedWrap();
  421. if (isNSW) BinOp->setHasNoSignedWrap();
  422. if (isExact) BinOp->setIsExact();
  423. BinOp->setDebugLoc(FirstInst->getDebugLoc());
  424. return BinOp;
  425. }
  426. CmpInst *CIOp = cast<CmpInst>(FirstInst);
  427. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  428. PhiVal, ConstantOp);
  429. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  430. return NewCI;
  431. }
  432. /// Return true if this PHI node is only used by a PHI node cycle that is dead.
  433. static bool DeadPHICycle(PHINode *PN,
  434. SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
  435. if (PN->use_empty()) return true;
  436. if (!PN->hasOneUse()) return false;
  437. // Remember this node, and if we find the cycle, return.
  438. if (!PotentiallyDeadPHIs.insert(PN).second)
  439. return true;
  440. // Don't scan crazily complex things.
  441. if (PotentiallyDeadPHIs.size() == 16)
  442. return false;
  443. if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
  444. return DeadPHICycle(PU, PotentiallyDeadPHIs);
  445. return false;
  446. }
  447. /// Return true if this phi node is always equal to NonPhiInVal.
  448. /// This happens with mutually cyclic phi nodes like:
  449. /// z = some value; x = phi (y, z); y = phi (x, z)
  450. static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
  451. SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
  452. // See if we already saw this PHI node.
  453. if (!ValueEqualPHIs.insert(PN).second)
  454. return true;
  455. // Don't scan crazily complex things.
  456. if (ValueEqualPHIs.size() == 16)
  457. return false;
  458. // Scan the operands to see if they are either phi nodes or are equal to
  459. // the value.
  460. for (Value *Op : PN->incoming_values()) {
  461. if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
  462. if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
  463. return false;
  464. } else if (Op != NonPhiInVal)
  465. return false;
  466. }
  467. return true;
  468. }
  469. namespace {
  470. struct PHIUsageRecord {
  471. unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
  472. unsigned Shift; // The amount shifted.
  473. Instruction *Inst; // The trunc instruction.
  474. PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
  475. : PHIId(pn), Shift(Sh), Inst(User) {}
  476. bool operator<(const PHIUsageRecord &RHS) const {
  477. if (PHIId < RHS.PHIId) return true;
  478. if (PHIId > RHS.PHIId) return false;
  479. if (Shift < RHS.Shift) return true;
  480. if (Shift > RHS.Shift) return false;
  481. return Inst->getType()->getPrimitiveSizeInBits() <
  482. RHS.Inst->getType()->getPrimitiveSizeInBits();
  483. }
  484. };
  485. struct LoweredPHIRecord {
  486. PHINode *PN; // The PHI that was lowered.
  487. unsigned Shift; // The amount shifted.
  488. unsigned Width; // The width extracted.
  489. LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
  490. : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
  491. // Ctor form used by DenseMap.
  492. LoweredPHIRecord(PHINode *pn, unsigned Sh)
  493. : PN(pn), Shift(Sh), Width(0) {}
  494. };
  495. }
  496. namespace llvm {
  497. template<>
  498. struct DenseMapInfo<LoweredPHIRecord> {
  499. static inline LoweredPHIRecord getEmptyKey() {
  500. return LoweredPHIRecord(nullptr, 0);
  501. }
  502. static inline LoweredPHIRecord getTombstoneKey() {
  503. return LoweredPHIRecord(nullptr, 1);
  504. }
  505. static unsigned getHashValue(const LoweredPHIRecord &Val) {
  506. return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
  507. (Val.Width>>3);
  508. }
  509. static bool isEqual(const LoweredPHIRecord &LHS,
  510. const LoweredPHIRecord &RHS) {
  511. return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
  512. LHS.Width == RHS.Width;
  513. }
  514. };
  515. }
  516. /// This is an integer PHI and we know that it has an illegal type: see if it is
  517. /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
  518. /// the various pieces being extracted. This sort of thing is introduced when
  519. /// SROA promotes an aggregate to large integer values.
  520. ///
  521. /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
  522. /// inttoptr. We should produce new PHIs in the right type.
  523. ///
  524. Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
  525. // PHIUsers - Keep track of all of the truncated values extracted from a set
  526. // of PHIs, along with their offset. These are the things we want to rewrite.
  527. SmallVector<PHIUsageRecord, 16> PHIUsers;
  528. // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
  529. // nodes which are extracted from. PHIsToSlice is a set we use to avoid
  530. // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
  531. // check the uses of (to ensure they are all extracts).
  532. SmallVector<PHINode*, 8> PHIsToSlice;
  533. SmallPtrSet<PHINode*, 8> PHIsInspected;
  534. PHIsToSlice.push_back(&FirstPhi);
  535. PHIsInspected.insert(&FirstPhi);
  536. for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
  537. PHINode *PN = PHIsToSlice[PHIId];
  538. // Scan the input list of the PHI. If any input is an invoke, and if the
  539. // input is defined in the predecessor, then we won't be split the critical
  540. // edge which is required to insert a truncate. Because of this, we have to
  541. // bail out.
  542. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  543. InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
  544. if (!II) continue;
  545. if (II->getParent() != PN->getIncomingBlock(i))
  546. continue;
  547. // If we have a phi, and if it's directly in the predecessor, then we have
  548. // a critical edge where we need to put the truncate. Since we can't
  549. // split the edge in instcombine, we have to bail out.
  550. return nullptr;
  551. }
  552. for (User *U : PN->users()) {
  553. Instruction *UserI = cast<Instruction>(U);
  554. // If the user is a PHI, inspect its uses recursively.
  555. if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
  556. if (PHIsInspected.insert(UserPN).second)
  557. PHIsToSlice.push_back(UserPN);
  558. continue;
  559. }
  560. // Truncates are always ok.
  561. if (isa<TruncInst>(UserI)) {
  562. PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
  563. continue;
  564. }
  565. // Otherwise it must be a lshr which can only be used by one trunc.
  566. if (UserI->getOpcode() != Instruction::LShr ||
  567. !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
  568. !isa<ConstantInt>(UserI->getOperand(1)))
  569. return nullptr;
  570. unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
  571. PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
  572. }
  573. }
  574. // If we have no users, they must be all self uses, just nuke the PHI.
  575. if (PHIUsers.empty())
  576. return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
  577. // If this phi node is transformable, create new PHIs for all the pieces
  578. // extracted out of it. First, sort the users by their offset and size.
  579. array_pod_sort(PHIUsers.begin(), PHIUsers.end());
  580. DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
  581. for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
  582. dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
  583. );
  584. // PredValues - This is a temporary used when rewriting PHI nodes. It is
  585. // hoisted out here to avoid construction/destruction thrashing.
  586. DenseMap<BasicBlock*, Value*> PredValues;
  587. // ExtractedVals - Each new PHI we introduce is saved here so we don't
  588. // introduce redundant PHIs.
  589. DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
  590. for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
  591. unsigned PHIId = PHIUsers[UserI].PHIId;
  592. PHINode *PN = PHIsToSlice[PHIId];
  593. unsigned Offset = PHIUsers[UserI].Shift;
  594. Type *Ty = PHIUsers[UserI].Inst->getType();
  595. PHINode *EltPHI;
  596. // If we've already lowered a user like this, reuse the previously lowered
  597. // value.
  598. if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
  599. // Otherwise, Create the new PHI node for this user.
  600. EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
  601. PN->getName()+".off"+Twine(Offset), PN);
  602. assert(EltPHI->getType() != PN->getType() &&
  603. "Truncate didn't shrink phi?");
  604. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  605. BasicBlock *Pred = PN->getIncomingBlock(i);
  606. Value *&PredVal = PredValues[Pred];
  607. // If we already have a value for this predecessor, reuse it.
  608. if (PredVal) {
  609. EltPHI->addIncoming(PredVal, Pred);
  610. continue;
  611. }
  612. // Handle the PHI self-reuse case.
  613. Value *InVal = PN->getIncomingValue(i);
  614. if (InVal == PN) {
  615. PredVal = EltPHI;
  616. EltPHI->addIncoming(PredVal, Pred);
  617. continue;
  618. }
  619. if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
  620. // If the incoming value was a PHI, and if it was one of the PHIs we
  621. // already rewrote it, just use the lowered value.
  622. if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
  623. PredVal = Res;
  624. EltPHI->addIncoming(PredVal, Pred);
  625. continue;
  626. }
  627. }
  628. // Otherwise, do an extract in the predecessor.
  629. Builder->SetInsertPoint(Pred, Pred->getTerminator());
  630. Value *Res = InVal;
  631. if (Offset)
  632. Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
  633. Offset), "extract");
  634. Res = Builder->CreateTrunc(Res, Ty, "extract.t");
  635. PredVal = Res;
  636. EltPHI->addIncoming(Res, Pred);
  637. // If the incoming value was a PHI, and if it was one of the PHIs we are
  638. // rewriting, we will ultimately delete the code we inserted. This
  639. // means we need to revisit that PHI to make sure we extract out the
  640. // needed piece.
  641. if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
  642. if (PHIsInspected.count(OldInVal)) {
  643. unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
  644. OldInVal)-PHIsToSlice.begin();
  645. PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
  646. cast<Instruction>(Res)));
  647. ++UserE;
  648. }
  649. }
  650. PredValues.clear();
  651. DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
  652. << *EltPHI << '\n');
  653. ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
  654. }
  655. // Replace the use of this piece with the PHI node.
  656. ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
  657. }
  658. // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
  659. // with undefs.
  660. Value *Undef = UndefValue::get(FirstPhi.getType());
  661. for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
  662. ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
  663. return ReplaceInstUsesWith(FirstPhi, Undef);
  664. }
  665. // PHINode simplification
  666. //
  667. Instruction *InstCombiner::visitPHINode(PHINode &PN) {
  668. if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
  669. return ReplaceInstUsesWith(PN, V);
  670. // If all PHI operands are the same operation, pull them through the PHI,
  671. // reducing code size.
  672. if (isa<Instruction>(PN.getIncomingValue(0)) &&
  673. isa<Instruction>(PN.getIncomingValue(1)) &&
  674. cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
  675. cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
  676. // FIXME: The hasOneUse check will fail for PHIs that use the value more
  677. // than themselves more than once.
  678. PN.getIncomingValue(0)->hasOneUse())
  679. if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
  680. return Result;
  681. // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
  682. // this PHI only has a single use (a PHI), and if that PHI only has one use (a
  683. // PHI)... break the cycle.
  684. if (PN.hasOneUse()) {
  685. Instruction *PHIUser = cast<Instruction>(PN.user_back());
  686. if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
  687. SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
  688. PotentiallyDeadPHIs.insert(&PN);
  689. if (DeadPHICycle(PU, PotentiallyDeadPHIs))
  690. return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
  691. }
  692. // If this phi has a single use, and if that use just computes a value for
  693. // the next iteration of a loop, delete the phi. This occurs with unused
  694. // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
  695. // common case here is good because the only other things that catch this
  696. // are induction variable analysis (sometimes) and ADCE, which is only run
  697. // late.
  698. if (PHIUser->hasOneUse() &&
  699. (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
  700. PHIUser->user_back() == &PN) {
  701. return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
  702. }
  703. }
  704. // We sometimes end up with phi cycles that non-obviously end up being the
  705. // same value, for example:
  706. // z = some value; x = phi (y, z); y = phi (x, z)
  707. // where the phi nodes don't necessarily need to be in the same block. Do a
  708. // quick check to see if the PHI node only contains a single non-phi value, if
  709. // so, scan to see if the phi cycle is actually equal to that value.
  710. {
  711. unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
  712. // Scan for the first non-phi operand.
  713. while (InValNo != NumIncomingVals &&
  714. isa<PHINode>(PN.getIncomingValue(InValNo)))
  715. ++InValNo;
  716. if (InValNo != NumIncomingVals) {
  717. Value *NonPhiInVal = PN.getIncomingValue(InValNo);
  718. // Scan the rest of the operands to see if there are any conflicts, if so
  719. // there is no need to recursively scan other phis.
  720. for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
  721. Value *OpVal = PN.getIncomingValue(InValNo);
  722. if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
  723. break;
  724. }
  725. // If we scanned over all operands, then we have one unique value plus
  726. // phi values. Scan PHI nodes to see if they all merge in each other or
  727. // the value.
  728. if (InValNo == NumIncomingVals) {
  729. SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
  730. if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
  731. return ReplaceInstUsesWith(PN, NonPhiInVal);
  732. }
  733. }
  734. }
  735. // If there are multiple PHIs, sort their operands so that they all list
  736. // the blocks in the same order. This will help identical PHIs be eliminated
  737. // by other passes. Other passes shouldn't depend on this for correctness
  738. // however.
  739. PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
  740. if (&PN != FirstPN)
  741. for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
  742. BasicBlock *BBA = PN.getIncomingBlock(i);
  743. BasicBlock *BBB = FirstPN->getIncomingBlock(i);
  744. if (BBA != BBB) {
  745. Value *VA = PN.getIncomingValue(i);
  746. unsigned j = PN.getBasicBlockIndex(BBB);
  747. Value *VB = PN.getIncomingValue(j);
  748. PN.setIncomingBlock(i, BBB);
  749. PN.setIncomingValue(i, VB);
  750. PN.setIncomingBlock(j, BBA);
  751. PN.setIncomingValue(j, VA);
  752. // NOTE: Instcombine normally would want us to "return &PN" if we
  753. // modified any of the operands of an instruction. However, since we
  754. // aren't adding or removing uses (just rearranging them) we don't do
  755. // this in this case.
  756. }
  757. }
  758. // If this is an integer PHI and we know that it has an illegal type, see if
  759. // it is only used by trunc or trunc(lshr) operations. If so, we split the
  760. // PHI into the various pieces being extracted. This sort of thing is
  761. // introduced when SROA promotes an aggregate to a single large integer type.
  762. if (PN.getType()->isIntegerTy() &&
  763. !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
  764. if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
  765. return Res;
  766. return nullptr;
  767. }