Local.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  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 family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/GlobalAlias.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/IntrinsicInst.h"
  22. #include "llvm/Metadata.h"
  23. #include "llvm/Operator.h"
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/Analysis/DebugInfo.h"
  27. #include "llvm/Analysis/DIBuilder.h"
  28. #include "llvm/Analysis/Dominators.h"
  29. #include "llvm/Analysis/InstructionSimplify.h"
  30. #include "llvm/Analysis/MemoryBuiltins.h"
  31. #include "llvm/Analysis/ProfileInfo.h"
  32. #include "llvm/Analysis/ValueTracking.h"
  33. #include "llvm/Target/TargetData.h"
  34. #include "llvm/Support/CFG.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/GetElementPtrTypeIterator.h"
  37. #include "llvm/Support/IRBuilder.h"
  38. #include "llvm/Support/MathExtras.h"
  39. #include "llvm/Support/ValueHandle.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. using namespace llvm;
  42. //===----------------------------------------------------------------------===//
  43. // Local constant propagation.
  44. //
  45. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  46. /// constant value, convert it into an unconditional branch to the constant
  47. /// destination. This is a nontrivial operation because the successors of this
  48. /// basic block must have their PHI nodes updated.
  49. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  50. /// conditions and indirectbr addresses this might make dead if
  51. /// DeleteDeadConditions is true.
  52. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions) {
  53. TerminatorInst *T = BB->getTerminator();
  54. IRBuilder<> Builder(T);
  55. // Branch - See if we are conditional jumping on constant
  56. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  57. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  58. BasicBlock *Dest1 = BI->getSuccessor(0);
  59. BasicBlock *Dest2 = BI->getSuccessor(1);
  60. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  61. // Are we branching on constant?
  62. // YES. Change to unconditional branch...
  63. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  64. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  65. //cerr << "Function: " << T->getParent()->getParent()
  66. // << "\nRemoving branch from " << T->getParent()
  67. // << "\n\nTo: " << OldDest << endl;
  68. // Let the basic block know that we are letting go of it. Based on this,
  69. // it will adjust it's PHI nodes.
  70. OldDest->removePredecessor(BB);
  71. // Replace the conditional branch with an unconditional one.
  72. Builder.CreateBr(Destination);
  73. BI->eraseFromParent();
  74. return true;
  75. }
  76. if (Dest2 == Dest1) { // Conditional branch to same location?
  77. // This branch matches something like this:
  78. // br bool %cond, label %Dest, label %Dest
  79. // and changes it into: br label %Dest
  80. // Let the basic block know that we are letting go of one copy of it.
  81. assert(BI->getParent() && "Terminator not inserted in block!");
  82. Dest1->removePredecessor(BI->getParent());
  83. // Replace the conditional branch with an unconditional one.
  84. Builder.CreateBr(Dest1);
  85. Value *Cond = BI->getCondition();
  86. BI->eraseFromParent();
  87. if (DeleteDeadConditions)
  88. RecursivelyDeleteTriviallyDeadInstructions(Cond);
  89. return true;
  90. }
  91. return false;
  92. }
  93. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  94. // If we are switching on a constant, we can convert the switch into a
  95. // single branch instruction!
  96. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  97. BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
  98. BasicBlock *DefaultDest = TheOnlyDest;
  99. assert(TheOnlyDest == SI->getDefaultDest() &&
  100. "Default destination is not successor #0?");
  101. // Figure out which case it goes to.
  102. for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
  103. // Found case matching a constant operand?
  104. if (SI->getSuccessorValue(i) == CI) {
  105. TheOnlyDest = SI->getSuccessor(i);
  106. break;
  107. }
  108. // Check to see if this branch is going to the same place as the default
  109. // dest. If so, eliminate it as an explicit compare.
  110. if (SI->getSuccessor(i) == DefaultDest) {
  111. // Remove this entry.
  112. DefaultDest->removePredecessor(SI->getParent());
  113. SI->removeCase(i);
  114. --i; --e; // Don't skip an entry...
  115. continue;
  116. }
  117. // Otherwise, check to see if the switch only branches to one destination.
  118. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  119. // destinations.
  120. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
  121. }
  122. if (CI && !TheOnlyDest) {
  123. // Branching on a constant, but not any of the cases, go to the default
  124. // successor.
  125. TheOnlyDest = SI->getDefaultDest();
  126. }
  127. // If we found a single destination that we can fold the switch into, do so
  128. // now.
  129. if (TheOnlyDest) {
  130. // Insert the new branch.
  131. Builder.CreateBr(TheOnlyDest);
  132. BasicBlock *BB = SI->getParent();
  133. // Remove entries from PHI nodes which we no longer branch to...
  134. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  135. // Found case matching a constant operand?
  136. BasicBlock *Succ = SI->getSuccessor(i);
  137. if (Succ == TheOnlyDest)
  138. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  139. else
  140. Succ->removePredecessor(BB);
  141. }
  142. // Delete the old switch.
  143. Value *Cond = SI->getCondition();
  144. SI->eraseFromParent();
  145. if (DeleteDeadConditions)
  146. RecursivelyDeleteTriviallyDeadInstructions(Cond);
  147. return true;
  148. }
  149. if (SI->getNumSuccessors() == 2) {
  150. // Otherwise, we can fold this switch into a conditional branch
  151. // instruction if it has only one non-default destination.
  152. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  153. SI->getSuccessorValue(1), "cond");
  154. // Insert the new branch.
  155. Builder.CreateCondBr(Cond, SI->getSuccessor(1), SI->getSuccessor(0));
  156. // Delete the old switch.
  157. SI->eraseFromParent();
  158. return true;
  159. }
  160. return false;
  161. }
  162. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  163. // indirectbr blockaddress(@F, @BB) -> br label @BB
  164. if (BlockAddress *BA =
  165. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  166. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  167. // Insert the new branch.
  168. Builder.CreateBr(TheOnlyDest);
  169. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  170. if (IBI->getDestination(i) == TheOnlyDest)
  171. TheOnlyDest = 0;
  172. else
  173. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  174. }
  175. Value *Address = IBI->getAddress();
  176. IBI->eraseFromParent();
  177. if (DeleteDeadConditions)
  178. RecursivelyDeleteTriviallyDeadInstructions(Address);
  179. // If we didn't find our destination in the IBI successor list, then we
  180. // have undefined behavior. Replace the unconditional branch with an
  181. // 'unreachable' instruction.
  182. if (TheOnlyDest) {
  183. BB->getTerminator()->eraseFromParent();
  184. new UnreachableInst(BB->getContext(), BB);
  185. }
  186. return true;
  187. }
  188. }
  189. return false;
  190. }
  191. //===----------------------------------------------------------------------===//
  192. // Local dead code elimination.
  193. //
  194. /// isInstructionTriviallyDead - Return true if the result produced by the
  195. /// instruction is not used, and the instruction has no side effects.
  196. ///
  197. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  198. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  199. // We don't want the landingpad instruction removed by anything this general.
  200. if (isa<LandingPadInst>(I))
  201. return false;
  202. // We don't want debug info removed by anything this general, unless
  203. // debug info is empty.
  204. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  205. if (DDI->getAddress())
  206. return false;
  207. return true;
  208. }
  209. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  210. if (DVI->getValue())
  211. return false;
  212. return true;
  213. }
  214. if (!I->mayHaveSideEffects()) return true;
  215. // Special case intrinsics that "may have side effects" but can be deleted
  216. // when dead.
  217. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  218. // Safe to delete llvm.stacksave if dead.
  219. if (II->getIntrinsicID() == Intrinsic::stacksave)
  220. return true;
  221. // Lifetime intrinsics are dead when their right-hand is undef.
  222. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  223. II->getIntrinsicID() == Intrinsic::lifetime_end)
  224. return isa<UndefValue>(II->getArgOperand(1));
  225. }
  226. if (extractMallocCall(I)) return true;
  227. if (CallInst *CI = isFreeCall(I))
  228. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  229. return C->isNullValue() || isa<UndefValue>(C);
  230. return false;
  231. }
  232. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  233. /// trivially dead instruction, delete it. If that makes any of its operands
  234. /// trivially dead, delete them too, recursively. Return true if any
  235. /// instructions were deleted.
  236. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
  237. Instruction *I = dyn_cast<Instruction>(V);
  238. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
  239. return false;
  240. SmallVector<Instruction*, 16> DeadInsts;
  241. DeadInsts.push_back(I);
  242. do {
  243. I = DeadInsts.pop_back_val();
  244. // Null out all of the instruction's operands to see if any operand becomes
  245. // dead as we go.
  246. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  247. Value *OpV = I->getOperand(i);
  248. I->setOperand(i, 0);
  249. if (!OpV->use_empty()) continue;
  250. // If the operand is an instruction that became dead as we nulled out the
  251. // operand, and if it is 'trivially' dead, delete it in a future loop
  252. // iteration.
  253. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  254. if (isInstructionTriviallyDead(OpI))
  255. DeadInsts.push_back(OpI);
  256. }
  257. I->eraseFromParent();
  258. } while (!DeadInsts.empty());
  259. return true;
  260. }
  261. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  262. /// This is similar to Instruction::hasOneUse() except this will also return
  263. /// true when there are no uses or multiple uses that all refer to the same
  264. /// value.
  265. static bool areAllUsesEqual(Instruction *I) {
  266. Value::use_iterator UI = I->use_begin();
  267. Value::use_iterator UE = I->use_end();
  268. if (UI == UE)
  269. return true;
  270. User *TheUse = *UI;
  271. for (++UI; UI != UE; ++UI) {
  272. if (*UI != TheUse)
  273. return false;
  274. }
  275. return true;
  276. }
  277. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  278. /// dead PHI node, due to being a def-use chain of single-use nodes that
  279. /// either forms a cycle or is terminated by a trivially dead instruction,
  280. /// delete it. If that makes any of its operands trivially dead, delete them
  281. /// too, recursively. Return true if a change was made.
  282. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
  283. SmallPtrSet<Instruction*, 4> Visited;
  284. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  285. I = cast<Instruction>(*I->use_begin())) {
  286. if (I->use_empty())
  287. return RecursivelyDeleteTriviallyDeadInstructions(I);
  288. // If we find an instruction more than once, we're on a cycle that
  289. // won't prove fruitful.
  290. if (!Visited.insert(I)) {
  291. // Break the cycle and delete the instruction and its operands.
  292. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  293. (void)RecursivelyDeleteTriviallyDeadInstructions(I);
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  300. /// simplify any instructions in it and recursively delete dead instructions.
  301. ///
  302. /// This returns true if it changed the code, note that it can delete
  303. /// instructions in other blocks as well in this block.
  304. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
  305. bool MadeChange = false;
  306. for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
  307. Instruction *Inst = BI++;
  308. if (Value *V = SimplifyInstruction(Inst, TD)) {
  309. WeakVH BIHandle(BI);
  310. ReplaceAndSimplifyAllUses(Inst, V, TD);
  311. MadeChange = true;
  312. if (BIHandle != BI)
  313. BI = BB->begin();
  314. continue;
  315. }
  316. if (Inst->isTerminator())
  317. break;
  318. WeakVH BIHandle(BI);
  319. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
  320. if (BIHandle != BI)
  321. BI = BB->begin();
  322. }
  323. return MadeChange;
  324. }
  325. //===----------------------------------------------------------------------===//
  326. // Control Flow Graph Restructuring.
  327. //
  328. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  329. /// method is called when we're about to delete Pred as a predecessor of BB. If
  330. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  331. ///
  332. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  333. /// nodes that collapse into identity values. For example, if we have:
  334. /// x = phi(1, 0, 0, 0)
  335. /// y = and x, z
  336. ///
  337. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  338. /// recursively fold the and to 0.
  339. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  340. TargetData *TD) {
  341. // This only adjusts blocks with PHI nodes.
  342. if (!isa<PHINode>(BB->begin()))
  343. return;
  344. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  345. // them down. This will leave us with single entry phi nodes and other phis
  346. // that can be removed.
  347. BB->removePredecessor(Pred, true);
  348. WeakVH PhiIt = &BB->front();
  349. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  350. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  351. Value *PNV = SimplifyInstruction(PN, TD);
  352. if (PNV == 0) continue;
  353. // If we're able to simplify the phi to a single value, substitute the new
  354. // value into all of its uses.
  355. assert(PNV != PN && "SimplifyInstruction broken!");
  356. Value *OldPhiIt = PhiIt;
  357. ReplaceAndSimplifyAllUses(PN, PNV, TD);
  358. // If recursive simplification ended up deleting the next PHI node we would
  359. // iterate to, then our iterator is invalid, restart scanning from the top
  360. // of the block.
  361. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  362. }
  363. }
  364. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  365. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  366. /// between them, moving the instructions in the predecessor into DestBB and
  367. /// deleting the predecessor block.
  368. ///
  369. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
  370. // If BB has single-entry PHI nodes, fold them.
  371. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  372. Value *NewVal = PN->getIncomingValue(0);
  373. // Replace self referencing PHI with undef, it must be dead.
  374. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  375. PN->replaceAllUsesWith(NewVal);
  376. PN->eraseFromParent();
  377. }
  378. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  379. assert(PredBB && "Block doesn't have a single predecessor!");
  380. // Zap anything that took the address of DestBB. Not doing this will give the
  381. // address an invalid value.
  382. if (DestBB->hasAddressTaken()) {
  383. BlockAddress *BA = BlockAddress::get(DestBB);
  384. Constant *Replacement =
  385. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  386. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  387. BA->getType()));
  388. BA->destroyConstant();
  389. }
  390. // Anything that branched to PredBB now branches to DestBB.
  391. PredBB->replaceAllUsesWith(DestBB);
  392. // Splice all the instructions from PredBB to DestBB.
  393. PredBB->getTerminator()->eraseFromParent();
  394. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  395. if (P) {
  396. DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
  397. if (DT) {
  398. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  399. DT->changeImmediateDominator(DestBB, PredBBIDom);
  400. DT->eraseNode(PredBB);
  401. }
  402. ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
  403. if (PI) {
  404. PI->replaceAllUses(PredBB, DestBB);
  405. PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
  406. }
  407. }
  408. // Nuke BB.
  409. PredBB->eraseFromParent();
  410. }
  411. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  412. /// almost-empty BB ending in an unconditional branch to Succ, into succ.
  413. ///
  414. /// Assumption: Succ is the single successor for BB.
  415. ///
  416. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  417. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  418. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  419. << Succ->getName() << "\n");
  420. // Shortcut, if there is only a single predecessor it must be BB and merging
  421. // is always safe
  422. if (Succ->getSinglePredecessor()) return true;
  423. // Make a list of the predecessors of BB
  424. typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
  425. BlockSet BBPreds(pred_begin(BB), pred_end(BB));
  426. // Use that list to make another list of common predecessors of BB and Succ
  427. BlockSet CommonPreds;
  428. for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
  429. PI != PE; ++PI) {
  430. BasicBlock *P = *PI;
  431. if (BBPreds.count(P))
  432. CommonPreds.insert(P);
  433. }
  434. // Shortcut, if there are no common predecessors, merging is always safe
  435. if (CommonPreds.empty())
  436. return true;
  437. // Look at all the phi nodes in Succ, to see if they present a conflict when
  438. // merging these blocks
  439. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  440. PHINode *PN = cast<PHINode>(I);
  441. // If the incoming value from BB is again a PHINode in
  442. // BB which has the same incoming value for *PI as PN does, we can
  443. // merge the phi nodes and then the blocks can still be merged
  444. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  445. if (BBPN && BBPN->getParent() == BB) {
  446. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  447. PI != PE; PI++) {
  448. if (BBPN->getIncomingValueForBlock(*PI)
  449. != PN->getIncomingValueForBlock(*PI)) {
  450. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  451. << Succ->getName() << " is conflicting with "
  452. << BBPN->getName() << " with regard to common predecessor "
  453. << (*PI)->getName() << "\n");
  454. return false;
  455. }
  456. }
  457. } else {
  458. Value* Val = PN->getIncomingValueForBlock(BB);
  459. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  460. PI != PE; PI++) {
  461. // See if the incoming value for the common predecessor is equal to the
  462. // one for BB, in which case this phi node will not prevent the merging
  463. // of the block.
  464. if (Val != PN->getIncomingValueForBlock(*PI)) {
  465. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  466. << Succ->getName() << " is conflicting with regard to common "
  467. << "predecessor " << (*PI)->getName() << "\n");
  468. return false;
  469. }
  470. }
  471. }
  472. }
  473. return true;
  474. }
  475. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  476. /// unconditional branch, and contains no instructions other than PHI nodes,
  477. /// potential side-effect free intrinsics and the branch. If possible,
  478. /// eliminate BB by rewriting all the predecessors to branch to the successor
  479. /// block and return true. If we can't transform, return false.
  480. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  481. assert(BB != &BB->getParent()->getEntryBlock() &&
  482. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  483. // We can't eliminate infinite loops.
  484. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  485. if (BB == Succ) return false;
  486. // Check to see if merging these blocks would cause conflicts for any of the
  487. // phi nodes in BB or Succ. If not, we can safely merge.
  488. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  489. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  490. // has uses which will not disappear when the PHI nodes are merged. It is
  491. // possible to handle such cases, but difficult: it requires checking whether
  492. // BB dominates Succ, which is non-trivial to calculate in the case where
  493. // Succ has multiple predecessors. Also, it requires checking whether
  494. // constructing the necessary self-referential PHI node doesn't intoduce any
  495. // conflicts; this isn't too difficult, but the previous code for doing this
  496. // was incorrect.
  497. //
  498. // Note that if this check finds a live use, BB dominates Succ, so BB is
  499. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  500. // folding the branch isn't profitable in that case anyway.
  501. if (!Succ->getSinglePredecessor()) {
  502. BasicBlock::iterator BBI = BB->begin();
  503. while (isa<PHINode>(*BBI)) {
  504. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  505. UI != E; ++UI) {
  506. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  507. if (PN->getIncomingBlock(UI) != BB)
  508. return false;
  509. } else {
  510. return false;
  511. }
  512. }
  513. ++BBI;
  514. }
  515. }
  516. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  517. if (isa<PHINode>(Succ->begin())) {
  518. // If there is more than one pred of succ, and there are PHI nodes in
  519. // the successor, then we need to add incoming edges for the PHI nodes
  520. //
  521. const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  522. // Loop over all of the PHI nodes in the successor of BB.
  523. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  524. PHINode *PN = cast<PHINode>(I);
  525. Value *OldVal = PN->removeIncomingValue(BB, false);
  526. assert(OldVal && "No entry in PHI for Pred BB!");
  527. // If this incoming value is one of the PHI nodes in BB, the new entries
  528. // in the PHI node are the entries from the old PHI.
  529. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  530. PHINode *OldValPN = cast<PHINode>(OldVal);
  531. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
  532. // Note that, since we are merging phi nodes and BB and Succ might
  533. // have common predecessors, we could end up with a phi node with
  534. // identical incoming branches. This will be cleaned up later (and
  535. // will trigger asserts if we try to clean it up now, without also
  536. // simplifying the corresponding conditional branch).
  537. PN->addIncoming(OldValPN->getIncomingValue(i),
  538. OldValPN->getIncomingBlock(i));
  539. } else {
  540. // Add an incoming value for each of the new incoming values.
  541. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
  542. PN->addIncoming(OldVal, BBPreds[i]);
  543. }
  544. }
  545. }
  546. if (Succ->getSinglePredecessor()) {
  547. // BB is the only predecessor of Succ, so Succ will end up with exactly
  548. // the same predecessors BB had.
  549. // Copy over any phi, debug or lifetime instruction.
  550. BB->getTerminator()->eraseFromParent();
  551. Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
  552. } else {
  553. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  554. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  555. assert(PN->use_empty() && "There shouldn't be any uses here!");
  556. PN->eraseFromParent();
  557. }
  558. }
  559. // Everything that jumped to BB now goes to Succ.
  560. BB->replaceAllUsesWith(Succ);
  561. if (!Succ->hasName()) Succ->takeName(BB);
  562. BB->eraseFromParent(); // Delete the old basic block.
  563. return true;
  564. }
  565. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  566. /// nodes in this block. This doesn't try to be clever about PHI nodes
  567. /// which differ only in the order of the incoming values, but instcombine
  568. /// orders them so it usually won't matter.
  569. ///
  570. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  571. bool Changed = false;
  572. // This implementation doesn't currently consider undef operands
  573. // specially. Theoretically, two phis which are identical except for
  574. // one having an undef where the other doesn't could be collapsed.
  575. // Map from PHI hash values to PHI nodes. If multiple PHIs have
  576. // the same hash value, the element is the first PHI in the
  577. // linked list in CollisionMap.
  578. DenseMap<uintptr_t, PHINode *> HashMap;
  579. // Maintain linked lists of PHI nodes with common hash values.
  580. DenseMap<PHINode *, PHINode *> CollisionMap;
  581. // Examine each PHI.
  582. for (BasicBlock::iterator I = BB->begin();
  583. PHINode *PN = dyn_cast<PHINode>(I++); ) {
  584. // Compute a hash value on the operands. Instcombine will likely have sorted
  585. // them, which helps expose duplicates, but we have to check all the
  586. // operands to be safe in case instcombine hasn't run.
  587. uintptr_t Hash = 0;
  588. // This hash algorithm is quite weak as hash functions go, but it seems
  589. // to do a good enough job for this particular purpose, and is very quick.
  590. for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
  591. Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
  592. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  593. }
  594. for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
  595. I != E; ++I) {
  596. Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
  597. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  598. }
  599. // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
  600. Hash >>= 1;
  601. // If we've never seen this hash value before, it's a unique PHI.
  602. std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
  603. HashMap.insert(std::make_pair(Hash, PN));
  604. if (Pair.second) continue;
  605. // Otherwise it's either a duplicate or a hash collision.
  606. for (PHINode *OtherPN = Pair.first->second; ; ) {
  607. if (OtherPN->isIdenticalTo(PN)) {
  608. // A duplicate. Replace this PHI with its duplicate.
  609. PN->replaceAllUsesWith(OtherPN);
  610. PN->eraseFromParent();
  611. Changed = true;
  612. break;
  613. }
  614. // A non-duplicate hash collision.
  615. DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
  616. if (I == CollisionMap.end()) {
  617. // Set this PHI to be the head of the linked list of colliding PHIs.
  618. PHINode *Old = Pair.first->second;
  619. Pair.first->second = PN;
  620. CollisionMap[PN] = Old;
  621. break;
  622. }
  623. // Procede to the next PHI in the list.
  624. OtherPN = I->second;
  625. }
  626. }
  627. return Changed;
  628. }
  629. /// enforceKnownAlignment - If the specified pointer points to an object that
  630. /// we control, modify the object's alignment to PrefAlign. This isn't
  631. /// often possible though. If alignment is important, a more reliable approach
  632. /// is to simply align all global variables and allocation instructions to
  633. /// their preferred alignment from the beginning.
  634. ///
  635. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  636. unsigned PrefAlign, const TargetData *TD) {
  637. V = V->stripPointerCasts();
  638. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  639. // If the preferred alignment is greater than the natural stack alignment
  640. // then don't round up. This avoids dynamic stack realignment.
  641. if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
  642. return Align;
  643. // If there is a requested alignment and if this is an alloca, round up.
  644. if (AI->getAlignment() >= PrefAlign)
  645. return AI->getAlignment();
  646. AI->setAlignment(PrefAlign);
  647. return PrefAlign;
  648. }
  649. if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  650. // If there is a large requested alignment and we can, bump up the alignment
  651. // of the global.
  652. if (GV->isDeclaration()) return Align;
  653. // If the memory we set aside for the global may not be the memory used by
  654. // the final program then it is impossible for us to reliably enforce the
  655. // preferred alignment.
  656. if (GV->isWeakForLinker()) return Align;
  657. if (GV->getAlignment() >= PrefAlign)
  658. return GV->getAlignment();
  659. // We can only increase the alignment of the global if it has no alignment
  660. // specified or if it is not assigned a section. If it is assigned a
  661. // section, the global could be densely packed with other objects in the
  662. // section, increasing the alignment could cause padding issues.
  663. if (!GV->hasSection() || GV->getAlignment() == 0)
  664. GV->setAlignment(PrefAlign);
  665. return GV->getAlignment();
  666. }
  667. return Align;
  668. }
  669. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  670. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  671. /// and it is more than the alignment of the ultimate object, see if we can
  672. /// increase the alignment of the ultimate object, making this check succeed.
  673. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  674. const TargetData *TD) {
  675. assert(V->getType()->isPointerTy() &&
  676. "getOrEnforceKnownAlignment expects a pointer!");
  677. unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
  678. APInt Mask = APInt::getAllOnesValue(BitWidth);
  679. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  680. ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
  681. unsigned TrailZ = KnownZero.countTrailingOnes();
  682. // Avoid trouble with rediculously large TrailZ values, such as
  683. // those computed from a null pointer.
  684. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  685. unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
  686. // LLVM doesn't support alignments larger than this currently.
  687. Align = std::min(Align, +Value::MaximumAlignment);
  688. if (PrefAlign > Align)
  689. Align = enforceKnownAlignment(V, Align, PrefAlign, TD);
  690. // We don't need to make any adjustment.
  691. return Align;
  692. }
  693. ///===---------------------------------------------------------------------===//
  694. /// Dbg Intrinsic utilities
  695. ///
  696. /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
  697. /// that has an associated llvm.dbg.decl intrinsic.
  698. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  699. StoreInst *SI, DIBuilder &Builder) {
  700. DIVariable DIVar(DDI->getVariable());
  701. if (!DIVar.Verify())
  702. return false;
  703. Instruction *DbgVal = NULL;
  704. // If an argument is zero extended then use argument directly. The ZExt
  705. // may be zapped by an optimization pass in future.
  706. Argument *ExtendedArg = NULL;
  707. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  708. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  709. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  710. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  711. if (ExtendedArg)
  712. DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
  713. else
  714. DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
  715. // Propagate any debug metadata from the store onto the dbg.value.
  716. DebugLoc SIDL = SI->getDebugLoc();
  717. if (!SIDL.isUnknown())
  718. DbgVal->setDebugLoc(SIDL);
  719. // Otherwise propagate debug metadata from dbg.declare.
  720. else
  721. DbgVal->setDebugLoc(DDI->getDebugLoc());
  722. return true;
  723. }
  724. /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
  725. /// that has an associated llvm.dbg.decl intrinsic.
  726. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  727. LoadInst *LI, DIBuilder &Builder) {
  728. DIVariable DIVar(DDI->getVariable());
  729. if (!DIVar.Verify())
  730. return false;
  731. Instruction *DbgVal =
  732. Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
  733. DIVar, LI);
  734. // Propagate any debug metadata from the store onto the dbg.value.
  735. DebugLoc LIDL = LI->getDebugLoc();
  736. if (!LIDL.isUnknown())
  737. DbgVal->setDebugLoc(LIDL);
  738. // Otherwise propagate debug metadata from dbg.declare.
  739. else
  740. DbgVal->setDebugLoc(DDI->getDebugLoc());
  741. return true;
  742. }
  743. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  744. /// of llvm.dbg.value intrinsics.
  745. bool llvm::LowerDbgDeclare(Function &F) {
  746. DIBuilder DIB(*F.getParent());
  747. SmallVector<DbgDeclareInst *, 4> Dbgs;
  748. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
  749. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
  750. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
  751. Dbgs.push_back(DDI);
  752. }
  753. if (Dbgs.empty())
  754. return false;
  755. for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
  756. E = Dbgs.end(); I != E; ++I) {
  757. DbgDeclareInst *DDI = *I;
  758. if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
  759. bool RemoveDDI = true;
  760. for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
  761. UI != E; ++UI)
  762. if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
  763. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  764. else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
  765. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  766. else
  767. RemoveDDI = false;
  768. if (RemoveDDI)
  769. DDI->eraseFromParent();
  770. }
  771. }
  772. return true;
  773. }
  774. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
  775. /// alloca 'V', if any.
  776. DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
  777. if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
  778. for (Value::use_iterator UI = DebugNode->use_begin(),
  779. E = DebugNode->use_end(); UI != E; ++UI)
  780. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
  781. return DDI;
  782. return 0;
  783. }