LoopUnswitch.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass transforms loops that contain branches on loop-invariant conditions
  11. // to have multiple loops. For example, it turns the left into the right code:
  12. //
  13. // for (...) if (lic)
  14. // A for (...)
  15. // if (lic) A; B; C
  16. // B else
  17. // C for (...)
  18. // A; C
  19. //
  20. // This can increase the size of the code exponentially (doubling it every time
  21. // a loop is unswitched) so we only unswitch if the resultant code will be
  22. // smaller than a threshold.
  23. //
  24. // This pass expects LICM to be run before it to hoist invariant conditions out
  25. // of the loop, to make the unswitching opportunity obvious.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "llvm/Transforms/Scalar.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/Analysis/GlobalsModRef.h"
  33. #include "llvm/Analysis/AssumptionCache.h"
  34. #include "llvm/Analysis/CodeMetrics.h"
  35. #include "llvm/Analysis/DivergenceAnalysis.h"
  36. #include "llvm/Analysis/InstructionSimplify.h"
  37. #include "llvm/Analysis/LoopInfo.h"
  38. #include "llvm/Analysis/LoopPass.h"
  39. #include "llvm/Analysis/ScalarEvolution.h"
  40. #include "llvm/Analysis/TargetTransformInfo.h"
  41. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  42. #include "llvm/Analysis/BlockFrequencyInfo.h"
  43. #include "llvm/Analysis/BranchProbabilityInfo.h"
  44. #include "llvm/Support/BranchProbability.h"
  45. #include "llvm/IR/Constants.h"
  46. #include "llvm/IR/DerivedTypes.h"
  47. #include "llvm/IR/Dominators.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/InstrTypes.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/IR/MDBuilder.h"
  53. #include "llvm/Support/CommandLine.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  57. #include "llvm/Transforms/Utils/Cloning.h"
  58. #include "llvm/Transforms/Utils/Local.h"
  59. #include "llvm/Transforms/Utils/LoopUtils.h"
  60. #include <algorithm>
  61. #include <map>
  62. #include <set>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "loop-unswitch"
  65. STATISTIC(NumBranches, "Number of branches unswitched");
  66. STATISTIC(NumSwitches, "Number of switches unswitched");
  67. STATISTIC(NumGuards, "Number of guards unswitched");
  68. STATISTIC(NumSelects , "Number of selects unswitched");
  69. STATISTIC(NumTrivial , "Number of unswitches that are trivial");
  70. STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
  71. STATISTIC(TotalInsts, "Total number of instructions analyzed");
  72. // The specific value of 100 here was chosen based only on intuition and a
  73. // few specific examples.
  74. static cl::opt<unsigned>
  75. Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
  76. cl::init(100), cl::Hidden);
  77. namespace {
  78. class LUAnalysisCache {
  79. typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
  80. UnswitchedValsMap;
  81. typedef UnswitchedValsMap::iterator UnswitchedValsIt;
  82. struct LoopProperties {
  83. unsigned CanBeUnswitchedCount;
  84. unsigned WasUnswitchedCount;
  85. unsigned SizeEstimation;
  86. UnswitchedValsMap UnswitchedVals;
  87. };
  88. // Here we use std::map instead of DenseMap, since we need to keep valid
  89. // LoopProperties pointer for current loop for better performance.
  90. typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
  91. typedef LoopPropsMap::iterator LoopPropsMapIt;
  92. LoopPropsMap LoopsProperties;
  93. UnswitchedValsMap *CurLoopInstructions;
  94. LoopProperties *CurrentLoopProperties;
  95. // A loop unswitching with an estimated cost above this threshold
  96. // is not performed. MaxSize is turned into unswitching quota for
  97. // the current loop, and reduced correspondingly, though note that
  98. // the quota is returned by releaseMemory() when the loop has been
  99. // processed, so that MaxSize will return to its previous
  100. // value. So in most cases MaxSize will equal the Threshold flag
  101. // when a new loop is processed. An exception to that is that
  102. // MaxSize will have a smaller value while processing nested loops
  103. // that were introduced due to loop unswitching of an outer loop.
  104. //
  105. // FIXME: The way that MaxSize works is subtle and depends on the
  106. // pass manager processing loops and calling releaseMemory() in a
  107. // specific order. It would be good to find a more straightforward
  108. // way of doing what MaxSize does.
  109. unsigned MaxSize;
  110. public:
  111. LUAnalysisCache()
  112. : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
  113. MaxSize(Threshold) {}
  114. // Analyze loop. Check its size, calculate is it possible to unswitch
  115. // it. Returns true if we can unswitch this loop.
  116. bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
  117. AssumptionCache *AC);
  118. // Clean all data related to given loop.
  119. void forgetLoop(const Loop *L);
  120. // Mark case value as unswitched.
  121. // Since SI instruction can be partly unswitched, in order to avoid
  122. // extra unswitching in cloned loops keep track all unswitched values.
  123. void setUnswitched(const SwitchInst *SI, const Value *V);
  124. // Check was this case value unswitched before or not.
  125. bool isUnswitched(const SwitchInst *SI, const Value *V);
  126. // Returns true if another unswitching could be done within the cost
  127. // threshold.
  128. bool CostAllowsUnswitching();
  129. // Clone all loop-unswitch related loop properties.
  130. // Redistribute unswitching quotas.
  131. // Note, that new loop data is stored inside the VMap.
  132. void cloneData(const Loop *NewLoop, const Loop *OldLoop,
  133. const ValueToValueMapTy &VMap);
  134. };
  135. class LoopUnswitch : public LoopPass {
  136. LoopInfo *LI; // Loop information
  137. LPPassManager *LPM;
  138. AssumptionCache *AC;
  139. // Used to check if second loop needs processing after
  140. // RewriteLoopBodyWithConditionConstant rewrites first loop.
  141. std::vector<Loop*> LoopProcessWorklist;
  142. LUAnalysisCache BranchesInfo;
  143. bool OptimizeForSize;
  144. bool redoLoop;
  145. Loop *currentLoop;
  146. DominatorTree *DT;
  147. BasicBlock *loopHeader;
  148. BasicBlock *loopPreheader;
  149. bool SanitizeMemory;
  150. LoopSafetyInfo SafetyInfo;
  151. // LoopBlocks contains all of the basic blocks of the loop, including the
  152. // preheader of the loop, the body of the loop, and the exit blocks of the
  153. // loop, in that order.
  154. std::vector<BasicBlock*> LoopBlocks;
  155. // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
  156. std::vector<BasicBlock*> NewBlocks;
  157. bool hasBranchDivergence;
  158. public:
  159. static char ID; // Pass ID, replacement for typeid
  160. explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false) :
  161. LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
  162. currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
  163. loopPreheader(nullptr), hasBranchDivergence(hasBranchDivergence) {
  164. initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
  165. }
  166. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  167. bool processCurrentLoop();
  168. bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
  169. /// This transformation requires natural loop information & requires that
  170. /// loop preheaders be inserted into the CFG.
  171. ///
  172. void getAnalysisUsage(AnalysisUsage &AU) const override {
  173. AU.addRequired<AssumptionCacheTracker>();
  174. AU.addRequired<TargetTransformInfoWrapperPass>();
  175. if (hasBranchDivergence)
  176. AU.addRequired<DivergenceAnalysis>();
  177. getLoopAnalysisUsage(AU);
  178. }
  179. private:
  180. void releaseMemory() override {
  181. BranchesInfo.forgetLoop(currentLoop);
  182. }
  183. void initLoopData() {
  184. loopHeader = currentLoop->getHeader();
  185. loopPreheader = currentLoop->getLoopPreheader();
  186. }
  187. /// Split all of the edges from inside the loop to their exit blocks.
  188. /// Update the appropriate Phi nodes as we do so.
  189. void SplitExitEdges(Loop *L,
  190. const SmallVectorImpl<BasicBlock *> &ExitBlocks);
  191. bool TryTrivialLoopUnswitch(bool &Changed);
  192. bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
  193. TerminatorInst *TI = nullptr);
  194. void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  195. BasicBlock *ExitBlock, TerminatorInst *TI);
  196. void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
  197. TerminatorInst *TI);
  198. void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  199. Constant *Val, bool isEqual);
  200. void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
  201. BasicBlock *TrueDest,
  202. BasicBlock *FalseDest,
  203. Instruction *InsertPt,
  204. TerminatorInst *TI);
  205. void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
  206. /// Given that the Invariant is not equal to Val. Simplify instructions
  207. /// in the loop.
  208. Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
  209. Constant *Val);
  210. };
  211. }
  212. // Analyze loop. Check its size, calculate is it possible to unswitch
  213. // it. Returns true if we can unswitch this loop.
  214. bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
  215. AssumptionCache *AC) {
  216. LoopPropsMapIt PropsIt;
  217. bool Inserted;
  218. std::tie(PropsIt, Inserted) =
  219. LoopsProperties.insert(std::make_pair(L, LoopProperties()));
  220. LoopProperties &Props = PropsIt->second;
  221. if (Inserted) {
  222. // New loop.
  223. // Limit the number of instructions to avoid causing significant code
  224. // expansion, and the number of basic blocks, to avoid loops with
  225. // large numbers of branches which cause loop unswitching to go crazy.
  226. // This is a very ad-hoc heuristic.
  227. SmallPtrSet<const Value *, 32> EphValues;
  228. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  229. // FIXME: This is overly conservative because it does not take into
  230. // consideration code simplification opportunities and code that can
  231. // be shared by the resultant unswitched loops.
  232. CodeMetrics Metrics;
  233. for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
  234. ++I)
  235. Metrics.analyzeBasicBlock(*I, TTI, EphValues);
  236. Props.SizeEstimation = Metrics.NumInsts;
  237. Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
  238. Props.WasUnswitchedCount = 0;
  239. MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
  240. if (Metrics.notDuplicatable) {
  241. DEBUG(dbgs() << "NOT unswitching loop %"
  242. << L->getHeader()->getName() << ", contents cannot be "
  243. << "duplicated!\n");
  244. return false;
  245. }
  246. }
  247. // Be careful. This links are good only before new loop addition.
  248. CurrentLoopProperties = &Props;
  249. CurLoopInstructions = &Props.UnswitchedVals;
  250. return true;
  251. }
  252. // Clean all data related to given loop.
  253. void LUAnalysisCache::forgetLoop(const Loop *L) {
  254. LoopPropsMapIt LIt = LoopsProperties.find(L);
  255. if (LIt != LoopsProperties.end()) {
  256. LoopProperties &Props = LIt->second;
  257. MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
  258. Props.SizeEstimation;
  259. LoopsProperties.erase(LIt);
  260. }
  261. CurrentLoopProperties = nullptr;
  262. CurLoopInstructions = nullptr;
  263. }
  264. // Mark case value as unswitched.
  265. // Since SI instruction can be partly unswitched, in order to avoid
  266. // extra unswitching in cloned loops keep track all unswitched values.
  267. void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
  268. (*CurLoopInstructions)[SI].insert(V);
  269. }
  270. // Check was this case value unswitched before or not.
  271. bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
  272. return (*CurLoopInstructions)[SI].count(V);
  273. }
  274. bool LUAnalysisCache::CostAllowsUnswitching() {
  275. return CurrentLoopProperties->CanBeUnswitchedCount > 0;
  276. }
  277. // Clone all loop-unswitch related loop properties.
  278. // Redistribute unswitching quotas.
  279. // Note, that new loop data is stored inside the VMap.
  280. void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
  281. const ValueToValueMapTy &VMap) {
  282. LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
  283. LoopProperties &OldLoopProps = *CurrentLoopProperties;
  284. UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
  285. // Reallocate "can-be-unswitched quota"
  286. --OldLoopProps.CanBeUnswitchedCount;
  287. ++OldLoopProps.WasUnswitchedCount;
  288. NewLoopProps.WasUnswitchedCount = 0;
  289. unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
  290. NewLoopProps.CanBeUnswitchedCount = Quota / 2;
  291. OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
  292. NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
  293. // Clone unswitched values info:
  294. // for new loop switches we clone info about values that was
  295. // already unswitched and has redundant successors.
  296. for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
  297. const SwitchInst *OldInst = I->first;
  298. Value *NewI = VMap.lookup(OldInst);
  299. const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
  300. assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
  301. NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
  302. }
  303. }
  304. char LoopUnswitch::ID = 0;
  305. INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  306. false, false)
  307. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  308. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  309. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  310. INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
  311. INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  312. false, false)
  313. Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
  314. return new LoopUnswitch(Os, hasBranchDivergence);
  315. }
  316. /// Operator chain lattice.
  317. enum OperatorChain {
  318. OC_OpChainNone, ///< There is no operator.
  319. OC_OpChainOr, ///< There are only ORs.
  320. OC_OpChainAnd, ///< There are only ANDs.
  321. OC_OpChainMixed ///< There are ANDs and ORs.
  322. };
  323. /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
  324. /// an invariant piece, return the invariant. Otherwise, return null.
  325. //
  326. /// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
  327. /// mixed operator chain, as we can not reliably find a value which will simplify
  328. /// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
  329. /// to simplify the chain.
  330. ///
  331. /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
  332. /// simplify the condition itself to a loop variant condition, but at the
  333. /// cost of creating an entirely new loop.
  334. static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
  335. OperatorChain &ParentChain,
  336. DenseMap<Value *, Value *> &Cache) {
  337. auto CacheIt = Cache.find(Cond);
  338. if (CacheIt != Cache.end())
  339. return CacheIt->second;
  340. // We started analyze new instruction, increment scanned instructions counter.
  341. ++TotalInsts;
  342. // We can never unswitch on vector conditions.
  343. if (Cond->getType()->isVectorTy())
  344. return nullptr;
  345. // Constants should be folded, not unswitched on!
  346. if (isa<Constant>(Cond)) return nullptr;
  347. // TODO: Handle: br (VARIANT|INVARIANT).
  348. // Hoist simple values out.
  349. if (L->makeLoopInvariant(Cond, Changed)) {
  350. Cache[Cond] = Cond;
  351. return Cond;
  352. }
  353. // Walk up the operator chain to find partial invariant conditions.
  354. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
  355. if (BO->getOpcode() == Instruction::And ||
  356. BO->getOpcode() == Instruction::Or) {
  357. // Given the previous operator, compute the current operator chain status.
  358. OperatorChain NewChain;
  359. switch (ParentChain) {
  360. case OC_OpChainNone:
  361. NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
  362. OC_OpChainOr;
  363. break;
  364. case OC_OpChainOr:
  365. NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
  366. OC_OpChainMixed;
  367. break;
  368. case OC_OpChainAnd:
  369. NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
  370. OC_OpChainMixed;
  371. break;
  372. case OC_OpChainMixed:
  373. NewChain = OC_OpChainMixed;
  374. break;
  375. }
  376. // If we reach a Mixed state, we do not want to keep walking up as we can not
  377. // reliably find a value that will simplify the chain. With this check, we
  378. // will return null on the first sight of mixed chain and the caller will
  379. // either backtrack to find partial LIV in other operand or return null.
  380. if (NewChain != OC_OpChainMixed) {
  381. // Update the current operator chain type before we search up the chain.
  382. ParentChain = NewChain;
  383. // If either the left or right side is invariant, we can unswitch on this,
  384. // which will cause the branch to go away in one loop and the condition to
  385. // simplify in the other one.
  386. if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
  387. ParentChain, Cache)) {
  388. Cache[Cond] = LHS;
  389. return LHS;
  390. }
  391. // We did not manage to find a partial LIV in operand(0). Backtrack and try
  392. // operand(1).
  393. ParentChain = NewChain;
  394. if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
  395. ParentChain, Cache)) {
  396. Cache[Cond] = RHS;
  397. return RHS;
  398. }
  399. }
  400. }
  401. Cache[Cond] = nullptr;
  402. return nullptr;
  403. }
  404. /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
  405. /// an invariant piece, return the invariant along with the operator chain type.
  406. /// Otherwise, return null.
  407. static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
  408. Loop *L,
  409. bool &Changed) {
  410. DenseMap<Value *, Value *> Cache;
  411. OperatorChain OpChain = OC_OpChainNone;
  412. Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
  413. // In case we do find a LIV, it can not be obtained by walking up a mixed
  414. // operator chain.
  415. assert((!FCond || OpChain != OC_OpChainMixed) &&
  416. "Do not expect a partial LIV with mixed operator chain");
  417. return {FCond, OpChain};
  418. }
  419. bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
  420. if (skipLoop(L))
  421. return false;
  422. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  423. *L->getHeader()->getParent());
  424. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  425. LPM = &LPM_Ref;
  426. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  427. currentLoop = L;
  428. Function *F = currentLoop->getHeader()->getParent();
  429. SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
  430. if (SanitizeMemory)
  431. computeLoopSafetyInfo(&SafetyInfo, L);
  432. bool Changed = false;
  433. do {
  434. assert(currentLoop->isLCSSAForm(*DT));
  435. redoLoop = false;
  436. Changed |= processCurrentLoop();
  437. } while(redoLoop);
  438. // FIXME: Reconstruct dom info, because it is not preserved properly.
  439. if (Changed)
  440. DT->recalculate(*F);
  441. return Changed;
  442. }
  443. // Return true if the BasicBlock BB is unreachable from the loop header.
  444. // Return false, otherwise.
  445. bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
  446. auto *Node = DT->getNode(BB)->getIDom();
  447. BasicBlock *DomBB = Node->getBlock();
  448. while (currentLoop->contains(DomBB)) {
  449. BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
  450. Node = DT->getNode(DomBB)->getIDom();
  451. DomBB = Node->getBlock();
  452. if (!BInst || !BInst->isConditional())
  453. continue;
  454. Value *Cond = BInst->getCondition();
  455. if (!isa<ConstantInt>(Cond))
  456. continue;
  457. BasicBlock *UnreachableSucc =
  458. Cond == ConstantInt::getTrue(Cond->getContext())
  459. ? BInst->getSuccessor(1)
  460. : BInst->getSuccessor(0);
  461. if (DT->dominates(UnreachableSucc, BB))
  462. return true;
  463. }
  464. return false;
  465. }
  466. /// Do actual work and unswitch loop if possible and profitable.
  467. bool LoopUnswitch::processCurrentLoop() {
  468. bool Changed = false;
  469. initLoopData();
  470. // If LoopSimplify was unable to form a preheader, don't do any unswitching.
  471. if (!loopPreheader)
  472. return false;
  473. // Loops with indirectbr cannot be cloned.
  474. if (!currentLoop->isSafeToClone())
  475. return false;
  476. // Without dedicated exits, splitting the exit edge may fail.
  477. if (!currentLoop->hasDedicatedExits())
  478. return false;
  479. LLVMContext &Context = loopHeader->getContext();
  480. // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
  481. if (!BranchesInfo.countLoop(
  482. currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  483. *currentLoop->getHeader()->getParent()),
  484. AC))
  485. return false;
  486. // Try trivial unswitch first before loop over other basic blocks in the loop.
  487. if (TryTrivialLoopUnswitch(Changed)) {
  488. return true;
  489. }
  490. // Run through the instructions in the loop, keeping track of three things:
  491. //
  492. // - That we do not unswitch loops containing convergent operations, as we
  493. // might be making them control dependent on the unswitch value when they
  494. // were not before.
  495. // FIXME: This could be refined to only bail if the convergent operation is
  496. // not already control-dependent on the unswitch value.
  497. //
  498. // - That basic blocks in the loop contain invokes whose predecessor edges we
  499. // cannot split.
  500. //
  501. // - The set of guard intrinsics encountered (these are non terminator
  502. // instructions that are also profitable to be unswitched).
  503. SmallVector<IntrinsicInst *, 4> Guards;
  504. for (const auto BB : currentLoop->blocks()) {
  505. for (auto &I : *BB) {
  506. auto CS = CallSite(&I);
  507. if (!CS) continue;
  508. if (CS.hasFnAttr(Attribute::Convergent))
  509. return false;
  510. if (auto *II = dyn_cast<InvokeInst>(&I))
  511. if (!II->getUnwindDest()->canSplitPredecessors())
  512. return false;
  513. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  514. if (II->getIntrinsicID() == Intrinsic::experimental_guard)
  515. Guards.push_back(II);
  516. }
  517. }
  518. // Do not do non-trivial unswitch while optimizing for size.
  519. // FIXME: Use Function::optForSize().
  520. if (OptimizeForSize ||
  521. loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
  522. return false;
  523. for (IntrinsicInst *Guard : Guards) {
  524. Value *LoopCond =
  525. FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
  526. if (LoopCond &&
  527. UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
  528. // NB! Unswitching (if successful) could have erased some of the
  529. // instructions in Guards leaving dangling pointers there. This is fine
  530. // because we're returning now, and won't look at Guards again.
  531. ++NumGuards;
  532. return true;
  533. }
  534. }
  535. // Loop over all of the basic blocks in the loop. If we find an interior
  536. // block that is branching on a loop-invariant condition, we can unswitch this
  537. // loop.
  538. for (Loop::block_iterator I = currentLoop->block_begin(),
  539. E = currentLoop->block_end(); I != E; ++I) {
  540. TerminatorInst *TI = (*I)->getTerminator();
  541. // Unswitching on a potentially uninitialized predicate is not
  542. // MSan-friendly. Limit this to the cases when the original predicate is
  543. // guaranteed to execute, to avoid creating a use-of-uninitialized-value
  544. // in the code that did not have one.
  545. // This is a workaround for the discrepancy between LLVM IR and MSan
  546. // semantics. See PR28054 for more details.
  547. if (SanitizeMemory &&
  548. !isGuaranteedToExecute(*TI, DT, currentLoop, &SafetyInfo))
  549. continue;
  550. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  551. // Some branches may be rendered unreachable because of previous
  552. // unswitching.
  553. // Unswitch only those branches that are reachable.
  554. if (isUnreachableDueToPreviousUnswitching(*I))
  555. continue;
  556. // If this isn't branching on an invariant condition, we can't unswitch
  557. // it.
  558. if (BI->isConditional()) {
  559. // See if this, or some part of it, is loop invariant. If so, we can
  560. // unswitch on it if we desire.
  561. Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
  562. currentLoop, Changed).first;
  563. if (LoopCond &&
  564. UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
  565. ++NumBranches;
  566. return true;
  567. }
  568. }
  569. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  570. Value *SC = SI->getCondition();
  571. Value *LoopCond;
  572. OperatorChain OpChain;
  573. std::tie(LoopCond, OpChain) =
  574. FindLIVLoopCondition(SC, currentLoop, Changed);
  575. unsigned NumCases = SI->getNumCases();
  576. if (LoopCond && NumCases) {
  577. // Find a value to unswitch on:
  578. // FIXME: this should chose the most expensive case!
  579. // FIXME: scan for a case with a non-critical edge?
  580. Constant *UnswitchVal = nullptr;
  581. // Find a case value such that at least one case value is unswitched
  582. // out.
  583. if (OpChain == OC_OpChainAnd) {
  584. // If the chain only has ANDs and the switch has a case value of 0.
  585. // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
  586. auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
  587. if (BranchesInfo.isUnswitched(SI, AllZero))
  588. continue;
  589. // We are unswitching 0 out.
  590. UnswitchVal = AllZero;
  591. } else if (OpChain == OC_OpChainOr) {
  592. // If the chain only has ORs and the switch has a case value of ~0.
  593. // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
  594. auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
  595. if (BranchesInfo.isUnswitched(SI, AllOne))
  596. continue;
  597. // We are unswitching ~0 out.
  598. UnswitchVal = AllOne;
  599. } else {
  600. assert(OpChain == OC_OpChainNone &&
  601. "Expect to unswitch on trivial chain");
  602. // Do not process same value again and again.
  603. // At this point we have some cases already unswitched and
  604. // some not yet unswitched. Let's find the first not yet unswitched one.
  605. for (auto Case : SI->cases()) {
  606. Constant *UnswitchValCandidate = Case.getCaseValue();
  607. if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
  608. UnswitchVal = UnswitchValCandidate;
  609. break;
  610. }
  611. }
  612. }
  613. if (!UnswitchVal)
  614. continue;
  615. if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
  616. ++NumSwitches;
  617. // In case of a full LIV, UnswitchVal is the value we unswitched out.
  618. // In case of a partial LIV, we only unswitch when its an AND-chain
  619. // or OR-chain. In both cases switch input value simplifies to
  620. // UnswitchVal.
  621. BranchesInfo.setUnswitched(SI, UnswitchVal);
  622. return true;
  623. }
  624. }
  625. }
  626. // Scan the instructions to check for unswitchable values.
  627. for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
  628. BBI != E; ++BBI)
  629. if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
  630. Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
  631. currentLoop, Changed).first;
  632. if (LoopCond && UnswitchIfProfitable(LoopCond,
  633. ConstantInt::getTrue(Context))) {
  634. ++NumSelects;
  635. return true;
  636. }
  637. }
  638. }
  639. return Changed;
  640. }
  641. /// Check to see if all paths from BB exit the loop with no side effects
  642. /// (including infinite loops).
  643. ///
  644. /// If true, we return true and set ExitBB to the block we
  645. /// exit through.
  646. ///
  647. static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
  648. BasicBlock *&ExitBB,
  649. std::set<BasicBlock*> &Visited) {
  650. if (!Visited.insert(BB).second) {
  651. // Already visited. Without more analysis, this could indicate an infinite
  652. // loop.
  653. return false;
  654. }
  655. if (!L->contains(BB)) {
  656. // Otherwise, this is a loop exit, this is fine so long as this is the
  657. // first exit.
  658. if (ExitBB) return false;
  659. ExitBB = BB;
  660. return true;
  661. }
  662. // Otherwise, this is an unvisited intra-loop node. Check all successors.
  663. for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
  664. // Check to see if the successor is a trivial loop exit.
  665. if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
  666. return false;
  667. }
  668. // Okay, everything after this looks good, check to make sure that this block
  669. // doesn't include any side effects.
  670. for (Instruction &I : *BB)
  671. if (I.mayHaveSideEffects())
  672. return false;
  673. return true;
  674. }
  675. /// Return true if the specified block unconditionally leads to an exit from
  676. /// the specified loop, and has no side-effects in the process. If so, return
  677. /// the block that is exited to, otherwise return null.
  678. static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
  679. std::set<BasicBlock*> Visited;
  680. Visited.insert(L->getHeader()); // Branches to header make infinite loops.
  681. BasicBlock *ExitBB = nullptr;
  682. if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
  683. return ExitBB;
  684. return nullptr;
  685. }
  686. /// We have found that we can unswitch currentLoop when LoopCond == Val to
  687. /// simplify the loop. If we decide that this is profitable,
  688. /// unswitch the loop, reprocess the pieces, then return true.
  689. bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
  690. TerminatorInst *TI) {
  691. // Check to see if it would be profitable to unswitch current loop.
  692. if (!BranchesInfo.CostAllowsUnswitching()) {
  693. DEBUG(dbgs() << "NOT unswitching loop %"
  694. << currentLoop->getHeader()->getName()
  695. << " at non-trivial condition '" << *Val
  696. << "' == " << *LoopCond << "\n"
  697. << ". Cost too high.\n");
  698. return false;
  699. }
  700. if (hasBranchDivergence &&
  701. getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
  702. DEBUG(dbgs() << "NOT unswitching loop %"
  703. << currentLoop->getHeader()->getName()
  704. << " at non-trivial condition '" << *Val
  705. << "' == " << *LoopCond << "\n"
  706. << ". Condition is divergent.\n");
  707. return false;
  708. }
  709. UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
  710. return true;
  711. }
  712. /// Recursively clone the specified loop and all of its children,
  713. /// mapping the blocks with the specified map.
  714. static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
  715. LoopInfo *LI, LPPassManager *LPM) {
  716. Loop &New = LPM->addLoop(PL);
  717. // Add all of the blocks in L to the new loop.
  718. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  719. I != E; ++I)
  720. if (LI->getLoopFor(*I) == L)
  721. New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
  722. // Add all of the subloops to the new loop.
  723. for (Loop *I : *L)
  724. CloneLoop(I, &New, VM, LI, LPM);
  725. return &New;
  726. }
  727. /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
  728. /// otherwise branch to FalseDest. Insert the code immediately before InsertPt.
  729. void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
  730. BasicBlock *TrueDest,
  731. BasicBlock *FalseDest,
  732. Instruction *InsertPt,
  733. TerminatorInst *TI) {
  734. // Insert a conditional branch on LIC to the two preheaders. The original
  735. // code is the true version and the new code is the false version.
  736. Value *BranchVal = LIC;
  737. bool Swapped = false;
  738. if (!isa<ConstantInt>(Val) ||
  739. Val->getType() != Type::getInt1Ty(LIC->getContext()))
  740. BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
  741. else if (Val != ConstantInt::getTrue(Val->getContext())) {
  742. // We want to enter the new loop when the condition is true.
  743. std::swap(TrueDest, FalseDest);
  744. Swapped = true;
  745. }
  746. // Insert the new branch.
  747. BranchInst *BI =
  748. IRBuilder<>(InsertPt).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
  749. if (Swapped)
  750. BI->swapProfMetadata();
  751. // If either edge is critical, split it. This helps preserve LoopSimplify
  752. // form for enclosing loops.
  753. auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
  754. SplitCriticalEdge(BI, 0, Options);
  755. SplitCriticalEdge(BI, 1, Options);
  756. }
  757. /// Given a loop that has a trivial unswitchable condition in it (a cond branch
  758. /// from its header block to its latch block, where the path through the loop
  759. /// that doesn't execute its body has no side-effects), unswitch it. This
  760. /// doesn't involve any code duplication, just moving the conditional branch
  761. /// outside of the loop and updating loop info.
  762. void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  763. BasicBlock *ExitBlock,
  764. TerminatorInst *TI) {
  765. DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
  766. << loopHeader->getName() << " [" << L->getBlocks().size()
  767. << " blocks] in Function "
  768. << L->getHeader()->getParent()->getName() << " on cond: " << *Val
  769. << " == " << *Cond << "\n");
  770. // First step, split the preheader, so that we know that there is a safe place
  771. // to insert the conditional branch. We will change loopPreheader to have a
  772. // conditional branch on Cond.
  773. BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
  774. // Now that we have a place to insert the conditional branch, create a place
  775. // to branch to: this is the exit block out of the loop that we should
  776. // short-circuit to.
  777. // Split this block now, so that the loop maintains its exit block, and so
  778. // that the jump from the preheader can execute the contents of the exit block
  779. // without actually branching to it (the exit block should be dominated by the
  780. // loop header, not the preheader).
  781. assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
  782. BasicBlock *NewExit = SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI);
  783. // Okay, now we have a position to branch from and a position to branch to,
  784. // insert the new conditional branch.
  785. EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
  786. loopPreheader->getTerminator(), TI);
  787. LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
  788. loopPreheader->getTerminator()->eraseFromParent();
  789. // We need to reprocess this loop, it could be unswitched again.
  790. redoLoop = true;
  791. // Now that we know that the loop is never entered when this condition is a
  792. // particular value, rewrite the loop with this info. We know that this will
  793. // at least eliminate the old branch.
  794. RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
  795. ++NumTrivial;
  796. }
  797. /// Check if the first non-constant condition starting from the loop header is
  798. /// a trivial unswitch condition: that is, a condition controls whether or not
  799. /// the loop does anything at all. If it is a trivial condition, unswitching
  800. /// produces no code duplications (equivalently, it produces a simpler loop and
  801. /// a new empty loop, which gets deleted). Therefore always unswitch trivial
  802. /// condition.
  803. bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
  804. BasicBlock *CurrentBB = currentLoop->getHeader();
  805. TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
  806. LLVMContext &Context = CurrentBB->getContext();
  807. // If loop header has only one reachable successor (currently via an
  808. // unconditional branch or constant foldable conditional branch, but
  809. // should also consider adding constant foldable switch instruction in
  810. // future), we should keep looking for trivial condition candidates in
  811. // the successor as well. An alternative is to constant fold conditions
  812. // and merge successors into loop header (then we only need to check header's
  813. // terminator). The reason for not doing this in LoopUnswitch pass is that
  814. // it could potentially break LoopPassManager's invariants. Folding dead
  815. // branches could either eliminate the current loop or make other loops
  816. // unreachable. LCSSA form might also not be preserved after deleting
  817. // branches. The following code keeps traversing loop header's successors
  818. // until it finds the trivial condition candidate (condition that is not a
  819. // constant). Since unswitching generates branches with constant conditions,
  820. // this scenario could be very common in practice.
  821. SmallSet<BasicBlock*, 8> Visited;
  822. while (true) {
  823. // If we exit loop or reach a previous visited block, then
  824. // we can not reach any trivial condition candidates (unfoldable
  825. // branch instructions or switch instructions) and no unswitch
  826. // can happen. Exit and return false.
  827. if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
  828. return false;
  829. // Check if this loop will execute any side-effecting instructions (e.g.
  830. // stores, calls, volatile loads) in the part of the loop that the code
  831. // *would* execute. Check the header first.
  832. for (Instruction &I : *CurrentBB)
  833. if (I.mayHaveSideEffects())
  834. return false;
  835. if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
  836. if (BI->isUnconditional()) {
  837. CurrentBB = BI->getSuccessor(0);
  838. } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
  839. CurrentBB = BI->getSuccessor(0);
  840. } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
  841. CurrentBB = BI->getSuccessor(1);
  842. } else {
  843. // Found a trivial condition candidate: non-foldable conditional branch.
  844. break;
  845. }
  846. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
  847. // At this point, any constant-foldable instructions should have probably
  848. // been folded.
  849. ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
  850. if (!Cond)
  851. break;
  852. // Find the target block we are definitely going to.
  853. CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
  854. } else {
  855. // We do not understand these terminator instructions.
  856. break;
  857. }
  858. CurrentTerm = CurrentBB->getTerminator();
  859. }
  860. // CondVal is the condition that controls the trivial condition.
  861. // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
  862. Constant *CondVal = nullptr;
  863. BasicBlock *LoopExitBB = nullptr;
  864. if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
  865. // If this isn't branching on an invariant condition, we can't unswitch it.
  866. if (!BI->isConditional())
  867. return false;
  868. Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
  869. currentLoop, Changed).first;
  870. // Unswitch only if the trivial condition itself is an LIV (not
  871. // partial LIV which could occur in and/or)
  872. if (!LoopCond || LoopCond != BI->getCondition())
  873. return false;
  874. // Check to see if a successor of the branch is guaranteed to
  875. // exit through a unique exit block without having any
  876. // side-effects. If so, determine the value of Cond that causes
  877. // it to do this.
  878. if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
  879. BI->getSuccessor(0)))) {
  880. CondVal = ConstantInt::getTrue(Context);
  881. } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
  882. BI->getSuccessor(1)))) {
  883. CondVal = ConstantInt::getFalse(Context);
  884. }
  885. // If we didn't find a single unique LoopExit block, or if the loop exit
  886. // block contains phi nodes, this isn't trivial.
  887. if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
  888. return false; // Can't handle this.
  889. UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
  890. CurrentTerm);
  891. ++NumBranches;
  892. return true;
  893. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
  894. // If this isn't switching on an invariant condition, we can't unswitch it.
  895. Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
  896. currentLoop, Changed).first;
  897. // Unswitch only if the trivial condition itself is an LIV (not
  898. // partial LIV which could occur in and/or)
  899. if (!LoopCond || LoopCond != SI->getCondition())
  900. return false;
  901. // Check to see if a successor of the switch is guaranteed to go to the
  902. // latch block or exit through a one exit block without having any
  903. // side-effects. If so, determine the value of Cond that causes it to do
  904. // this.
  905. // Note that we can't trivially unswitch on the default case or
  906. // on already unswitched cases.
  907. for (auto Case : SI->cases()) {
  908. BasicBlock *LoopExitCandidate;
  909. if ((LoopExitCandidate =
  910. isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
  911. // Okay, we found a trivial case, remember the value that is trivial.
  912. ConstantInt *CaseVal = Case.getCaseValue();
  913. // Check that it was not unswitched before, since already unswitched
  914. // trivial vals are looks trivial too.
  915. if (BranchesInfo.isUnswitched(SI, CaseVal))
  916. continue;
  917. LoopExitBB = LoopExitCandidate;
  918. CondVal = CaseVal;
  919. break;
  920. }
  921. }
  922. // If we didn't find a single unique LoopExit block, or if the loop exit
  923. // block contains phi nodes, this isn't trivial.
  924. if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
  925. return false; // Can't handle this.
  926. UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
  927. nullptr);
  928. // We are only unswitching full LIV.
  929. BranchesInfo.setUnswitched(SI, CondVal);
  930. ++NumSwitches;
  931. return true;
  932. }
  933. return false;
  934. }
  935. /// Split all of the edges from inside the loop to their exit blocks.
  936. /// Update the appropriate Phi nodes as we do so.
  937. void LoopUnswitch::SplitExitEdges(Loop *L,
  938. const SmallVectorImpl<BasicBlock *> &ExitBlocks){
  939. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  940. BasicBlock *ExitBlock = ExitBlocks[i];
  941. SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
  942. pred_end(ExitBlock));
  943. // Although SplitBlockPredecessors doesn't preserve loop-simplify in
  944. // general, if we call it on all predecessors of all exits then it does.
  945. SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
  946. /*PreserveLCSSA*/ true);
  947. }
  948. }
  949. /// We determined that the loop is profitable to unswitch when LIC equal Val.
  950. /// Split it into loop versions and test the condition outside of either loop.
  951. /// Return the loops created as Out1/Out2.
  952. void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
  953. Loop *L, TerminatorInst *TI) {
  954. Function *F = loopHeader->getParent();
  955. DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
  956. << loopHeader->getName() << " [" << L->getBlocks().size()
  957. << " blocks] in Function " << F->getName()
  958. << " when '" << *Val << "' == " << *LIC << "\n");
  959. if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
  960. SEWP->getSE().forgetLoop(L);
  961. LoopBlocks.clear();
  962. NewBlocks.clear();
  963. // First step, split the preheader and exit blocks, and add these blocks to
  964. // the LoopBlocks list.
  965. BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
  966. LoopBlocks.push_back(NewPreheader);
  967. // We want the loop to come after the preheader, but before the exit blocks.
  968. LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
  969. SmallVector<BasicBlock*, 8> ExitBlocks;
  970. L->getUniqueExitBlocks(ExitBlocks);
  971. // Split all of the edges from inside the loop to their exit blocks. Update
  972. // the appropriate Phi nodes as we do so.
  973. SplitExitEdges(L, ExitBlocks);
  974. // The exit blocks may have been changed due to edge splitting, recompute.
  975. ExitBlocks.clear();
  976. L->getUniqueExitBlocks(ExitBlocks);
  977. // Add exit blocks to the loop blocks.
  978. LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
  979. // Next step, clone all of the basic blocks that make up the loop (including
  980. // the loop preheader and exit blocks), keeping track of the mapping between
  981. // the instructions and blocks.
  982. NewBlocks.reserve(LoopBlocks.size());
  983. ValueToValueMapTy VMap;
  984. for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
  985. BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
  986. NewBlocks.push_back(NewBB);
  987. VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
  988. LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
  989. }
  990. // Splice the newly inserted blocks into the function right before the
  991. // original preheader.
  992. F->getBasicBlockList().splice(NewPreheader->getIterator(),
  993. F->getBasicBlockList(),
  994. NewBlocks[0]->getIterator(), F->end());
  995. // Now we create the new Loop object for the versioned loop.
  996. Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
  997. // Recalculate unswitching quota, inherit simplified switches info for NewBB,
  998. // Probably clone more loop-unswitch related loop properties.
  999. BranchesInfo.cloneData(NewLoop, L, VMap);
  1000. Loop *ParentLoop = L->getParentLoop();
  1001. if (ParentLoop) {
  1002. // Make sure to add the cloned preheader and exit blocks to the parent loop
  1003. // as well.
  1004. ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
  1005. }
  1006. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  1007. BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
  1008. // The new exit block should be in the same loop as the old one.
  1009. if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
  1010. ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
  1011. assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
  1012. "Exit block should have been split to have one successor!");
  1013. BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
  1014. // If the successor of the exit block had PHI nodes, add an entry for
  1015. // NewExit.
  1016. for (BasicBlock::iterator I = ExitSucc->begin();
  1017. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1018. Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
  1019. ValueToValueMapTy::iterator It = VMap.find(V);
  1020. if (It != VMap.end()) V = It->second;
  1021. PN->addIncoming(V, NewExit);
  1022. }
  1023. if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
  1024. PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
  1025. &*ExitSucc->getFirstInsertionPt());
  1026. for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
  1027. I != E; ++I) {
  1028. BasicBlock *BB = *I;
  1029. LandingPadInst *LPI = BB->getLandingPadInst();
  1030. LPI->replaceAllUsesWith(PN);
  1031. PN->addIncoming(LPI, BB);
  1032. }
  1033. }
  1034. }
  1035. // Rewrite the code to refer to itself.
  1036. for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
  1037. for (Instruction &I : *NewBlocks[i]) {
  1038. RemapInstruction(&I, VMap,
  1039. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  1040. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  1041. if (II->getIntrinsicID() == Intrinsic::assume)
  1042. AC->registerAssumption(II);
  1043. }
  1044. }
  1045. // Rewrite the original preheader to select between versions of the loop.
  1046. BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
  1047. assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
  1048. "Preheader splitting did not work correctly!");
  1049. // Emit the new branch that selects between the two versions of this loop.
  1050. EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
  1051. TI);
  1052. LPM->deleteSimpleAnalysisValue(OldBR, L);
  1053. OldBR->eraseFromParent();
  1054. LoopProcessWorklist.push_back(NewLoop);
  1055. redoLoop = true;
  1056. // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
  1057. // deletes the instruction (for example by simplifying a PHI that feeds into
  1058. // the condition that we're unswitching on), we don't rewrite the second
  1059. // iteration.
  1060. WeakVH LICHandle(LIC);
  1061. // Now we rewrite the original code to know that the condition is true and the
  1062. // new code to know that the condition is false.
  1063. RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
  1064. // It's possible that simplifying one loop could cause the other to be
  1065. // changed to another value or a constant. If its a constant, don't simplify
  1066. // it.
  1067. if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
  1068. LICHandle && !isa<Constant>(LICHandle))
  1069. RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
  1070. }
  1071. /// Remove all instances of I from the worklist vector specified.
  1072. static void RemoveFromWorklist(Instruction *I,
  1073. std::vector<Instruction*> &Worklist) {
  1074. Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
  1075. Worklist.end());
  1076. }
  1077. /// When we find that I really equals V, remove I from the
  1078. /// program, replacing all uses with V and update the worklist.
  1079. static void ReplaceUsesOfWith(Instruction *I, Value *V,
  1080. std::vector<Instruction*> &Worklist,
  1081. Loop *L, LPPassManager *LPM) {
  1082. DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
  1083. // Add uses to the worklist, which may be dead now.
  1084. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  1085. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  1086. Worklist.push_back(Use);
  1087. // Add users to the worklist which may be simplified now.
  1088. for (User *U : I->users())
  1089. Worklist.push_back(cast<Instruction>(U));
  1090. LPM->deleteSimpleAnalysisValue(I, L);
  1091. RemoveFromWorklist(I, Worklist);
  1092. I->replaceAllUsesWith(V);
  1093. I->eraseFromParent();
  1094. ++NumSimplify;
  1095. }
  1096. /// We know either that the value LIC has the value specified by Val in the
  1097. /// specified loop, or we know it does NOT have that value.
  1098. /// Rewrite any uses of LIC or of properties correlated to it.
  1099. void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  1100. Constant *Val,
  1101. bool IsEqual) {
  1102. assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
  1103. // FIXME: Support correlated properties, like:
  1104. // for (...)
  1105. // if (li1 < li2)
  1106. // ...
  1107. // if (li1 > li2)
  1108. // ...
  1109. // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
  1110. // selects, switches.
  1111. std::vector<Instruction*> Worklist;
  1112. LLVMContext &Context = Val->getContext();
  1113. // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
  1114. // in the loop with the appropriate one directly.
  1115. if (IsEqual || (isa<ConstantInt>(Val) &&
  1116. Val->getType()->isIntegerTy(1))) {
  1117. Value *Replacement;
  1118. if (IsEqual)
  1119. Replacement = Val;
  1120. else
  1121. Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
  1122. !cast<ConstantInt>(Val)->getZExtValue());
  1123. for (User *U : LIC->users()) {
  1124. Instruction *UI = dyn_cast<Instruction>(U);
  1125. if (!UI || !L->contains(UI))
  1126. continue;
  1127. Worklist.push_back(UI);
  1128. }
  1129. for (Instruction *UI : Worklist)
  1130. UI->replaceUsesOfWith(LIC, Replacement);
  1131. SimplifyCode(Worklist, L);
  1132. return;
  1133. }
  1134. // Otherwise, we don't know the precise value of LIC, but we do know that it
  1135. // is certainly NOT "Val". As such, simplify any uses in the loop that we
  1136. // can. This case occurs when we unswitch switch statements.
  1137. for (User *U : LIC->users()) {
  1138. Instruction *UI = dyn_cast<Instruction>(U);
  1139. if (!UI || !L->contains(UI))
  1140. continue;
  1141. // At this point, we know LIC is definitely not Val. Try to use some simple
  1142. // logic to simplify the user w.r.t. to the context.
  1143. if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
  1144. if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
  1145. // This in-loop instruction has been simplified w.r.t. its context,
  1146. // i.e. LIC != Val, make sure we propagate its replacement value to
  1147. // all its users.
  1148. //
  1149. // We can not yet delete UI, the LIC user, yet, because that would invalidate
  1150. // the LIC->users() iterator !. However, we can make this instruction
  1151. // dead by replacing all its users and push it onto the worklist so that
  1152. // it can be properly deleted and its operands simplified.
  1153. UI->replaceAllUsesWith(Replacement);
  1154. }
  1155. }
  1156. // This is a LIC user, push it into the worklist so that SimplifyCode can
  1157. // attempt to simplify it.
  1158. Worklist.push_back(UI);
  1159. // If we know that LIC is not Val, use this info to simplify code.
  1160. SwitchInst *SI = dyn_cast<SwitchInst>(UI);
  1161. if (!SI || !isa<ConstantInt>(Val)) continue;
  1162. // NOTE: if a case value for the switch is unswitched out, we record it
  1163. // after the unswitch finishes. We can not record it here as the switch
  1164. // is not a direct user of the partial LIV.
  1165. SwitchInst::CaseHandle DeadCase =
  1166. *SI->findCaseValue(cast<ConstantInt>(Val));
  1167. // Default case is live for multiple values.
  1168. if (DeadCase == *SI->case_default())
  1169. continue;
  1170. // Found a dead case value. Don't remove PHI nodes in the
  1171. // successor if they become single-entry, those PHI nodes may
  1172. // be in the Users list.
  1173. BasicBlock *Switch = SI->getParent();
  1174. BasicBlock *SISucc = DeadCase.getCaseSuccessor();
  1175. BasicBlock *Latch = L->getLoopLatch();
  1176. if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
  1177. // If the DeadCase successor dominates the loop latch, then the
  1178. // transformation isn't safe since it will delete the sole predecessor edge
  1179. // to the latch.
  1180. if (Latch && DT->dominates(SISucc, Latch))
  1181. continue;
  1182. // FIXME: This is a hack. We need to keep the successor around
  1183. // and hooked up so as to preserve the loop structure, because
  1184. // trying to update it is complicated. So instead we preserve the
  1185. // loop structure and put the block on a dead code path.
  1186. SplitEdge(Switch, SISucc, DT, LI);
  1187. // Compute the successors instead of relying on the return value
  1188. // of SplitEdge, since it may have split the switch successor
  1189. // after PHI nodes.
  1190. BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
  1191. BasicBlock *OldSISucc = *succ_begin(NewSISucc);
  1192. // Create an "unreachable" destination.
  1193. BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
  1194. Switch->getParent(),
  1195. OldSISucc);
  1196. new UnreachableInst(Context, Abort);
  1197. // Force the new case destination to branch to the "unreachable"
  1198. // block while maintaining a (dead) CFG edge to the old block.
  1199. NewSISucc->getTerminator()->eraseFromParent();
  1200. BranchInst::Create(Abort, OldSISucc,
  1201. ConstantInt::getTrue(Context), NewSISucc);
  1202. // Release the PHI operands for this edge.
  1203. for (BasicBlock::iterator II = NewSISucc->begin();
  1204. PHINode *PN = dyn_cast<PHINode>(II); ++II)
  1205. PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
  1206. UndefValue::get(PN->getType()));
  1207. // Tell the domtree about the new block. We don't fully update the
  1208. // domtree here -- instead we force it to do a full recomputation
  1209. // after the pass is complete -- but we do need to inform it of
  1210. // new blocks.
  1211. DT->addNewBlock(Abort, NewSISucc);
  1212. }
  1213. SimplifyCode(Worklist, L);
  1214. }
  1215. /// Now that we have simplified some instructions in the loop, walk over it and
  1216. /// constant prop, dce, and fold control flow where possible. Note that this is
  1217. /// effectively a very simple loop-structure-aware optimizer. During processing
  1218. /// of this loop, L could very well be deleted, so it must not be used.
  1219. ///
  1220. /// FIXME: When the loop optimizer is more mature, separate this out to a new
  1221. /// pass.
  1222. ///
  1223. void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
  1224. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  1225. while (!Worklist.empty()) {
  1226. Instruction *I = Worklist.back();
  1227. Worklist.pop_back();
  1228. // Simple DCE.
  1229. if (isInstructionTriviallyDead(I)) {
  1230. DEBUG(dbgs() << "Remove dead instruction '" << *I);
  1231. // Add uses to the worklist, which may be dead now.
  1232. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  1233. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  1234. Worklist.push_back(Use);
  1235. LPM->deleteSimpleAnalysisValue(I, L);
  1236. RemoveFromWorklist(I, Worklist);
  1237. I->eraseFromParent();
  1238. ++NumSimplify;
  1239. continue;
  1240. }
  1241. // See if instruction simplification can hack this up. This is common for
  1242. // things like "select false, X, Y" after unswitching made the condition be
  1243. // 'false'. TODO: update the domtree properly so we can pass it here.
  1244. if (Value *V = SimplifyInstruction(I, DL))
  1245. if (LI->replacementPreservesLCSSAForm(I, V)) {
  1246. ReplaceUsesOfWith(I, V, Worklist, L, LPM);
  1247. continue;
  1248. }
  1249. // Special case hacks that appear commonly in unswitched code.
  1250. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1251. if (BI->isUnconditional()) {
  1252. // If BI's parent is the only pred of the successor, fold the two blocks
  1253. // together.
  1254. BasicBlock *Pred = BI->getParent();
  1255. BasicBlock *Succ = BI->getSuccessor(0);
  1256. BasicBlock *SinglePred = Succ->getSinglePredecessor();
  1257. if (!SinglePred) continue; // Nothing to do.
  1258. assert(SinglePred == Pred && "CFG broken");
  1259. DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
  1260. << Succ->getName() << "\n");
  1261. // Resolve any single entry PHI nodes in Succ.
  1262. while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
  1263. ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
  1264. // If Succ has any successors with PHI nodes, update them to have
  1265. // entries coming from Pred instead of Succ.
  1266. Succ->replaceAllUsesWith(Pred);
  1267. // Move all of the successor contents from Succ to Pred.
  1268. Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
  1269. Succ->begin(), Succ->end());
  1270. LPM->deleteSimpleAnalysisValue(BI, L);
  1271. RemoveFromWorklist(BI, Worklist);
  1272. BI->eraseFromParent();
  1273. // Remove Succ from the loop tree.
  1274. LI->removeBlock(Succ);
  1275. LPM->deleteSimpleAnalysisValue(Succ, L);
  1276. Succ->eraseFromParent();
  1277. ++NumSimplify;
  1278. continue;
  1279. }
  1280. continue;
  1281. }
  1282. }
  1283. }
  1284. /// Simple simplifications we can do given the information that Cond is
  1285. /// definitely not equal to Val.
  1286. Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
  1287. Value *Invariant,
  1288. Constant *Val) {
  1289. // icmp eq cond, val -> false
  1290. ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
  1291. if (CI && CI->isEquality()) {
  1292. Value *Op0 = CI->getOperand(0);
  1293. Value *Op1 = CI->getOperand(1);
  1294. if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
  1295. LLVMContext &Ctx = Inst->getContext();
  1296. if (CI->getPredicate() == CmpInst::ICMP_EQ)
  1297. return ConstantInt::getFalse(Ctx);
  1298. else
  1299. return ConstantInt::getTrue(Ctx);
  1300. }
  1301. }
  1302. // FIXME: there may be other opportunities, e.g. comparison with floating
  1303. // point, or Invariant - Val != 0, etc.
  1304. return nullptr;
  1305. }