SimplifyCFG.cpp 107 KB

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