SimplifyCFG.cpp 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972
  1. //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
  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. // Peephole optimize the CFG.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "simplifycfg"
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/IntrinsicInst.h"
  20. #include "llvm/LLVMContext.h"
  21. #include "llvm/Metadata.h"
  22. #include "llvm/Operator.h"
  23. #include "llvm/Type.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/SetVector.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/Support/CFG.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/ConstantRange.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/IRBuilder.h"
  39. #include "llvm/Support/NoFolder.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <algorithm>
  42. #include <set>
  43. #include <map>
  44. using namespace llvm;
  45. static cl::opt<unsigned>
  46. PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
  47. cl::desc("Control the amount of phi node folding to perform (default = 1)"));
  48. static cl::opt<bool>
  49. DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  50. cl::desc("Duplicate return instructions into unconditional branches"));
  51. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  52. namespace {
  53. class SimplifyCFGOpt {
  54. const TargetData *const TD;
  55. Value *isValueEqualityComparison(TerminatorInst *TI);
  56. BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
  57. std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
  58. bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  59. BasicBlock *Pred,
  60. IRBuilder<> &Builder);
  61. bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  62. IRBuilder<> &Builder);
  63. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  64. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  65. bool SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder);
  66. bool SimplifyUnreachable(UnreachableInst *UI);
  67. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  68. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  69. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
  70. bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
  71. public:
  72. explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
  73. bool run(BasicBlock *BB);
  74. };
  75. }
  76. /// SafeToMergeTerminators - Return true if it is safe to merge these two
  77. /// terminator instructions together.
  78. ///
  79. static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
  80. if (SI1 == SI2) return false; // Can't merge with self!
  81. // It is not safe to merge these two switch instructions if they have a common
  82. // successor, and if that successor has a PHI node, and if *that* PHI node has
  83. // conflicting incoming values from the two switch blocks.
  84. BasicBlock *SI1BB = SI1->getParent();
  85. BasicBlock *SI2BB = SI2->getParent();
  86. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  87. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  88. if (SI1Succs.count(*I))
  89. for (BasicBlock::iterator BBI = (*I)->begin();
  90. isa<PHINode>(BBI); ++BBI) {
  91. PHINode *PN = cast<PHINode>(BBI);
  92. if (PN->getIncomingValueForBlock(SI1BB) !=
  93. PN->getIncomingValueForBlock(SI2BB))
  94. return false;
  95. }
  96. return true;
  97. }
  98. /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
  99. /// now be entries in it from the 'NewPred' block. The values that will be
  100. /// flowing into the PHI nodes will be the same as those coming in from
  101. /// ExistPred, an existing predecessor of Succ.
  102. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  103. BasicBlock *ExistPred) {
  104. if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
  105. PHINode *PN;
  106. for (BasicBlock::iterator I = Succ->begin();
  107. (PN = dyn_cast<PHINode>(I)); ++I)
  108. PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
  109. }
  110. /// GetIfCondition - Given a basic block (BB) with two predecessors (and at
  111. /// least one PHI node in it), check to see if the merge at this block is due
  112. /// to an "if condition". If so, return the boolean condition that determines
  113. /// which entry into BB will be taken. Also, return by references the block
  114. /// that will be entered from if the condition is true, and the block that will
  115. /// be entered if the condition is false.
  116. ///
  117. /// This does no checking to see if the true/false blocks have large or unsavory
  118. /// instructions in them.
  119. static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  120. BasicBlock *&IfFalse) {
  121. PHINode *SomePHI = cast<PHINode>(BB->begin());
  122. assert(SomePHI->getNumIncomingValues() == 2 &&
  123. "Function can only handle blocks with 2 predecessors!");
  124. BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
  125. BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
  126. // We can only handle branches. Other control flow will be lowered to
  127. // branches if possible anyway.
  128. BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
  129. BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
  130. if (Pred1Br == 0 || Pred2Br == 0)
  131. return 0;
  132. // Eliminate code duplication by ensuring that Pred1Br is conditional if
  133. // either are.
  134. if (Pred2Br->isConditional()) {
  135. // If both branches are conditional, we don't have an "if statement". In
  136. // reality, we could transform this case, but since the condition will be
  137. // required anyway, we stand no chance of eliminating it, so the xform is
  138. // probably not profitable.
  139. if (Pred1Br->isConditional())
  140. return 0;
  141. std::swap(Pred1, Pred2);
  142. std::swap(Pred1Br, Pred2Br);
  143. }
  144. if (Pred1Br->isConditional()) {
  145. // The only thing we have to watch out for here is to make sure that Pred2
  146. // doesn't have incoming edges from other blocks. If it does, the condition
  147. // doesn't dominate BB.
  148. if (Pred2->getSinglePredecessor() == 0)
  149. return 0;
  150. // If we found a conditional branch predecessor, make sure that it branches
  151. // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
  152. if (Pred1Br->getSuccessor(0) == BB &&
  153. Pred1Br->getSuccessor(1) == Pred2) {
  154. IfTrue = Pred1;
  155. IfFalse = Pred2;
  156. } else if (Pred1Br->getSuccessor(0) == Pred2 &&
  157. Pred1Br->getSuccessor(1) == BB) {
  158. IfTrue = Pred2;
  159. IfFalse = Pred1;
  160. } else {
  161. // We know that one arm of the conditional goes to BB, so the other must
  162. // go somewhere unrelated, and this must not be an "if statement".
  163. return 0;
  164. }
  165. return Pred1Br->getCondition();
  166. }
  167. // Ok, if we got here, both predecessors end with an unconditional branch to
  168. // BB. Don't panic! If both blocks only have a single (identical)
  169. // predecessor, and THAT is a conditional branch, then we're all ok!
  170. BasicBlock *CommonPred = Pred1->getSinglePredecessor();
  171. if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
  172. return 0;
  173. // Otherwise, if this is a conditional branch, then we can use it!
  174. BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
  175. if (BI == 0) return 0;
  176. assert(BI->isConditional() && "Two successors but not conditional?");
  177. if (BI->getSuccessor(0) == Pred1) {
  178. IfTrue = Pred1;
  179. IfFalse = Pred2;
  180. } else {
  181. IfTrue = Pred2;
  182. IfFalse = Pred1;
  183. }
  184. return BI->getCondition();
  185. }
  186. /// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
  187. /// given instruction, which is assumed to be safe to speculate. 1 means
  188. /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
  189. static unsigned ComputeSpeculationCost(const User *I) {
  190. assert(isSafeToSpeculativelyExecute(I) &&
  191. "Instruction is not safe to speculatively execute!");
  192. switch (Operator::getOpcode(I)) {
  193. default:
  194. // In doubt, be conservative.
  195. return UINT_MAX;
  196. case Instruction::GetElementPtr:
  197. // GEPs are cheap if all indices are constant.
  198. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  199. return UINT_MAX;
  200. return 1;
  201. case Instruction::Load:
  202. case Instruction::Add:
  203. case Instruction::Sub:
  204. case Instruction::And:
  205. case Instruction::Or:
  206. case Instruction::Xor:
  207. case Instruction::Shl:
  208. case Instruction::LShr:
  209. case Instruction::AShr:
  210. case Instruction::ICmp:
  211. case Instruction::Trunc:
  212. case Instruction::ZExt:
  213. case Instruction::SExt:
  214. return 1; // These are all cheap.
  215. case Instruction::Call:
  216. case Instruction::Select:
  217. return 2;
  218. }
  219. }
  220. /// DominatesMergePoint - If we have a merge point of an "if condition" as
  221. /// accepted above, return true if the specified value dominates the block. We
  222. /// don't handle the true generality of domination here, just a special case
  223. /// which works well enough for us.
  224. ///
  225. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  226. /// see if V (which must be an instruction) and its recursive operands
  227. /// that do not dominate BB have a combined cost lower than CostRemaining and
  228. /// are non-trapping. If both are true, the instruction is inserted into the
  229. /// set and true is returned.
  230. ///
  231. /// The cost for most non-trapping instructions is defined as 1 except for
  232. /// Select whose cost is 2.
  233. ///
  234. /// After this function returns, CostRemaining is decreased by the cost of
  235. /// V plus its non-dominating operands. If that cost is greater than
  236. /// CostRemaining, false is returned and CostRemaining is undefined.
  237. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  238. SmallPtrSet<Instruction*, 4> *AggressiveInsts,
  239. unsigned &CostRemaining) {
  240. Instruction *I = dyn_cast<Instruction>(V);
  241. if (!I) {
  242. // Non-instructions all dominate instructions, but not all constantexprs
  243. // can be executed unconditionally.
  244. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  245. if (C->canTrap())
  246. return false;
  247. return true;
  248. }
  249. BasicBlock *PBB = I->getParent();
  250. // We don't want to allow weird loops that might have the "if condition" in
  251. // the bottom of this block.
  252. if (PBB == BB) return false;
  253. // If this instruction is defined in a block that contains an unconditional
  254. // branch to BB, then it must be in the 'conditional' part of the "if
  255. // statement". If not, it definitely dominates the region.
  256. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  257. if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
  258. return true;
  259. // If we aren't allowing aggressive promotion anymore, then don't consider
  260. // instructions in the 'if region'.
  261. if (AggressiveInsts == 0) return false;
  262. // If we have seen this instruction before, don't count it again.
  263. if (AggressiveInsts->count(I)) return true;
  264. // Okay, it looks like the instruction IS in the "condition". Check to
  265. // see if it's a cheap instruction to unconditionally compute, and if it
  266. // only uses stuff defined outside of the condition. If so, hoist it out.
  267. if (!isSafeToSpeculativelyExecute(I))
  268. return false;
  269. unsigned Cost = ComputeSpeculationCost(I);
  270. if (Cost > CostRemaining)
  271. return false;
  272. CostRemaining -= Cost;
  273. // Okay, we can only really hoist these out if their operands do
  274. // not take us over the cost threshold.
  275. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  276. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
  277. return false;
  278. // Okay, it's safe to do this! Remember this instruction.
  279. AggressiveInsts->insert(I);
  280. return true;
  281. }
  282. /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
  283. /// and PointerNullValue. Return NULL if value is not a constant int.
  284. static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
  285. // Normal constant int.
  286. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  287. if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
  288. return CI;
  289. // This is some kind of pointer constant. Turn it into a pointer-sized
  290. // ConstantInt if possible.
  291. IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
  292. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  293. if (isa<ConstantPointerNull>(V))
  294. return ConstantInt::get(PtrTy, 0);
  295. // IntToPtr const int.
  296. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  297. if (CE->getOpcode() == Instruction::IntToPtr)
  298. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  299. // The constant is very likely to have the right type already.
  300. if (CI->getType() == PtrTy)
  301. return CI;
  302. else
  303. return cast<ConstantInt>
  304. (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  305. }
  306. return 0;
  307. }
  308. /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
  309. /// collection of icmp eq/ne instructions that compare a value against a
  310. /// constant, return the value being compared, and stick the constant into the
  311. /// Values vector.
  312. static Value *
  313. GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
  314. const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
  315. Instruction *I = dyn_cast<Instruction>(V);
  316. if (I == 0) return 0;
  317. // If this is an icmp against a constant, handle this as one of the cases.
  318. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
  319. if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
  320. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
  321. UsedICmps++;
  322. Vals.push_back(C);
  323. return I->getOperand(0);
  324. }
  325. // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
  326. // the set.
  327. ConstantRange Span =
  328. ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
  329. // If this is an and/!= check then we want to optimize "x ugt 2" into
  330. // x != 0 && x != 1.
  331. if (!isEQ)
  332. Span = Span.inverse();
  333. // If there are a ton of values, we don't want to make a ginormous switch.
  334. if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
  335. // We don't handle wrapped sets yet.
  336. Span.isWrappedSet())
  337. return 0;
  338. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  339. Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
  340. UsedICmps++;
  341. return I->getOperand(0);
  342. }
  343. return 0;
  344. }
  345. // Otherwise, we can only handle an | or &, depending on isEQ.
  346. if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
  347. return 0;
  348. unsigned NumValsBeforeLHS = Vals.size();
  349. unsigned UsedICmpsBeforeLHS = UsedICmps;
  350. if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
  351. isEQ, UsedICmps)) {
  352. unsigned NumVals = Vals.size();
  353. unsigned UsedICmpsBeforeRHS = UsedICmps;
  354. if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
  355. isEQ, UsedICmps)) {
  356. if (LHS == RHS)
  357. return LHS;
  358. Vals.resize(NumVals);
  359. UsedICmps = UsedICmpsBeforeRHS;
  360. }
  361. // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
  362. // set it and return success.
  363. if (Extra == 0 || Extra == I->getOperand(1)) {
  364. Extra = I->getOperand(1);
  365. return LHS;
  366. }
  367. Vals.resize(NumValsBeforeLHS);
  368. UsedICmps = UsedICmpsBeforeLHS;
  369. return 0;
  370. }
  371. // If the LHS can't be folded in, but Extra is available and RHS can, try to
  372. // use LHS as Extra.
  373. if (Extra == 0 || Extra == I->getOperand(0)) {
  374. Value *OldExtra = Extra;
  375. Extra = I->getOperand(0);
  376. if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
  377. isEQ, UsedICmps))
  378. return RHS;
  379. assert(Vals.size() == NumValsBeforeLHS);
  380. Extra = OldExtra;
  381. }
  382. return 0;
  383. }
  384. static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
  385. Instruction *Cond = 0;
  386. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  387. Cond = dyn_cast<Instruction>(SI->getCondition());
  388. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  389. if (BI->isConditional())
  390. Cond = dyn_cast<Instruction>(BI->getCondition());
  391. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  392. Cond = dyn_cast<Instruction>(IBI->getAddress());
  393. }
  394. TI->eraseFromParent();
  395. if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
  396. }
  397. /// isValueEqualityComparison - Return true if the specified terminator checks
  398. /// to see if a value is equal to constant integer value.
  399. Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
  400. Value *CV = 0;
  401. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  402. // Do not permit merging of large switch instructions into their
  403. // predecessors unless there is only one predecessor.
  404. if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
  405. pred_end(SI->getParent())) <= 128)
  406. CV = SI->getCondition();
  407. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  408. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  409. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
  410. if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
  411. ICI->getPredicate() == ICmpInst::ICMP_NE) &&
  412. GetConstantInt(ICI->getOperand(1), TD))
  413. CV = ICI->getOperand(0);
  414. // Unwrap any lossless ptrtoint cast.
  415. if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
  416. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
  417. CV = PTII->getOperand(0);
  418. return CV;
  419. }
  420. /// GetValueEqualityComparisonCases - Given a value comparison instruction,
  421. /// decode all of the 'cases' that it represents and return the 'default' block.
  422. BasicBlock *SimplifyCFGOpt::
  423. GetValueEqualityComparisonCases(TerminatorInst *TI,
  424. std::vector<std::pair<ConstantInt*,
  425. BasicBlock*> > &Cases) {
  426. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  427. Cases.reserve(SI->getNumCases());
  428. for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
  429. Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
  430. return SI->getDefaultDest();
  431. }
  432. BranchInst *BI = cast<BranchInst>(TI);
  433. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  434. Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
  435. BI->getSuccessor(ICI->getPredicate() ==
  436. ICmpInst::ICMP_NE)));
  437. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  438. }
  439. /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
  440. /// in the list that match the specified block.
  441. static void EliminateBlockCases(BasicBlock *BB,
  442. std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
  443. for (unsigned i = 0, e = Cases.size(); i != e; ++i)
  444. if (Cases[i].second == BB) {
  445. Cases.erase(Cases.begin()+i);
  446. --i; --e;
  447. }
  448. }
  449. /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
  450. /// well.
  451. static bool
  452. ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
  453. std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
  454. std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
  455. // Make V1 be smaller than V2.
  456. if (V1->size() > V2->size())
  457. std::swap(V1, V2);
  458. if (V1->size() == 0) return false;
  459. if (V1->size() == 1) {
  460. // Just scan V2.
  461. ConstantInt *TheVal = (*V1)[0].first;
  462. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  463. if (TheVal == (*V2)[i].first)
  464. return true;
  465. }
  466. // Otherwise, just sort both lists and compare element by element.
  467. array_pod_sort(V1->begin(), V1->end());
  468. array_pod_sort(V2->begin(), V2->end());
  469. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  470. while (i1 != e1 && i2 != e2) {
  471. if ((*V1)[i1].first == (*V2)[i2].first)
  472. return true;
  473. if ((*V1)[i1].first < (*V2)[i2].first)
  474. ++i1;
  475. else
  476. ++i2;
  477. }
  478. return false;
  479. }
  480. /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
  481. /// terminator instruction and its block is known to only have a single
  482. /// predecessor block, check to see if that predecessor is also a value
  483. /// comparison with the same value, and if that comparison determines the
  484. /// outcome of this comparison. If so, simplify TI. This does a very limited
  485. /// form of jump threading.
  486. bool SimplifyCFGOpt::
  487. SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  488. BasicBlock *Pred,
  489. IRBuilder<> &Builder) {
  490. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  491. if (!PredVal) return false; // Not a value comparison in predecessor.
  492. Value *ThisVal = isValueEqualityComparison(TI);
  493. assert(ThisVal && "This isn't a value comparison!!");
  494. if (ThisVal != PredVal) return false; // Different predicates.
  495. // Find out information about when control will move from Pred to TI's block.
  496. std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
  497. BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
  498. PredCases);
  499. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  500. // Find information about how control leaves this block.
  501. std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
  502. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  503. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  504. // If TI's block is the default block from Pred's comparison, potentially
  505. // simplify TI based on this knowledge.
  506. if (PredDef == TI->getParent()) {
  507. // If we are here, we know that the value is none of those cases listed in
  508. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  509. // can simplify TI.
  510. if (!ValuesOverlap(PredCases, ThisCases))
  511. return false;
  512. if (isa<BranchInst>(TI)) {
  513. // Okay, one of the successors of this condbr is dead. Convert it to a
  514. // uncond br.
  515. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  516. // Insert the new branch.
  517. Instruction *NI = Builder.CreateBr(ThisDef);
  518. (void) NI;
  519. // Remove PHI node entries for the dead edge.
  520. ThisCases[0].second->removePredecessor(TI->getParent());
  521. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  522. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  523. EraseTerminatorInstAndDCECond(TI);
  524. return true;
  525. }
  526. SwitchInst *SI = cast<SwitchInst>(TI);
  527. // Okay, TI has cases that are statically dead, prune them away.
  528. SmallPtrSet<Constant*, 16> DeadCases;
  529. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  530. DeadCases.insert(PredCases[i].first);
  531. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  532. << "Through successor TI: " << *TI);
  533. for (unsigned i = SI->getNumCases()-1; i != 0; --i)
  534. if (DeadCases.count(SI->getCaseValue(i))) {
  535. SI->getSuccessor(i)->removePredecessor(TI->getParent());
  536. SI->removeCase(i);
  537. }
  538. DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  539. return true;
  540. }
  541. // Otherwise, TI's block must correspond to some matched value. Find out
  542. // which value (or set of values) this is.
  543. ConstantInt *TIV = 0;
  544. BasicBlock *TIBB = TI->getParent();
  545. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  546. if (PredCases[i].second == TIBB) {
  547. if (TIV != 0)
  548. return false; // Cannot handle multiple values coming to this block.
  549. TIV = PredCases[i].first;
  550. }
  551. assert(TIV && "No edge from pred to succ?");
  552. // Okay, we found the one constant that our value can be if we get into TI's
  553. // BB. Find out which successor will unconditionally be branched to.
  554. BasicBlock *TheRealDest = 0;
  555. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  556. if (ThisCases[i].first == TIV) {
  557. TheRealDest = ThisCases[i].second;
  558. break;
  559. }
  560. // If not handled by any explicit cases, it is handled by the default case.
  561. if (TheRealDest == 0) TheRealDest = ThisDef;
  562. // Remove PHI node entries for dead edges.
  563. BasicBlock *CheckEdge = TheRealDest;
  564. for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
  565. if (*SI != CheckEdge)
  566. (*SI)->removePredecessor(TIBB);
  567. else
  568. CheckEdge = 0;
  569. // Insert the new branch.
  570. Instruction *NI = Builder.CreateBr(TheRealDest);
  571. (void) NI;
  572. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  573. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  574. EraseTerminatorInstAndDCECond(TI);
  575. return true;
  576. }
  577. namespace {
  578. /// ConstantIntOrdering - This class implements a stable ordering of constant
  579. /// integers that does not depend on their address. This is important for
  580. /// applications that sort ConstantInt's to ensure uniqueness.
  581. struct ConstantIntOrdering {
  582. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  583. return LHS->getValue().ult(RHS->getValue());
  584. }
  585. };
  586. }
  587. static int ConstantIntSortPredicate(const void *P1, const void *P2) {
  588. const ConstantInt *LHS = *(const ConstantInt**)P1;
  589. const ConstantInt *RHS = *(const ConstantInt**)P2;
  590. if (LHS->getValue().ult(RHS->getValue()))
  591. return 1;
  592. if (LHS->getValue() == RHS->getValue())
  593. return 0;
  594. return -1;
  595. }
  596. /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
  597. /// equality comparison instruction (either a switch or a branch on "X == c").
  598. /// See if any of the predecessors of the terminator block are value comparisons
  599. /// on the same value. If so, and if safe to do so, fold them together.
  600. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  601. IRBuilder<> &Builder) {
  602. BasicBlock *BB = TI->getParent();
  603. Value *CV = isValueEqualityComparison(TI); // CondVal
  604. assert(CV && "Not a comparison?");
  605. bool Changed = false;
  606. SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
  607. while (!Preds.empty()) {
  608. BasicBlock *Pred = Preds.pop_back_val();
  609. // See if the predecessor is a comparison with the same value.
  610. TerminatorInst *PTI = Pred->getTerminator();
  611. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  612. if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
  613. // Figure out which 'cases' to copy from SI to PSI.
  614. std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
  615. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  616. std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
  617. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  618. // Based on whether the default edge from PTI goes to BB or not, fill in
  619. // PredCases and PredDefault with the new switch cases we would like to
  620. // build.
  621. SmallVector<BasicBlock*, 8> NewSuccessors;
  622. if (PredDefault == BB) {
  623. // If this is the default destination from PTI, only the edges in TI
  624. // that don't occur in PTI, or that branch to BB will be activated.
  625. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  626. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  627. if (PredCases[i].second != BB)
  628. PTIHandled.insert(PredCases[i].first);
  629. else {
  630. // The default destination is BB, we don't need explicit targets.
  631. std::swap(PredCases[i], PredCases.back());
  632. PredCases.pop_back();
  633. --i; --e;
  634. }
  635. // Reconstruct the new switch statement we will be building.
  636. if (PredDefault != BBDefault) {
  637. PredDefault->removePredecessor(Pred);
  638. PredDefault = BBDefault;
  639. NewSuccessors.push_back(BBDefault);
  640. }
  641. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  642. if (!PTIHandled.count(BBCases[i].first) &&
  643. BBCases[i].second != BBDefault) {
  644. PredCases.push_back(BBCases[i]);
  645. NewSuccessors.push_back(BBCases[i].second);
  646. }
  647. } else {
  648. // If this is not the default destination from PSI, only the edges
  649. // in SI that occur in PSI with a destination of BB will be
  650. // activated.
  651. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  652. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  653. if (PredCases[i].second == BB) {
  654. PTIHandled.insert(PredCases[i].first);
  655. std::swap(PredCases[i], PredCases.back());
  656. PredCases.pop_back();
  657. --i; --e;
  658. }
  659. // Okay, now we know which constants were sent to BB from the
  660. // predecessor. Figure out where they will all go now.
  661. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  662. if (PTIHandled.count(BBCases[i].first)) {
  663. // If this is one we are capable of getting...
  664. PredCases.push_back(BBCases[i]);
  665. NewSuccessors.push_back(BBCases[i].second);
  666. PTIHandled.erase(BBCases[i].first);// This constant is taken care of
  667. }
  668. // If there are any constants vectored to BB that TI doesn't handle,
  669. // they must go to the default destination of TI.
  670. for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
  671. PTIHandled.begin(),
  672. E = PTIHandled.end(); I != E; ++I) {
  673. PredCases.push_back(std::make_pair(*I, BBDefault));
  674. NewSuccessors.push_back(BBDefault);
  675. }
  676. }
  677. // Okay, at this point, we know which new successor Pred will get. Make
  678. // sure we update the number of entries in the PHI nodes for these
  679. // successors.
  680. for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
  681. AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
  682. Builder.SetInsertPoint(PTI);
  683. // Convert pointer to int before we switch.
  684. if (CV->getType()->isPointerTy()) {
  685. assert(TD && "Cannot switch on pointer without TargetData");
  686. CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
  687. "magicptr");
  688. }
  689. // Now that the successors are updated, create the new Switch instruction.
  690. SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
  691. PredCases.size());
  692. NewSI->setDebugLoc(PTI->getDebugLoc());
  693. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  694. NewSI->addCase(PredCases[i].first, PredCases[i].second);
  695. EraseTerminatorInstAndDCECond(PTI);
  696. // Okay, last check. If BB is still a successor of PSI, then we must
  697. // have an infinite loop case. If so, add an infinitely looping block
  698. // to handle the case to preserve the behavior of the code.
  699. BasicBlock *InfLoopBlock = 0;
  700. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  701. if (NewSI->getSuccessor(i) == BB) {
  702. if (InfLoopBlock == 0) {
  703. // Insert it at the end of the function, because it's either code,
  704. // or it won't matter if it's hot. :)
  705. InfLoopBlock = BasicBlock::Create(BB->getContext(),
  706. "infloop", BB->getParent());
  707. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  708. }
  709. NewSI->setSuccessor(i, InfLoopBlock);
  710. }
  711. Changed = true;
  712. }
  713. }
  714. return Changed;
  715. }
  716. // isSafeToHoistInvoke - If we would need to insert a select that uses the
  717. // value of this invoke (comments in HoistThenElseCodeToIf explain why we
  718. // would need to do this), we can't hoist the invoke, as there is nowhere
  719. // to put the select in this case.
  720. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  721. Instruction *I1, Instruction *I2) {
  722. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  723. PHINode *PN;
  724. for (BasicBlock::iterator BBI = SI->begin();
  725. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  726. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  727. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  728. if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
  729. return false;
  730. }
  731. }
  732. }
  733. return true;
  734. }
  735. /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
  736. /// BB2, hoist any common code in the two blocks up into the branch block. The
  737. /// caller of this function guarantees that BI's block dominates BB1 and BB2.
  738. static bool HoistThenElseCodeToIf(BranchInst *BI) {
  739. // This does very trivial matching, with limited scanning, to find identical
  740. // instructions in the two blocks. In particular, we don't want to get into
  741. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  742. // such, we currently just scan for obviously identical instructions in an
  743. // identical order.
  744. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  745. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  746. BasicBlock::iterator BB1_Itr = BB1->begin();
  747. BasicBlock::iterator BB2_Itr = BB2->begin();
  748. Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
  749. // Skip debug info if it is not identical.
  750. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  751. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  752. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  753. while (isa<DbgInfoIntrinsic>(I1))
  754. I1 = BB1_Itr++;
  755. while (isa<DbgInfoIntrinsic>(I2))
  756. I2 = BB2_Itr++;
  757. }
  758. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  759. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  760. return false;
  761. // If we get here, we can hoist at least one instruction.
  762. BasicBlock *BIParent = BI->getParent();
  763. do {
  764. // If we are hoisting the terminator instruction, don't move one (making a
  765. // broken BB), instead clone it, and remove BI.
  766. if (isa<TerminatorInst>(I1))
  767. goto HoistTerminator;
  768. // For a normal instruction, we just move one to right before the branch,
  769. // then replace all uses of the other with the first. Finally, we remove
  770. // the now redundant second instruction.
  771. BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
  772. if (!I2->use_empty())
  773. I2->replaceAllUsesWith(I1);
  774. I1->intersectOptionalDataWith(I2);
  775. I2->eraseFromParent();
  776. I1 = BB1_Itr++;
  777. I2 = BB2_Itr++;
  778. // Skip debug info if it is not identical.
  779. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  780. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  781. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  782. while (isa<DbgInfoIntrinsic>(I1))
  783. I1 = BB1_Itr++;
  784. while (isa<DbgInfoIntrinsic>(I2))
  785. I2 = BB2_Itr++;
  786. }
  787. } while (I1->isIdenticalToWhenDefined(I2));
  788. return true;
  789. HoistTerminator:
  790. // It may not be possible to hoist an invoke.
  791. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  792. return true;
  793. // Okay, it is safe to hoist the terminator.
  794. Instruction *NT = I1->clone();
  795. BIParent->getInstList().insert(BI, NT);
  796. if (!NT->getType()->isVoidTy()) {
  797. I1->replaceAllUsesWith(NT);
  798. I2->replaceAllUsesWith(NT);
  799. NT->takeName(I1);
  800. }
  801. IRBuilder<true, NoFolder> Builder(NT);
  802. // Hoisting one of the terminators from our successor is a great thing.
  803. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  804. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  805. // nodes, so we insert select instruction to compute the final result.
  806. std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
  807. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  808. PHINode *PN;
  809. for (BasicBlock::iterator BBI = SI->begin();
  810. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  811. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  812. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  813. if (BB1V == BB2V) continue;
  814. // These values do not agree. Insert a select instruction before NT
  815. // that determines the right value.
  816. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  817. if (SI == 0)
  818. SI = cast<SelectInst>
  819. (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  820. BB1V->getName()+"."+BB2V->getName()));
  821. // Make the PHI node use the select for all incoming values for BB1/BB2
  822. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  823. if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
  824. PN->setIncomingValue(i, SI);
  825. }
  826. }
  827. // Update any PHI nodes in our new successors.
  828. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
  829. AddPredecessorToBlock(*SI, BIParent, BB1);
  830. EraseTerminatorInstAndDCECond(BI);
  831. return true;
  832. }
  833. /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
  834. /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
  835. /// (for now, restricted to a single instruction that's side effect free) from
  836. /// the BB1 into the branch block to speculatively execute it.
  837. ///
  838. /// Turn
  839. /// BB:
  840. /// %t1 = icmp
  841. /// br i1 %t1, label %BB1, label %BB2
  842. /// BB1:
  843. /// %t3 = add %t2, c
  844. /// br label BB2
  845. /// BB2:
  846. /// =>
  847. /// BB:
  848. /// %t1 = icmp
  849. /// %t4 = add %t2, c
  850. /// %t3 = select i1 %t1, %t2, %t3
  851. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
  852. // Only speculatively execution a single instruction (not counting the
  853. // terminator) for now.
  854. Instruction *HInst = NULL;
  855. Instruction *Term = BB1->getTerminator();
  856. for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
  857. BBI != BBE; ++BBI) {
  858. Instruction *I = BBI;
  859. // Skip debug info.
  860. if (isa<DbgInfoIntrinsic>(I)) continue;
  861. if (I == Term) break;
  862. if (HInst)
  863. return false;
  864. HInst = I;
  865. }
  866. BasicBlock *BIParent = BI->getParent();
  867. // Check the instruction to be hoisted, if there is one.
  868. if (HInst) {
  869. // Don't hoist the instruction if it's unsafe or expensive.
  870. if (!isSafeToSpeculativelyExecute(HInst))
  871. return false;
  872. if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
  873. return false;
  874. // Do not hoist the instruction if any of its operands are defined but not
  875. // used in this BB. The transformation will prevent the operand from
  876. // being sunk into the use block.
  877. for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
  878. i != e; ++i) {
  879. Instruction *OpI = dyn_cast<Instruction>(*i);
  880. if (OpI && OpI->getParent() == BIParent &&
  881. !OpI->mayHaveSideEffects() &&
  882. !OpI->isUsedInBasicBlock(BIParent))
  883. return false;
  884. }
  885. }
  886. // Be conservative for now. FP select instruction can often be expensive.
  887. Value *BrCond = BI->getCondition();
  888. if (isa<FCmpInst>(BrCond))
  889. return false;
  890. // If BB1 is actually on the false edge of the conditional branch, remember
  891. // to swap the select operands later.
  892. bool Invert = false;
  893. if (BB1 != BI->getSuccessor(0)) {
  894. assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
  895. Invert = true;
  896. }
  897. // Collect interesting PHIs, and scan for hazards.
  898. SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
  899. BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
  900. for (BasicBlock::iterator I = BB2->begin();
  901. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  902. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  903. Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
  904. // Skip PHIs which are trivial.
  905. if (BB1V == BIParentV)
  906. continue;
  907. // Check for saftey.
  908. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
  909. // An unfolded ConstantExpr could end up getting expanded into
  910. // Instructions. Don't speculate this and another instruction at
  911. // the same time.
  912. if (HInst)
  913. return false;
  914. if (!isSafeToSpeculativelyExecute(CE))
  915. return false;
  916. if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
  917. return false;
  918. }
  919. // Ok, we may insert a select for this PHI.
  920. PHIs.insert(std::make_pair(BB1V, BIParentV));
  921. }
  922. // If there are no PHIs to process, bail early. This helps ensure idempotence
  923. // as well.
  924. if (PHIs.empty())
  925. return false;
  926. // If we get here, we can hoist the instruction and if-convert.
  927. DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
  928. // Hoist the instruction.
  929. if (HInst)
  930. BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
  931. // Insert selects and rewrite the PHI operands.
  932. IRBuilder<true, NoFolder> Builder(BI);
  933. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  934. Value *TrueV = PHIs[i].first;
  935. Value *FalseV = PHIs[i].second;
  936. // Create a select whose true value is the speculatively executed value and
  937. // false value is the previously determined FalseV.
  938. SelectInst *SI;
  939. if (Invert)
  940. SI = cast<SelectInst>
  941. (Builder.CreateSelect(BrCond, FalseV, TrueV,
  942. FalseV->getName() + "." + TrueV->getName()));
  943. else
  944. SI = cast<SelectInst>
  945. (Builder.CreateSelect(BrCond, TrueV, FalseV,
  946. TrueV->getName() + "." + FalseV->getName()));
  947. // Make the PHI node use the select for all incoming values for "then" and
  948. // "if" blocks.
  949. for (BasicBlock::iterator I = BB2->begin();
  950. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  951. unsigned BB1I = PN->getBasicBlockIndex(BB1);
  952. unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
  953. Value *BB1V = PN->getIncomingValue(BB1I);
  954. Value *BIParentV = PN->getIncomingValue(BIParentI);
  955. if (TrueV == BB1V && FalseV == BIParentV) {
  956. PN->setIncomingValue(BB1I, SI);
  957. PN->setIncomingValue(BIParentI, SI);
  958. }
  959. }
  960. }
  961. ++NumSpeculations;
  962. return true;
  963. }
  964. /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
  965. /// across this block.
  966. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  967. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  968. unsigned Size = 0;
  969. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  970. if (isa<DbgInfoIntrinsic>(BBI))
  971. continue;
  972. if (Size > 10) return false; // Don't clone large BB's.
  973. ++Size;
  974. // We can only support instructions that do not define values that are
  975. // live outside of the current basic block.
  976. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  977. UI != E; ++UI) {
  978. Instruction *U = cast<Instruction>(*UI);
  979. if (U->getParent() != BB || isa<PHINode>(U)) return false;
  980. }
  981. // Looks ok, continue checking.
  982. }
  983. return true;
  984. }
  985. /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
  986. /// that is defined in the same block as the branch and if any PHI entries are
  987. /// constants, thread edges corresponding to that entry to be branches to their
  988. /// ultimate destination.
  989. static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
  990. BasicBlock *BB = BI->getParent();
  991. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  992. // NOTE: we currently cannot transform this case if the PHI node is used
  993. // outside of the block.
  994. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  995. return false;
  996. // Degenerate case of a single entry PHI.
  997. if (PN->getNumIncomingValues() == 1) {
  998. FoldSingleEntryPHINodes(PN->getParent());
  999. return true;
  1000. }
  1001. // Now we know that this block has multiple preds and two succs.
  1002. if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
  1003. // Okay, this is a simple enough basic block. See if any phi values are
  1004. // constants.
  1005. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1006. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1007. if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
  1008. // Okay, we now know that all edges from PredBB should be revectored to
  1009. // branch to RealDest.
  1010. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1011. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1012. if (RealDest == BB) continue; // Skip self loops.
  1013. // Skip if the predecessor's terminator is an indirect branch.
  1014. if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
  1015. // The dest block might have PHI nodes, other predecessors and other
  1016. // difficult cases. Instead of being smart about this, just insert a new
  1017. // block that jumps to the destination block, effectively splitting
  1018. // the edge we are about to create.
  1019. BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
  1020. RealDest->getName()+".critedge",
  1021. RealDest->getParent(), RealDest);
  1022. BranchInst::Create(RealDest, EdgeBB);
  1023. // Update PHI nodes.
  1024. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1025. // BB may have instructions that are being threaded over. Clone these
  1026. // instructions into EdgeBB. We know that there will be no uses of the
  1027. // cloned instructions outside of EdgeBB.
  1028. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1029. DenseMap<Value*, Value*> TranslateMap; // Track translated values.
  1030. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1031. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1032. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1033. continue;
  1034. }
  1035. // Clone the instruction.
  1036. Instruction *N = BBI->clone();
  1037. if (BBI->hasName()) N->setName(BBI->getName()+".c");
  1038. // Update operands due to translation.
  1039. for (User::op_iterator i = N->op_begin(), e = N->op_end();
  1040. i != e; ++i) {
  1041. DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
  1042. if (PI != TranslateMap.end())
  1043. *i = PI->second;
  1044. }
  1045. // Check for trivial simplification.
  1046. if (Value *V = SimplifyInstruction(N, TD)) {
  1047. TranslateMap[BBI] = V;
  1048. delete N; // Instruction folded away, don't need actual inst
  1049. } else {
  1050. // Insert the new instruction into its new home.
  1051. EdgeBB->getInstList().insert(InsertPt, N);
  1052. if (!BBI->use_empty())
  1053. TranslateMap[BBI] = N;
  1054. }
  1055. }
  1056. // Loop over all of the edges from PredBB to BB, changing them to branch
  1057. // to EdgeBB instead.
  1058. TerminatorInst *PredBBTI = PredBB->getTerminator();
  1059. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1060. if (PredBBTI->getSuccessor(i) == BB) {
  1061. BB->removePredecessor(PredBB);
  1062. PredBBTI->setSuccessor(i, EdgeBB);
  1063. }
  1064. // Recurse, simplifying any other constants.
  1065. return FoldCondBranchOnPHI(BI, TD) | true;
  1066. }
  1067. return false;
  1068. }
  1069. /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
  1070. /// PHI node, see if we can eliminate it.
  1071. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
  1072. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1073. // statement", which has a very simple dominance structure. Basically, we
  1074. // are trying to find the condition that is being branched on, which
  1075. // subsequently causes this merge to happen. We really want control
  1076. // dependence information for this check, but simplifycfg can't keep it up
  1077. // to date, and this catches most of the cases we care about anyway.
  1078. BasicBlock *BB = PN->getParent();
  1079. BasicBlock *IfTrue, *IfFalse;
  1080. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  1081. if (!IfCond ||
  1082. // Don't bother if the branch will be constant folded trivially.
  1083. isa<ConstantInt>(IfCond))
  1084. return false;
  1085. // Okay, we found that we can merge this two-entry phi node into a select.
  1086. // Doing so would require us to fold *all* two entry phi nodes in this block.
  1087. // At some point this becomes non-profitable (particularly if the target
  1088. // doesn't support cmov's). Only do this transformation if there are two or
  1089. // fewer PHI nodes in this block.
  1090. unsigned NumPhis = 0;
  1091. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  1092. if (NumPhis > 2)
  1093. return false;
  1094. // Loop over the PHI's seeing if we can promote them all to select
  1095. // instructions. While we are at it, keep track of the instructions
  1096. // that need to be moved to the dominating block.
  1097. SmallPtrSet<Instruction*, 4> AggressiveInsts;
  1098. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  1099. MaxCostVal1 = PHINodeFoldingThreshold;
  1100. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  1101. PHINode *PN = cast<PHINode>(II++);
  1102. if (Value *V = SimplifyInstruction(PN, TD)) {
  1103. PN->replaceAllUsesWith(V);
  1104. PN->eraseFromParent();
  1105. continue;
  1106. }
  1107. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
  1108. MaxCostVal0) ||
  1109. !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
  1110. MaxCostVal1))
  1111. return false;
  1112. }
  1113. // If we folded the the first phi, PN dangles at this point. Refresh it. If
  1114. // we ran out of PHIs then we simplified them all.
  1115. PN = dyn_cast<PHINode>(BB->begin());
  1116. if (PN == 0) return true;
  1117. // Don't fold i1 branches on PHIs which contain binary operators. These can
  1118. // often be turned into switches and other things.
  1119. if (PN->getType()->isIntegerTy(1) &&
  1120. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  1121. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  1122. isa<BinaryOperator>(IfCond)))
  1123. return false;
  1124. // If we all PHI nodes are promotable, check to make sure that all
  1125. // instructions in the predecessor blocks can be promoted as well. If
  1126. // not, we won't be able to get rid of the control flow, so it's not
  1127. // worth promoting to select instructions.
  1128. BasicBlock *DomBlock = 0;
  1129. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  1130. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  1131. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  1132. IfBlock1 = 0;
  1133. } else {
  1134. DomBlock = *pred_begin(IfBlock1);
  1135. for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
  1136. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1137. // This is not an aggressive instruction that we can promote.
  1138. // Because of this, we won't be able to get rid of the control
  1139. // flow, so the xform is not worth it.
  1140. return false;
  1141. }
  1142. }
  1143. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  1144. IfBlock2 = 0;
  1145. } else {
  1146. DomBlock = *pred_begin(IfBlock2);
  1147. for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
  1148. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1149. // This is not an aggressive instruction that we can promote.
  1150. // Because of this, we won't be able to get rid of the control
  1151. // flow, so the xform is not worth it.
  1152. return false;
  1153. }
  1154. }
  1155. DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
  1156. << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
  1157. // If we can still promote the PHI nodes after this gauntlet of tests,
  1158. // do all of the PHI's now.
  1159. Instruction *InsertPt = DomBlock->getTerminator();
  1160. IRBuilder<true, NoFolder> Builder(InsertPt);
  1161. // Move all 'aggressive' instructions, which are defined in the
  1162. // conditional parts of the if's up to the dominating block.
  1163. if (IfBlock1)
  1164. DomBlock->getInstList().splice(InsertPt,
  1165. IfBlock1->getInstList(), IfBlock1->begin(),
  1166. IfBlock1->getTerminator());
  1167. if (IfBlock2)
  1168. DomBlock->getInstList().splice(InsertPt,
  1169. IfBlock2->getInstList(), IfBlock2->begin(),
  1170. IfBlock2->getTerminator());
  1171. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  1172. // Change the PHI node into a select instruction.
  1173. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  1174. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  1175. SelectInst *NV =
  1176. cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
  1177. PN->replaceAllUsesWith(NV);
  1178. NV->takeName(PN);
  1179. PN->eraseFromParent();
  1180. }
  1181. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  1182. // has been flattened. Change DomBlock to jump directly to our new block to
  1183. // avoid other simplifycfg's kicking in on the diamond.
  1184. TerminatorInst *OldTI = DomBlock->getTerminator();
  1185. Builder.SetInsertPoint(OldTI);
  1186. Builder.CreateBr(BB);
  1187. OldTI->eraseFromParent();
  1188. return true;
  1189. }
  1190. /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
  1191. /// to two returning blocks, try to merge them together into one return,
  1192. /// introducing a select if the return values disagree.
  1193. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  1194. IRBuilder<> &Builder) {
  1195. assert(BI->isConditional() && "Must be a conditional branch");
  1196. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1197. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1198. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  1199. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  1200. // Check to ensure both blocks are empty (just a return) or optionally empty
  1201. // with PHI nodes. If there are other instructions, merging would cause extra
  1202. // computation on one path or the other.
  1203. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  1204. return false;
  1205. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  1206. return false;
  1207. Builder.SetInsertPoint(BI);
  1208. // Okay, we found a branch that is going to two return nodes. If
  1209. // there is no return value for this function, just change the
  1210. // branch into a return.
  1211. if (FalseRet->getNumOperands() == 0) {
  1212. TrueSucc->removePredecessor(BI->getParent());
  1213. FalseSucc->removePredecessor(BI->getParent());
  1214. Builder.CreateRetVoid();
  1215. EraseTerminatorInstAndDCECond(BI);
  1216. return true;
  1217. }
  1218. // Otherwise, figure out what the true and false return values are
  1219. // so we can insert a new select instruction.
  1220. Value *TrueValue = TrueRet->getReturnValue();
  1221. Value *FalseValue = FalseRet->getReturnValue();
  1222. // Unwrap any PHI nodes in the return blocks.
  1223. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  1224. if (TVPN->getParent() == TrueSucc)
  1225. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  1226. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  1227. if (FVPN->getParent() == FalseSucc)
  1228. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  1229. // In order for this transformation to be safe, we must be able to
  1230. // unconditionally execute both operands to the return. This is
  1231. // normally the case, but we could have a potentially-trapping
  1232. // constant expression that prevents this transformation from being
  1233. // safe.
  1234. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  1235. if (TCV->canTrap())
  1236. return false;
  1237. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  1238. if (FCV->canTrap())
  1239. return false;
  1240. // Okay, we collected all the mapped values and checked them for sanity, and
  1241. // defined to really do this transformation. First, update the CFG.
  1242. TrueSucc->removePredecessor(BI->getParent());
  1243. FalseSucc->removePredecessor(BI->getParent());
  1244. // Insert select instructions where needed.
  1245. Value *BrCond = BI->getCondition();
  1246. if (TrueValue) {
  1247. // Insert a select if the results differ.
  1248. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  1249. } else if (isa<UndefValue>(TrueValue)) {
  1250. TrueValue = FalseValue;
  1251. } else {
  1252. TrueValue = Builder.CreateSelect(BrCond, TrueValue,
  1253. FalseValue, "retval");
  1254. }
  1255. }
  1256. Value *RI = !TrueValue ?
  1257. Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  1258. (void) RI;
  1259. DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  1260. << "\n " << *BI << "NewRet = " << *RI
  1261. << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
  1262. EraseTerminatorInstAndDCECond(BI);
  1263. return true;
  1264. }
  1265. /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
  1266. /// probabilities of the branch taking each edge. Fills in the two APInt
  1267. /// parameters and return true, or returns false if no or invalid metadata was
  1268. /// found.
  1269. static bool ExtractBranchMetadata(BranchInst *BI,
  1270. APInt &ProbTrue, APInt &ProbFalse) {
  1271. assert(BI->isConditional() &&
  1272. "Looking for probabilities on unconditional branch?");
  1273. MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  1274. if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
  1275. ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
  1276. ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
  1277. if (!CITrue || !CIFalse) return false;
  1278. ProbTrue = CITrue->getValue();
  1279. ProbFalse = CIFalse->getValue();
  1280. assert(ProbTrue.getBitWidth() == 32 && ProbFalse.getBitWidth() == 32 &&
  1281. "Branch probability metadata must be 32-bit integers");
  1282. return true;
  1283. }
  1284. /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
  1285. /// predecessor branches to us and one of our successors, fold the block into
  1286. /// the predecessor and use logical operations to pick the right destination.
  1287. bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
  1288. BasicBlock *BB = BI->getParent();
  1289. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  1290. if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  1291. Cond->getParent() != BB || !Cond->hasOneUse())
  1292. return false;
  1293. // Only allow this if the condition is a simple instruction that can be
  1294. // executed unconditionally. It must be in the same block as the branch, and
  1295. // must be at the front of the block.
  1296. BasicBlock::iterator FrontIt = BB->front();
  1297. // Ignore dbg intrinsics.
  1298. while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
  1299. // Allow a single instruction to be hoisted in addition to the compare
  1300. // that feeds the branch. We later ensure that any values that _it_ uses
  1301. // were also live in the predecessor, so that we don't unnecessarily create
  1302. // register pressure or inhibit out-of-order execution.
  1303. Instruction *BonusInst = 0;
  1304. if (&*FrontIt != Cond &&
  1305. FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
  1306. isSafeToSpeculativelyExecute(FrontIt)) {
  1307. BonusInst = &*FrontIt;
  1308. ++FrontIt;
  1309. // Ignore dbg intrinsics.
  1310. while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
  1311. }
  1312. // Only a single bonus inst is allowed.
  1313. if (&*FrontIt != Cond)
  1314. return false;
  1315. // Make sure the instruction after the condition is the cond branch.
  1316. BasicBlock::iterator CondIt = Cond; ++CondIt;
  1317. // Ingore dbg intrinsics.
  1318. while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
  1319. if (&*CondIt != BI)
  1320. return false;
  1321. // Cond is known to be a compare or binary operator. Check to make sure that
  1322. // neither operand is a potentially-trapping constant expression.
  1323. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  1324. if (CE->canTrap())
  1325. return false;
  1326. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  1327. if (CE->canTrap())
  1328. return false;
  1329. // Finally, don't infinitely unroll conditional loops.
  1330. BasicBlock *TrueDest = BI->getSuccessor(0);
  1331. BasicBlock *FalseDest = BI->getSuccessor(1);
  1332. if (TrueDest == BB || FalseDest == BB)
  1333. return false;
  1334. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1335. BasicBlock *PredBlock = *PI;
  1336. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  1337. // Check that we have two conditional branches. If there is a PHI node in
  1338. // the common successor, verify that the same value flows in from both
  1339. // blocks.
  1340. if (PBI == 0 || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
  1341. continue;
  1342. // Determine if the two branches share a common destination.
  1343. Instruction::BinaryOps Opc;
  1344. bool InvertPredCond = false;
  1345. if (PBI->getSuccessor(0) == TrueDest)
  1346. Opc = Instruction::Or;
  1347. else if (PBI->getSuccessor(1) == FalseDest)
  1348. Opc = Instruction::And;
  1349. else if (PBI->getSuccessor(0) == FalseDest)
  1350. Opc = Instruction::And, InvertPredCond = true;
  1351. else if (PBI->getSuccessor(1) == TrueDest)
  1352. Opc = Instruction::Or, InvertPredCond = true;
  1353. else
  1354. continue;
  1355. // Ensure that any values used in the bonus instruction are also used
  1356. // by the terminator of the predecessor. This means that those values
  1357. // must already have been resolved, so we won't be inhibiting the
  1358. // out-of-order core by speculating them earlier.
  1359. if (BonusInst) {
  1360. // Collect the values used by the bonus inst
  1361. SmallPtrSet<Value*, 4> UsedValues;
  1362. for (Instruction::op_iterator OI = BonusInst->op_begin(),
  1363. OE = BonusInst->op_end(); OI != OE; ++OI) {
  1364. Value *V = *OI;
  1365. if (!isa<Constant>(V))
  1366. UsedValues.insert(V);
  1367. }
  1368. SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
  1369. Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
  1370. // Walk up to four levels back up the use-def chain of the predecessor's
  1371. // terminator to see if all those values were used. The choice of four
  1372. // levels is arbitrary, to provide a compile-time-cost bound.
  1373. while (!Worklist.empty()) {
  1374. std::pair<Value*, unsigned> Pair = Worklist.back();
  1375. Worklist.pop_back();
  1376. if (Pair.second >= 4) continue;
  1377. UsedValues.erase(Pair.first);
  1378. if (UsedValues.empty()) break;
  1379. if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
  1380. for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
  1381. OI != OE; ++OI)
  1382. Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
  1383. }
  1384. }
  1385. if (!UsedValues.empty()) return false;
  1386. }
  1387. DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  1388. IRBuilder<> Builder(PBI);
  1389. // If we need to invert the condition in the pred block to match, do so now.
  1390. if (InvertPredCond) {
  1391. Value *NewCond = PBI->getCondition();
  1392. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  1393. CmpInst *CI = cast<CmpInst>(NewCond);
  1394. CI->setPredicate(CI->getInversePredicate());
  1395. } else {
  1396. NewCond = Builder.CreateNot(NewCond,
  1397. PBI->getCondition()->getName()+".not");
  1398. }
  1399. PBI->setCondition(NewCond);
  1400. PBI->swapSuccessors();
  1401. }
  1402. // If we have a bonus inst, clone it into the predecessor block.
  1403. Instruction *NewBonus = 0;
  1404. if (BonusInst) {
  1405. NewBonus = BonusInst->clone();
  1406. PredBlock->getInstList().insert(PBI, NewBonus);
  1407. NewBonus->takeName(BonusInst);
  1408. BonusInst->setName(BonusInst->getName()+".old");
  1409. }
  1410. // Clone Cond into the predecessor basic block, and or/and the
  1411. // two conditions together.
  1412. Instruction *New = Cond->clone();
  1413. if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
  1414. PredBlock->getInstList().insert(PBI, New);
  1415. New->takeName(Cond);
  1416. Cond->setName(New->getName()+".old");
  1417. Instruction *NewCond =
  1418. cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
  1419. New, "or.cond"));
  1420. PBI->setCondition(NewCond);
  1421. if (PBI->getSuccessor(0) == BB) {
  1422. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  1423. PBI->setSuccessor(0, TrueDest);
  1424. }
  1425. if (PBI->getSuccessor(1) == BB) {
  1426. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  1427. PBI->setSuccessor(1, FalseDest);
  1428. }
  1429. // TODO: If BB is reachable from all paths through PredBlock, then we
  1430. // could replace PBI's branch probabilities with BI's.
  1431. // Merge probability data into PredBlock's branch.
  1432. APInt A, B, C, D;
  1433. if (ExtractBranchMetadata(PBI, C, D) && ExtractBranchMetadata(BI, A, B)) {
  1434. // Given IR which does:
  1435. // bbA:
  1436. // br i1 %x, label %bbB, label %bbC
  1437. // bbB:
  1438. // br i1 %y, label %bbD, label %bbC
  1439. // Let's call the probability that we take the edge from %bbA to %bbB
  1440. // 'a', from %bbA to %bbC, 'b', from %bbB to %bbD 'c' and from %bbB to
  1441. // %bbC probability 'd'.
  1442. //
  1443. // We transform the IR into:
  1444. // bbA:
  1445. // br i1 %z, label %bbD, label %bbC
  1446. // where the probability of going to %bbD is (a*c) and going to bbC is
  1447. // (b+a*d).
  1448. //
  1449. // Probabilities aren't stored as ratios directly. Using branch weights,
  1450. // we get:
  1451. // (a*c)% = A*C, (b+(a*d))% = A*D+B*C+B*D.
  1452. bool Overflow1 = false, Overflow2 = false, Overflow3 = false;
  1453. bool Overflow4 = false, Overflow5 = false, Overflow6 = false;
  1454. APInt ProbTrue = A.umul_ov(C, Overflow1);
  1455. APInt Tmp1 = A.umul_ov(D, Overflow2);
  1456. APInt Tmp2 = B.umul_ov(C, Overflow3);
  1457. APInt Tmp3 = B.umul_ov(D, Overflow4);
  1458. APInt Tmp4 = Tmp1.uadd_ov(Tmp2, Overflow5);
  1459. APInt ProbFalse = Tmp4.uadd_ov(Tmp3, Overflow6);
  1460. APInt GCD = APIntOps::GreatestCommonDivisor(ProbTrue, ProbFalse);
  1461. ProbTrue = ProbTrue.udiv(GCD);
  1462. ProbFalse = ProbFalse.udiv(GCD);
  1463. if (Overflow1 || Overflow2 || Overflow3 || Overflow4 || Overflow5 ||
  1464. Overflow6) {
  1465. DEBUG(dbgs() << "Overflow recomputing branch weight on: " << *PBI
  1466. << "when merging with: " << *BI);
  1467. PBI->setMetadata(LLVMContext::MD_prof, NULL);
  1468. } else {
  1469. LLVMContext &Context = BI->getContext();
  1470. Value *Ops[3];
  1471. Ops[0] = BI->getMetadata(LLVMContext::MD_prof)->getOperand(0);
  1472. Ops[1] = ConstantInt::get(Context, ProbTrue);
  1473. Ops[2] = ConstantInt::get(Context, ProbFalse);
  1474. PBI->setMetadata(LLVMContext::MD_prof, MDNode::get(Context, Ops));
  1475. }
  1476. } else {
  1477. PBI->setMetadata(LLVMContext::MD_prof, NULL);
  1478. }
  1479. // Copy any debug value intrinsics into the end of PredBlock.
  1480. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  1481. if (isa<DbgInfoIntrinsic>(*I))
  1482. I->clone()->insertBefore(PBI);
  1483. return true;
  1484. }
  1485. return false;
  1486. }
  1487. /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
  1488. /// predecessor of another block, this function tries to simplify it. We know
  1489. /// that PBI and BI are both conditional branches, and BI is in one of the
  1490. /// successor blocks of PBI - PBI branches to BI.
  1491. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
  1492. assert(PBI->isConditional() && BI->isConditional());
  1493. BasicBlock *BB = BI->getParent();
  1494. // If this block ends with a branch instruction, and if there is a
  1495. // predecessor that ends on a branch of the same condition, make
  1496. // this conditional branch redundant.
  1497. if (PBI->getCondition() == BI->getCondition() &&
  1498. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  1499. // Okay, the outcome of this conditional branch is statically
  1500. // knowable. If this block had a single pred, handle specially.
  1501. if (BB->getSinglePredecessor()) {
  1502. // Turn this into a branch on constant.
  1503. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  1504. BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  1505. CondIsTrue));
  1506. return true; // Nuke the branch on constant.
  1507. }
  1508. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  1509. // in the constant and simplify the block result. Subsequent passes of
  1510. // simplifycfg will thread the block.
  1511. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  1512. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  1513. PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
  1514. std::distance(PB, PE),
  1515. BI->getCondition()->getName() + ".pr",
  1516. BB->begin());
  1517. // Okay, we're going to insert the PHI node. Since PBI is not the only
  1518. // predecessor, compute the PHI'd conditional value for all of the preds.
  1519. // Any predecessor where the condition is not computable we keep symbolic.
  1520. for (pred_iterator PI = PB; PI != PE; ++PI) {
  1521. BasicBlock *P = *PI;
  1522. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
  1523. PBI != BI && PBI->isConditional() &&
  1524. PBI->getCondition() == BI->getCondition() &&
  1525. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  1526. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  1527. NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  1528. CondIsTrue), P);
  1529. } else {
  1530. NewPN->addIncoming(BI->getCondition(), P);
  1531. }
  1532. }
  1533. BI->setCondition(NewPN);
  1534. return true;
  1535. }
  1536. }
  1537. // If this is a conditional branch in an empty block, and if any
  1538. // predecessors is a conditional branch to one of our destinations,
  1539. // fold the conditions into logical ops and one cond br.
  1540. BasicBlock::iterator BBI = BB->begin();
  1541. // Ignore dbg intrinsics.
  1542. while (isa<DbgInfoIntrinsic>(BBI))
  1543. ++BBI;
  1544. if (&*BBI != BI)
  1545. return false;
  1546. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  1547. if (CE->canTrap())
  1548. return false;
  1549. int PBIOp, BIOp;
  1550. if (PBI->getSuccessor(0) == BI->getSuccessor(0))
  1551. PBIOp = BIOp = 0;
  1552. else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
  1553. PBIOp = 0, BIOp = 1;
  1554. else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
  1555. PBIOp = 1, BIOp = 0;
  1556. else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
  1557. PBIOp = BIOp = 1;
  1558. else
  1559. return false;
  1560. // Check to make sure that the other destination of this branch
  1561. // isn't BB itself. If so, this is an infinite loop that will
  1562. // keep getting unwound.
  1563. if (PBI->getSuccessor(PBIOp) == BB)
  1564. return false;
  1565. // Do not perform this transformation if it would require
  1566. // insertion of a large number of select instructions. For targets
  1567. // without predication/cmovs, this is a big pessimization.
  1568. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  1569. unsigned NumPhis = 0;
  1570. for (BasicBlock::iterator II = CommonDest->begin();
  1571. isa<PHINode>(II); ++II, ++NumPhis)
  1572. if (NumPhis > 2) // Disable this xform.
  1573. return false;
  1574. // Finally, if everything is ok, fold the branches to logical ops.
  1575. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  1576. DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  1577. << "AND: " << *BI->getParent());
  1578. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  1579. // branch in it, where one edge (OtherDest) goes back to itself but the other
  1580. // exits. We don't *know* that the program avoids the infinite loop
  1581. // (even though that seems likely). If we do this xform naively, we'll end up
  1582. // recursively unpeeling the loop. Since we know that (after the xform is
  1583. // done) that the block *is* infinite if reached, we just make it an obviously
  1584. // infinite loop with no cond branch.
  1585. if (OtherDest == BB) {
  1586. // Insert it at the end of the function, because it's either code,
  1587. // or it won't matter if it's hot. :)
  1588. BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
  1589. "infloop", BB->getParent());
  1590. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  1591. OtherDest = InfLoopBlock;
  1592. }
  1593. DEBUG(dbgs() << *PBI->getParent()->getParent());
  1594. // BI may have other predecessors. Because of this, we leave
  1595. // it alone, but modify PBI.
  1596. // Make sure we get to CommonDest on True&True directions.
  1597. Value *PBICond = PBI->getCondition();
  1598. IRBuilder<true, NoFolder> Builder(PBI);
  1599. if (PBIOp)
  1600. PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
  1601. Value *BICond = BI->getCondition();
  1602. if (BIOp)
  1603. BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
  1604. // Merge the conditions.
  1605. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  1606. // Modify PBI to branch on the new condition to the new dests.
  1607. PBI->setCondition(Cond);
  1608. PBI->setSuccessor(0, CommonDest);
  1609. PBI->setSuccessor(1, OtherDest);
  1610. // OtherDest may have phi nodes. If so, add an entry from PBI's
  1611. // block that are identical to the entries for BI's block.
  1612. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  1613. // We know that the CommonDest already had an edge from PBI to
  1614. // it. If it has PHIs though, the PHIs may have different
  1615. // entries for BB and PBI's BB. If so, insert a select to make
  1616. // them agree.
  1617. PHINode *PN;
  1618. for (BasicBlock::iterator II = CommonDest->begin();
  1619. (PN = dyn_cast<PHINode>(II)); ++II) {
  1620. Value *BIV = PN->getIncomingValueForBlock(BB);
  1621. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  1622. Value *PBIV = PN->getIncomingValue(PBBIdx);
  1623. if (BIV != PBIV) {
  1624. // Insert a select in PBI to pick the right value.
  1625. Value *NV = cast<SelectInst>
  1626. (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
  1627. PN->setIncomingValue(PBBIdx, NV);
  1628. }
  1629. }
  1630. DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  1631. DEBUG(dbgs() << *PBI->getParent()->getParent());
  1632. // This basic block is probably dead. We know it has at least
  1633. // one fewer predecessor.
  1634. return true;
  1635. }
  1636. // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
  1637. // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
  1638. // Takes care of updating the successors and removing the old terminator.
  1639. // Also makes sure not to introduce new successors by assuming that edges to
  1640. // non-successor TrueBBs and FalseBBs aren't reachable.
  1641. static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
  1642. BasicBlock *TrueBB, BasicBlock *FalseBB){
  1643. // Remove any superfluous successor edges from the CFG.
  1644. // First, figure out which successors to preserve.
  1645. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  1646. // successor.
  1647. BasicBlock *KeepEdge1 = TrueBB;
  1648. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
  1649. // Then remove the rest.
  1650. for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
  1651. BasicBlock *Succ = OldTerm->getSuccessor(I);
  1652. // Make sure only to keep exactly one copy of each edge.
  1653. if (Succ == KeepEdge1)
  1654. KeepEdge1 = 0;
  1655. else if (Succ == KeepEdge2)
  1656. KeepEdge2 = 0;
  1657. else
  1658. Succ->removePredecessor(OldTerm->getParent());
  1659. }
  1660. IRBuilder<> Builder(OldTerm);
  1661. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  1662. // Insert an appropriate new terminator.
  1663. if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
  1664. if (TrueBB == FalseBB)
  1665. // We were only looking for one successor, and it was present.
  1666. // Create an unconditional branch to it.
  1667. Builder.CreateBr(TrueBB);
  1668. else
  1669. // We found both of the successors we were looking for.
  1670. // Create a conditional branch sharing the condition of the select.
  1671. Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  1672. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  1673. // Neither of the selected blocks were successors, so this
  1674. // terminator must be unreachable.
  1675. new UnreachableInst(OldTerm->getContext(), OldTerm);
  1676. } else {
  1677. // One of the selected values was a successor, but the other wasn't.
  1678. // Insert an unconditional branch to the one that was found;
  1679. // the edge to the one that wasn't must be unreachable.
  1680. if (KeepEdge1 == 0)
  1681. // Only TrueBB was found.
  1682. Builder.CreateBr(TrueBB);
  1683. else
  1684. // Only FalseBB was found.
  1685. Builder.CreateBr(FalseBB);
  1686. }
  1687. EraseTerminatorInstAndDCECond(OldTerm);
  1688. return true;
  1689. }
  1690. // SimplifySwitchOnSelect - Replaces
  1691. // (switch (select cond, X, Y)) on constant X, Y
  1692. // with a branch - conditional if X and Y lead to distinct BBs,
  1693. // unconditional otherwise.
  1694. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  1695. // Check for constant integer values in the select.
  1696. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  1697. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  1698. if (!TrueVal || !FalseVal)
  1699. return false;
  1700. // Find the relevant condition and destinations.
  1701. Value *Condition = Select->getCondition();
  1702. BasicBlock *TrueBB = SI->getSuccessor(SI->findCaseValue(TrueVal));
  1703. BasicBlock *FalseBB = SI->getSuccessor(SI->findCaseValue(FalseVal));
  1704. // Perform the actual simplification.
  1705. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
  1706. }
  1707. // SimplifyIndirectBrOnSelect - Replaces
  1708. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  1709. // blockaddress(@fn, BlockB)))
  1710. // with
  1711. // (br cond, BlockA, BlockB).
  1712. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  1713. // Check that both operands of the select are block addresses.
  1714. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  1715. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  1716. if (!TBA || !FBA)
  1717. return false;
  1718. // Extract the actual blocks.
  1719. BasicBlock *TrueBB = TBA->getBasicBlock();
  1720. BasicBlock *FalseBB = FBA->getBasicBlock();
  1721. // Perform the actual simplification.
  1722. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
  1723. }
  1724. /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
  1725. /// instruction (a seteq/setne with a constant) as the only instruction in a
  1726. /// block that ends with an uncond branch. We are looking for a very specific
  1727. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  1728. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  1729. /// default value goes to an uncond block with a seteq in it, we get something
  1730. /// like:
  1731. ///
  1732. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  1733. /// DEFAULT:
  1734. /// %tmp = icmp eq i8 %A, 92
  1735. /// br label %end
  1736. /// end:
  1737. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  1738. ///
  1739. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  1740. /// the PHI, merging the third icmp into the switch.
  1741. static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
  1742. const TargetData *TD,
  1743. IRBuilder<> &Builder) {
  1744. BasicBlock *BB = ICI->getParent();
  1745. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  1746. // complex.
  1747. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
  1748. Value *V = ICI->getOperand(0);
  1749. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  1750. // The pattern we're looking for is where our only predecessor is a switch on
  1751. // 'V' and this block is the default case for the switch. In this case we can
  1752. // fold the compared value into the switch to simplify things.
  1753. BasicBlock *Pred = BB->getSinglePredecessor();
  1754. if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
  1755. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  1756. if (SI->getCondition() != V)
  1757. return false;
  1758. // If BB is reachable on a non-default case, then we simply know the value of
  1759. // V in this block. Substitute it and constant fold the icmp instruction
  1760. // away.
  1761. if (SI->getDefaultDest() != BB) {
  1762. ConstantInt *VVal = SI->findCaseDest(BB);
  1763. assert(VVal && "Should have a unique destination value");
  1764. ICI->setOperand(0, VVal);
  1765. if (Value *V = SimplifyInstruction(ICI, TD)) {
  1766. ICI->replaceAllUsesWith(V);
  1767. ICI->eraseFromParent();
  1768. }
  1769. // BB is now empty, so it is likely to simplify away.
  1770. return SimplifyCFG(BB) | true;
  1771. }
  1772. // Ok, the block is reachable from the default dest. If the constant we're
  1773. // comparing exists in one of the other edges, then we can constant fold ICI
  1774. // and zap it.
  1775. if (SI->findCaseValue(Cst) != 0) {
  1776. Value *V;
  1777. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  1778. V = ConstantInt::getFalse(BB->getContext());
  1779. else
  1780. V = ConstantInt::getTrue(BB->getContext());
  1781. ICI->replaceAllUsesWith(V);
  1782. ICI->eraseFromParent();
  1783. // BB is now empty, so it is likely to simplify away.
  1784. return SimplifyCFG(BB) | true;
  1785. }
  1786. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  1787. // the block.
  1788. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  1789. PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
  1790. if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
  1791. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  1792. return false;
  1793. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  1794. // true in the PHI.
  1795. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  1796. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  1797. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  1798. std::swap(DefaultCst, NewCst);
  1799. // Replace ICI (which is used by the PHI for the default value) with true or
  1800. // false depending on if it is EQ or NE.
  1801. ICI->replaceAllUsesWith(DefaultCst);
  1802. ICI->eraseFromParent();
  1803. // Okay, the switch goes to this block on a default value. Add an edge from
  1804. // the switch to the merge point on the compared value.
  1805. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
  1806. BB->getParent(), BB);
  1807. SI->addCase(Cst, NewBB);
  1808. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  1809. Builder.SetInsertPoint(NewBB);
  1810. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  1811. Builder.CreateBr(SuccBlock);
  1812. PHIUse->addIncoming(NewCst, NewBB);
  1813. return true;
  1814. }
  1815. /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
  1816. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  1817. /// fold it into a switch instruction if so.
  1818. static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
  1819. IRBuilder<> &Builder) {
  1820. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  1821. if (Cond == 0) return false;
  1822. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  1823. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  1824. // 'setne's and'ed together, collect them.
  1825. Value *CompVal = 0;
  1826. std::vector<ConstantInt*> Values;
  1827. bool TrueWhenEqual = true;
  1828. Value *ExtraCase = 0;
  1829. unsigned UsedICmps = 0;
  1830. if (Cond->getOpcode() == Instruction::Or) {
  1831. CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
  1832. UsedICmps);
  1833. } else if (Cond->getOpcode() == Instruction::And) {
  1834. CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
  1835. UsedICmps);
  1836. TrueWhenEqual = false;
  1837. }
  1838. // If we didn't have a multiply compared value, fail.
  1839. if (CompVal == 0) return false;
  1840. // Avoid turning single icmps into a switch.
  1841. if (UsedICmps <= 1)
  1842. return false;
  1843. // There might be duplicate constants in the list, which the switch
  1844. // instruction can't handle, remove them now.
  1845. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  1846. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  1847. // If Extra was used, we require at least two switch values to do the
  1848. // transformation. A switch with one value is just an cond branch.
  1849. if (ExtraCase && Values.size() < 2) return false;
  1850. // Figure out which block is which destination.
  1851. BasicBlock *DefaultBB = BI->getSuccessor(1);
  1852. BasicBlock *EdgeBB = BI->getSuccessor(0);
  1853. if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
  1854. BasicBlock *BB = BI->getParent();
  1855. DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  1856. << " cases into SWITCH. BB is:\n" << *BB);
  1857. // If there are any extra values that couldn't be folded into the switch
  1858. // then we evaluate them with an explicit branch first. Split the block
  1859. // right before the condbr to handle it.
  1860. if (ExtraCase) {
  1861. BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
  1862. // Remove the uncond branch added to the old block.
  1863. TerminatorInst *OldTI = BB->getTerminator();
  1864. Builder.SetInsertPoint(OldTI);
  1865. if (TrueWhenEqual)
  1866. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  1867. else
  1868. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  1869. OldTI->eraseFromParent();
  1870. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  1871. // for the edge we just added.
  1872. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  1873. DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  1874. << "\nEXTRABB = " << *BB);
  1875. BB = NewBB;
  1876. }
  1877. Builder.SetInsertPoint(BI);
  1878. // Convert pointer to int before we switch.
  1879. if (CompVal->getType()->isPointerTy()) {
  1880. assert(TD && "Cannot switch on pointer without TargetData");
  1881. CompVal = Builder.CreatePtrToInt(CompVal,
  1882. TD->getIntPtrType(CompVal->getContext()),
  1883. "magicptr");
  1884. }
  1885. // Create the new switch instruction now.
  1886. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  1887. // Add all of the 'cases' to the switch instruction.
  1888. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  1889. New->addCase(Values[i], EdgeBB);
  1890. // We added edges from PI to the EdgeBB. As such, if there were any
  1891. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  1892. // the number of edges added.
  1893. for (BasicBlock::iterator BBI = EdgeBB->begin();
  1894. isa<PHINode>(BBI); ++BBI) {
  1895. PHINode *PN = cast<PHINode>(BBI);
  1896. Value *InVal = PN->getIncomingValueForBlock(BB);
  1897. for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
  1898. PN->addIncoming(InVal, BB);
  1899. }
  1900. // Erase the old branch instruction.
  1901. EraseTerminatorInstAndDCECond(BI);
  1902. DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  1903. return true;
  1904. }
  1905. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  1906. // If this is a trivial landing pad that just continues unwinding the caught
  1907. // exception then zap the landing pad, turning its invokes into calls.
  1908. BasicBlock *BB = RI->getParent();
  1909. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  1910. if (RI->getValue() != LPInst)
  1911. // Not a landing pad, or the resume is not unwinding the exception that
  1912. // caused control to branch here.
  1913. return false;
  1914. // Check that there are no other instructions except for debug intrinsics.
  1915. BasicBlock::iterator I = LPInst, E = RI;
  1916. while (++I != E)
  1917. if (!isa<DbgInfoIntrinsic>(I))
  1918. return false;
  1919. // Turn all invokes that unwind here into calls and delete the basic block.
  1920. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  1921. InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
  1922. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  1923. // Insert a call instruction before the invoke.
  1924. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  1925. Call->takeName(II);
  1926. Call->setCallingConv(II->getCallingConv());
  1927. Call->setAttributes(II->getAttributes());
  1928. Call->setDebugLoc(II->getDebugLoc());
  1929. // Anything that used the value produced by the invoke instruction now uses
  1930. // the value produced by the call instruction. Note that we do this even
  1931. // for void functions and calls with no uses so that the callgraph edge is
  1932. // updated.
  1933. II->replaceAllUsesWith(Call);
  1934. BB->removePredecessor(II->getParent());
  1935. // Insert a branch to the normal destination right before the invoke.
  1936. BranchInst::Create(II->getNormalDest(), II);
  1937. // Finally, delete the invoke instruction!
  1938. II->eraseFromParent();
  1939. }
  1940. // The landingpad is now unreachable. Zap it.
  1941. BB->eraseFromParent();
  1942. return true;
  1943. }
  1944. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  1945. BasicBlock *BB = RI->getParent();
  1946. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  1947. // Find predecessors that end with branches.
  1948. SmallVector<BasicBlock*, 8> UncondBranchPreds;
  1949. SmallVector<BranchInst*, 8> CondBranchPreds;
  1950. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1951. BasicBlock *P = *PI;
  1952. TerminatorInst *PTI = P->getTerminator();
  1953. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  1954. if (BI->isUnconditional())
  1955. UncondBranchPreds.push_back(P);
  1956. else
  1957. CondBranchPreds.push_back(BI);
  1958. }
  1959. }
  1960. // If we found some, do the transformation!
  1961. if (!UncondBranchPreds.empty() && DupRet) {
  1962. while (!UncondBranchPreds.empty()) {
  1963. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  1964. DEBUG(dbgs() << "FOLDING: " << *BB
  1965. << "INTO UNCOND BRANCH PRED: " << *Pred);
  1966. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  1967. }
  1968. // If we eliminated all predecessors of the block, delete the block now.
  1969. if (pred_begin(BB) == pred_end(BB))
  1970. // We know there are no successors, so just nuke the block.
  1971. BB->eraseFromParent();
  1972. return true;
  1973. }
  1974. // Check out all of the conditional branches going to this return
  1975. // instruction. If any of them just select between returns, change the
  1976. // branch itself into a select/return pair.
  1977. while (!CondBranchPreds.empty()) {
  1978. BranchInst *BI = CondBranchPreds.pop_back_val();
  1979. // Check to see if the non-BB successor is also a return block.
  1980. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  1981. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  1982. SimplifyCondBranchToTwoReturns(BI, Builder))
  1983. return true;
  1984. }
  1985. return false;
  1986. }
  1987. bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder) {
  1988. // Check to see if the first instruction in this block is just an unwind.
  1989. // If so, replace any invoke instructions which use this as an exception
  1990. // destination with call instructions.
  1991. BasicBlock *BB = UI->getParent();
  1992. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  1993. bool Changed = false;
  1994. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  1995. while (!Preds.empty()) {
  1996. BasicBlock *Pred = Preds.back();
  1997. InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
  1998. if (II && II->getUnwindDest() == BB) {
  1999. // Insert a new branch instruction before the invoke, because this
  2000. // is now a fall through.
  2001. Builder.SetInsertPoint(II);
  2002. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2003. Pred->getInstList().remove(II); // Take out of symbol table
  2004. // Insert the call now.
  2005. SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
  2006. Builder.SetInsertPoint(BI);
  2007. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2008. Args, II->getName());
  2009. CI->setCallingConv(II->getCallingConv());
  2010. CI->setAttributes(II->getAttributes());
  2011. // If the invoke produced a value, the Call now does instead.
  2012. II->replaceAllUsesWith(CI);
  2013. delete II;
  2014. Changed = true;
  2015. }
  2016. Preds.pop_back();
  2017. }
  2018. // If this block is now dead (and isn't the entry block), remove it.
  2019. if (pred_begin(BB) == pred_end(BB) &&
  2020. BB != &BB->getParent()->getEntryBlock()) {
  2021. // We know there are no successors, so just nuke the block.
  2022. BB->eraseFromParent();
  2023. return true;
  2024. }
  2025. return Changed;
  2026. }
  2027. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  2028. BasicBlock *BB = UI->getParent();
  2029. bool Changed = false;
  2030. // If there are any instructions immediately before the unreachable that can
  2031. // be removed, do so.
  2032. while (UI != BB->begin()) {
  2033. BasicBlock::iterator BBI = UI;
  2034. --BBI;
  2035. // Do not delete instructions that can have side effects which might cause
  2036. // the unreachable to not be reachable; specifically, calls and volatile
  2037. // operations may have this effect.
  2038. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
  2039. if (BBI->mayHaveSideEffects()) {
  2040. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  2041. if (SI->isVolatile())
  2042. break;
  2043. } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  2044. if (LI->isVolatile())
  2045. break;
  2046. } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  2047. if (RMWI->isVolatile())
  2048. break;
  2049. } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  2050. if (CXI->isVolatile())
  2051. break;
  2052. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  2053. !isa<LandingPadInst>(BBI)) {
  2054. break;
  2055. }
  2056. // Note that deleting LandingPad's here is in fact okay, although it
  2057. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  2058. // all the predecessors of this block will be the unwind edges of Invokes,
  2059. // and we can therefore guarantee this block will be erased.
  2060. }
  2061. // Delete this instruction (any uses are guaranteed to be dead)
  2062. if (!BBI->use_empty())
  2063. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  2064. BBI->eraseFromParent();
  2065. Changed = true;
  2066. }
  2067. // If the unreachable instruction is the first in the block, take a gander
  2068. // at all of the predecessors of this instruction, and simplify them.
  2069. if (&BB->front() != UI) return Changed;
  2070. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  2071. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  2072. TerminatorInst *TI = Preds[i]->getTerminator();
  2073. IRBuilder<> Builder(TI);
  2074. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2075. if (BI->isUnconditional()) {
  2076. if (BI->getSuccessor(0) == BB) {
  2077. new UnreachableInst(TI->getContext(), TI);
  2078. TI->eraseFromParent();
  2079. Changed = true;
  2080. }
  2081. } else {
  2082. if (BI->getSuccessor(0) == BB) {
  2083. Builder.CreateBr(BI->getSuccessor(1));
  2084. EraseTerminatorInstAndDCECond(BI);
  2085. } else if (BI->getSuccessor(1) == BB) {
  2086. Builder.CreateBr(BI->getSuccessor(0));
  2087. EraseTerminatorInstAndDCECond(BI);
  2088. Changed = true;
  2089. }
  2090. }
  2091. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2092. for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
  2093. if (SI->getSuccessor(i) == BB) {
  2094. BB->removePredecessor(SI->getParent());
  2095. SI->removeCase(i);
  2096. --i; --e;
  2097. Changed = true;
  2098. }
  2099. // If the default value is unreachable, figure out the most popular
  2100. // destination and make it the default.
  2101. if (SI->getSuccessor(0) == BB) {
  2102. std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
  2103. for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
  2104. std::pair<unsigned, unsigned> &entry =
  2105. Popularity[SI->getSuccessor(i)];
  2106. if (entry.first == 0) {
  2107. entry.first = 1;
  2108. entry.second = i;
  2109. } else {
  2110. entry.first++;
  2111. }
  2112. }
  2113. // Find the most popular block.
  2114. unsigned MaxPop = 0;
  2115. unsigned MaxIndex = 0;
  2116. BasicBlock *MaxBlock = 0;
  2117. for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
  2118. I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
  2119. if (I->second.first > MaxPop ||
  2120. (I->second.first == MaxPop && MaxIndex > I->second.second)) {
  2121. MaxPop = I->second.first;
  2122. MaxIndex = I->second.second;
  2123. MaxBlock = I->first;
  2124. }
  2125. }
  2126. if (MaxBlock) {
  2127. // Make this the new default, allowing us to delete any explicit
  2128. // edges to it.
  2129. SI->setSuccessor(0, MaxBlock);
  2130. Changed = true;
  2131. // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
  2132. // it.
  2133. if (isa<PHINode>(MaxBlock->begin()))
  2134. for (unsigned i = 0; i != MaxPop-1; ++i)
  2135. MaxBlock->removePredecessor(SI->getParent());
  2136. for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
  2137. if (SI->getSuccessor(i) == MaxBlock) {
  2138. SI->removeCase(i);
  2139. --i; --e;
  2140. }
  2141. }
  2142. }
  2143. } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
  2144. if (II->getUnwindDest() == BB) {
  2145. // Convert the invoke to a call instruction. This would be a good
  2146. // place to note that the call does not throw though.
  2147. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2148. II->removeFromParent(); // Take out of symbol table
  2149. // Insert the call now...
  2150. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
  2151. Builder.SetInsertPoint(BI);
  2152. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2153. Args, II->getName());
  2154. CI->setCallingConv(II->getCallingConv());
  2155. CI->setAttributes(II->getAttributes());
  2156. // If the invoke produced a value, the call does now instead.
  2157. II->replaceAllUsesWith(CI);
  2158. delete II;
  2159. Changed = true;
  2160. }
  2161. }
  2162. }
  2163. // If this block is now dead, remove it.
  2164. if (pred_begin(BB) == pred_end(BB) &&
  2165. BB != &BB->getParent()->getEntryBlock()) {
  2166. // We know there are no successors, so just nuke the block.
  2167. BB->eraseFromParent();
  2168. return true;
  2169. }
  2170. return Changed;
  2171. }
  2172. /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
  2173. /// integer range comparison into a sub, an icmp and a branch.
  2174. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  2175. assert(SI->getNumCases() > 2 && "Degenerate switch?");
  2176. // Make sure all cases point to the same destination and gather the values.
  2177. SmallVector<ConstantInt *, 16> Cases;
  2178. Cases.push_back(SI->getCaseValue(1));
  2179. for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
  2180. if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
  2181. return false;
  2182. Cases.push_back(SI->getCaseValue(I));
  2183. }
  2184. assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
  2185. // Sort the case values, then check if they form a range we can transform.
  2186. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  2187. for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
  2188. if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
  2189. return false;
  2190. }
  2191. Constant *Offset = ConstantExpr::getNeg(Cases.back());
  2192. Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
  2193. Value *Sub = SI->getCondition();
  2194. if (!Offset->isNullValue())
  2195. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
  2196. Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  2197. Builder.CreateCondBr(Cmp, SI->getSuccessor(1), SI->getDefaultDest());
  2198. // Prune obsolete incoming values off the successor's PHI nodes.
  2199. for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
  2200. isa<PHINode>(BBI); ++BBI) {
  2201. for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
  2202. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2203. }
  2204. SI->eraseFromParent();
  2205. return true;
  2206. }
  2207. /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
  2208. /// and use it to remove dead cases.
  2209. static bool EliminateDeadSwitchCases(SwitchInst *SI) {
  2210. Value *Cond = SI->getCondition();
  2211. unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
  2212. APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
  2213. ComputeMaskedBits(Cond, APInt::getAllOnesValue(Bits), KnownZero, KnownOne);
  2214. // Gather dead cases.
  2215. SmallVector<ConstantInt*, 8> DeadCases;
  2216. for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
  2217. if ((SI->getCaseValue(I)->getValue() & KnownZero) != 0 ||
  2218. (SI->getCaseValue(I)->getValue() & KnownOne) != KnownOne) {
  2219. DeadCases.push_back(SI->getCaseValue(I));
  2220. DEBUG(dbgs() << "SimplifyCFG: switch case '"
  2221. << SI->getCaseValue(I)->getValue() << "' is dead.\n");
  2222. }
  2223. }
  2224. // Remove dead cases from the switch.
  2225. for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
  2226. unsigned Case = SI->findCaseValue(DeadCases[I]);
  2227. // Prune unused values from PHI nodes.
  2228. SI->getSuccessor(Case)->removePredecessor(SI->getParent());
  2229. SI->removeCase(Case);
  2230. }
  2231. return !DeadCases.empty();
  2232. }
  2233. /// FindPHIForConditionForwarding - If BB would be eligible for simplification
  2234. /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  2235. /// by an unconditional branch), look at the phi node for BB in the successor
  2236. /// block and see if the incoming value is equal to CaseValue. If so, return
  2237. /// the phi node, and set PhiIndex to BB's index in the phi node.
  2238. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  2239. BasicBlock *BB,
  2240. int *PhiIndex) {
  2241. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  2242. return NULL; // BB must be empty to be a candidate for simplification.
  2243. if (!BB->getSinglePredecessor())
  2244. return NULL; // BB must be dominated by the switch.
  2245. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  2246. if (!Branch || !Branch->isUnconditional())
  2247. return NULL; // Terminator must be unconditional branch.
  2248. BasicBlock *Succ = Branch->getSuccessor(0);
  2249. BasicBlock::iterator I = Succ->begin();
  2250. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  2251. int Idx = PHI->getBasicBlockIndex(BB);
  2252. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  2253. Value *InValue = PHI->getIncomingValue(Idx);
  2254. if (InValue != CaseValue) continue;
  2255. *PhiIndex = Idx;
  2256. return PHI;
  2257. }
  2258. return NULL;
  2259. }
  2260. /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
  2261. /// instruction to a phi node dominated by the switch, if that would mean that
  2262. /// some of the destination blocks of the switch can be folded away.
  2263. /// Returns true if a change is made.
  2264. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  2265. typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
  2266. ForwardingNodesMap ForwardingNodes;
  2267. for (unsigned I = 1; I < SI->getNumCases(); ++I) { // 0 is the default case.
  2268. ConstantInt *CaseValue = SI->getCaseValue(I);
  2269. BasicBlock *CaseDest = SI->getSuccessor(I);
  2270. int PhiIndex;
  2271. PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
  2272. &PhiIndex);
  2273. if (!PHI) continue;
  2274. ForwardingNodes[PHI].push_back(PhiIndex);
  2275. }
  2276. bool Changed = false;
  2277. for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
  2278. E = ForwardingNodes.end(); I != E; ++I) {
  2279. PHINode *Phi = I->first;
  2280. SmallVector<int,4> &Indexes = I->second;
  2281. if (Indexes.size() < 2) continue;
  2282. for (size_t I = 0, E = Indexes.size(); I != E; ++I)
  2283. Phi->setIncomingValue(Indexes[I], SI->getCondition());
  2284. Changed = true;
  2285. }
  2286. return Changed;
  2287. }
  2288. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  2289. // If this switch is too complex to want to look at, ignore it.
  2290. if (!isValueEqualityComparison(SI))
  2291. return false;
  2292. BasicBlock *BB = SI->getParent();
  2293. // If we only have one predecessor, and if it is a branch on this value,
  2294. // see if that predecessor totally determines the outcome of this switch.
  2295. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  2296. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  2297. return SimplifyCFG(BB) | true;
  2298. Value *Cond = SI->getCondition();
  2299. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  2300. if (SimplifySwitchOnSelect(SI, Select))
  2301. return SimplifyCFG(BB) | true;
  2302. // If the block only contains the switch, see if we can fold the block
  2303. // away into any preds.
  2304. BasicBlock::iterator BBI = BB->begin();
  2305. // Ignore dbg intrinsics.
  2306. while (isa<DbgInfoIntrinsic>(BBI))
  2307. ++BBI;
  2308. if (SI == &*BBI)
  2309. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  2310. return SimplifyCFG(BB) | true;
  2311. // Try to transform the switch into an icmp and a branch.
  2312. if (TurnSwitchRangeIntoICmp(SI, Builder))
  2313. return SimplifyCFG(BB) | true;
  2314. // Remove unreachable cases.
  2315. if (EliminateDeadSwitchCases(SI))
  2316. return SimplifyCFG(BB) | true;
  2317. if (ForwardSwitchConditionToPHI(SI))
  2318. return SimplifyCFG(BB) | true;
  2319. return false;
  2320. }
  2321. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  2322. BasicBlock *BB = IBI->getParent();
  2323. bool Changed = false;
  2324. // Eliminate redundant destinations.
  2325. SmallPtrSet<Value *, 8> Succs;
  2326. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  2327. BasicBlock *Dest = IBI->getDestination(i);
  2328. if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
  2329. Dest->removePredecessor(BB);
  2330. IBI->removeDestination(i);
  2331. --i; --e;
  2332. Changed = true;
  2333. }
  2334. }
  2335. if (IBI->getNumDestinations() == 0) {
  2336. // If the indirectbr has no successors, change it to unreachable.
  2337. new UnreachableInst(IBI->getContext(), IBI);
  2338. EraseTerminatorInstAndDCECond(IBI);
  2339. return true;
  2340. }
  2341. if (IBI->getNumDestinations() == 1) {
  2342. // If the indirectbr has one successor, change it to a direct branch.
  2343. BranchInst::Create(IBI->getDestination(0), IBI);
  2344. EraseTerminatorInstAndDCECond(IBI);
  2345. return true;
  2346. }
  2347. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  2348. if (SimplifyIndirectBrOnSelect(IBI, SI))
  2349. return SimplifyCFG(BB) | true;
  2350. }
  2351. return Changed;
  2352. }
  2353. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
  2354. BasicBlock *BB = BI->getParent();
  2355. // If the Terminator is the only non-phi instruction, simplify the block.
  2356. BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
  2357. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  2358. TryToSimplifyUncondBranchFromEmptyBlock(BB))
  2359. return true;
  2360. // If the only instruction in the block is a seteq/setne comparison
  2361. // against a constant, try to simplify the block.
  2362. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  2363. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  2364. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  2365. ;
  2366. if (I->isTerminator() &&
  2367. TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
  2368. return true;
  2369. }
  2370. return false;
  2371. }
  2372. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  2373. BasicBlock *BB = BI->getParent();
  2374. // Conditional branch
  2375. if (isValueEqualityComparison(BI)) {
  2376. // If we only have one predecessor, and if it is a branch on this value,
  2377. // see if that predecessor totally determines the outcome of this
  2378. // switch.
  2379. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  2380. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  2381. return SimplifyCFG(BB) | true;
  2382. // This block must be empty, except for the setcond inst, if it exists.
  2383. // Ignore dbg intrinsics.
  2384. BasicBlock::iterator I = BB->begin();
  2385. // Ignore dbg intrinsics.
  2386. while (isa<DbgInfoIntrinsic>(I))
  2387. ++I;
  2388. if (&*I == BI) {
  2389. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  2390. return SimplifyCFG(BB) | true;
  2391. } else if (&*I == cast<Instruction>(BI->getCondition())){
  2392. ++I;
  2393. // Ignore dbg intrinsics.
  2394. while (isa<DbgInfoIntrinsic>(I))
  2395. ++I;
  2396. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  2397. return SimplifyCFG(BB) | true;
  2398. }
  2399. }
  2400. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  2401. if (SimplifyBranchOnICmpChain(BI, TD, Builder))
  2402. return true;
  2403. // If this basic block is ONLY a compare and a branch, and if a predecessor
  2404. // branches to us and one of our successors, fold the comparison into the
  2405. // predecessor and use logical operations to pick the right destination.
  2406. if (FoldBranchToCommonDest(BI))
  2407. return SimplifyCFG(BB) | true;
  2408. // We have a conditional branch to two blocks that are only reachable
  2409. // from BI. We know that the condbr dominates the two blocks, so see if
  2410. // there is any identical code in the "then" and "else" blocks. If so, we
  2411. // can hoist it up to the branching block.
  2412. if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
  2413. if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
  2414. if (HoistThenElseCodeToIf(BI))
  2415. return SimplifyCFG(BB) | true;
  2416. } else {
  2417. // If Successor #1 has multiple preds, we may be able to conditionally
  2418. // execute Successor #0 if it branches to successor #1.
  2419. TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
  2420. if (Succ0TI->getNumSuccessors() == 1 &&
  2421. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  2422. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
  2423. return SimplifyCFG(BB) | true;
  2424. }
  2425. } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
  2426. // If Successor #0 has multiple preds, we may be able to conditionally
  2427. // execute Successor #1 if it branches to successor #0.
  2428. TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
  2429. if (Succ1TI->getNumSuccessors() == 1 &&
  2430. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  2431. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
  2432. return SimplifyCFG(BB) | true;
  2433. }
  2434. // If this is a branch on a phi node in the current block, thread control
  2435. // through this block if any PHI node entries are constants.
  2436. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  2437. if (PN->getParent() == BI->getParent())
  2438. if (FoldCondBranchOnPHI(BI, TD))
  2439. return SimplifyCFG(BB) | true;
  2440. // Scan predecessor blocks for conditional branches.
  2441. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  2442. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  2443. if (PBI != BI && PBI->isConditional())
  2444. if (SimplifyCondBranchToCondBranch(PBI, BI))
  2445. return SimplifyCFG(BB) | true;
  2446. return false;
  2447. }
  2448. /// Check if passing a value to an instruction will cause undefined behavior.
  2449. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  2450. Constant *C = dyn_cast<Constant>(V);
  2451. if (!C)
  2452. return false;
  2453. if (!I->hasOneUse()) // Only look at single-use instructions, for compile time
  2454. return false;
  2455. if (C->isNullValue()) {
  2456. Instruction *Use = I->use_back();
  2457. // Now make sure that there are no instructions in between that can alter
  2458. // control flow (eg. calls)
  2459. for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
  2460. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  2461. return false;
  2462. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  2463. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  2464. if (GEP->getPointerOperand() == I)
  2465. return passingValueIsAlwaysUndefined(V, GEP);
  2466. // Look through bitcasts.
  2467. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  2468. return passingValueIsAlwaysUndefined(V, BC);
  2469. // Load from null is undefined.
  2470. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  2471. return LI->getPointerAddressSpace() == 0;
  2472. // Store to null is undefined.
  2473. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  2474. return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
  2475. }
  2476. return false;
  2477. }
  2478. /// If BB has an incoming value that will always trigger undefined behavior
  2479. /// (eg. null pointer dereference), remove the branch leading here.
  2480. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  2481. for (BasicBlock::iterator i = BB->begin();
  2482. PHINode *PHI = dyn_cast<PHINode>(i); ++i)
  2483. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
  2484. if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
  2485. TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
  2486. IRBuilder<> Builder(T);
  2487. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  2488. BB->removePredecessor(PHI->getIncomingBlock(i));
  2489. // Turn uncoditional branches into unreachables and remove the dead
  2490. // destination from conditional branches.
  2491. if (BI->isUnconditional())
  2492. Builder.CreateUnreachable();
  2493. else
  2494. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
  2495. BI->getSuccessor(0));
  2496. BI->eraseFromParent();
  2497. return true;
  2498. }
  2499. // TODO: SwitchInst.
  2500. }
  2501. return false;
  2502. }
  2503. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  2504. bool Changed = false;
  2505. assert(BB && BB->getParent() && "Block not embedded in function!");
  2506. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  2507. // Remove basic blocks that have no predecessors (except the entry block)...
  2508. // or that just have themself as a predecessor. These are unreachable.
  2509. if ((pred_begin(BB) == pred_end(BB) &&
  2510. BB != &BB->getParent()->getEntryBlock()) ||
  2511. BB->getSinglePredecessor() == BB) {
  2512. DEBUG(dbgs() << "Removing BB: \n" << *BB);
  2513. DeleteDeadBlock(BB);
  2514. return true;
  2515. }
  2516. // Check to see if we can constant propagate this terminator instruction
  2517. // away...
  2518. Changed |= ConstantFoldTerminator(BB, true);
  2519. // Check for and eliminate duplicate PHI nodes in this block.
  2520. Changed |= EliminateDuplicatePHINodes(BB);
  2521. // Check for and remove branches that will always cause undefined behavior.
  2522. Changed |= removeUndefIntroducingPredecessor(BB);
  2523. // Merge basic blocks into their predecessor if there is only one distinct
  2524. // pred, and if there is only one distinct successor of the predecessor, and
  2525. // if there are no PHI nodes.
  2526. //
  2527. if (MergeBlockIntoPredecessor(BB))
  2528. return true;
  2529. IRBuilder<> Builder(BB);
  2530. // If there is a trivial two-entry PHI node in this basic block, and we can
  2531. // eliminate it, do so now.
  2532. if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
  2533. if (PN->getNumIncomingValues() == 2)
  2534. Changed |= FoldTwoEntryPHINode(PN, TD);
  2535. Builder.SetInsertPoint(BB->getTerminator());
  2536. if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  2537. if (BI->isUnconditional()) {
  2538. if (SimplifyUncondBranch(BI, Builder)) return true;
  2539. } else {
  2540. if (SimplifyCondBranch(BI, Builder)) return true;
  2541. }
  2542. } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  2543. if (SimplifyResume(RI, Builder)) return true;
  2544. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  2545. if (SimplifyReturn(RI, Builder)) return true;
  2546. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  2547. if (SimplifySwitch(SI, Builder)) return true;
  2548. } else if (UnreachableInst *UI =
  2549. dyn_cast<UnreachableInst>(BB->getTerminator())) {
  2550. if (SimplifyUnreachable(UI)) return true;
  2551. } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
  2552. if (SimplifyUnwind(UI, Builder)) return true;
  2553. } else if (IndirectBrInst *IBI =
  2554. dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  2555. if (SimplifyIndirectBr(IBI)) return true;
  2556. }
  2557. return Changed;
  2558. }
  2559. /// SimplifyCFG - This function is used to do simplification of a CFG. For
  2560. /// example, it adjusts branches to branches to eliminate the extra hop, it
  2561. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  2562. /// of the CFG. It returns true if a modification was made.
  2563. ///
  2564. bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
  2565. return SimplifyCFGOpt(TD).run(BB);
  2566. }