JumpThreading.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
  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 Jump Threading pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/CFG.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/LazyValueInfo.h"
  24. #include "llvm/Analysis/Loads.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/ValueHandle.h"
  31. #include "llvm/Pass.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  36. #include "llvm/Transforms/Utils/Local.h"
  37. #include "llvm/Transforms/Utils/SSAUpdater.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "jump-threading"
  40. STATISTIC(NumThreads, "Number of jumps threaded");
  41. STATISTIC(NumFolds, "Number of terminators folded");
  42. STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
  43. #if 0 // HLSL Change Starts - option pending
  44. static cl::opt<unsigned>
  45. BBDuplicateThreshold("jump-threading-threshold",
  46. cl::desc("Max block size to duplicate for jump threading"),
  47. cl::init(6), cl::Hidden);
  48. #else
  49. static const unsigned BBDuplicateThreshold = 6;
  50. #endif // HLSL Change Ends
  51. namespace {
  52. // These are at global scope so static functions can use them too.
  53. typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
  54. typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
  55. // This is used to keep track of what kind of constant we're currently hoping
  56. // to find.
  57. enum ConstantPreference {
  58. WantInteger,
  59. WantBlockAddress
  60. };
  61. /// This pass performs 'jump threading', which looks at blocks that have
  62. /// multiple predecessors and multiple successors. If one or more of the
  63. /// predecessors of the block can be proven to always jump to one of the
  64. /// successors, we forward the edge from the predecessor to the successor by
  65. /// duplicating the contents of this block.
  66. ///
  67. /// An example of when this can occur is code like this:
  68. ///
  69. /// if () { ...
  70. /// X = 4;
  71. /// }
  72. /// if (X < 3) {
  73. ///
  74. /// In this case, the unconditional branch at the end of the first if can be
  75. /// revectored to the false side of the second if.
  76. ///
  77. class JumpThreading : public FunctionPass {
  78. TargetLibraryInfo *TLI;
  79. LazyValueInfo *LVI;
  80. #ifdef NDEBUG
  81. SmallPtrSet<BasicBlock*, 16> LoopHeaders;
  82. #else
  83. SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
  84. #endif
  85. DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
  86. unsigned BBDupThreshold;
  87. // RAII helper for updating the recursion stack.
  88. struct RecursionSetRemover {
  89. DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
  90. std::pair<Value*, BasicBlock*> ThePair;
  91. RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
  92. std::pair<Value*, BasicBlock*> P)
  93. : TheSet(S), ThePair(P) { }
  94. ~RecursionSetRemover() {
  95. TheSet.erase(ThePair);
  96. }
  97. };
  98. public:
  99. static char ID; // Pass identification
  100. JumpThreading(int T = -1) : FunctionPass(ID) {
  101. BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
  102. initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
  103. }
  104. bool runOnFunction(Function &F) override;
  105. void getAnalysisUsage(AnalysisUsage &AU) const override {
  106. AU.addRequired<LazyValueInfo>();
  107. AU.addPreserved<LazyValueInfo>();
  108. AU.addRequired<TargetLibraryInfoWrapperPass>();
  109. }
  110. void FindLoopHeaders(Function &F);
  111. bool ProcessBlock(BasicBlock *BB);
  112. bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
  113. BasicBlock *SuccBB);
  114. bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
  115. const SmallVectorImpl<BasicBlock *> &PredBBs);
  116. bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
  117. PredValueInfo &Result,
  118. ConstantPreference Preference,
  119. Instruction *CxtI = nullptr);
  120. bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
  121. ConstantPreference Preference,
  122. Instruction *CxtI = nullptr);
  123. bool ProcessBranchOnPHI(PHINode *PN);
  124. bool ProcessBranchOnXOR(BinaryOperator *BO);
  125. bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
  126. bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
  127. };
  128. }
  129. char JumpThreading::ID = 0;
  130. INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
  131. "Jump Threading", false, false)
  132. INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
  133. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  134. INITIALIZE_PASS_END(JumpThreading, "jump-threading",
  135. "Jump Threading", false, false)
  136. // Public interface to the Jump Threading pass
  137. FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); }
  138. /// runOnFunction - Top level algorithm.
  139. ///
  140. bool JumpThreading::runOnFunction(Function &F) {
  141. if (skipOptnoneFunction(F))
  142. return false;
  143. DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
  144. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  145. LVI = &getAnalysis<LazyValueInfo>();
  146. // Remove unreachable blocks from function as they may result in infinite
  147. // loop. We do threading if we found something profitable. Jump threading a
  148. // branch can create other opportunities. If these opportunities form a cycle
  149. // i.e. if any jump treading is undoing previous threading in the path, then
  150. // we will loop forever. We take care of this issue by not jump threading for
  151. // back edges. This works for normal cases but not for unreachable blocks as
  152. // they may have cycle with no back edge.
  153. removeUnreachableBlocks(F);
  154. FindLoopHeaders(F);
  155. bool Changed, EverChanged = false;
  156. do {
  157. Changed = false;
  158. for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
  159. BasicBlock *BB = I;
  160. // Thread all of the branches we can over this block.
  161. while (ProcessBlock(BB))
  162. Changed = true;
  163. ++I;
  164. // If the block is trivially dead, zap it. This eliminates the successor
  165. // edges which simplifies the CFG.
  166. if ((pred_empty(BB)
  167. // HLSL change begin - delete self loop.
  168. || BB->getSinglePredecessor() == BB
  169. // HLSL change end.
  170. ) &&
  171. BB != &BB->getParent()->getEntryBlock()) {
  172. DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
  173. << "' with terminator: " << *BB->getTerminator() << '\n');
  174. LoopHeaders.erase(BB);
  175. LVI->eraseBlock(BB);
  176. DeleteDeadBlock(BB);
  177. Changed = true;
  178. continue;
  179. }
  180. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  181. // Can't thread an unconditional jump, but if the block is "almost
  182. // empty", we can replace uses of it with uses of the successor and make
  183. // this dead.
  184. if (BI && BI->isUnconditional() &&
  185. BB != &BB->getParent()->getEntryBlock() &&
  186. // If the terminator is the only non-phi instruction, try to nuke it.
  187. BB->getFirstNonPHIOrDbg()->isTerminator()) {
  188. // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
  189. // block, we have to make sure it isn't in the LoopHeaders set. We
  190. // reinsert afterward if needed.
  191. bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
  192. BasicBlock *Succ = BI->getSuccessor(0);
  193. // FIXME: It is always conservatively correct to drop the info
  194. // for a block even if it doesn't get erased. This isn't totally
  195. // awesome, but it allows us to use AssertingVH to prevent nasty
  196. // dangling pointer issues within LazyValueInfo.
  197. LVI->eraseBlock(BB);
  198. if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
  199. Changed = true;
  200. // If we deleted BB and BB was the header of a loop, then the
  201. // successor is now the header of the loop.
  202. BB = Succ;
  203. }
  204. if (ErasedFromLoopHeaders)
  205. LoopHeaders.insert(BB);
  206. }
  207. }
  208. EverChanged |= Changed;
  209. } while (Changed);
  210. LoopHeaders.clear();
  211. return EverChanged;
  212. }
  213. /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
  214. /// thread across it. Stop scanning the block when passing the threshold.
  215. static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
  216. unsigned Threshold) {
  217. /// Ignore PHI nodes, these will be flattened when duplication happens.
  218. BasicBlock::const_iterator I = BB->getFirstNonPHI();
  219. // FIXME: THREADING will delete values that are just used to compute the
  220. // branch, so they shouldn't count against the duplication cost.
  221. // Sum up the cost of each instruction until we get to the terminator. Don't
  222. // include the terminator because the copy won't include it.
  223. unsigned Size = 0;
  224. for (; !isa<TerminatorInst>(I); ++I) {
  225. // Stop scanning the block if we've reached the threshold.
  226. if (Size > Threshold)
  227. return Size;
  228. // Debugger intrinsics don't incur code size.
  229. if (isa<DbgInfoIntrinsic>(I)) continue;
  230. // If this is a pointer->pointer bitcast, it is free.
  231. if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
  232. continue;
  233. // All other instructions count for at least one unit.
  234. ++Size;
  235. // Calls are more expensive. If they are non-intrinsic calls, we model them
  236. // as having cost of 4. If they are a non-vector intrinsic, we model them
  237. // as having cost of 2 total, and if they are a vector intrinsic, we model
  238. // them as having cost 1.
  239. if (const CallInst *CI = dyn_cast<CallInst>(I)) {
  240. if (CI->cannotDuplicate())
  241. // Blocks with NoDuplicate are modelled as having infinite cost, so they
  242. // are never duplicated.
  243. return ~0U;
  244. else if (!isa<IntrinsicInst>(CI))
  245. Size += 3;
  246. else if (!CI->getType()->isVectorTy())
  247. Size += 1;
  248. }
  249. }
  250. // Threading through a switch statement is particularly profitable. If this
  251. // block ends in a switch, decrease its cost to make it more likely to happen.
  252. if (isa<SwitchInst>(I))
  253. Size = Size > 6 ? Size-6 : 0;
  254. // The same holds for indirect branches, but slightly more so.
  255. if (isa<IndirectBrInst>(I))
  256. Size = Size > 8 ? Size-8 : 0;
  257. return Size;
  258. }
  259. /// FindLoopHeaders - We do not want jump threading to turn proper loop
  260. /// structures into irreducible loops. Doing this breaks up the loop nesting
  261. /// hierarchy and pessimizes later transformations. To prevent this from
  262. /// happening, we first have to find the loop headers. Here we approximate this
  263. /// by finding targets of backedges in the CFG.
  264. ///
  265. /// Note that there definitely are cases when we want to allow threading of
  266. /// edges across a loop header. For example, threading a jump from outside the
  267. /// loop (the preheader) to an exit block of the loop is definitely profitable.
  268. /// It is also almost always profitable to thread backedges from within the loop
  269. /// to exit blocks, and is often profitable to thread backedges to other blocks
  270. /// within the loop (forming a nested loop). This simple analysis is not rich
  271. /// enough to track all of these properties and keep it up-to-date as the CFG
  272. /// mutates, so we don't allow any of these transformations.
  273. ///
  274. void JumpThreading::FindLoopHeaders(Function &F) {
  275. SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
  276. FindFunctionBackedges(F, Edges);
  277. for (unsigned i = 0, e = Edges.size(); i != e; ++i)
  278. LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
  279. }
  280. /// getKnownConstant - Helper method to determine if we can thread over a
  281. /// terminator with the given value as its condition, and if so what value to
  282. /// use for that. What kind of value this is depends on whether we want an
  283. /// integer or a block address, but an undef is always accepted.
  284. /// Returns null if Val is null or not an appropriate constant.
  285. static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
  286. if (!Val)
  287. return nullptr;
  288. // Undef is "known" enough.
  289. if (UndefValue *U = dyn_cast<UndefValue>(Val))
  290. return U;
  291. if (Preference == WantBlockAddress)
  292. return dyn_cast<BlockAddress>(Val->stripPointerCasts());
  293. return dyn_cast<ConstantInt>(Val);
  294. }
  295. /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
  296. /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
  297. /// in any of our predecessors. If so, return the known list of value and pred
  298. /// BB in the result vector.
  299. ///
  300. /// This returns true if there were any known values.
  301. ///
  302. bool JumpThreading::
  303. ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
  304. ConstantPreference Preference,
  305. Instruction *CxtI) {
  306. // This method walks up use-def chains recursively. Because of this, we could
  307. // get into an infinite loop going around loops in the use-def chain. To
  308. // prevent this, keep track of what (value, block) pairs we've already visited
  309. // and terminate the search if we loop back to them
  310. if (!RecursionSet.insert(std::make_pair(V, BB)).second)
  311. return false;
  312. // An RAII help to remove this pair from the recursion set once the recursion
  313. // stack pops back out again.
  314. RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
  315. // If V is a constant, then it is known in all predecessors.
  316. if (Constant *KC = getKnownConstant(V, Preference)) {
  317. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  318. Result.push_back(std::make_pair(KC, *PI));
  319. return true;
  320. }
  321. // If V is a non-instruction value, or an instruction in a different block,
  322. // then it can't be derived from a PHI.
  323. Instruction *I = dyn_cast<Instruction>(V);
  324. if (!I || I->getParent() != BB) {
  325. // Okay, if this is a live-in value, see if it has a known value at the end
  326. // of any of our predecessors.
  327. //
  328. // FIXME: This should be an edge property, not a block end property.
  329. /// TODO: Per PR2563, we could infer value range information about a
  330. /// predecessor based on its terminator.
  331. //
  332. // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
  333. // "I" is a non-local compare-with-a-constant instruction. This would be
  334. // able to handle value inequalities better, for example if the compare is
  335. // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
  336. // Perhaps getConstantOnEdge should be smart enough to do this?
  337. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  338. BasicBlock *P = *PI;
  339. // If the value is known by LazyValueInfo to be a constant in a
  340. // predecessor, use that information to try to thread this block.
  341. Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
  342. if (Constant *KC = getKnownConstant(PredCst, Preference))
  343. Result.push_back(std::make_pair(KC, P));
  344. }
  345. return !Result.empty();
  346. }
  347. /// If I is a PHI node, then we know the incoming values for any constants.
  348. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  349. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  350. Value *InVal = PN->getIncomingValue(i);
  351. if (Constant *KC = getKnownConstant(InVal, Preference)) {
  352. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  353. } else {
  354. Constant *CI = LVI->getConstantOnEdge(InVal,
  355. PN->getIncomingBlock(i),
  356. BB, CxtI);
  357. if (Constant *KC = getKnownConstant(CI, Preference))
  358. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  359. }
  360. }
  361. return !Result.empty();
  362. }
  363. PredValueInfoTy LHSVals, RHSVals;
  364. // Handle some boolean conditions.
  365. if (I->getType()->getPrimitiveSizeInBits() == 1) {
  366. assert(Preference == WantInteger && "One-bit non-integer type?");
  367. // X | true -> true
  368. // X & false -> false
  369. if (I->getOpcode() == Instruction::Or ||
  370. I->getOpcode() == Instruction::And) {
  371. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  372. WantInteger, CxtI);
  373. ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
  374. WantInteger, CxtI);
  375. if (LHSVals.empty() && RHSVals.empty())
  376. return false;
  377. ConstantInt *InterestingVal;
  378. if (I->getOpcode() == Instruction::Or)
  379. InterestingVal = ConstantInt::getTrue(I->getContext());
  380. else
  381. InterestingVal = ConstantInt::getFalse(I->getContext());
  382. SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
  383. // Scan for the sentinel. If we find an undef, force it to the
  384. // interesting value: x|undef -> true and x&undef -> false.
  385. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
  386. if (LHSVals[i].first == InterestingVal ||
  387. isa<UndefValue>(LHSVals[i].first)) {
  388. Result.push_back(LHSVals[i]);
  389. Result.back().first = InterestingVal;
  390. LHSKnownBBs.insert(LHSVals[i].second);
  391. }
  392. for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
  393. if (RHSVals[i].first == InterestingVal ||
  394. isa<UndefValue>(RHSVals[i].first)) {
  395. // If we already inferred a value for this block on the LHS, don't
  396. // re-add it.
  397. if (!LHSKnownBBs.count(RHSVals[i].second)) {
  398. Result.push_back(RHSVals[i]);
  399. Result.back().first = InterestingVal;
  400. }
  401. }
  402. return !Result.empty();
  403. }
  404. // Handle the NOT form of XOR.
  405. if (I->getOpcode() == Instruction::Xor &&
  406. isa<ConstantInt>(I->getOperand(1)) &&
  407. cast<ConstantInt>(I->getOperand(1))->isOne()) {
  408. ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
  409. WantInteger, CxtI);
  410. if (Result.empty())
  411. return false;
  412. // Invert the known values.
  413. for (unsigned i = 0, e = Result.size(); i != e; ++i)
  414. Result[i].first = ConstantExpr::getNot(Result[i].first);
  415. return true;
  416. }
  417. // Try to simplify some other binary operator values.
  418. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  419. assert(Preference != WantBlockAddress
  420. && "A binary operator creating a block address?");
  421. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
  422. PredValueInfoTy LHSVals;
  423. ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
  424. WantInteger, CxtI);
  425. // Try to use constant folding to simplify the binary operator.
  426. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
  427. Constant *V = LHSVals[i].first;
  428. Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
  429. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  430. Result.push_back(std::make_pair(KC, LHSVals[i].second));
  431. }
  432. }
  433. return !Result.empty();
  434. }
  435. // Handle compare with phi operand, where the PHI is defined in this block.
  436. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  437. assert(Preference == WantInteger && "Compares only produce integers");
  438. PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
  439. if (PN && PN->getParent() == BB) {
  440. const DataLayout &DL = PN->getModule()->getDataLayout();
  441. // We can do this simplification if any comparisons fold to true or false.
  442. // See if any do.
  443. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  444. BasicBlock *PredBB = PN->getIncomingBlock(i);
  445. Value *LHS = PN->getIncomingValue(i);
  446. Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
  447. Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
  448. if (!Res) {
  449. if (!isa<Constant>(RHS))
  450. continue;
  451. LazyValueInfo::Tristate
  452. ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
  453. cast<Constant>(RHS), PredBB, BB,
  454. CxtI ? CxtI : Cmp);
  455. if (ResT == LazyValueInfo::Unknown)
  456. continue;
  457. Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
  458. }
  459. if (Constant *KC = getKnownConstant(Res, WantInteger))
  460. Result.push_back(std::make_pair(KC, PredBB));
  461. }
  462. return !Result.empty();
  463. }
  464. // If comparing a live-in value against a constant, see if we know the
  465. // live-in value on any predecessors.
  466. if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
  467. if (!isa<Instruction>(Cmp->getOperand(0)) ||
  468. cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
  469. Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
  470. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
  471. BasicBlock *P = *PI;
  472. // If the value is known by LazyValueInfo to be a constant in a
  473. // predecessor, use that information to try to thread this block.
  474. LazyValueInfo::Tristate Res =
  475. LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
  476. RHSCst, P, BB, CxtI ? CxtI : Cmp);
  477. if (Res == LazyValueInfo::Unknown)
  478. continue;
  479. Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
  480. Result.push_back(std::make_pair(ResC, P));
  481. }
  482. return !Result.empty();
  483. }
  484. // Try to find a constant value for the LHS of a comparison,
  485. // and evaluate it statically if we can.
  486. if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
  487. PredValueInfoTy LHSVals;
  488. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  489. WantInteger, CxtI);
  490. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
  491. Constant *V = LHSVals[i].first;
  492. Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
  493. V, CmpConst);
  494. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  495. Result.push_back(std::make_pair(KC, LHSVals[i].second));
  496. }
  497. return !Result.empty();
  498. }
  499. }
  500. }
  501. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  502. // Handle select instructions where at least one operand is a known constant
  503. // and we can figure out the condition value for any predecessor block.
  504. Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
  505. Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
  506. PredValueInfoTy Conds;
  507. if ((TrueVal || FalseVal) &&
  508. ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
  509. WantInteger, CxtI)) {
  510. for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
  511. Constant *Cond = Conds[i].first;
  512. // Figure out what value to use for the condition.
  513. bool KnownCond;
  514. if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
  515. // A known boolean.
  516. KnownCond = CI->isOne();
  517. } else {
  518. assert(isa<UndefValue>(Cond) && "Unexpected condition value");
  519. // Either operand will do, so be sure to pick the one that's a known
  520. // constant.
  521. // FIXME: Do this more cleverly if both values are known constants?
  522. KnownCond = (TrueVal != nullptr);
  523. }
  524. // See if the select has a known constant value for this predecessor.
  525. if (Constant *Val = KnownCond ? TrueVal : FalseVal)
  526. Result.push_back(std::make_pair(Val, Conds[i].second));
  527. }
  528. return !Result.empty();
  529. }
  530. }
  531. // If all else fails, see if LVI can figure out a constant value for us.
  532. Constant *CI = LVI->getConstant(V, BB, CxtI);
  533. if (Constant *KC = getKnownConstant(CI, Preference)) {
  534. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  535. Result.push_back(std::make_pair(KC, *PI));
  536. }
  537. return !Result.empty();
  538. }
  539. /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
  540. /// in an undefined jump, decide which block is best to revector to.
  541. ///
  542. /// Since we can pick an arbitrary destination, we pick the successor with the
  543. /// fewest predecessors. This should reduce the in-degree of the others.
  544. ///
  545. static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
  546. TerminatorInst *BBTerm = BB->getTerminator();
  547. unsigned MinSucc = 0;
  548. BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
  549. // Compute the successor with the minimum number of predecessors.
  550. unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  551. for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  552. TestBB = BBTerm->getSuccessor(i);
  553. unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  554. if (NumPreds < MinNumPreds) {
  555. MinSucc = i;
  556. MinNumPreds = NumPreds;
  557. }
  558. }
  559. return MinSucc;
  560. }
  561. static bool hasAddressTakenAndUsed(BasicBlock *BB) {
  562. if (!BB->hasAddressTaken()) return false;
  563. // If the block has its address taken, it may be a tree of dead constants
  564. // hanging off of it. These shouldn't keep the block alive.
  565. BlockAddress *BA = BlockAddress::get(BB);
  566. BA->removeDeadConstantUsers();
  567. return !BA->use_empty();
  568. }
  569. /// ProcessBlock - If there are any predecessors whose control can be threaded
  570. /// through to a successor, transform them now.
  571. bool JumpThreading::ProcessBlock(BasicBlock *BB) {
  572. // If the block is trivially dead, just return and let the caller nuke it.
  573. // This simplifies other transformations.
  574. if (pred_empty(BB) &&
  575. BB != &BB->getParent()->getEntryBlock())
  576. return false;
  577. // If this block has a single predecessor, and if that pred has a single
  578. // successor, merge the blocks. This encourages recursive jump threading
  579. // because now the condition in this block can be threaded through
  580. // predecessors of our predecessor block.
  581. if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
  582. if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
  583. SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
  584. // If SinglePred was a loop header, BB becomes one.
  585. if (LoopHeaders.erase(SinglePred))
  586. LoopHeaders.insert(BB);
  587. LVI->eraseBlock(SinglePred);
  588. MergeBasicBlockIntoOnlyPred(BB);
  589. return true;
  590. }
  591. }
  592. // What kind of constant we're looking for.
  593. ConstantPreference Preference = WantInteger;
  594. // Look to see if the terminator is a conditional branch, switch or indirect
  595. // branch, if not we can't thread it.
  596. Value *Condition;
  597. Instruction *Terminator = BB->getTerminator();
  598. if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
  599. // Can't thread an unconditional jump.
  600. if (BI->isUnconditional()) return false;
  601. Condition = BI->getCondition();
  602. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
  603. Condition = SI->getCondition();
  604. } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
  605. // Can't thread indirect branch with no successors.
  606. if (IB->getNumSuccessors() == 0) return false;
  607. Condition = IB->getAddress()->stripPointerCasts();
  608. Preference = WantBlockAddress;
  609. } else {
  610. return false; // Must be an invoke.
  611. }
  612. // Run constant folding to see if we can reduce the condition to a simple
  613. // constant.
  614. if (Instruction *I = dyn_cast<Instruction>(Condition)) {
  615. Value *SimpleVal =
  616. ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
  617. if (SimpleVal) {
  618. I->replaceAllUsesWith(SimpleVal);
  619. I->eraseFromParent();
  620. Condition = SimpleVal;
  621. }
  622. }
  623. // If the terminator is branching on an undef, we can pick any of the
  624. // successors to branch to. Let GetBestDestForJumpOnUndef decide.
  625. if (isa<UndefValue>(Condition)) {
  626. unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
  627. // Fold the branch/switch.
  628. TerminatorInst *BBTerm = BB->getTerminator();
  629. for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  630. if (i == BestSucc) continue;
  631. BBTerm->getSuccessor(i)->removePredecessor(BB, true);
  632. }
  633. DEBUG(dbgs() << " In block '" << BB->getName()
  634. << "' folding undef terminator: " << *BBTerm << '\n');
  635. BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
  636. BBTerm->eraseFromParent();
  637. return true;
  638. }
  639. // If the terminator of this block is branching on a constant, simplify the
  640. // terminator to an unconditional branch. This can occur due to threading in
  641. // other blocks.
  642. if (getKnownConstant(Condition, Preference)) {
  643. DEBUG(dbgs() << " In block '" << BB->getName()
  644. << "' folding terminator: " << *BB->getTerminator() << '\n');
  645. ++NumFolds;
  646. ConstantFoldTerminator(BB, true);
  647. return true;
  648. }
  649. Instruction *CondInst = dyn_cast<Instruction>(Condition);
  650. // All the rest of our checks depend on the condition being an instruction.
  651. if (!CondInst) {
  652. // FIXME: Unify this with code below.
  653. if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
  654. return true;
  655. return false;
  656. }
  657. if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
  658. // If we're branching on a conditional, LVI might be able to determine
  659. // it's value at the branch instruction. We only handle comparisons
  660. // against a constant at this time.
  661. // TODO: This should be extended to handle switches as well.
  662. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  663. Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
  664. if (CondBr && CondConst && CondBr->isConditional()) {
  665. LazyValueInfo::Tristate Ret =
  666. LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
  667. CondConst, CondBr);
  668. if (Ret != LazyValueInfo::Unknown) {
  669. unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
  670. unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
  671. CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
  672. BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
  673. CondBr->eraseFromParent();
  674. if (CondCmp->use_empty())
  675. CondCmp->eraseFromParent();
  676. else if (CondCmp->getParent() == BB) {
  677. // If the fact we just learned is true for all uses of the
  678. // condition, replace it with a constant value
  679. auto *CI = Ret == LazyValueInfo::True ?
  680. ConstantInt::getTrue(CondCmp->getType()) :
  681. ConstantInt::getFalse(CondCmp->getType());
  682. CondCmp->replaceAllUsesWith(CI);
  683. CondCmp->eraseFromParent();
  684. }
  685. return true;
  686. }
  687. }
  688. if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
  689. return true;
  690. }
  691. // Check for some cases that are worth simplifying. Right now we want to look
  692. // for loads that are used by a switch or by the condition for the branch. If
  693. // we see one, check to see if it's partially redundant. If so, insert a PHI
  694. // which can then be used to thread the values.
  695. //
  696. Value *SimplifyValue = CondInst;
  697. if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
  698. if (isa<Constant>(CondCmp->getOperand(1)))
  699. SimplifyValue = CondCmp->getOperand(0);
  700. // TODO: There are other places where load PRE would be profitable, such as
  701. // more complex comparisons.
  702. if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
  703. if (SimplifyPartiallyRedundantLoad(LI))
  704. return true;
  705. // Handle a variety of cases where we are branching on something derived from
  706. // a PHI node in the current block. If we can prove that any predecessors
  707. // compute a predictable value based on a PHI node, thread those predecessors.
  708. //
  709. if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
  710. return true;
  711. // If this is an otherwise-unfoldable branch on a phi node in the current
  712. // block, see if we can simplify.
  713. if (PHINode *PN = dyn_cast<PHINode>(CondInst))
  714. if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  715. return ProcessBranchOnPHI(PN);
  716. // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
  717. if (CondInst->getOpcode() == Instruction::Xor &&
  718. CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  719. return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
  720. // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
  721. // "(X == 4)", thread through this block.
  722. return false;
  723. }
  724. /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
  725. /// load instruction, eliminate it by replacing it with a PHI node. This is an
  726. /// important optimization that encourages jump threading, and needs to be run
  727. /// interlaced with other jump threading tasks.
  728. bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
  729. // Don't hack volatile/atomic loads.
  730. if (!LI->isSimple()) return false;
  731. // If the load is defined in a block with exactly one predecessor, it can't be
  732. // partially redundant.
  733. BasicBlock *LoadBB = LI->getParent();
  734. if (LoadBB->getSinglePredecessor())
  735. return false;
  736. // If the load is defined in a landing pad, it can't be partially redundant,
  737. // because the edges between the invoke and the landing pad cannot have other
  738. // instructions between them.
  739. if (LoadBB->isLandingPad())
  740. return false;
  741. Value *LoadedPtr = LI->getOperand(0);
  742. // If the loaded operand is defined in the LoadBB, it can't be available.
  743. // TODO: Could do simple PHI translation, that would be fun :)
  744. if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
  745. if (PtrOp->getParent() == LoadBB)
  746. return false;
  747. // Scan a few instructions up from the load, to see if it is obviously live at
  748. // the entry to its block.
  749. BasicBlock::iterator BBIt = LI;
  750. if (Value *AvailableVal =
  751. FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
  752. // If the value if the load is locally available within the block, just use
  753. // it. This frequently occurs for reg2mem'd allocas.
  754. //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
  755. // If the returned value is the load itself, replace with an undef. This can
  756. // only happen in dead loops.
  757. if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
  758. if (AvailableVal->getType() != LI->getType())
  759. AvailableVal =
  760. CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
  761. LI->replaceAllUsesWith(AvailableVal);
  762. LI->eraseFromParent();
  763. return true;
  764. }
  765. // Otherwise, if we scanned the whole block and got to the top of the block,
  766. // we know the block is locally transparent to the load. If not, something
  767. // might clobber its value.
  768. if (BBIt != LoadBB->begin())
  769. return false;
  770. // If all of the loads and stores that feed the value have the same AA tags,
  771. // then we can propagate them onto any newly inserted loads.
  772. AAMDNodes AATags;
  773. LI->getAAMetadata(AATags);
  774. SmallPtrSet<BasicBlock*, 8> PredsScanned;
  775. typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
  776. AvailablePredsTy AvailablePreds;
  777. BasicBlock *OneUnavailablePred = nullptr;
  778. // If we got here, the loaded value is transparent through to the start of the
  779. // block. Check to see if it is available in any of the predecessor blocks.
  780. for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
  781. PI != PE; ++PI) {
  782. BasicBlock *PredBB = *PI;
  783. // If we already scanned this predecessor, skip it.
  784. if (!PredsScanned.insert(PredBB).second)
  785. continue;
  786. // Scan the predecessor to see if the value is available in the pred.
  787. BBIt = PredBB->end();
  788. AAMDNodes ThisAATags;
  789. Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
  790. nullptr, &ThisAATags);
  791. if (!PredAvailable) {
  792. OneUnavailablePred = PredBB;
  793. continue;
  794. }
  795. // If AA tags disagree or are not present, forget about them.
  796. if (AATags != ThisAATags) AATags = AAMDNodes();
  797. // If so, this load is partially redundant. Remember this info so that we
  798. // can create a PHI node.
  799. AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
  800. }
  801. // If the loaded value isn't available in any predecessor, it isn't partially
  802. // redundant.
  803. if (AvailablePreds.empty()) return false;
  804. // Okay, the loaded value is available in at least one (and maybe all!)
  805. // predecessors. If the value is unavailable in more than one unique
  806. // predecessor, we want to insert a merge block for those common predecessors.
  807. // This ensures that we only have to insert one reload, thus not increasing
  808. // code size.
  809. BasicBlock *UnavailablePred = nullptr;
  810. // If there is exactly one predecessor where the value is unavailable, the
  811. // already computed 'OneUnavailablePred' block is it. If it ends in an
  812. // unconditional branch, we know that it isn't a critical edge.
  813. if (PredsScanned.size() == AvailablePreds.size()+1 &&
  814. OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
  815. UnavailablePred = OneUnavailablePred;
  816. } else if (PredsScanned.size() != AvailablePreds.size()) {
  817. // Otherwise, we had multiple unavailable predecessors or we had a critical
  818. // edge from the one.
  819. SmallVector<BasicBlock*, 8> PredsToSplit;
  820. SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
  821. for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
  822. AvailablePredSet.insert(AvailablePreds[i].first);
  823. // Add all the unavailable predecessors to the PredsToSplit list.
  824. for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
  825. PI != PE; ++PI) {
  826. BasicBlock *P = *PI;
  827. // If the predecessor is an indirect goto, we can't split the edge.
  828. if (isa<IndirectBrInst>(P->getTerminator()))
  829. return false;
  830. if (!AvailablePredSet.count(P))
  831. PredsToSplit.push_back(P);
  832. }
  833. // Split them out to their own block.
  834. UnavailablePred =
  835. SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split");
  836. }
  837. // If the value isn't available in all predecessors, then there will be
  838. // exactly one where it isn't available. Insert a load on that edge and add
  839. // it to the AvailablePreds list.
  840. if (UnavailablePred) {
  841. assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
  842. "Can't handle critical edge here!");
  843. LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
  844. LI->getAlignment(),
  845. UnavailablePred->getTerminator());
  846. NewVal->setDebugLoc(LI->getDebugLoc());
  847. if (AATags)
  848. NewVal->setAAMetadata(AATags);
  849. AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
  850. }
  851. // Now we know that each predecessor of this block has a value in
  852. // AvailablePreds, sort them for efficient access as we're walking the preds.
  853. array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
  854. // Create a PHI node at the start of the block for the PRE'd load value.
  855. pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
  856. PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
  857. LoadBB->begin());
  858. PN->takeName(LI);
  859. PN->setDebugLoc(LI->getDebugLoc());
  860. // Insert new entries into the PHI for each predecessor. A single block may
  861. // have multiple entries here.
  862. for (pred_iterator PI = PB; PI != PE; ++PI) {
  863. BasicBlock *P = *PI;
  864. AvailablePredsTy::iterator I =
  865. std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
  866. std::make_pair(P, (Value*)nullptr));
  867. assert(I != AvailablePreds.end() && I->first == P &&
  868. "Didn't find entry for predecessor!");
  869. // If we have an available predecessor but it requires casting, insert the
  870. // cast in the predecessor and use the cast. Note that we have to update the
  871. // AvailablePreds vector as we go so that all of the PHI entries for this
  872. // predecessor use the same bitcast.
  873. Value *&PredV = I->second;
  874. if (PredV->getType() != LI->getType())
  875. PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
  876. P->getTerminator());
  877. PN->addIncoming(PredV, I->first);
  878. }
  879. //cerr << "PRE: " << *LI << *PN << "\n";
  880. LI->replaceAllUsesWith(PN);
  881. LI->eraseFromParent();
  882. return true;
  883. }
  884. /// FindMostPopularDest - The specified list contains multiple possible
  885. /// threadable destinations. Pick the one that occurs the most frequently in
  886. /// the list.
  887. static BasicBlock *
  888. FindMostPopularDest(BasicBlock *BB,
  889. const SmallVectorImpl<std::pair<BasicBlock*,
  890. BasicBlock*> > &PredToDestList) {
  891. assert(!PredToDestList.empty());
  892. // Determine popularity. If there are multiple possible destinations, we
  893. // explicitly choose to ignore 'undef' destinations. We prefer to thread
  894. // blocks with known and real destinations to threading undef. We'll handle
  895. // them later if interesting.
  896. DenseMap<BasicBlock*, unsigned> DestPopularity;
  897. for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
  898. if (PredToDestList[i].second)
  899. DestPopularity[PredToDestList[i].second]++;
  900. // Find the most popular dest.
  901. DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
  902. BasicBlock *MostPopularDest = DPI->first;
  903. unsigned Popularity = DPI->second;
  904. SmallVector<BasicBlock*, 4> SamePopularity;
  905. for (++DPI; DPI != DestPopularity.end(); ++DPI) {
  906. // If the popularity of this entry isn't higher than the popularity we've
  907. // seen so far, ignore it.
  908. if (DPI->second < Popularity)
  909. ; // ignore.
  910. else if (DPI->second == Popularity) {
  911. // If it is the same as what we've seen so far, keep track of it.
  912. SamePopularity.push_back(DPI->first);
  913. } else {
  914. // If it is more popular, remember it.
  915. SamePopularity.clear();
  916. MostPopularDest = DPI->first;
  917. Popularity = DPI->second;
  918. }
  919. }
  920. // Okay, now we know the most popular destination. If there is more than one
  921. // destination, we need to determine one. This is arbitrary, but we need
  922. // to make a deterministic decision. Pick the first one that appears in the
  923. // successor list.
  924. if (!SamePopularity.empty()) {
  925. SamePopularity.push_back(MostPopularDest);
  926. TerminatorInst *TI = BB->getTerminator();
  927. for (unsigned i = 0; ; ++i) {
  928. assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
  929. if (std::find(SamePopularity.begin(), SamePopularity.end(),
  930. TI->getSuccessor(i)) == SamePopularity.end())
  931. continue;
  932. MostPopularDest = TI->getSuccessor(i);
  933. break;
  934. }
  935. }
  936. // Okay, we have finally picked the most popular destination.
  937. return MostPopularDest;
  938. }
  939. bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
  940. ConstantPreference Preference,
  941. Instruction *CxtI) {
  942. // If threading this would thread across a loop header, don't even try to
  943. // thread the edge.
  944. if (LoopHeaders.count(BB))
  945. return false;
  946. PredValueInfoTy PredValues;
  947. if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
  948. return false;
  949. assert(!PredValues.empty() &&
  950. "ComputeValueKnownInPredecessors returned true with no values");
  951. DEBUG(dbgs() << "IN BB: " << *BB;
  952. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
  953. dbgs() << " BB '" << BB->getName() << "': FOUND condition = "
  954. << *PredValues[i].first
  955. << " for pred '" << PredValues[i].second->getName() << "'.\n";
  956. });
  957. // Decide what we want to thread through. Convert our list of known values to
  958. // a list of known destinations for each pred. This also discards duplicate
  959. // predecessors and keeps track of the undefined inputs (which are represented
  960. // as a null dest in the PredToDestList).
  961. SmallPtrSet<BasicBlock*, 16> SeenPreds;
  962. SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
  963. BasicBlock *OnlyDest = nullptr;
  964. BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
  965. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
  966. BasicBlock *Pred = PredValues[i].second;
  967. if (!SeenPreds.insert(Pred).second)
  968. continue; // Duplicate predecessor entry.
  969. // If the predecessor ends with an indirect goto, we can't change its
  970. // destination.
  971. if (isa<IndirectBrInst>(Pred->getTerminator()))
  972. continue;
  973. Constant *Val = PredValues[i].first;
  974. BasicBlock *DestBB;
  975. if (isa<UndefValue>(Val))
  976. DestBB = nullptr;
  977. else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
  978. DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
  979. else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  980. DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
  981. } else {
  982. assert(isa<IndirectBrInst>(BB->getTerminator())
  983. && "Unexpected terminator");
  984. DestBB = cast<BlockAddress>(Val)->getBasicBlock();
  985. }
  986. // If we have exactly one destination, remember it for efficiency below.
  987. if (PredToDestList.empty())
  988. OnlyDest = DestBB;
  989. else if (OnlyDest != DestBB)
  990. OnlyDest = MultipleDestSentinel;
  991. PredToDestList.push_back(std::make_pair(Pred, DestBB));
  992. }
  993. // If all edges were unthreadable, we fail.
  994. if (PredToDestList.empty())
  995. return false;
  996. // Determine which is the most common successor. If we have many inputs and
  997. // this block is a switch, we want to start by threading the batch that goes
  998. // to the most popular destination first. If we only know about one
  999. // threadable destination (the common case) we can avoid this.
  1000. BasicBlock *MostPopularDest = OnlyDest;
  1001. if (MostPopularDest == MultipleDestSentinel)
  1002. MostPopularDest = FindMostPopularDest(BB, PredToDestList);
  1003. // Now that we know what the most popular destination is, factor all
  1004. // predecessors that will jump to it into a single predecessor.
  1005. SmallVector<BasicBlock*, 16> PredsToFactor;
  1006. for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
  1007. if (PredToDestList[i].second == MostPopularDest) {
  1008. BasicBlock *Pred = PredToDestList[i].first;
  1009. // This predecessor may be a switch or something else that has multiple
  1010. // edges to the block. Factor each of these edges by listing them
  1011. // according to # occurrences in PredsToFactor.
  1012. TerminatorInst *PredTI = Pred->getTerminator();
  1013. for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
  1014. if (PredTI->getSuccessor(i) == BB)
  1015. PredsToFactor.push_back(Pred);
  1016. }
  1017. // If the threadable edges are branching on an undefined value, we get to pick
  1018. // the destination that these predecessors should get to.
  1019. if (!MostPopularDest)
  1020. MostPopularDest = BB->getTerminator()->
  1021. getSuccessor(GetBestDestForJumpOnUndef(BB));
  1022. // Ok, try to thread it!
  1023. return ThreadEdge(BB, PredsToFactor, MostPopularDest);
  1024. }
  1025. /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
  1026. /// a PHI node in the current block. See if there are any simplifications we
  1027. /// can do based on inputs to the phi node.
  1028. ///
  1029. bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
  1030. BasicBlock *BB = PN->getParent();
  1031. // TODO: We could make use of this to do it once for blocks with common PHI
  1032. // values.
  1033. SmallVector<BasicBlock*, 1> PredBBs;
  1034. PredBBs.resize(1);
  1035. // If any of the predecessor blocks end in an unconditional branch, we can
  1036. // *duplicate* the conditional branch into that block in order to further
  1037. // encourage jump threading and to eliminate cases where we have branch on a
  1038. // phi of an icmp (branch on icmp is much better).
  1039. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1040. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1041. if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
  1042. if (PredBr->isUnconditional()) {
  1043. PredBBs[0] = PredBB;
  1044. // Try to duplicate BB into PredBB.
  1045. if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
  1046. return true;
  1047. }
  1048. }
  1049. return false;
  1050. }
  1051. /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
  1052. /// a xor instruction in the current block. See if there are any
  1053. /// simplifications we can do based on inputs to the xor.
  1054. ///
  1055. bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
  1056. BasicBlock *BB = BO->getParent();
  1057. // If either the LHS or RHS of the xor is a constant, don't do this
  1058. // optimization.
  1059. if (isa<ConstantInt>(BO->getOperand(0)) ||
  1060. isa<ConstantInt>(BO->getOperand(1)))
  1061. return false;
  1062. // If the first instruction in BB isn't a phi, we won't be able to infer
  1063. // anything special about any particular predecessor.
  1064. if (!isa<PHINode>(BB->front()))
  1065. return false;
  1066. // If we have a xor as the branch input to this block, and we know that the
  1067. // LHS or RHS of the xor in any predecessor is true/false, then we can clone
  1068. // the condition into the predecessor and fix that value to true, saving some
  1069. // logical ops on that path and encouraging other paths to simplify.
  1070. //
  1071. // This copies something like this:
  1072. //
  1073. // BB:
  1074. // %X = phi i1 [1], [%X']
  1075. // %Y = icmp eq i32 %A, %B
  1076. // %Z = xor i1 %X, %Y
  1077. // br i1 %Z, ...
  1078. //
  1079. // Into:
  1080. // BB':
  1081. // %Y = icmp ne i32 %A, %B
  1082. // br i1 %Z, ...
  1083. PredValueInfoTy XorOpValues;
  1084. bool isLHS = true;
  1085. if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
  1086. WantInteger, BO)) {
  1087. assert(XorOpValues.empty());
  1088. if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
  1089. WantInteger, BO))
  1090. return false;
  1091. isLHS = false;
  1092. }
  1093. assert(!XorOpValues.empty() &&
  1094. "ComputeValueKnownInPredecessors returned true with no values");
  1095. // Scan the information to see which is most popular: true or false. The
  1096. // predecessors can be of the set true, false, or undef.
  1097. unsigned NumTrue = 0, NumFalse = 0;
  1098. for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
  1099. if (isa<UndefValue>(XorOpValues[i].first))
  1100. // Ignore undefs for the count.
  1101. continue;
  1102. if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
  1103. ++NumFalse;
  1104. else
  1105. ++NumTrue;
  1106. }
  1107. // Determine which value to split on, true, false, or undef if neither.
  1108. ConstantInt *SplitVal = nullptr;
  1109. if (NumTrue > NumFalse)
  1110. SplitVal = ConstantInt::getTrue(BB->getContext());
  1111. else if (NumTrue != 0 || NumFalse != 0)
  1112. SplitVal = ConstantInt::getFalse(BB->getContext());
  1113. // Collect all of the blocks that this can be folded into so that we can
  1114. // factor this once and clone it once.
  1115. SmallVector<BasicBlock*, 8> BlocksToFoldInto;
  1116. for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
  1117. if (XorOpValues[i].first != SplitVal &&
  1118. !isa<UndefValue>(XorOpValues[i].first))
  1119. continue;
  1120. BlocksToFoldInto.push_back(XorOpValues[i].second);
  1121. }
  1122. // If we inferred a value for all of the predecessors, then duplication won't
  1123. // help us. However, we can just replace the LHS or RHS with the constant.
  1124. if (BlocksToFoldInto.size() ==
  1125. cast<PHINode>(BB->front()).getNumIncomingValues()) {
  1126. if (!SplitVal) {
  1127. // If all preds provide undef, just nuke the xor, because it is undef too.
  1128. BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
  1129. BO->eraseFromParent();
  1130. } else if (SplitVal->isZero()) {
  1131. // If all preds provide 0, replace the xor with the other input.
  1132. BO->replaceAllUsesWith(BO->getOperand(isLHS));
  1133. BO->eraseFromParent();
  1134. } else {
  1135. // If all preds provide 1, set the computed value to 1.
  1136. BO->setOperand(!isLHS, SplitVal);
  1137. }
  1138. return true;
  1139. }
  1140. // Try to duplicate BB into PredBB.
  1141. return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
  1142. }
  1143. /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
  1144. /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
  1145. /// NewPred using the entries from OldPred (suitably mapped).
  1146. static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
  1147. BasicBlock *OldPred,
  1148. BasicBlock *NewPred,
  1149. DenseMap<Instruction*, Value*> &ValueMap) {
  1150. for (BasicBlock::iterator PNI = PHIBB->begin();
  1151. PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
  1152. // Ok, we have a PHI node. Figure out what the incoming value was for the
  1153. // DestBlock.
  1154. Value *IV = PN->getIncomingValueForBlock(OldPred);
  1155. // Remap the value if necessary.
  1156. if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
  1157. DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
  1158. if (I != ValueMap.end())
  1159. IV = I->second;
  1160. }
  1161. PN->addIncoming(IV, NewPred);
  1162. }
  1163. }
  1164. /// ThreadEdge - We have decided that it is safe and profitable to factor the
  1165. /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
  1166. /// across BB. Transform the IR to reflect this change.
  1167. bool JumpThreading::ThreadEdge(BasicBlock *BB,
  1168. const SmallVectorImpl<BasicBlock*> &PredBBs,
  1169. BasicBlock *SuccBB) {
  1170. // If threading to the same block as we come from, we would infinite loop.
  1171. if (SuccBB == BB) {
  1172. DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
  1173. << "' - would thread to self!\n");
  1174. return false;
  1175. }
  1176. // If threading this would thread across a loop header, don't thread the edge.
  1177. // See the comments above FindLoopHeaders for justifications and caveats.
  1178. if (LoopHeaders.count(BB)) {
  1179. DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
  1180. << "' to dest BB '" << SuccBB->getName()
  1181. << "' - it might create an irreducible loop!\n");
  1182. return false;
  1183. }
  1184. unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
  1185. if (JumpThreadCost > BBDupThreshold) {
  1186. DEBUG(dbgs() << " Not threading BB '" << BB->getName()
  1187. << "' - Cost is too high: " << JumpThreadCost << "\n");
  1188. return false;
  1189. }
  1190. // And finally, do it! Start by factoring the predecessors is needed.
  1191. BasicBlock *PredBB;
  1192. if (PredBBs.size() == 1)
  1193. PredBB = PredBBs[0];
  1194. else {
  1195. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1196. << " common predecessors.\n");
  1197. PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
  1198. }
  1199. // And finally, do it!
  1200. DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
  1201. << SuccBB->getName() << "' with cost: " << JumpThreadCost
  1202. << ", across block:\n "
  1203. << *BB << "\n");
  1204. LVI->threadEdge(PredBB, BB, SuccBB);
  1205. // We are going to have to map operands from the original BB block to the new
  1206. // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
  1207. // account for entry from PredBB.
  1208. DenseMap<Instruction*, Value*> ValueMapping;
  1209. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
  1210. BB->getName()+".thread",
  1211. BB->getParent(), BB);
  1212. NewBB->moveAfter(PredBB);
  1213. BasicBlock::iterator BI = BB->begin();
  1214. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1215. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1216. // Clone the non-phi instructions of BB into NewBB, keeping track of the
  1217. // mapping and using it to remap operands in the cloned instructions.
  1218. for (; !isa<TerminatorInst>(BI); ++BI) {
  1219. Instruction *New = BI->clone();
  1220. New->setName(BI->getName());
  1221. NewBB->getInstList().push_back(New);
  1222. ValueMapping[BI] = New;
  1223. // Remap operands to patch up intra-block references.
  1224. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1225. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1226. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1227. if (I != ValueMapping.end())
  1228. New->setOperand(i, I->second);
  1229. }
  1230. }
  1231. // We didn't copy the terminator from BB over to NewBB, because there is now
  1232. // an unconditional jump to SuccBB. Insert the unconditional jump.
  1233. BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
  1234. NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
  1235. // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
  1236. // PHI nodes for NewBB now.
  1237. AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
  1238. // If there were values defined in BB that are used outside the block, then we
  1239. // now have to update all uses of the value to use either the original value,
  1240. // the cloned value, or some PHI derived value. This can require arbitrary
  1241. // PHI insertion, of which we are prepared to do, clean these up now.
  1242. SSAUpdater SSAUpdate;
  1243. SmallVector<Use*, 16> UsesToRename;
  1244. for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
  1245. // Scan all uses of this instruction to see if it is used outside of its
  1246. // block, and if so, record them in UsesToRename.
  1247. for (Use &U : I->uses()) {
  1248. Instruction *User = cast<Instruction>(U.getUser());
  1249. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1250. if (UserPN->getIncomingBlock(U) == BB)
  1251. continue;
  1252. } else if (User->getParent() == BB)
  1253. continue;
  1254. UsesToRename.push_back(&U);
  1255. }
  1256. // If there are no uses outside the block, we're done with this instruction.
  1257. if (UsesToRename.empty())
  1258. continue;
  1259. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
  1260. // We found a use of I outside of BB. Rename all uses of I that are outside
  1261. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1262. // with the two values we know.
  1263. SSAUpdate.Initialize(I->getType(), I->getName());
  1264. SSAUpdate.AddAvailableValue(BB, I);
  1265. SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
  1266. while (!UsesToRename.empty())
  1267. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1268. DEBUG(dbgs() << "\n");
  1269. }
  1270. // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
  1271. // NewBB instead of BB. This eliminates predecessors from BB, which requires
  1272. // us to simplify any PHI nodes in BB.
  1273. TerminatorInst *PredTerm = PredBB->getTerminator();
  1274. for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
  1275. if (PredTerm->getSuccessor(i) == BB) {
  1276. BB->removePredecessor(PredBB, true);
  1277. PredTerm->setSuccessor(i, NewBB);
  1278. }
  1279. // At this point, the IR is fully up to date and consistent. Do a quick scan
  1280. // over the new instructions and zap any that are constants or dead. This
  1281. // frequently happens because of phi translation.
  1282. SimplifyInstructionsInBlock(NewBB, TLI);
  1283. // Threaded an edge!
  1284. ++NumThreads;
  1285. return true;
  1286. }
  1287. /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
  1288. /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
  1289. /// If we can duplicate the contents of BB up into PredBB do so now, this
  1290. /// improves the odds that the branch will be on an analyzable instruction like
  1291. /// a compare.
  1292. bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
  1293. const SmallVectorImpl<BasicBlock *> &PredBBs) {
  1294. assert(!PredBBs.empty() && "Can't handle an empty set");
  1295. // If BB is a loop header, then duplicating this block outside the loop would
  1296. // cause us to transform this into an irreducible loop, don't do this.
  1297. // See the comments above FindLoopHeaders for justifications and caveats.
  1298. if (LoopHeaders.count(BB)) {
  1299. DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
  1300. << "' into predecessor block '" << PredBBs[0]->getName()
  1301. << "' - it might create an irreducible loop!\n");
  1302. return false;
  1303. }
  1304. unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
  1305. if (DuplicationCost > BBDupThreshold) {
  1306. DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
  1307. << "' - Cost is too high: " << DuplicationCost << "\n");
  1308. return false;
  1309. }
  1310. // And finally, do it! Start by factoring the predecessors is needed.
  1311. BasicBlock *PredBB;
  1312. if (PredBBs.size() == 1)
  1313. PredBB = PredBBs[0];
  1314. else {
  1315. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1316. << " common predecessors.\n");
  1317. PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
  1318. }
  1319. // Okay, we decided to do this! Clone all the instructions in BB onto the end
  1320. // of PredBB.
  1321. DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
  1322. << PredBB->getName() << "' to eliminate branch on phi. Cost: "
  1323. << DuplicationCost << " block is:" << *BB << "\n");
  1324. // Unless PredBB ends with an unconditional branch, split the edge so that we
  1325. // can just clone the bits from BB into the end of the new PredBB.
  1326. BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
  1327. if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
  1328. PredBB = SplitEdge(PredBB, BB);
  1329. OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
  1330. }
  1331. // We are going to have to map operands from the original BB block into the
  1332. // PredBB block. Evaluate PHI nodes in BB.
  1333. DenseMap<Instruction*, Value*> ValueMapping;
  1334. BasicBlock::iterator BI = BB->begin();
  1335. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1336. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1337. // Clone the non-phi instructions of BB into PredBB, keeping track of the
  1338. // mapping and using it to remap operands in the cloned instructions.
  1339. for (; BI != BB->end(); ++BI) {
  1340. Instruction *New = BI->clone();
  1341. // Remap operands to patch up intra-block references.
  1342. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1343. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1344. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1345. if (I != ValueMapping.end())
  1346. New->setOperand(i, I->second);
  1347. }
  1348. // If this instruction can be simplified after the operands are updated,
  1349. // just use the simplified value instead. This frequently happens due to
  1350. // phi translation.
  1351. if (Value *IV =
  1352. SimplifyInstruction(New, BB->getModule()->getDataLayout())) {
  1353. delete New;
  1354. ValueMapping[BI] = IV;
  1355. } else {
  1356. // Otherwise, insert the new instruction into the block.
  1357. New->setName(BI->getName());
  1358. PredBB->getInstList().insert(OldPredBranch, New);
  1359. ValueMapping[BI] = New;
  1360. }
  1361. }
  1362. // Check to see if the targets of the branch had PHI nodes. If so, we need to
  1363. // add entries to the PHI nodes for branch from PredBB now.
  1364. BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
  1365. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
  1366. ValueMapping);
  1367. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
  1368. ValueMapping);
  1369. // If there were values defined in BB that are used outside the block, then we
  1370. // now have to update all uses of the value to use either the original value,
  1371. // the cloned value, or some PHI derived value. This can require arbitrary
  1372. // PHI insertion, of which we are prepared to do, clean these up now.
  1373. SSAUpdater SSAUpdate;
  1374. SmallVector<Use*, 16> UsesToRename;
  1375. for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
  1376. // Scan all uses of this instruction to see if it is used outside of its
  1377. // block, and if so, record them in UsesToRename.
  1378. for (Use &U : I->uses()) {
  1379. Instruction *User = cast<Instruction>(U.getUser());
  1380. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1381. if (UserPN->getIncomingBlock(U) == BB)
  1382. continue;
  1383. } else if (User->getParent() == BB)
  1384. continue;
  1385. UsesToRename.push_back(&U);
  1386. }
  1387. // If there are no uses outside the block, we're done with this instruction.
  1388. if (UsesToRename.empty())
  1389. continue;
  1390. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
  1391. // We found a use of I outside of BB. Rename all uses of I that are outside
  1392. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1393. // with the two values we know.
  1394. SSAUpdate.Initialize(I->getType(), I->getName());
  1395. SSAUpdate.AddAvailableValue(BB, I);
  1396. SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
  1397. while (!UsesToRename.empty())
  1398. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1399. DEBUG(dbgs() << "\n");
  1400. }
  1401. // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
  1402. // that we nuked.
  1403. BB->removePredecessor(PredBB, true);
  1404. // Remove the unconditional branch at the end of the PredBB block.
  1405. OldPredBranch->eraseFromParent();
  1406. ++NumDupes;
  1407. return true;
  1408. }
  1409. /// TryToUnfoldSelect - Look for blocks of the form
  1410. /// bb1:
  1411. /// %a = select
  1412. /// br bb
  1413. ///
  1414. /// bb2:
  1415. /// %p = phi [%a, %bb] ...
  1416. /// %c = icmp %p
  1417. /// br i1 %c
  1418. ///
  1419. /// And expand the select into a branch structure if one of its arms allows %c
  1420. /// to be folded. This later enables threading from bb1 over bb2.
  1421. bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
  1422. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  1423. PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
  1424. Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
  1425. if (!CondBr || !CondBr->isConditional() || !CondLHS ||
  1426. CondLHS->getParent() != BB)
  1427. return false;
  1428. for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
  1429. BasicBlock *Pred = CondLHS->getIncomingBlock(I);
  1430. SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
  1431. // Look if one of the incoming values is a select in the corresponding
  1432. // predecessor.
  1433. if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
  1434. continue;
  1435. BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
  1436. if (!PredTerm || !PredTerm->isUnconditional())
  1437. continue;
  1438. // Now check if one of the select values would allow us to constant fold the
  1439. // terminator in BB. We don't do the transform if both sides fold, those
  1440. // cases will be threaded in any case.
  1441. LazyValueInfo::Tristate LHSFolds =
  1442. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
  1443. CondRHS, Pred, BB, CondCmp);
  1444. LazyValueInfo::Tristate RHSFolds =
  1445. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
  1446. CondRHS, Pred, BB, CondCmp);
  1447. if ((LHSFolds != LazyValueInfo::Unknown ||
  1448. RHSFolds != LazyValueInfo::Unknown) &&
  1449. LHSFolds != RHSFolds) {
  1450. // Expand the select.
  1451. //
  1452. // Pred --
  1453. // | v
  1454. // | NewBB
  1455. // | |
  1456. // |-----
  1457. // v
  1458. // BB
  1459. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
  1460. BB->getParent(), BB);
  1461. // Move the unconditional branch to NewBB.
  1462. PredTerm->removeFromParent();
  1463. NewBB->getInstList().insert(NewBB->end(), PredTerm);
  1464. // Create a conditional branch and update PHI nodes.
  1465. BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
  1466. CondLHS->setIncomingValue(I, SI->getFalseValue());
  1467. CondLHS->addIncoming(SI->getTrueValue(), NewBB);
  1468. // The select is now dead.
  1469. SI->eraseFromParent();
  1470. // Update any other PHI nodes in BB.
  1471. for (BasicBlock::iterator BI = BB->begin();
  1472. PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
  1473. if (Phi != CondLHS)
  1474. Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
  1475. return true;
  1476. }
  1477. }
  1478. return false;
  1479. }