Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 1 | //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 9 | // |
Chris Lattner | a704ac8 | 2002-10-08 21:36:33 +0000 | [diff] [blame] | 10 | // Peephole optimize the CFG. |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "llvm/Transforms/Utils/Local.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/DenseMap.h" |
| 16 | #include "llvm/ADT/STLExtras.h" |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/SetOperations.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SetVector.h" |
| 19 | #include "llvm/ADT/SmallPtrSet.h" |
| 20 | #include "llvm/ADT/SmallVector.h" |
| 21 | #include "llvm/ADT/Statistic.h" |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 26 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 27 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Constants.h" |
| 29 | #include "llvm/IR/DataLayout.h" |
| 30 | #include "llvm/IR/DerivedTypes.h" |
| 31 | #include "llvm/IR/GlobalVariable.h" |
| 32 | #include "llvm/IR/IRBuilder.h" |
| 33 | #include "llvm/IR/Instructions.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
| 35 | #include "llvm/IR/LLVMContext.h" |
| 36 | #include "llvm/IR/MDBuilder.h" |
| 37 | #include "llvm/IR/Metadata.h" |
| 38 | #include "llvm/IR/Module.h" |
Chandler Carruth | 64396b0 | 2014-03-04 12:05:47 +0000 | [diff] [blame] | 39 | #include "llvm/IR/NoFolder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 40 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 41 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 42 | #include "llvm/IR/Type.h" |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 43 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 44 | #include "llvm/Support/Debug.h" |
| 45 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/Local.h" |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 49 | #include <algorithm> |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 50 | #include <map> |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 51 | #include <set> |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 52 | using namespace llvm; |
Benjamin Kramer | 3717222 | 2013-07-04 14:22:02 +0000 | [diff] [blame] | 53 | using namespace PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 54 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 55 | #define DEBUG_TYPE "simplifycfg" |
| 56 | |
James Molloy | 1b6207e | 2015-02-13 10:48:30 +0000 | [diff] [blame] | 57 | // Chosen as 2 so as to be cheap, but still to have enough power to fold |
| 58 | // a select, so the "clamp" idiom (of a min followed by a max) will be caught. |
| 59 | // To catch this, we need to fold a compare and a select, hence '2' being the |
| 60 | // minimum reasonable default. |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 61 | static cl::opt<unsigned> |
James Molloy | 1b6207e | 2015-02-13 10:48:30 +0000 | [diff] [blame] | 62 | PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), |
| 63 | cl::desc("Control the amount of phi node folding to perform (default = 2)")); |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 64 | |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 65 | static cl::opt<bool> |
| 66 | DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), |
| 67 | cl::desc("Duplicate return instructions into unconditional branches")); |
| 68 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 69 | static cl::opt<bool> |
| 70 | SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), |
| 71 | cl::desc("Sink common instructions down to the end block")); |
| 72 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 73 | static cl::opt<bool> HoistCondStores( |
| 74 | "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), |
| 75 | cl::desc("Hoist conditional stores if an unconditional store precedes")); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 76 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 77 | static cl::opt<bool> MergeCondStores( |
| 78 | "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), |
| 79 | cl::desc("Hoist conditional stores even if an unconditional store does not " |
| 80 | "precede - hoist multiple conditional stores into a single " |
| 81 | "predicated store")); |
| 82 | |
| 83 | static cl::opt<bool> MergeCondStoresAggressively( |
| 84 | "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), |
| 85 | cl::desc("When merging conditional stores, do so even if the resultant " |
| 86 | "basic blocks are unlikely to be if-converted as a result")); |
| 87 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 88 | STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 89 | STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 90 | STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables"); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 91 | STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)"); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 92 | STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 93 | STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 94 | STATISTIC(NumSpeculations, "Number of speculative executed instructions"); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 95 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 96 | namespace { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 97 | // The first field contains the value that the switch produces when a certain |
Sanjay Patel | 9361d35 | 2015-09-10 16:31:19 +0000 | [diff] [blame] | 98 | // case group is selected, and the second field is a vector containing the |
| 99 | // cases composing the case group. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 100 | typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2> |
| 101 | SwitchCaseResultVectorTy; |
| 102 | // The first field contains the phi node that generates a result of the switch |
Sanjay Patel | 9361d35 | 2015-09-10 16:31:19 +0000 | [diff] [blame] | 103 | // and the second field contains the value generated for a certain case in the |
| 104 | // switch for that PHI. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 105 | typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy; |
| 106 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 107 | /// ValueEqualityComparisonCase - Represents a case of a switch. |
| 108 | struct ValueEqualityComparisonCase { |
| 109 | ConstantInt *Value; |
| 110 | BasicBlock *Dest; |
| 111 | |
| 112 | ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) |
| 113 | : Value(Value), Dest(Dest) {} |
| 114 | |
| 115 | bool operator<(ValueEqualityComparisonCase RHS) const { |
| 116 | // Comparing pointers is ok as we only rely on the order for uniquing. |
| 117 | return Value < RHS.Value; |
| 118 | } |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 119 | |
| 120 | bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 121 | }; |
| 122 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 123 | class SimplifyCFGOpt { |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 124 | const TargetTransformInfo &TTI; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 125 | const DataLayout &DL; |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 126 | unsigned BonusInstThreshold; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 127 | AssumptionCache *AC; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 128 | Value *isValueEqualityComparison(TerminatorInst *TI); |
| 129 | BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 130 | std::vector<ValueEqualityComparisonCase> &Cases); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 131 | bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 132 | BasicBlock *Pred, |
| 133 | IRBuilder<> &Builder); |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 134 | bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 135 | IRBuilder<> &Builder); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 136 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 137 | bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 138 | bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 139 | bool SimplifyCleanupReturn(CleanupReturnInst *RI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 140 | bool SimplifyUnreachable(UnreachableInst *UI); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 141 | bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 142 | bool SimplifyIndirectBr(IndirectBrInst *IBI); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 143 | bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 144 | bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 145 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 146 | public: |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 147 | SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, |
| 148 | unsigned BonusInstThreshold, AssumptionCache *AC) |
| 149 | : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {} |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 150 | bool run(BasicBlock *BB); |
| 151 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 152 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 153 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 154 | /// Return true if it is safe to merge these two |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 155 | /// terminator instructions together. |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 156 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { |
| 157 | if (SI1 == SI2) return false; // Can't merge with self! |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 158 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 159 | // It is not safe to merge these two switch instructions if they have a common |
| 160 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 161 | // conflicting incoming values from the two switch blocks. |
| 162 | BasicBlock *SI1BB = SI1->getParent(); |
| 163 | BasicBlock *SI2BB = SI2->getParent(); |
Chris Lattner | b7b7514 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 164 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 165 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 166 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 167 | if (SI1Succs.count(*I)) |
| 168 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 169 | isa<PHINode>(BBI); ++BBI) { |
| 170 | PHINode *PN = cast<PHINode>(BBI); |
| 171 | if (PN->getIncomingValueForBlock(SI1BB) != |
| 172 | PN->getIncomingValueForBlock(SI2BB)) |
| 173 | return false; |
| 174 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 175 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 176 | return true; |
| 177 | } |
| 178 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 179 | /// Return true if it is safe and profitable to merge these two terminator |
| 180 | /// instructions together, where SI1 is an unconditional branch. PhiNodes will |
| 181 | /// store all PHI nodes in common successors. |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 182 | static bool isProfitableToFoldUnconditional(BranchInst *SI1, |
| 183 | BranchInst *SI2, |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 184 | Instruction *Cond, |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 185 | SmallVectorImpl<PHINode*> &PhiNodes) { |
| 186 | if (SI1 == SI2) return false; // Can't merge with self! |
| 187 | assert(SI1->isUnconditional() && SI2->isConditional()); |
| 188 | |
| 189 | // We fold the unconditional branch if we can easily update all PHI nodes in |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 190 | // common successors: |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 191 | // 1> We have a constant incoming value for the conditional branch; |
| 192 | // 2> We have "Cond" as the incoming value for the unconditional branch; |
| 193 | // 3> SI2->getCondition() and Cond have same operands. |
| 194 | CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); |
| 195 | if (!Ci2) return false; |
| 196 | if (!(Cond->getOperand(0) == Ci2->getOperand(0) && |
| 197 | Cond->getOperand(1) == Ci2->getOperand(1)) && |
| 198 | !(Cond->getOperand(0) == Ci2->getOperand(1) && |
| 199 | Cond->getOperand(1) == Ci2->getOperand(0))) |
| 200 | return false; |
| 201 | |
| 202 | BasicBlock *SI1BB = SI1->getParent(); |
| 203 | BasicBlock *SI2BB = SI2->getParent(); |
| 204 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 205 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 206 | if (SI1Succs.count(*I)) |
| 207 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 208 | isa<PHINode>(BBI); ++BBI) { |
| 209 | PHINode *PN = cast<PHINode>(BBI); |
| 210 | if (PN->getIncomingValueForBlock(SI1BB) != Cond || |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 211 | !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 212 | return false; |
| 213 | PhiNodes.push_back(PN); |
| 214 | } |
| 215 | return true; |
| 216 | } |
| 217 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 218 | /// Update PHI nodes in Succ to indicate that there will now be entries in it |
| 219 | /// from the 'NewPred' block. The values that will be flowing into the PHI nodes |
| 220 | /// will be the same as those coming in from ExistPred, an existing predecessor |
| 221 | /// of Succ. |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 222 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 223 | BasicBlock *ExistPred) { |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 224 | if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 225 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 226 | PHINode *PN; |
| 227 | for (BasicBlock::iterator I = Succ->begin(); |
| 228 | (PN = dyn_cast<PHINode>(I)); ++I) |
| 229 | PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 230 | } |
| 231 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 232 | /// Compute an abstract "cost" of speculating the given instruction, |
| 233 | /// which is assumed to be safe to speculate. TCC_Free means cheap, |
| 234 | /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 235 | /// expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 236 | static unsigned ComputeSpeculationCost(const User *I, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 237 | const TargetTransformInfo &TTI) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 238 | assert(isSafeToSpeculativelyExecute(I) && |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 239 | "Instruction is not safe to speculatively execute!"); |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 240 | return TTI.getUserCost(I); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 241 | } |
Sanjay Patel | f9b7763 | 2015-09-15 15:24:42 +0000 | [diff] [blame] | 242 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 243 | /// If we have a merge point of an "if condition" as accepted above, |
| 244 | /// return true if the specified value dominates the block. We |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 245 | /// don't handle the true generality of domination here, just a special case |
| 246 | /// which works well enough for us. |
| 247 | /// |
| 248 | /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 249 | /// see if V (which must be an instruction) and its recursive operands |
| 250 | /// that do not dominate BB have a combined cost lower than CostRemaining and |
| 251 | /// are non-trapping. If both are true, the instruction is inserted into the |
| 252 | /// set and true is returned. |
| 253 | /// |
| 254 | /// The cost for most non-trapping instructions is defined as 1 except for |
| 255 | /// Select whose cost is 2. |
| 256 | /// |
| 257 | /// After this function returns, CostRemaining is decreased by the cost of |
| 258 | /// V plus its non-dominating operands. If that cost is greater than |
| 259 | /// CostRemaining, false is returned and CostRemaining is undefined. |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 260 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 261 | SmallPtrSetImpl<Instruction*> *AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 262 | unsigned &CostRemaining, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 263 | const TargetTransformInfo &TTI) { |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 264 | Instruction *I = dyn_cast<Instruction>(V); |
Chris Lattner | b8b1159 | 2006-10-20 00:42:07 +0000 | [diff] [blame] | 265 | if (!I) { |
| 266 | // Non-instructions all dominate instructions, but not all constantexprs |
| 267 | // can be executed unconditionally. |
| 268 | if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| 269 | if (C->canTrap()) |
| 270 | return false; |
| 271 | return true; |
| 272 | } |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 273 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 274 | |
Chris Lattner | 0ce80cd | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 275 | // We don't want to allow weird loops that might have the "if condition" in |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 276 | // the bottom of this block. |
| 277 | if (PBB == BB) return false; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 278 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 279 | // If this instruction is defined in a block that contains an unconditional |
| 280 | // branch to BB, then it must be in the 'conditional' part of the "if |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 281 | // statement". If not, it definitely dominates the region. |
| 282 | BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 283 | if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 284 | return true; |
Eli Friedman | b8f6a4f | 2009-07-17 04:28:42 +0000 | [diff] [blame] | 285 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 286 | // If we aren't allowing aggressive promotion anymore, then don't consider |
| 287 | // instructions in the 'if region'. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 288 | if (!AggressiveInsts) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 289 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 290 | // If we have seen this instruction before, don't count it again. |
| 291 | if (AggressiveInsts->count(I)) return true; |
| 292 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 293 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 294 | // see if it's a cheap instruction to unconditionally compute, and if it |
| 295 | // only uses stuff defined outside of the condition. If so, hoist it out. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 296 | if (!isSafeToSpeculativelyExecute(I)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 297 | return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 298 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 299 | unsigned Cost = ComputeSpeculationCost(I, TTI); |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 300 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 301 | if (Cost > CostRemaining) |
| 302 | return false; |
| 303 | |
| 304 | CostRemaining -= Cost; |
| 305 | |
| 306 | // Okay, we can only really hoist these out if their operands do |
| 307 | // not take us over the cost threshold. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 308 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 309 | if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 310 | return false; |
| 311 | // Okay, it's safe to do this! Remember this instruction. |
| 312 | AggressiveInsts->insert(I); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 313 | return true; |
| 314 | } |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 315 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 316 | /// Extract ConstantInt from value, looking through IntToPtr |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 317 | /// and PointerNullValue. Return NULL if value is not a constant int. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 318 | static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 319 | // Normal constant int. |
| 320 | ConstantInt *CI = dyn_cast<ConstantInt>(V); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 321 | if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 322 | return CI; |
| 323 | |
| 324 | // This is some kind of pointer constant. Turn it into a pointer-sized |
| 325 | // ConstantInt if possible. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 326 | IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 327 | |
| 328 | // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). |
| 329 | if (isa<ConstantPointerNull>(V)) |
| 330 | return ConstantInt::get(PtrTy, 0); |
| 331 | |
| 332 | // IntToPtr const int. |
| 333 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 334 | if (CE->getOpcode() == Instruction::IntToPtr) |
| 335 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { |
| 336 | // The constant is very likely to have the right type already. |
| 337 | if (CI->getType() == PtrTy) |
| 338 | return CI; |
| 339 | else |
| 340 | return cast<ConstantInt> |
| 341 | (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); |
| 342 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 343 | return nullptr; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 344 | } |
| 345 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 346 | namespace { |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 347 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 348 | /// Given a chain of or (||) or and (&&) comparison of a value against a |
| 349 | /// constant, this will try to recover the information required for a switch |
| 350 | /// structure. |
| 351 | /// It will depth-first traverse the chain of comparison, seeking for patterns |
| 352 | /// like %a == 12 or %a < 4 and combine them to produce a set of integer |
| 353 | /// representing the different cases for the switch. |
| 354 | /// Note that if the chain is composed of '||' it will build the set of elements |
| 355 | /// that matches the comparisons (i.e. any of this value validate the chain) |
| 356 | /// while for a chain of '&&' it will build the set elements that make the test |
| 357 | /// fail. |
| 358 | struct ConstantComparesGatherer { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 359 | const DataLayout &DL; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 360 | Value *CompValue; /// Value found for the switch comparison |
| 361 | Value *Extra; /// Extra clause to be checked before the switch |
| 362 | SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch |
| 363 | unsigned UsedICmps; /// Number of comparisons matched in the and/or chain |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 364 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 365 | /// Construct and compute the result for the comparison instruction Cond |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 366 | ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) |
| 367 | : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) { |
| 368 | gather(Cond); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 369 | } |
| 370 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 371 | /// Prevent copy |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 372 | ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 373 | ConstantComparesGatherer & |
Aaron Ballman | f9a1897 | 2015-02-15 22:54:22 +0000 | [diff] [blame] | 374 | operator=(const ConstantComparesGatherer &) = delete; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 375 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 376 | private: |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 377 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 378 | /// Try to set the current value used for the comparison, it succeeds only if |
| 379 | /// it wasn't set before or if the new value is the same as the old one |
| 380 | bool setValueOnce(Value *NewVal) { |
| 381 | if(CompValue && CompValue != NewVal) return false; |
| 382 | CompValue = NewVal; |
| 383 | return (CompValue != nullptr); |
| 384 | } |
| 385 | |
| 386 | /// Try to match Instruction "I" as a comparison against a constant and |
| 387 | /// populates the array Vals with the set of values that match (or do not |
| 388 | /// match depending on isEQ). |
| 389 | /// Return false on failure. On success, the Value the comparison matched |
| 390 | /// against is placed in CompValue. |
| 391 | /// If CompValue is already set, the function is expected to fail if a match |
| 392 | /// is found but the value compared to is different. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 393 | bool matchInstruction(Instruction *I, bool isEQ) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 394 | // If this is an icmp against a constant, handle this as one of the cases. |
| 395 | ICmpInst *ICI; |
| 396 | ConstantInt *C; |
| 397 | if (!((ICI = dyn_cast<ICmpInst>(I)) && |
| 398 | (C = GetConstantInt(I->getOperand(1), DL)))) { |
| 399 | return false; |
| 400 | } |
| 401 | |
| 402 | Value *RHSVal; |
| 403 | ConstantInt *RHSC; |
| 404 | |
| 405 | // Pattern match a special case |
| 406 | // (x & ~2^x) == y --> x == y || x == y|2^x |
| 407 | // This undoes a transformation done by instcombine to fuse 2 compares. |
| 408 | if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) { |
| 409 | if (match(ICI->getOperand(0), |
| 410 | m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 411 | APInt Not = ~RHSC->getValue(); |
| 412 | if (Not.isPowerOf2()) { |
| 413 | // If we already have a value for the switch, it has to match! |
| 414 | if(!setValueOnce(RHSVal)) |
| 415 | return false; |
| 416 | |
| 417 | Vals.push_back(C); |
| 418 | Vals.push_back(ConstantInt::get(C->getContext(), |
| 419 | C->getValue() | Not)); |
| 420 | UsedICmps++; |
| 421 | return true; |
| 422 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 423 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 424 | |
| 425 | // If we already have a value for the switch, it has to match! |
| 426 | if(!setValueOnce(ICI->getOperand(0))) |
| 427 | return false; |
| 428 | |
| 429 | UsedICmps++; |
| 430 | Vals.push_back(C); |
| 431 | return ICI->getOperand(0); |
| 432 | } |
| 433 | |
| 434 | // If we have "x ult 3", for example, then we can add 0,1,2 to the set. |
Sanjoy Das | 7182d36 | 2015-03-18 00:41:24 +0000 | [diff] [blame] | 435 | ConstantRange Span = ConstantRange::makeAllowedICmpRegion( |
| 436 | ICI->getPredicate(), C->getValue()); |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 437 | |
| 438 | // Shift the range if the compare is fed by an add. This is the range |
| 439 | // compare idiom as emitted by instcombine. |
| 440 | Value *CandidateVal = I->getOperand(0); |
| 441 | if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 442 | Span = Span.subtract(RHSC->getValue()); |
| 443 | CandidateVal = RHSVal; |
| 444 | } |
| 445 | |
| 446 | // If this is an and/!= check, then we are looking to build the set of |
| 447 | // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into |
| 448 | // x != 0 && x != 1. |
| 449 | if (!isEQ) |
| 450 | Span = Span.inverse(); |
| 451 | |
| 452 | // If there are a ton of values, we don't want to make a ginormous switch. |
| 453 | if (Span.getSetSize().ugt(8) || Span.isEmptySet()) { |
| 454 | return false; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 455 | } |
| 456 | |
| 457 | // If we already have a value for the switch, it has to match! |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 458 | if(!setValueOnce(CandidateVal)) |
| 459 | return false; |
| 460 | |
| 461 | // Add all values from the range to the set |
| 462 | for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) |
| 463 | Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 464 | |
| 465 | UsedICmps++; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 466 | return true; |
| 467 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 468 | } |
| 469 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 470 | /// Given a potentially 'or'd or 'and'd together collection of icmp |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 471 | /// eq/ne/lt/gt instructions that compare a value against a constant, extract |
| 472 | /// the value being compared, and stick the list constants into the Vals |
| 473 | /// vector. |
| 474 | /// One "Extra" case is allowed to differ from the other. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 475 | void gather(Value *V) { |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 476 | Instruction *I = dyn_cast<Instruction>(V); |
| 477 | bool isEQ = (I->getOpcode() == Instruction::Or); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 478 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 479 | // Keep a stack (SmallVector for efficiency) for depth-first traversal |
| 480 | SmallVector<Value *, 8> DFT; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 481 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 482 | // Initialize |
| 483 | DFT.push_back(V); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 484 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 485 | while(!DFT.empty()) { |
| 486 | V = DFT.pop_back_val(); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 487 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 488 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 489 | // If it is a || (or && depending on isEQ), process the operands. |
| 490 | if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { |
| 491 | DFT.push_back(I->getOperand(1)); |
| 492 | DFT.push_back(I->getOperand(0)); |
| 493 | continue; |
| 494 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 495 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 496 | // Try to match the current instruction |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 497 | if (matchInstruction(I, isEQ)) |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 498 | // Match succeed, continue the loop |
| 499 | continue; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 500 | } |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 501 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 502 | // One element of the sequence of || (or &&) could not be match as a |
| 503 | // comparison against the same value as the others. |
| 504 | // We allow only one "Extra" case to be checked before the switch |
| 505 | if (!Extra) { |
| 506 | Extra = V; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 507 | continue; |
| 508 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 509 | // Failed to parse a proper sequence, abort now |
| 510 | CompValue = nullptr; |
| 511 | break; |
Chris Lattner | 5a177e6 | 2010-12-13 04:26:26 +0000 | [diff] [blame] | 512 | } |
Anton Korobeynikov | 1bfd121 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 513 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 514 | }; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 515 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 516 | } |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 517 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 518 | static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 519 | Instruction *Cond = nullptr; |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 520 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 521 | Cond = dyn_cast<Instruction>(SI->getCondition()); |
| 522 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 523 | if (BI->isConditional()) |
| 524 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 525 | } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { |
| 526 | Cond = dyn_cast<Instruction>(IBI->getAddress()); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 527 | } |
| 528 | |
| 529 | TI->eraseFromParent(); |
| 530 | if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond); |
| 531 | } |
| 532 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 533 | /// Return true if the specified terminator checks |
Chris Lattner | 8e84c12 | 2008-11-27 23:25:44 +0000 | [diff] [blame] | 534 | /// to see if a value is equal to constant integer value. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 535 | Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 536 | Value *CV = nullptr; |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 537 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 538 | // Do not permit merging of large switch instructions into their |
| 539 | // predecessors unless there is only one predecessor. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 540 | if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()), |
| 541 | pred_end(SI->getParent())) <= 128) |
| 542 | CV = SI->getCondition(); |
| 543 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 544 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 545 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 546 | if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 547 | CV = ICI->getOperand(0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 548 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 549 | |
| 550 | // Unwrap any lossless ptrtoint cast. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 551 | if (CV) { |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 552 | if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { |
| 553 | Value *Ptr = PTII->getPointerOperand(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 554 | if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 555 | CV = Ptr; |
| 556 | } |
| 557 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 558 | return CV; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 559 | } |
| 560 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 561 | /// Given a value comparison instruction, |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 562 | /// decode all of the 'cases' that it represents and return the 'default' block. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 563 | BasicBlock *SimplifyCFGOpt:: |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 564 | GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 565 | std::vector<ValueEqualityComparisonCase> |
| 566 | &Cases) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 567 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 568 | Cases.reserve(SI->getNumCases()); |
| 569 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) |
| 570 | Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(), |
| 571 | i.getCaseSuccessor())); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 572 | return SI->getDefaultDest(); |
| 573 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 574 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 575 | BranchInst *BI = cast<BranchInst>(TI); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 576 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 577 | BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); |
| 578 | Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1), |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 579 | DL), |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 580 | Succ)); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 581 | return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 582 | } |
| 583 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 584 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 585 | /// Given a vector of bb/value pairs, remove any entries |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 586 | /// in the list that match the specified block. |
| 587 | static void EliminateBlockCases(BasicBlock *BB, |
| 588 | std::vector<ValueEqualityComparisonCase> &Cases) { |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 589 | Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 590 | } |
| 591 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 592 | /// Return true if there are any keys in C1 that exist in C2 as well. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 593 | static bool |
| 594 | ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, |
| 595 | std::vector<ValueEqualityComparisonCase > &C2) { |
| 596 | std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; |
| 597 | |
| 598 | // Make V1 be smaller than V2. |
| 599 | if (V1->size() > V2->size()) |
| 600 | std::swap(V1, V2); |
| 601 | |
| 602 | if (V1->size() == 0) return false; |
| 603 | if (V1->size() == 1) { |
| 604 | // Just scan V2. |
| 605 | ConstantInt *TheVal = (*V1)[0].Value; |
| 606 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 607 | if (TheVal == (*V2)[i].Value) |
| 608 | return true; |
| 609 | } |
| 610 | |
| 611 | // Otherwise, just sort both lists and compare element by element. |
| 612 | array_pod_sort(V1->begin(), V1->end()); |
| 613 | array_pod_sort(V2->begin(), V2->end()); |
| 614 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 615 | while (i1 != e1 && i2 != e2) { |
| 616 | if ((*V1)[i1].Value == (*V2)[i2].Value) |
| 617 | return true; |
| 618 | if ((*V1)[i1].Value < (*V2)[i2].Value) |
| 619 | ++i1; |
| 620 | else |
| 621 | ++i2; |
| 622 | } |
| 623 | return false; |
| 624 | } |
| 625 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 626 | /// If TI is known to be a terminator instruction and its block is known to |
| 627 | /// only have a single predecessor block, check to see if that predecessor is |
| 628 | /// also a value comparison with the same value, and if that comparison |
| 629 | /// determines the outcome of this comparison. If so, simplify TI. This does a |
| 630 | /// very limited form of jump threading. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 631 | bool SimplifyCFGOpt:: |
| 632 | SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 633 | BasicBlock *Pred, |
| 634 | IRBuilder<> &Builder) { |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 635 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| 636 | if (!PredVal) return false; // Not a value comparison in predecessor. |
| 637 | |
| 638 | Value *ThisVal = isValueEqualityComparison(TI); |
| 639 | assert(ThisVal && "This isn't a value comparison!!"); |
| 640 | if (ThisVal != PredVal) return false; // Different predicates. |
| 641 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 642 | // TODO: Preserve branch weight metadata, similarly to how |
| 643 | // FoldValueComparisonIntoPredecessors preserves it. |
| 644 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 645 | // Find out information about when control will move from Pred to TI's block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 646 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 647 | BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), |
| 648 | PredCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 649 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 650 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 651 | // Find information about how control leaves this block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 652 | std::vector<ValueEqualityComparisonCase> ThisCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 653 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 654 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 655 | |
| 656 | // If TI's block is the default block from Pred's comparison, potentially |
| 657 | // simplify TI based on this knowledge. |
| 658 | if (PredDef == TI->getParent()) { |
| 659 | // If we are here, we know that the value is none of those cases listed in |
| 660 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 661 | // can simplify TI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 662 | if (!ValuesOverlap(PredCases, ThisCases)) |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 663 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 664 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 665 | if (isa<BranchInst>(TI)) { |
| 666 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 667 | // uncond br. |
| 668 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 669 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 670 | Instruction *NI = Builder.CreateBr(ThisDef); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 671 | (void) NI; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 672 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 673 | // Remove PHI node entries for the dead edge. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 674 | ThisCases[0].Dest->removePredecessor(TI->getParent()); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 675 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 676 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 677 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 678 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 679 | EraseTerminatorInstAndDCECond(TI); |
| 680 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 681 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 682 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 683 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 684 | // Okay, TI has cases that are statically dead, prune them away. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 685 | SmallPtrSet<Constant*, 16> DeadCases; |
| 686 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 687 | DeadCases.insert(PredCases[i].Value); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 688 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 689 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 690 | << "Through successor TI: " << *TI); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 691 | |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 692 | // Collect branch weights into a vector. |
| 693 | SmallVector<uint32_t, 8> Weights; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 694 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 695 | bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); |
| 696 | if (HasWeight) |
| 697 | for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| 698 | ++MD_i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 699 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 700 | Weights.push_back(CI->getValue().getZExtValue()); |
| 701 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 702 | for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { |
| 703 | --i; |
| 704 | if (DeadCases.count(i.getCaseValue())) { |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 705 | if (HasWeight) { |
| 706 | std::swap(Weights[i.getCaseIndex()+1], Weights.back()); |
| 707 | Weights.pop_back(); |
| 708 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 709 | i.getCaseSuccessor()->removePredecessor(TI->getParent()); |
| 710 | SI->removeCase(i); |
| 711 | } |
| 712 | } |
Manman Ren | 97c1876 | 2012-10-11 22:28:34 +0000 | [diff] [blame] | 713 | if (HasWeight && Weights.size() >= 2) |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 714 | SI->setMetadata(LLVMContext::MD_prof, |
| 715 | MDBuilder(SI->getParent()->getContext()). |
| 716 | createBranchWeights(Weights)); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 717 | |
| 718 | DEBUG(dbgs() << "Leaving: " << *TI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 719 | return true; |
| 720 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 721 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 722 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 723 | // which value (or set of values) this is. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 724 | ConstantInt *TIV = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 725 | BasicBlock *TIBB = TI->getParent(); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 726 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 727 | if (PredCases[i].Dest == TIBB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 728 | if (TIV) |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 729 | return false; // Cannot handle multiple values coming to this block. |
| 730 | TIV = PredCases[i].Value; |
| 731 | } |
| 732 | assert(TIV && "No edge from pred to succ?"); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 733 | |
| 734 | // Okay, we found the one constant that our value can be if we get into TI's |
| 735 | // BB. Find out which successor will unconditionally be branched to. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 736 | BasicBlock *TheRealDest = nullptr; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 737 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 738 | if (ThisCases[i].Value == TIV) { |
| 739 | TheRealDest = ThisCases[i].Dest; |
| 740 | break; |
| 741 | } |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 742 | |
| 743 | // If not handled by any explicit cases, it is handled by the default case. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 744 | if (!TheRealDest) TheRealDest = ThisDef; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 745 | |
| 746 | // Remove PHI node entries for dead edges. |
| 747 | BasicBlock *CheckEdge = TheRealDest; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 748 | for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) |
| 749 | if (*SI != CheckEdge) |
| 750 | (*SI)->removePredecessor(TIBB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 751 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 752 | CheckEdge = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 753 | |
| 754 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 755 | Instruction *NI = Builder.CreateBr(TheRealDest); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 756 | (void) NI; |
| 757 | |
| 758 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 759 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
| 760 | |
| 761 | EraseTerminatorInstAndDCECond(TI); |
| 762 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 763 | } |
| 764 | |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 765 | namespace { |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 766 | /// This class implements a stable ordering of constant |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 767 | /// integers that does not depend on their address. This is important for |
| 768 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 769 | struct ConstantIntOrdering { |
| 770 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| 771 | return LHS->getValue().ult(RHS->getValue()); |
| 772 | } |
| 773 | }; |
| 774 | } |
Dale Johannesen | 5a41b2d | 2009-03-12 01:00:26 +0000 | [diff] [blame] | 775 | |
Benjamin Kramer | 8817cca | 2013-09-22 14:09:50 +0000 | [diff] [blame] | 776 | static int ConstantIntSortPredicate(ConstantInt *const *P1, |
| 777 | ConstantInt *const *P2) { |
| 778 | const ConstantInt *LHS = *P1; |
| 779 | const ConstantInt *RHS = *P2; |
Chris Lattner | e893e26 | 2010-12-15 04:52:41 +0000 | [diff] [blame] | 780 | if (LHS->getValue().ult(RHS->getValue())) |
| 781 | return 1; |
| 782 | if (LHS->getValue() == RHS->getValue()) |
| 783 | return 0; |
| 784 | return -1; |
Chris Lattner | 7c8e604 | 2010-12-13 02:00:58 +0000 | [diff] [blame] | 785 | } |
| 786 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 787 | static inline bool HasBranchWeights(const Instruction* I) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 788 | MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 789 | if (ProfMD && ProfMD->getOperand(0)) |
| 790 | if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) |
| 791 | return MDS->getString().equals("branch_weights"); |
| 792 | |
| 793 | return false; |
| 794 | } |
| 795 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 796 | /// Get Weights of a given TerminatorInst, the default weight is at the front |
| 797 | /// of the vector. If TI is a conditional eq, we need to swap the branch-weight |
| 798 | /// metadata. |
| 799 | static void GetBranchWeights(TerminatorInst *TI, |
| 800 | SmallVectorImpl<uint64_t> &Weights) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 801 | MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 802 | assert(MD); |
| 803 | for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 804 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 805 | Weights.push_back(CI->getValue().getZExtValue()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 806 | } |
| 807 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 808 | // If TI is a conditional eq, the default case is the false case, |
| 809 | // and the corresponding branch-weight data is at index 2. We swap the |
| 810 | // default weight to be the first entry. |
| 811 | if (BranchInst* BI = dyn_cast<BranchInst>(TI)) { |
| 812 | assert(Weights.size() == 2); |
| 813 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| 814 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 815 | std::swap(Weights.front(), Weights.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 816 | } |
| 817 | } |
| 818 | |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 819 | /// Keep halving the weights until all can fit in uint32_t. |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 820 | static void FitWeights(MutableArrayRef<uint64_t> Weights) { |
Benjamin Kramer | 79da941 | 2014-03-09 14:42:55 +0000 | [diff] [blame] | 821 | uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); |
| 822 | if (Max > UINT_MAX) { |
| 823 | unsigned Offset = 32 - countLeadingZeros(Max); |
| 824 | for (uint64_t &I : Weights) |
| 825 | I >>= Offset; |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 826 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 827 | } |
| 828 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 829 | /// The specified terminator is a value equality comparison instruction |
| 830 | /// (either a switch or a branch on "X == c"). |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 831 | /// See if any of the predecessors of the terminator block are value comparisons |
| 832 | /// on the same value. If so, and if safe to do so, fold them together. |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 833 | bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 834 | IRBuilder<> &Builder) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 835 | BasicBlock *BB = TI->getParent(); |
| 836 | Value *CV = isValueEqualityComparison(TI); // CondVal |
| 837 | assert(CV && "Not a comparison?"); |
| 838 | bool Changed = false; |
| 839 | |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 840 | SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 841 | while (!Preds.empty()) { |
Dan Gohman | 9a6fef0 | 2009-05-06 17:22:41 +0000 | [diff] [blame] | 842 | BasicBlock *Pred = Preds.pop_back_val(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 843 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 844 | // See if the predecessor is a comparison with the same value. |
| 845 | TerminatorInst *PTI = Pred->getTerminator(); |
| 846 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| 847 | |
| 848 | if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { |
| 849 | // Figure out which 'cases' to copy from SI to PSI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 850 | std::vector<ValueEqualityComparisonCase> BBCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 851 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 852 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 853 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 854 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 855 | |
| 856 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 857 | // PredCases and PredDefault with the new switch cases we would like to |
| 858 | // build. |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 859 | SmallVector<BasicBlock*, 8> NewSuccessors; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 860 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 861 | // Update the branch weight metadata along the way |
| 862 | SmallVector<uint64_t, 8> Weights; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 863 | bool PredHasWeights = HasBranchWeights(PTI); |
| 864 | bool SuccHasWeights = HasBranchWeights(TI); |
| 865 | |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 866 | if (PredHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 867 | GetBranchWeights(PTI, Weights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 868 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 869 | if (Weights.size() != 1 + PredCases.size()) |
| 870 | PredHasWeights = SuccHasWeights = false; |
| 871 | } else if (SuccHasWeights) |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 872 | // If there are no predecessor weights but there are successor weights, |
| 873 | // populate Weights with 1, which will later be scaled to the sum of |
| 874 | // successor's weights |
| 875 | Weights.assign(1 + PredCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 876 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 877 | SmallVector<uint64_t, 8> SuccWeights; |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 878 | if (SuccHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 879 | GetBranchWeights(TI, SuccWeights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 880 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 881 | if (SuccWeights.size() != 1 + BBCases.size()) |
| 882 | PredHasWeights = SuccHasWeights = false; |
| 883 | } else if (PredHasWeights) |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 884 | SuccWeights.assign(1 + BBCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 885 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 886 | if (PredDefault == BB) { |
| 887 | // If this is the default destination from PTI, only the edges in TI |
| 888 | // that don't occur in PTI, or that branch to BB will be activated. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 889 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
| 890 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 891 | if (PredCases[i].Dest != BB) |
| 892 | PTIHandled.insert(PredCases[i].Value); |
| 893 | else { |
| 894 | // The default destination is BB, we don't need explicit targets. |
| 895 | std::swap(PredCases[i], PredCases.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 896 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 897 | if (PredHasWeights || SuccHasWeights) { |
| 898 | // Increase weight for the default case. |
| 899 | Weights[0] += Weights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 900 | std::swap(Weights[i+1], Weights.back()); |
| 901 | Weights.pop_back(); |
| 902 | } |
| 903 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 904 | PredCases.pop_back(); |
| 905 | --i; --e; |
| 906 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 907 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 908 | // Reconstruct the new switch statement we will be building. |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 909 | if (PredDefault != BBDefault) { |
| 910 | PredDefault->removePredecessor(Pred); |
| 911 | PredDefault = BBDefault; |
| 912 | NewSuccessors.push_back(BBDefault); |
| 913 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 914 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 915 | unsigned CasesFromPred = Weights.size(); |
| 916 | uint64_t ValidTotalSuccWeight = 0; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 917 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 918 | if (!PTIHandled.count(BBCases[i].Value) && |
| 919 | BBCases[i].Dest != BBDefault) { |
| 920 | PredCases.push_back(BBCases[i]); |
| 921 | NewSuccessors.push_back(BBCases[i].Dest); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 922 | if (SuccHasWeights || PredHasWeights) { |
| 923 | // The default weight is at index 0, so weight for the ith case |
| 924 | // should be at index i+1. Scale the cases from successor by |
| 925 | // PredDefaultWeight (Weights[0]). |
| 926 | Weights.push_back(Weights[0] * SuccWeights[i+1]); |
| 927 | ValidTotalSuccWeight += SuccWeights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 928 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 929 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 930 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 931 | if (SuccHasWeights || PredHasWeights) { |
| 932 | ValidTotalSuccWeight += SuccWeights[0]; |
| 933 | // Scale the cases from predecessor by ValidTotalSuccWeight. |
| 934 | for (unsigned i = 1; i < CasesFromPred; ++i) |
| 935 | Weights[i] *= ValidTotalSuccWeight; |
| 936 | // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). |
| 937 | Weights[0] *= SuccWeights[0]; |
| 938 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 939 | } else { |
| 940 | // If this is not the default destination from PSI, only the edges |
| 941 | // in SI that occur in PSI with a destination of BB will be |
| 942 | // activated. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 943 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 944 | std::map<ConstantInt*, uint64_t> WeightsForHandled; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 945 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 946 | if (PredCases[i].Dest == BB) { |
| 947 | PTIHandled.insert(PredCases[i].Value); |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 948 | |
| 949 | if (PredHasWeights || SuccHasWeights) { |
| 950 | WeightsForHandled[PredCases[i].Value] = Weights[i+1]; |
| 951 | std::swap(Weights[i+1], Weights.back()); |
| 952 | Weights.pop_back(); |
| 953 | } |
| 954 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 955 | std::swap(PredCases[i], PredCases.back()); |
| 956 | PredCases.pop_back(); |
| 957 | --i; --e; |
| 958 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 959 | |
| 960 | // Okay, now we know which constants were sent to BB from the |
| 961 | // predecessor. Figure out where they will all go now. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 962 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 963 | if (PTIHandled.count(BBCases[i].Value)) { |
| 964 | // If this is one we are capable of getting... |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 965 | if (PredHasWeights || SuccHasWeights) |
| 966 | Weights.push_back(WeightsForHandled[BBCases[i].Value]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 967 | PredCases.push_back(BBCases[i]); |
| 968 | NewSuccessors.push_back(BBCases[i].Dest); |
| 969 | PTIHandled.erase(BBCases[i].Value);// This constant is taken care of |
| 970 | } |
| 971 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 972 | // If there are any constants vectored to BB that TI doesn't handle, |
| 973 | // they must go to the default destination of TI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 974 | for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 975 | PTIHandled.begin(), |
| 976 | E = PTIHandled.end(); I != E; ++I) { |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 977 | if (PredHasWeights || SuccHasWeights) |
| 978 | Weights.push_back(WeightsForHandled[*I]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 979 | PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 980 | NewSuccessors.push_back(BBDefault); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 981 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 982 | } |
| 983 | |
| 984 | // Okay, at this point, we know which new successor Pred will get. Make |
| 985 | // sure we update the number of entries in the PHI nodes for these |
| 986 | // successors. |
Sanjay Patel | f4b34b7 | 2015-09-10 16:25:38 +0000 | [diff] [blame] | 987 | for (BasicBlock *NewSuccessor : NewSuccessors) |
| 988 | AddPredecessorToBlock(NewSuccessor, Pred, BB); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 989 | |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 990 | Builder.SetInsertPoint(PTI); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 991 | // Convert pointer to int before we switch. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 992 | if (CV->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 993 | CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 994 | "magicptr"); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 995 | } |
| 996 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 997 | // Now that the successors are updated, create the new Switch instruction. |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 998 | SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, |
| 999 | PredCases.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 1000 | NewSI->setDebugLoc(PTI->getDebugLoc()); |
Sanjay Patel | 5e7bd91 | 2015-09-10 16:15:21 +0000 | [diff] [blame] | 1001 | for (ValueEqualityComparisonCase &V : PredCases) |
| 1002 | NewSI->addCase(V.Value, V.Dest); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1003 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1004 | if (PredHasWeights || SuccHasWeights) { |
| 1005 | // Halve the weights if any of them cannot fit in an uint32_t |
| 1006 | FitWeights(Weights); |
| 1007 | |
| 1008 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 1009 | |
| 1010 | NewSI->setMetadata(LLVMContext::MD_prof, |
| 1011 | MDBuilder(BB->getContext()). |
| 1012 | createBranchWeights(MDWeights)); |
| 1013 | } |
| 1014 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1015 | EraseTerminatorInstAndDCECond(PTI); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1016 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1017 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 1018 | // have an infinite loop case. If so, add an infinitely looping block |
| 1019 | // to handle the case to preserve the behavior of the code. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1020 | BasicBlock *InfLoopBlock = nullptr; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1021 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 1022 | if (NewSI->getSuccessor(i) == BB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1023 | if (!InfLoopBlock) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 1024 | // Insert it at the end of the function, because it's either code, |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1025 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1026 | InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 1027 | "infloop", BB->getParent()); |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1028 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1029 | } |
| 1030 | NewSI->setSuccessor(i, InfLoopBlock); |
| 1031 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1032 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1033 | Changed = true; |
| 1034 | } |
| 1035 | } |
| 1036 | return Changed; |
| 1037 | } |
| 1038 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1039 | // If we would need to insert a select that uses the value of this invoke |
| 1040 | // (comments in HoistThenElseCodeToIf explain why we would need to do this), we |
| 1041 | // can't hoist the invoke, as there is nowhere to put the select in this case. |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1042 | static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, |
| 1043 | Instruction *I1, Instruction *I2) { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1044 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1045 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1046 | for (BasicBlock::iterator BBI = SI->begin(); |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1047 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1048 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1049 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1050 | if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) { |
| 1051 | return false; |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | return true; |
| 1056 | } |
| 1057 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1058 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); |
| 1059 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1060 | /// Given a conditional branch that goes to BB1 and BB2, hoist any common code |
| 1061 | /// in the two blocks up into the branch block. The caller of this function |
| 1062 | /// guarantees that BI's block dominates BB1 and BB2. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1063 | static bool HoistThenElseCodeToIf(BranchInst *BI, |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1064 | const TargetTransformInfo &TTI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1065 | // This does very trivial matching, with limited scanning, to find identical |
| 1066 | // instructions in the two blocks. In particular, we don't want to get into |
| 1067 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 1068 | // such, we currently just scan for obviously identical instructions in an |
| 1069 | // identical order. |
| 1070 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 1071 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| 1072 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1073 | BasicBlock::iterator BB1_Itr = BB1->begin(); |
| 1074 | BasicBlock::iterator BB2_Itr = BB2->begin(); |
| 1075 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1076 | Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1077 | // Skip debug info if it is not identical. |
| 1078 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1079 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1080 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1081 | while (isa<DbgInfoIntrinsic>(I1)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1082 | I1 = &*BB1_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1083 | while (isa<DbgInfoIntrinsic>(I2)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1084 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1085 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1086 | if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1087 | (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1088 | return false; |
| 1089 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1090 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1091 | |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1092 | bool Changed = false; |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1093 | do { |
| 1094 | // If we are hoisting the terminator instruction, don't move one (making a |
| 1095 | // broken BB), instead clone it, and remove BI. |
| 1096 | if (isa<TerminatorInst>(I1)) |
| 1097 | goto HoistTerminator; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1098 | |
Chad Rosier | 5439005 | 2015-02-23 19:15:16 +0000 | [diff] [blame] | 1099 | if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) |
| 1100 | return Changed; |
| 1101 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1102 | // For a normal instruction, we just move one to right before the branch, |
| 1103 | // then replace all uses of the other with the first. Finally, we remove |
| 1104 | // the now redundant second instruction. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1105 | BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1106 | if (!I2->use_empty()) |
| 1107 | I2->replaceAllUsesWith(I1); |
Dan Gohman | c8a27f2 | 2009-08-25 22:11:20 +0000 | [diff] [blame] | 1108 | I1->intersectOptionalDataWith(I2); |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1109 | unsigned KnownIDs[] = { |
Piotr Padlewski | dc9b2cf | 2015-10-02 22:12:22 +0000 | [diff] [blame] | 1110 | LLVMContext::MD_tbaa, LLVMContext::MD_range, |
| 1111 | LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load, |
Artur Pilipenko | 5c5011d | 2015-11-02 17:53:51 +0000 | [diff] [blame] | 1112 | LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group, |
| 1113 | LLVMContext::MD_align, LLVMContext::MD_dereferenceable, |
| 1114 | LLVMContext::MD_dereferenceable_or_null}; |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1115 | combineMetadata(I1, I2, KnownIDs); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1116 | I2->eraseFromParent(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1117 | Changed = true; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1118 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1119 | I1 = &*BB1_Itr++; |
| 1120 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1121 | // Skip debug info if it is not identical. |
| 1122 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1123 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1124 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1125 | while (isa<DbgInfoIntrinsic>(I1)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1126 | I1 = &*BB1_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1127 | while (isa<DbgInfoIntrinsic>(I2)) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1128 | I2 = &*BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1129 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1130 | } while (I1->isIdenticalToWhenDefined(I2)); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1131 | |
| 1132 | return true; |
| 1133 | |
| 1134 | HoistTerminator: |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1135 | // It may not be possible to hoist an invoke. |
| 1136 | if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1137 | return Changed; |
| 1138 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1139 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1140 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1141 | for (BasicBlock::iterator BBI = SI->begin(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1142 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1143 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1144 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1145 | if (BB1V == BB2V) |
| 1146 | continue; |
| 1147 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1148 | // Check for passingValueIsAlwaysUndefined here because we would rather |
| 1149 | // eliminate undefined control flow then converting it to a select. |
| 1150 | if (passingValueIsAlwaysUndefined(BB1V, PN) || |
| 1151 | passingValueIsAlwaysUndefined(BB2V, PN)) |
| 1152 | return Changed; |
| 1153 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1154 | if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1155 | return Changed; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1156 | if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1157 | return Changed; |
| 1158 | } |
| 1159 | } |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1160 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1161 | // Okay, it is safe to hoist the terminator. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 1162 | Instruction *NT = I1->clone(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1163 | BIParent->getInstList().insert(BI->getIterator(), NT); |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1164 | if (!NT->getType()->isVoidTy()) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1165 | I1->replaceAllUsesWith(NT); |
| 1166 | I2->replaceAllUsesWith(NT); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1167 | NT->takeName(I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1168 | } |
| 1169 | |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1170 | IRBuilder<true, NoFolder> Builder(NT); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1171 | // Hoisting one of the terminators from our successor is a great thing. |
| 1172 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 1173 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 1174 | // nodes, so we insert select instruction to compute the final result. |
| 1175 | std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1176 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1177 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1178 | for (BasicBlock::iterator BBI = SI->begin(); |
Chris Lattner | 0194457 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 1179 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1180 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1181 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1182 | if (BB1V == BB2V) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1183 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1184 | // These values do not agree. Insert a select instruction before NT |
| 1185 | // that determines the right value. |
| 1186 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1187 | if (!SI) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1188 | SI = cast<SelectInst> |
| 1189 | (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, |
| 1190 | BB1V->getName()+"."+BB2V->getName())); |
| 1191 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1192 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 1193 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 1194 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 1195 | PN->setIncomingValue(i, SI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1196 | } |
| 1197 | } |
| 1198 | |
| 1199 | // Update any PHI nodes in our new successors. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1200 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) |
| 1201 | AddPredecessorToBlock(*SI, BIParent, BB1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1202 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1203 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1204 | return true; |
| 1205 | } |
| 1206 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1207 | /// Given an unconditional branch that goes to BBEnd, |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1208 | /// check whether BBEnd has only two predecessors and the other predecessor |
| 1209 | /// ends with an unconditional branch. If it is true, sink any common code |
| 1210 | /// in the two predecessors to BBEnd. |
| 1211 | static bool SinkThenElseCodeToEnd(BranchInst *BI1) { |
| 1212 | assert(BI1->isUnconditional()); |
| 1213 | BasicBlock *BB1 = BI1->getParent(); |
| 1214 | BasicBlock *BBEnd = BI1->getSuccessor(0); |
| 1215 | |
| 1216 | // Check that BBEnd has two predecessors and the other predecessor ends with |
| 1217 | // an unconditional branch. |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1218 | pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd); |
| 1219 | BasicBlock *Pred0 = *PI++; |
| 1220 | if (PI == PE) // Only one predecessor. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1221 | return false; |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1222 | BasicBlock *Pred1 = *PI++; |
| 1223 | if (PI != PE) // More than two predecessors. |
| 1224 | return false; |
| 1225 | BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1226 | BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator()); |
| 1227 | if (!BI2 || !BI2->isUnconditional()) |
| 1228 | return false; |
| 1229 | |
| 1230 | // Gather the PHI nodes in BBEnd. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1231 | SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1232 | Instruction *FirstNonPhiInBBEnd = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1233 | for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) { |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1234 | if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 1235 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1236 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1237 | JointValueMap[std::make_pair(BB1V, BB2V)] = PN; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1238 | } else { |
| 1239 | FirstNonPhiInBBEnd = &*I; |
| 1240 | break; |
| 1241 | } |
| 1242 | } |
| 1243 | if (!FirstNonPhiInBBEnd) |
| 1244 | return false; |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1245 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1246 | // This does very trivial matching, with limited scanning, to find identical |
| 1247 | // instructions in the two blocks. We scan backward for obviously identical |
| 1248 | // instructions in an identical order. |
| 1249 | BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(), |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1250 | RE1 = BB1->getInstList().rend(), |
| 1251 | RI2 = BB2->getInstList().rbegin(), |
| 1252 | RE2 = BB2->getInstList().rend(); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1253 | // Skip debug info. |
| 1254 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1255 | if (RI1 == RE1) |
| 1256 | return false; |
| 1257 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1258 | if (RI2 == RE2) |
| 1259 | return false; |
| 1260 | // Skip the unconditional branches. |
| 1261 | ++RI1; |
| 1262 | ++RI2; |
| 1263 | |
| 1264 | bool Changed = false; |
| 1265 | while (RI1 != RE1 && RI2 != RE2) { |
| 1266 | // Skip debug info. |
| 1267 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1268 | if (RI1 == RE1) |
| 1269 | return Changed; |
| 1270 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1271 | if (RI2 == RE2) |
| 1272 | return Changed; |
| 1273 | |
| 1274 | Instruction *I1 = &*RI1, *I2 = &*RI2; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1275 | auto InstPair = std::make_pair(I1, I2); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1276 | // I1 and I2 should have a single use in the same PHI node, and they |
| 1277 | // perform the same operation. |
| 1278 | // Cannot move control-flow-involving, volatile loads, vaarg, etc. |
| 1279 | if (isa<PHINode>(I1) || isa<PHINode>(I2) || |
| 1280 | isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) || |
David Majnemer | ba275f9 | 2015-08-19 19:54:02 +0000 | [diff] [blame] | 1281 | I1->isEHPad() || I2->isEHPad() || |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1282 | isa<AllocaInst>(I1) || isa<AllocaInst>(I2) || |
| 1283 | I1->mayHaveSideEffects() || I2->mayHaveSideEffects() || |
| 1284 | I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() || |
| 1285 | !I1->hasOneUse() || !I2->hasOneUse() || |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1286 | !JointValueMap.count(InstPair)) |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1287 | return Changed; |
| 1288 | |
| 1289 | // Check whether we should swap the operands of ICmpInst. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1290 | // TODO: Add support of communativity. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1291 | ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2); |
| 1292 | bool SwapOpnds = false; |
| 1293 | if (ICmp1 && ICmp2 && |
| 1294 | ICmp1->getOperand(0) != ICmp2->getOperand(0) && |
| 1295 | ICmp1->getOperand(1) != ICmp2->getOperand(1) && |
| 1296 | (ICmp1->getOperand(0) == ICmp2->getOperand(1) || |
| 1297 | ICmp1->getOperand(1) == ICmp2->getOperand(0))) { |
| 1298 | ICmp2->swapOperands(); |
| 1299 | SwapOpnds = true; |
| 1300 | } |
| 1301 | if (!I1->isSameOperationAs(I2)) { |
| 1302 | if (SwapOpnds) |
| 1303 | ICmp2->swapOperands(); |
| 1304 | return Changed; |
| 1305 | } |
| 1306 | |
| 1307 | // The operands should be either the same or they need to be generated |
| 1308 | // with a PHI node after sinking. We only handle the case where there is |
| 1309 | // a single pair of different operands. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1310 | Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1311 | unsigned Op1Idx = ~0U; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1312 | for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) { |
| 1313 | if (I1->getOperand(I) == I2->getOperand(I)) |
| 1314 | continue; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1315 | // Early exit if we have more-than one pair of different operands or if |
| 1316 | // we need a PHI node to replace a constant. |
| 1317 | if (Op1Idx != ~0U || |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1318 | isa<Constant>(I1->getOperand(I)) || |
| 1319 | isa<Constant>(I2->getOperand(I))) { |
| 1320 | // If we can't sink the instructions, undo the swapping. |
| 1321 | if (SwapOpnds) |
| 1322 | ICmp2->swapOperands(); |
| 1323 | return Changed; |
| 1324 | } |
| 1325 | DifferentOp1 = I1->getOperand(I); |
| 1326 | Op1Idx = I; |
| 1327 | DifferentOp2 = I2->getOperand(I); |
| 1328 | } |
| 1329 | |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1330 | DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n"); |
| 1331 | DEBUG(dbgs() << " " << *I2 << "\n"); |
| 1332 | |
| 1333 | // We insert the pair of different operands to JointValueMap and |
| 1334 | // remove (I1, I2) from JointValueMap. |
| 1335 | if (Op1Idx != ~0U) { |
| 1336 | auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)]; |
| 1337 | if (!NewPN) { |
| 1338 | NewPN = |
| 1339 | PHINode::Create(DifferentOp1->getType(), 2, |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1340 | DifferentOp1->getName() + ".sink", &BBEnd->front()); |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1341 | NewPN->addIncoming(DifferentOp1, BB1); |
| 1342 | NewPN->addIncoming(DifferentOp2, BB2); |
| 1343 | DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";); |
| 1344 | } |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1345 | // I1 should use NewPN instead of DifferentOp1. |
| 1346 | I1->setOperand(Op1Idx, NewPN); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1347 | } |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1348 | PHINode *OldPN = JointValueMap[InstPair]; |
| 1349 | JointValueMap.erase(InstPair); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1350 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1351 | // We need to update RE1 and RE2 if we are going to sink the first |
| 1352 | // instruction in the basic block down. |
| 1353 | bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin()); |
| 1354 | // Sink the instruction. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1355 | BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(), |
| 1356 | BB1->getInstList(), I1); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1357 | if (!OldPN->use_empty()) |
| 1358 | OldPN->replaceAllUsesWith(I1); |
| 1359 | OldPN->eraseFromParent(); |
| 1360 | |
| 1361 | if (!I2->use_empty()) |
| 1362 | I2->replaceAllUsesWith(I1); |
| 1363 | I1->intersectOptionalDataWith(I2); |
Philip Reames | d92c2a7 | 2014-10-22 16:37:13 +0000 | [diff] [blame] | 1364 | // TODO: Use combineMetadata here to preserve what metadata we can |
| 1365 | // (analogous to the hoisting case above). |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1366 | I2->eraseFromParent(); |
| 1367 | |
| 1368 | if (UpdateRE1) |
| 1369 | RE1 = BB1->getInstList().rend(); |
| 1370 | if (UpdateRE2) |
| 1371 | RE2 = BB2->getInstList().rend(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1372 | FirstNonPhiInBBEnd = &*I1; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1373 | NumSinkCommons++; |
| 1374 | Changed = true; |
| 1375 | } |
| 1376 | return Changed; |
| 1377 | } |
| 1378 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1379 | /// \brief Determine if we can hoist sink a sole store instruction out of a |
| 1380 | /// conditional block. |
| 1381 | /// |
| 1382 | /// We are looking for code like the following: |
| 1383 | /// BrBB: |
| 1384 | /// store i32 %add, i32* %arrayidx2 |
| 1385 | /// ... // No other stores or function calls (we could be calling a memory |
| 1386 | /// ... // function). |
| 1387 | /// %cmp = icmp ult %x, %y |
| 1388 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1389 | /// ThenBB: |
| 1390 | /// store i32 %add5, i32* %arrayidx2 |
| 1391 | /// br label EndBB |
| 1392 | /// EndBB: |
| 1393 | /// ... |
| 1394 | /// We are going to transform this into: |
| 1395 | /// BrBB: |
| 1396 | /// store i32 %add, i32* %arrayidx2 |
| 1397 | /// ... // |
| 1398 | /// %cmp = icmp ult %x, %y |
| 1399 | /// %add.add5 = select i1 %cmp, i32 %add, %add5 |
| 1400 | /// store i32 %add.add5, i32* %arrayidx2 |
| 1401 | /// ... |
| 1402 | /// |
| 1403 | /// \return The pointer to the value of the previous store if the store can be |
| 1404 | /// hoisted into the predecessor block. 0 otherwise. |
Benjamin Kramer | ad5c24f | 2013-05-23 16:09:15 +0000 | [diff] [blame] | 1405 | static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, |
| 1406 | BasicBlock *StoreBB, BasicBlock *EndBB) { |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1407 | StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); |
| 1408 | if (!StoreToHoist) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1409 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1410 | |
| 1411 | // Volatile or atomic. |
| 1412 | if (!StoreToHoist->isSimple()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1413 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1414 | |
| 1415 | Value *StorePtr = StoreToHoist->getPointerOperand(); |
| 1416 | |
| 1417 | // Look for a store to the same pointer in BrBB. |
| 1418 | unsigned MaxNumInstToLookAt = 10; |
| 1419 | for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), |
| 1420 | RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) { |
| 1421 | Instruction *CurI = &*RI; |
| 1422 | |
| 1423 | // Could be calling an instruction that effects memory like free(). |
| 1424 | if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1425 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1426 | |
| 1427 | StoreInst *SI = dyn_cast<StoreInst>(CurI); |
| 1428 | // Found the previous store make sure it stores to the same location. |
| 1429 | if (SI && SI->getPointerOperand() == StorePtr) |
| 1430 | // Found the previous store, return its value operand. |
| 1431 | return SI->getValueOperand(); |
| 1432 | else if (SI) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1433 | return nullptr; // Unknown store. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1434 | } |
| 1435 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1436 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1437 | } |
| 1438 | |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1439 | /// \brief Speculate a conditional basic block flattening the CFG. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1440 | /// |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1441 | /// Note that this is a very risky transform currently. Speculating |
| 1442 | /// instructions like this is most often not desirable. Instead, there is an MI |
| 1443 | /// pass which can do it with full awareness of the resource constraints. |
| 1444 | /// However, some cases are "obvious" and we should do directly. An example of |
| 1445 | /// this is speculating a single, reasonably cheap instruction. |
| 1446 | /// |
| 1447 | /// There is only one distinct advantage to flattening the CFG at the IR level: |
| 1448 | /// it makes very common but simplistic optimizations such as are common in |
| 1449 | /// instcombine and the DAG combiner more powerful by removing CFG edges and |
| 1450 | /// modeling their effects with easier to reason about SSA value graphs. |
| 1451 | /// |
| 1452 | /// |
| 1453 | /// An illustration of this transform is turning this IR: |
| 1454 | /// \code |
| 1455 | /// BB: |
| 1456 | /// %cmp = icmp ult %x, %y |
| 1457 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1458 | /// ThenBB: |
| 1459 | /// %sub = sub %x, %y |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1460 | /// br label BB2 |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1461 | /// EndBB: |
| 1462 | /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] |
| 1463 | /// ... |
| 1464 | /// \endcode |
| 1465 | /// |
| 1466 | /// Into this IR: |
| 1467 | /// \code |
| 1468 | /// BB: |
| 1469 | /// %cmp = icmp ult %x, %y |
| 1470 | /// %sub = sub %x, %y |
| 1471 | /// %cond = select i1 %cmp, 0, %sub |
| 1472 | /// ... |
| 1473 | /// \endcode |
| 1474 | /// |
| 1475 | /// \returns true if the conditional block is removed. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1476 | static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1477 | const TargetTransformInfo &TTI) { |
Chandler Carruth | 1d20c02 | 2013-01-24 08:22:40 +0000 | [diff] [blame] | 1478 | // Be conservative for now. FP select instruction can often be expensive. |
| 1479 | Value *BrCond = BI->getCondition(); |
| 1480 | if (isa<FCmpInst>(BrCond)) |
| 1481 | return false; |
| 1482 | |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1483 | BasicBlock *BB = BI->getParent(); |
| 1484 | BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); |
| 1485 | |
| 1486 | // If ThenBB is actually on the false edge of the conditional branch, remember |
| 1487 | // to swap the select operands later. |
| 1488 | bool Invert = false; |
| 1489 | if (ThenBB != BI->getSuccessor(0)) { |
| 1490 | assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); |
| 1491 | Invert = true; |
| 1492 | } |
| 1493 | assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); |
| 1494 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1495 | // Keep a count of how many times instructions are used within CondBB when |
| 1496 | // they are candidates for sinking into CondBB. Specifically: |
| 1497 | // - They are defined in BB, and |
| 1498 | // - They have no side effects, and |
| 1499 | // - All of their uses are in CondBB. |
| 1500 | SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; |
| 1501 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1502 | unsigned SpeculationCost = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1503 | Value *SpeculatedStoreValue = nullptr; |
| 1504 | StoreInst *SpeculatedStore = nullptr; |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1505 | for (BasicBlock::iterator BBI = ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1506 | BBE = std::prev(ThenBB->end()); |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1507 | BBI != BBE; ++BBI) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1508 | Instruction *I = &*BBI; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1509 | // Skip debug info. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1510 | if (isa<DbgInfoIntrinsic>(I)) |
| 1511 | continue; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1512 | |
Mark Lacey | 274f48b | 2015-04-12 18:18:51 +0000 | [diff] [blame] | 1513 | // Only speculatively execute a single instruction (not counting the |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1514 | // terminator) for now. |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1515 | ++SpeculationCost; |
| 1516 | if (SpeculationCost > 1) |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1517 | return false; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1518 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1519 | // Don't hoist the instruction if it's unsafe or expensive. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1520 | if (!isSafeToSpeculativelyExecute(I) && |
| 1521 | !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( |
| 1522 | I, BB, ThenBB, EndBB)))) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1523 | return false; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1524 | if (!SpeculatedStoreValue && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1525 | ComputeSpeculationCost(I, TTI) > |
| 1526 | PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1527 | return false; |
| 1528 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1529 | // Store the store speculation candidate. |
| 1530 | if (SpeculatedStoreValue) |
| 1531 | SpeculatedStore = cast<StoreInst>(I); |
| 1532 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1533 | // Do not hoist the instruction if any of its operands are defined but not |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1534 | // used in BB. The transformation will prevent the operand from |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1535 | // being sunk into the use block. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1536 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1537 | i != e; ++i) { |
| 1538 | Instruction *OpI = dyn_cast<Instruction>(*i); |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1539 | if (!OpI || OpI->getParent() != BB || |
| 1540 | OpI->mayHaveSideEffects()) |
| 1541 | continue; // Not a candidate for sinking. |
| 1542 | |
| 1543 | ++SinkCandidateUseCounts[OpI]; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1544 | } |
| 1545 | } |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1546 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1547 | // Consider any sink candidates which are only used in CondBB as costs for |
| 1548 | // speculation. Note, while we iterate over a DenseMap here, we are summing |
| 1549 | // and so iteration order isn't significant. |
| 1550 | for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I = |
| 1551 | SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end(); |
| 1552 | I != E; ++I) |
| 1553 | if (I->first->getNumUses() == I->second) { |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1554 | ++SpeculationCost; |
| 1555 | if (SpeculationCost > 1) |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1556 | return false; |
| 1557 | } |
| 1558 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1559 | // Check that the PHI nodes can be converted to selects. |
| 1560 | bool HaveRewritablePHIs = false; |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1561 | for (BasicBlock::iterator I = EndBB->begin(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1562 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1563 | Value *OrigV = PN->getIncomingValueForBlock(BB); |
| 1564 | Value *ThenV = PN->getIncomingValueForBlock(ThenBB); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1565 | |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1566 | // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1567 | // Skip PHIs which are trivial. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1568 | if (ThenV == OrigV) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1569 | continue; |
| 1570 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1571 | // Don't convert to selects if we could remove undefined behavior instead. |
| 1572 | if (passingValueIsAlwaysUndefined(OrigV, PN) || |
| 1573 | passingValueIsAlwaysUndefined(ThenV, PN)) |
| 1574 | return false; |
| 1575 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1576 | HaveRewritablePHIs = true; |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1577 | ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); |
| 1578 | ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); |
| 1579 | if (!OrigCE && !ThenCE) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1580 | continue; // Known safe and cheap. |
| 1581 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1582 | if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || |
| 1583 | (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1584 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1585 | unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; |
| 1586 | unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1587 | unsigned MaxCost = 2 * PHINodeFoldingThreshold * |
| 1588 | TargetTransformInfo::TCC_Basic; |
| 1589 | if (OrigCost + ThenCost > MaxCost) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1590 | return false; |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1591 | |
Chandler Carruth | 01bffaa | 2013-01-24 12:05:17 +0000 | [diff] [blame] | 1592 | // Account for the cost of an unfolded ConstantExpr which could end up |
| 1593 | // getting expanded into Instructions. |
| 1594 | // FIXME: This doesn't account for how many operations are combined in the |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1595 | // constant expression. |
| 1596 | ++SpeculationCost; |
| 1597 | if (SpeculationCost > 1) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1598 | return false; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1599 | } |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1600 | |
| 1601 | // If there are no PHIs to process, bail early. This helps ensure idempotence |
| 1602 | // as well. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1603 | if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1604 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1605 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1606 | // If we get here, we can hoist the instruction and if-convert. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1607 | DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1608 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1609 | // Insert a select of the value of the speculated store. |
| 1610 | if (SpeculatedStoreValue) { |
| 1611 | IRBuilder<true, NoFolder> Builder(BI); |
| 1612 | Value *TrueV = SpeculatedStore->getValueOperand(); |
| 1613 | Value *FalseV = SpeculatedStoreValue; |
| 1614 | if (Invert) |
| 1615 | std::swap(TrueV, FalseV); |
| 1616 | Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() + |
| 1617 | "." + FalseV->getName()); |
| 1618 | SpeculatedStore->setOperand(0, S); |
| 1619 | } |
| 1620 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1621 | // Hoist the instructions. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1622 | BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), |
| 1623 | ThenBB->begin(), std::prev(ThenBB->end())); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1624 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1625 | // Insert selects and rewrite the PHI operands. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1626 | IRBuilder<true, NoFolder> Builder(BI); |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1627 | for (BasicBlock::iterator I = EndBB->begin(); |
| 1628 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
| 1629 | unsigned OrigI = PN->getBasicBlockIndex(BB); |
| 1630 | unsigned ThenI = PN->getBasicBlockIndex(ThenBB); |
| 1631 | Value *OrigV = PN->getIncomingValue(OrigI); |
| 1632 | Value *ThenV = PN->getIncomingValue(ThenI); |
| 1633 | |
| 1634 | // Skip PHIs which are trivial. |
| 1635 | if (OrigV == ThenV) |
| 1636 | continue; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1637 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1638 | // Create a select whose true value is the speculatively executed value and |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1639 | // false value is the preexisting value. Swap them if the branch |
| 1640 | // destinations were inverted. |
| 1641 | Value *TrueV = ThenV, *FalseV = OrigV; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1642 | if (Invert) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1643 | std::swap(TrueV, FalseV); |
| 1644 | Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, |
| 1645 | TrueV->getName() + "." + FalseV->getName()); |
| 1646 | PN->setIncomingValue(OrigI, V); |
| 1647 | PN->setIncomingValue(ThenI, V); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1648 | } |
| 1649 | |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1650 | ++NumSpeculations; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1651 | return true; |
| 1652 | } |
| 1653 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1654 | /// \returns True if this block contains a CallInst with the NoDuplicate |
| 1655 | /// attribute. |
| 1656 | static bool HasNoDuplicateCall(const BasicBlock *BB) { |
| 1657 | for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 1658 | const CallInst *CI = dyn_cast<CallInst>(I); |
| 1659 | if (!CI) |
| 1660 | continue; |
| 1661 | if (CI->cannotDuplicate()) |
| 1662 | return true; |
| 1663 | } |
| 1664 | return false; |
| 1665 | } |
| 1666 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1667 | /// Return true if we can thread a branch across this block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1668 | static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| 1669 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1670 | unsigned Size = 0; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1671 | |
Devang Patel | 84fceff | 2009-03-10 18:00:05 +0000 | [diff] [blame] | 1672 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1673 | if (isa<DbgInfoIntrinsic>(BBI)) |
| 1674 | continue; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1675 | if (Size > 10) return false; // Don't clone large BB's. |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1676 | ++Size; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1677 | |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1678 | // We can only support instructions that do not define values that are |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1679 | // live outside of the current basic block. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1680 | for (User *U : BBI->users()) { |
| 1681 | Instruction *UI = cast<Instruction>(U); |
| 1682 | if (UI->getParent() != BB || isa<PHINode>(UI)) return false; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1683 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1684 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1685 | // Looks ok, continue checking. |
| 1686 | } |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1687 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1688 | return true; |
| 1689 | } |
| 1690 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1691 | /// If we have a conditional branch on a PHI node value that is defined in the |
| 1692 | /// same block as the branch and if any PHI entries are constants, thread edges |
| 1693 | /// corresponding to that entry to be branches to their ultimate destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1694 | static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) { |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1695 | BasicBlock *BB = BI->getParent(); |
| 1696 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
Chris Lattner | 049cb44 | 2005-09-19 23:57:04 +0000 | [diff] [blame] | 1697 | // NOTE: we currently cannot transform this case if the PHI node is used |
| 1698 | // outside of the block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1699 | if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| 1700 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1701 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1702 | // Degenerate case of a single entry PHI. |
| 1703 | if (PN->getNumIncomingValues() == 1) { |
Chris Lattner | dc3f6f2 | 2008-12-03 19:44:02 +0000 | [diff] [blame] | 1704 | FoldSingleEntryPHINodes(PN->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1705 | return true; |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1706 | } |
| 1707 | |
| 1708 | // Now we know that this block has multiple preds and two succs. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1709 | if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1710 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1711 | if (HasNoDuplicateCall(BB)) return false; |
| 1712 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1713 | // Okay, this is a simple enough basic block. See if any phi values are |
| 1714 | // constants. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1715 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1716 | ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1717 | if (!CB || !CB->getType()->isIntegerTy(1)) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1718 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1719 | // Okay, we now know that all edges from PredBB should be revectored to |
| 1720 | // branch to RealDest. |
| 1721 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 1722 | BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1723 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1724 | if (RealDest == BB) continue; // Skip self loops. |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1725 | // Skip if the predecessor's terminator is an indirect branch. |
| 1726 | if (isa<IndirectBrInst>(PredBB->getTerminator())) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1727 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1728 | // The dest block might have PHI nodes, other predecessors and other |
| 1729 | // difficult cases. Instead of being smart about this, just insert a new |
| 1730 | // block that jumps to the destination block, effectively splitting |
| 1731 | // the edge we are about to create. |
| 1732 | BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(), |
| 1733 | RealDest->getName()+".critedge", |
| 1734 | RealDest->getParent(), RealDest); |
| 1735 | BranchInst::Create(RealDest, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1736 | |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 1737 | // Update PHI nodes. |
| 1738 | AddPredecessorToBlock(RealDest, EdgeBB, BB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1739 | |
| 1740 | // BB may have instructions that are being threaded over. Clone these |
| 1741 | // instructions into EdgeBB. We know that there will be no uses of the |
| 1742 | // cloned instructions outside of EdgeBB. |
| 1743 | BasicBlock::iterator InsertPt = EdgeBB->begin(); |
| 1744 | DenseMap<Value*, Value*> TranslateMap; // Track translated values. |
| 1745 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| 1746 | if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| 1747 | TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| 1748 | continue; |
| 1749 | } |
| 1750 | // Clone the instruction. |
| 1751 | Instruction *N = BBI->clone(); |
| 1752 | if (BBI->hasName()) N->setName(BBI->getName()+".c"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1753 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1754 | // Update operands due to translation. |
| 1755 | for (User::op_iterator i = N->op_begin(), e = N->op_end(); |
| 1756 | i != e; ++i) { |
| 1757 | DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i); |
| 1758 | if (PI != TranslateMap.end()) |
| 1759 | *i = PI->second; |
| 1760 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1761 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1762 | // Check for trivial simplification. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1763 | if (Value *V = SimplifyInstruction(N, DL)) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1764 | TranslateMap[&*BBI] = V; |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1765 | delete N; // Instruction folded away, don't need actual inst |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1766 | } else { |
| 1767 | // Insert the new instruction into its new home. |
| 1768 | EdgeBB->getInstList().insert(InsertPt, N); |
| 1769 | if (!BBI->use_empty()) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1770 | TranslateMap[&*BBI] = N; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | // Loop over all of the edges from PredBB to BB, changing them to branch |
| 1775 | // to EdgeBB instead. |
| 1776 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 1777 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 1778 | if (PredBBTI->getSuccessor(i) == BB) { |
| 1779 | BB->removePredecessor(PredBB); |
| 1780 | PredBBTI->setSuccessor(i, EdgeBB); |
| 1781 | } |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1782 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1783 | // Recurse, simplifying any other constants. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1784 | return FoldCondBranchOnPHI(BI, DL) | true; |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1785 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1786 | |
| 1787 | return false; |
| 1788 | } |
| 1789 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1790 | /// Given a BB that starts with the specified two-entry PHI node, |
| 1791 | /// see if we can eliminate it. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1792 | static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, |
| 1793 | const DataLayout &DL) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1794 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 1795 | // statement", which has a very simple dominance structure. Basically, we |
| 1796 | // are trying to find the condition that is being branched on, which |
| 1797 | // subsequently causes this merge to happen. We really want control |
| 1798 | // dependence information for this check, but simplifycfg can't keep it up |
| 1799 | // to date, and this catches most of the cases we care about anyway. |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1800 | BasicBlock *BB = PN->getParent(); |
| 1801 | BasicBlock *IfTrue, *IfFalse; |
| 1802 | Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1803 | if (!IfCond || |
| 1804 | // Don't bother if the branch will be constant folded trivially. |
| 1805 | isa<ConstantInt>(IfCond)) |
| 1806 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1807 | |
Chris Lattner | 95adf8f1 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 1808 | // Okay, we found that we can merge this two-entry phi node into a select. |
| 1809 | // Doing so would require us to fold *all* two entry phi nodes in this block. |
| 1810 | // At some point this becomes non-profitable (particularly if the target |
| 1811 | // doesn't support cmov's). Only do this transformation if there are two or |
| 1812 | // fewer PHI nodes in this block. |
| 1813 | unsigned NumPhis = 0; |
| 1814 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| 1815 | if (NumPhis > 2) |
| 1816 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1817 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1818 | // Loop over the PHI's seeing if we can promote them all to select |
| 1819 | // instructions. While we are at it, keep track of the instructions |
| 1820 | // that need to be moved to the dominating block. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1821 | SmallPtrSet<Instruction*, 4> AggressiveInsts; |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 1822 | unsigned MaxCostVal0 = PHINodeFoldingThreshold, |
| 1823 | MaxCostVal1 = PHINodeFoldingThreshold; |
James Molloy | 7c33657 | 2015-02-11 12:15:41 +0000 | [diff] [blame] | 1824 | MaxCostVal0 *= TargetTransformInfo::TCC_Basic; |
| 1825 | MaxCostVal1 *= TargetTransformInfo::TCC_Basic; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1826 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1827 | for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { |
| 1828 | PHINode *PN = cast<PHINode>(II++); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1829 | if (Value *V = SimplifyInstruction(PN, DL)) { |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1830 | PN->replaceAllUsesWith(V); |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1831 | PN->eraseFromParent(); |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1832 | continue; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1833 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1834 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1835 | if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1836 | MaxCostVal0, TTI) || |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1837 | !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1838 | MaxCostVal1, TTI)) |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1839 | return false; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1840 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1841 | |
Sylvestre Ledru | 35521e2 | 2012-07-23 08:51:15 +0000 | [diff] [blame] | 1842 | // If we folded the first phi, PN dangles at this point. Refresh it. If |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1843 | // we ran out of PHIs then we simplified them all. |
| 1844 | PN = dyn_cast<PHINode>(BB->begin()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1845 | if (!PN) return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1846 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1847 | // Don't fold i1 branches on PHIs which contain binary operators. These can |
| 1848 | // often be turned into switches and other things. |
| 1849 | if (PN->getType()->isIntegerTy(1) && |
| 1850 | (isa<BinaryOperator>(PN->getIncomingValue(0)) || |
| 1851 | isa<BinaryOperator>(PN->getIncomingValue(1)) || |
| 1852 | isa<BinaryOperator>(IfCond))) |
| 1853 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1854 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1855 | // If we all PHI nodes are promotable, check to make sure that all |
| 1856 | // instructions in the predecessor blocks can be promoted as well. If |
| 1857 | // not, we won't be able to get rid of the control flow, so it's not |
| 1858 | // worth promoting to select instructions. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1859 | BasicBlock *DomBlock = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1860 | BasicBlock *IfBlock1 = PN->getIncomingBlock(0); |
| 1861 | BasicBlock *IfBlock2 = PN->getIncomingBlock(1); |
| 1862 | if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1863 | IfBlock1 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1864 | } else { |
| 1865 | DomBlock = *pred_begin(IfBlock1); |
| 1866 | for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1867 | if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1868 | // This is not an aggressive instruction that we can promote. |
| 1869 | // Because of this, we won't be able to get rid of the control |
| 1870 | // flow, so the xform is not worth it. |
| 1871 | return false; |
| 1872 | } |
| 1873 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1874 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1875 | if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1876 | IfBlock2 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1877 | } else { |
| 1878 | DomBlock = *pred_begin(IfBlock2); |
| 1879 | for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1880 | if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1881 | // This is not an aggressive instruction that we can promote. |
| 1882 | // Because of this, we won't be able to get rid of the control |
| 1883 | // flow, so the xform is not worth it. |
| 1884 | return false; |
| 1885 | } |
| 1886 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1887 | |
Chris Lattner | 9fd838d | 2010-12-14 07:23:10 +0000 | [diff] [blame] | 1888 | DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1889 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1890 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1891 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 1892 | // do all of the PHI's now. |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1893 | Instruction *InsertPt = DomBlock->getTerminator(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1894 | IRBuilder<true, NoFolder> Builder(InsertPt); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1895 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1896 | // Move all 'aggressive' instructions, which are defined in the |
| 1897 | // conditional parts of the if's up to the dominating block. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1898 | if (IfBlock1) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1899 | DomBlock->getInstList().splice(InsertPt->getIterator(), |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1900 | IfBlock1->getInstList(), IfBlock1->begin(), |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1901 | IfBlock1->getTerminator()->getIterator()); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1902 | if (IfBlock2) |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1903 | DomBlock->getInstList().splice(InsertPt->getIterator(), |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1904 | IfBlock2->getInstList(), IfBlock2->begin(), |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 1905 | IfBlock2->getTerminator()->getIterator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1906 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1907 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 1908 | // Change the PHI node into a select instruction. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1909 | Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| 1910 | Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1911 | |
| 1912 | SelectInst *NV = |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1913 | cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, "")); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1914 | PN->replaceAllUsesWith(NV); |
| 1915 | NV->takeName(PN); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1916 | PN->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1917 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1918 | |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1919 | // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement |
| 1920 | // has been flattened. Change DomBlock to jump directly to our new block to |
| 1921 | // avoid other simplifycfg's kicking in on the diamond. |
| 1922 | TerminatorInst *OldTI = DomBlock->getTerminator(); |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1923 | Builder.SetInsertPoint(OldTI); |
| 1924 | Builder.CreateBr(BB); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1925 | OldTI->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1926 | return true; |
| 1927 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1928 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 1929 | /// If we found a conditional branch that goes to two returning blocks, |
| 1930 | /// try to merge them together into one return, |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1931 | /// introducing a select if the return values disagree. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1932 | static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1933 | IRBuilder<> &Builder) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1934 | assert(BI->isConditional() && "Must be a conditional branch"); |
| 1935 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1936 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1937 | ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| 1938 | ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1939 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1940 | // Check to ensure both blocks are empty (just a return) or optionally empty |
| 1941 | // with PHI nodes. If there are other instructions, merging would cause extra |
| 1942 | // computation on one path or the other. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1943 | if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1944 | return false; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1945 | if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1946 | return false; |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1947 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1948 | Builder.SetInsertPoint(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1949 | // Okay, we found a branch that is going to two return nodes. If |
| 1950 | // there is no return value for this function, just change the |
| 1951 | // branch into a return. |
| 1952 | if (FalseRet->getNumOperands() == 0) { |
| 1953 | TrueSucc->removePredecessor(BI->getParent()); |
| 1954 | FalseSucc->removePredecessor(BI->getParent()); |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1955 | Builder.CreateRetVoid(); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1956 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1957 | return true; |
| 1958 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1959 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1960 | // Otherwise, figure out what the true and false return values are |
| 1961 | // so we can insert a new select instruction. |
| 1962 | Value *TrueValue = TrueRet->getReturnValue(); |
| 1963 | Value *FalseValue = FalseRet->getReturnValue(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1964 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1965 | // Unwrap any PHI nodes in the return blocks. |
| 1966 | if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) |
| 1967 | if (TVPN->getParent() == TrueSucc) |
| 1968 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 1969 | if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) |
| 1970 | if (FVPN->getParent() == FalseSucc) |
| 1971 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1972 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1973 | // In order for this transformation to be safe, we must be able to |
| 1974 | // unconditionally execute both operands to the return. This is |
| 1975 | // normally the case, but we could have a potentially-trapping |
| 1976 | // constant expression that prevents this transformation from being |
| 1977 | // safe. |
| 1978 | if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) |
| 1979 | if (TCV->canTrap()) |
| 1980 | return false; |
| 1981 | if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) |
| 1982 | if (FCV->canTrap()) |
| 1983 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1984 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1985 | // Okay, we collected all the mapped values and checked them for sanity, and |
| 1986 | // defined to really do this transformation. First, update the CFG. |
| 1987 | TrueSucc->removePredecessor(BI->getParent()); |
| 1988 | FalseSucc->removePredecessor(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1989 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1990 | // Insert select instructions where needed. |
| 1991 | Value *BrCond = BI->getCondition(); |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1992 | if (TrueValue) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1993 | // Insert a select if the results differ. |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1994 | if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { |
| 1995 | } else if (isa<UndefValue>(TrueValue)) { |
| 1996 | TrueValue = FalseValue; |
| 1997 | } else { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1998 | TrueValue = Builder.CreateSelect(BrCond, TrueValue, |
| 1999 | FalseValue, "retval"); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2000 | } |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2001 | } |
| 2002 | |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2003 | Value *RI = !TrueValue ? |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2004 | Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); |
| 2005 | |
Daniel Dunbar | 5e0a58b | 2009-08-23 10:29:55 +0000 | [diff] [blame] | 2006 | (void) RI; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2007 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2008 | DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2009 | << "\n " << *BI << "NewRet = " << *RI |
| 2010 | << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2011 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 2012 | EraseTerminatorInstAndDCECond(BI); |
| 2013 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2014 | return true; |
| 2015 | } |
| 2016 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2017 | /// Given a conditional BranchInstruction, retrieve the probabilities of the |
| 2018 | /// branch taking each edge. Fills in the two APInt parameters and returns true, |
| 2019 | /// or returns false if no or invalid metadata was found. |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2020 | static bool ExtractBranchMetadata(BranchInst *BI, |
| 2021 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 2022 | assert(BI->isConditional() && |
| 2023 | "Looking for probabilities on unconditional branch?"); |
| 2024 | MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 2025 | if (!ProfileData || ProfileData->getNumOperands() != 3) return false; |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 2026 | ConstantInt *CITrue = |
| 2027 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 2028 | ConstantInt *CIFalse = |
| 2029 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2030 | if (!CITrue || !CIFalse) return false; |
| 2031 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 2032 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 2033 | return true; |
| 2034 | } |
| 2035 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2036 | /// Return true if the given instruction is available |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2037 | /// in its predecessor block. If yes, the instruction will be removed. |
Benjamin Kramer | abbfe69 | 2012-07-13 13:25:15 +0000 | [diff] [blame] | 2038 | static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2039 | if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) |
| 2040 | return false; |
| 2041 | for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) { |
| 2042 | Instruction *PBI = &*I; |
| 2043 | // Check whether Inst and PBI generate the same value. |
| 2044 | if (Inst->isIdenticalTo(PBI)) { |
| 2045 | Inst->replaceAllUsesWith(PBI); |
| 2046 | Inst->eraseFromParent(); |
| 2047 | return true; |
| 2048 | } |
| 2049 | } |
| 2050 | return false; |
| 2051 | } |
Nick Lewycky | 3c3feaf | 2012-01-25 09:43:14 +0000 | [diff] [blame] | 2052 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2053 | /// If this basic block is simple enough, and if a predecessor branches to us |
| 2054 | /// and one of our successors, fold the block into the predecessor and use |
| 2055 | /// logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2056 | bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2057 | BasicBlock *BB = BI->getParent(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2058 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2059 | Instruction *Cond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2060 | if (BI->isConditional()) |
| 2061 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 2062 | else { |
| 2063 | // For unconditional branch, check for a simple CFG pattern, where |
| 2064 | // BB has a single predecessor and BB's successor is also its predecessor's |
| 2065 | // successor. If such pattern exisits, check for CSE between BB and its |
| 2066 | // predecessor. |
| 2067 | if (BasicBlock *PB = BB->getSinglePredecessor()) |
| 2068 | if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) |
| 2069 | if (PBI->isConditional() && |
| 2070 | (BI->getSuccessor(0) == PBI->getSuccessor(0) || |
| 2071 | BI->getSuccessor(0) == PBI->getSuccessor(1))) { |
| 2072 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); |
| 2073 | I != E; ) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2074 | Instruction *Curr = &*I++; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2075 | if (isa<CmpInst>(Curr)) { |
| 2076 | Cond = Curr; |
| 2077 | break; |
| 2078 | } |
| 2079 | // Quit if we can't remove this instruction. |
| 2080 | if (!checkCSEInPredecessor(Curr, PB)) |
| 2081 | return false; |
| 2082 | } |
| 2083 | } |
| 2084 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2085 | if (!Cond) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2086 | return false; |
| 2087 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2088 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2089 | if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || |
| 2090 | Cond->getParent() != BB || !Cond->hasOneUse()) |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2091 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2092 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2093 | // Make sure the instruction after the condition is the cond branch. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2094 | BasicBlock::iterator CondIt = ++Cond->getIterator(); |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2095 | |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2096 | // Ignore dbg intrinsics. |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2097 | while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2098 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2099 | if (&*CondIt != BI) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2100 | return false; |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2101 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2102 | // Only allow this transformation if computing the condition doesn't involve |
| 2103 | // too many instructions and these involved instructions can be executed |
| 2104 | // unconditionally. We denote all involved instructions except the condition |
| 2105 | // as "bonus instructions", and only allow this transformation when the |
| 2106 | // number of the bonus instructions does not exceed a certain threshold. |
| 2107 | unsigned NumBonusInsts = 0; |
| 2108 | for (auto I = BB->begin(); Cond != I; ++I) { |
| 2109 | // Ignore dbg intrinsics. |
| 2110 | if (isa<DbgInfoIntrinsic>(I)) |
| 2111 | continue; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2112 | if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2113 | return false; |
| 2114 | // I has only one use and can be executed unconditionally. |
| 2115 | Instruction *User = dyn_cast<Instruction>(I->user_back()); |
| 2116 | if (User == nullptr || User->getParent() != BB) |
| 2117 | return false; |
| 2118 | // I is used in the same BB. Since BI uses Cond and doesn't have more slots |
| 2119 | // to use any other instruction, User must be an instruction between next(I) |
| 2120 | // and Cond. |
| 2121 | ++NumBonusInsts; |
| 2122 | // Early exits once we reach the limit. |
| 2123 | if (NumBonusInsts > BonusInstThreshold) |
| 2124 | return false; |
| 2125 | } |
| 2126 | |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2127 | // Cond is known to be a compare or binary operator. Check to make sure that |
| 2128 | // neither operand is a potentially-trapping constant expression. |
| 2129 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) |
| 2130 | if (CE->canTrap()) |
| 2131 | return false; |
| 2132 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) |
| 2133 | if (CE->canTrap()) |
| 2134 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2135 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2136 | // Finally, don't infinitely unroll conditional loops. |
| 2137 | BasicBlock *TrueDest = BI->getSuccessor(0); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2138 | BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2139 | if (TrueDest == BB || FalseDest == BB) |
| 2140 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2141 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2142 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 2143 | BasicBlock *PredBlock = *PI; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2144 | BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2145 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2146 | // Check that we have two conditional branches. If there is a PHI node in |
| 2147 | // the common successor, verify that the same value flows in from both |
| 2148 | // blocks. |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2149 | SmallVector<PHINode*, 4> PHIs; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2150 | if (!PBI || PBI->isUnconditional() || |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2151 | (BI->isConditional() && |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2152 | !SafeToMergeTerminators(BI, PBI)) || |
| 2153 | (!BI->isConditional() && |
| 2154 | !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2155 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2156 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2157 | // Determine if the two branches share a common destination. |
Axel Naumann | 4a12706 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 2158 | Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2159 | bool InvertPredCond = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2160 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2161 | if (BI->isConditional()) { |
| 2162 | if (PBI->getSuccessor(0) == TrueDest) |
| 2163 | Opc = Instruction::Or; |
| 2164 | else if (PBI->getSuccessor(1) == FalseDest) |
| 2165 | Opc = Instruction::And; |
| 2166 | else if (PBI->getSuccessor(0) == FalseDest) |
| 2167 | Opc = Instruction::And, InvertPredCond = true; |
| 2168 | else if (PBI->getSuccessor(1) == TrueDest) |
| 2169 | Opc = Instruction::Or, InvertPredCond = true; |
| 2170 | else |
| 2171 | continue; |
| 2172 | } else { |
| 2173 | if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) |
| 2174 | continue; |
| 2175 | } |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2176 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2177 | DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2178 | IRBuilder<> Builder(PBI); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2179 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2180 | // If we need to invert the condition in the pred block to match, do so now. |
| 2181 | if (InvertPredCond) { |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2182 | Value *NewCond = PBI->getCondition(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2183 | |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2184 | if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { |
| 2185 | CmpInst *CI = cast<CmpInst>(NewCond); |
| 2186 | CI->setPredicate(CI->getInversePredicate()); |
| 2187 | } else { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2188 | NewCond = Builder.CreateNot(NewCond, |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2189 | PBI->getCondition()->getName()+".not"); |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2190 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2191 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2192 | PBI->setCondition(NewCond); |
Nick Lewycky | 8d302df | 2011-12-26 20:54:14 +0000 | [diff] [blame] | 2193 | PBI->swapSuccessors(); |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2194 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2195 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2196 | // If we have bonus instructions, clone them into the predecessor block. |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2197 | // Note that there may be multiple predecessor blocks, so we cannot move |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2198 | // bonus instructions to a predecessor block. |
| 2199 | ValueToValueMapTy VMap; // maps original values to cloned values |
| 2200 | // We already make sure Cond is the last instruction before BI. Therefore, |
Sanjay Patel | adb110c | 2015-06-24 20:07:50 +0000 | [diff] [blame] | 2201 | // all instructions before Cond other than DbgInfoIntrinsic are bonus |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2202 | // instructions. |
| 2203 | for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) { |
| 2204 | if (isa<DbgInfoIntrinsic>(BonusInst)) |
| 2205 | continue; |
| 2206 | Instruction *NewBonusInst = BonusInst->clone(); |
| 2207 | RemapInstruction(NewBonusInst, VMap, |
| 2208 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2209 | VMap[&*BonusInst] = NewBonusInst; |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2210 | |
| 2211 | // If we moved a load, we cannot any longer claim any knowledge about |
| 2212 | // its potential value. The previous information might have been valid |
| 2213 | // only given the branch precondition. |
| 2214 | // For an analogous reason, we must also drop all the metadata whose |
| 2215 | // semantics we don't understand. |
Adrian Prantl | cbdfdb7 | 2015-08-20 22:00:30 +0000 | [diff] [blame] | 2216 | NewBonusInst->dropUnknownNonDebugMetadata(); |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2217 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2218 | PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); |
| 2219 | NewBonusInst->takeName(&*BonusInst); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2220 | BonusInst->setName(BonusInst->getName() + ".old"); |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2221 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2222 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2223 | // Clone Cond into the predecessor basic block, and or/and the |
| 2224 | // two conditions together. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 2225 | Instruction *New = Cond->clone(); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2226 | RemapInstruction(New, VMap, |
| 2227 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2228 | PredBlock->getInstList().insert(PBI->getIterator(), New); |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2229 | New->takeName(Cond); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2230 | Cond->setName(New->getName() + ".old"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2231 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2232 | if (BI->isConditional()) { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2233 | Instruction *NewCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2234 | cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(), |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2235 | New, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2236 | PBI->setCondition(NewCond); |
| 2237 | |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2238 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2239 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2240 | PredFalseWeight); |
| 2241 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2242 | SuccFalseWeight); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2243 | SmallVector<uint64_t, 8> NewWeights; |
| 2244 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2245 | if (PBI->getSuccessor(0) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2246 | if (PredHasWeights && SuccHasWeights) { |
| 2247 | // PBI: br i1 %x, BB, FalseDest |
| 2248 | // BI: br i1 %y, TrueDest, FalseDest |
| 2249 | //TrueWeight is TrueWeight for PBI * TrueWeight for BI. |
| 2250 | NewWeights.push_back(PredTrueWeight * SuccTrueWeight); |
| 2251 | //FalseWeight is FalseWeight for PBI * TotalWeight for BI + |
| 2252 | // TrueWeight for PBI * FalseWeight for BI. |
| 2253 | // We assume that total weights of a BranchInst can fit into 32 bits. |
| 2254 | // Therefore, we will not have overflow using 64-bit arithmetic. |
| 2255 | NewWeights.push_back(PredFalseWeight * (SuccFalseWeight + |
| 2256 | SuccTrueWeight) + PredTrueWeight * SuccFalseWeight); |
| 2257 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2258 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
| 2259 | PBI->setSuccessor(0, TrueDest); |
| 2260 | } |
| 2261 | if (PBI->getSuccessor(1) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2262 | if (PredHasWeights && SuccHasWeights) { |
| 2263 | // PBI: br i1 %x, TrueDest, BB |
| 2264 | // BI: br i1 %y, TrueDest, FalseDest |
| 2265 | //TrueWeight is TrueWeight for PBI * TotalWeight for BI + |
| 2266 | // FalseWeight for PBI * TrueWeight for BI. |
| 2267 | NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + |
| 2268 | SuccTrueWeight) + PredFalseWeight * SuccTrueWeight); |
| 2269 | //FalseWeight is FalseWeight for PBI * FalseWeight for BI. |
| 2270 | NewWeights.push_back(PredFalseWeight * SuccFalseWeight); |
| 2271 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2272 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
| 2273 | PBI->setSuccessor(1, FalseDest); |
| 2274 | } |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2275 | if (NewWeights.size() == 2) { |
| 2276 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2277 | FitWeights(NewWeights); |
| 2278 | |
| 2279 | SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end()); |
| 2280 | PBI->setMetadata(LLVMContext::MD_prof, |
| 2281 | MDBuilder(BI->getContext()). |
| 2282 | createBranchWeights(MDWeights)); |
| 2283 | } else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2284 | PBI->setMetadata(LLVMContext::MD_prof, nullptr); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2285 | } else { |
| 2286 | // Update PHI nodes in the common successors. |
| 2287 | for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 2288 | ConstantInt *PBI_C = cast<ConstantInt>( |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2289 | PHIs[i]->getIncomingValueForBlock(PBI->getParent())); |
| 2290 | assert(PBI_C->getType()->isIntegerTy(1)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2291 | Instruction *MergedCond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2292 | if (PBI->getSuccessor(0) == TrueDest) { |
| 2293 | // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) |
| 2294 | // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) |
| 2295 | // is false: !PBI_Cond and BI_Value |
| 2296 | Instruction *NotCond = |
| 2297 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2298 | "not.cond")); |
| 2299 | MergedCond = |
| 2300 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2301 | NotCond, New, |
| 2302 | "and.cond")); |
| 2303 | if (PBI_C->isOne()) |
| 2304 | MergedCond = |
| 2305 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2306 | PBI->getCondition(), MergedCond, |
| 2307 | "or.cond")); |
| 2308 | } else { |
| 2309 | // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) |
| 2310 | // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) |
| 2311 | // is false: PBI_Cond and BI_Value |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2312 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2313 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2314 | PBI->getCondition(), New, |
| 2315 | "and.cond")); |
| 2316 | if (PBI_C->isOne()) { |
| 2317 | Instruction *NotCond = |
| 2318 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2319 | "not.cond")); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2320 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2321 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2322 | NotCond, MergedCond, |
| 2323 | "or.cond")); |
| 2324 | } |
| 2325 | } |
| 2326 | // Update PHI Node. |
| 2327 | PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), |
| 2328 | MergedCond); |
| 2329 | } |
| 2330 | // Change PBI from Conditional to Unconditional. |
| 2331 | BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); |
| 2332 | EraseTerminatorInstAndDCECond(PBI); |
| 2333 | PBI = New_PBI; |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2334 | } |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2335 | |
Nick Lewycky | c554a9b | 2011-12-27 04:31:52 +0000 | [diff] [blame] | 2336 | // TODO: If BB is reachable from all paths through PredBlock, then we |
| 2337 | // could replace PBI's branch probabilities with BI's. |
| 2338 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2339 | // Copy any debug value intrinsics into the end of PredBlock. |
| 2340 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 2341 | if (isa<DbgInfoIntrinsic>(*I)) |
| 2342 | I->clone()->insertBefore(PBI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2343 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2344 | return true; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2345 | } |
| 2346 | return false; |
| 2347 | } |
| 2348 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2349 | // If there is only one store in BB1 and BB2, return it, otherwise return |
| 2350 | // nullptr. |
| 2351 | static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { |
| 2352 | StoreInst *S = nullptr; |
| 2353 | for (auto *BB : {BB1, BB2}) { |
| 2354 | if (!BB) |
| 2355 | continue; |
| 2356 | for (auto &I : *BB) |
| 2357 | if (auto *SI = dyn_cast<StoreInst>(&I)) { |
| 2358 | if (S) |
| 2359 | // Multiple stores seen. |
| 2360 | return nullptr; |
| 2361 | else |
| 2362 | S = SI; |
| 2363 | } |
| 2364 | } |
| 2365 | return S; |
| 2366 | } |
| 2367 | |
| 2368 | static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, |
| 2369 | Value *AlternativeV = nullptr) { |
| 2370 | // PHI is going to be a PHI node that allows the value V that is defined in |
| 2371 | // BB to be referenced in BB's only successor. |
| 2372 | // |
| 2373 | // If AlternativeV is nullptr, the only value we care about in PHI is V. It |
| 2374 | // doesn't matter to us what the other operand is (it'll never get used). We |
| 2375 | // could just create a new PHI with an undef incoming value, but that could |
| 2376 | // increase register pressure if EarlyCSE/InstCombine can't fold it with some |
| 2377 | // other PHI. So here we directly look for some PHI in BB's successor with V |
| 2378 | // as an incoming operand. If we find one, we use it, else we create a new |
| 2379 | // one. |
| 2380 | // |
| 2381 | // If AlternativeV is not nullptr, we care about both incoming values in PHI. |
| 2382 | // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] |
| 2383 | // where OtherBB is the single other predecessor of BB's only successor. |
| 2384 | PHINode *PHI = nullptr; |
| 2385 | BasicBlock *Succ = BB->getSingleSuccessor(); |
| 2386 | |
| 2387 | for (auto I = Succ->begin(); isa<PHINode>(I); ++I) |
| 2388 | if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { |
| 2389 | PHI = cast<PHINode>(I); |
| 2390 | if (!AlternativeV) |
| 2391 | break; |
| 2392 | |
| 2393 | assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2); |
| 2394 | auto PredI = pred_begin(Succ); |
| 2395 | BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; |
| 2396 | if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) |
| 2397 | break; |
| 2398 | PHI = nullptr; |
| 2399 | } |
| 2400 | if (PHI) |
| 2401 | return PHI; |
| 2402 | |
| 2403 | PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", Succ->begin()); |
| 2404 | PHI->addIncoming(V, BB); |
| 2405 | for (BasicBlock *PredBB : predecessors(Succ)) |
| 2406 | if (PredBB != BB) |
| 2407 | PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()), |
| 2408 | PredBB); |
| 2409 | return PHI; |
| 2410 | } |
| 2411 | |
| 2412 | static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, |
| 2413 | BasicBlock *QTB, BasicBlock *QFB, |
| 2414 | BasicBlock *PostBB, Value *Address, |
| 2415 | bool InvertPCond, bool InvertQCond) { |
| 2416 | auto IsaBitcastOfPointerType = [](const Instruction &I) { |
| 2417 | return Operator::getOpcode(&I) == Instruction::BitCast && |
| 2418 | I.getType()->isPointerTy(); |
| 2419 | }; |
| 2420 | |
| 2421 | // If we're not in aggressive mode, we only optimize if we have some |
| 2422 | // confidence that by optimizing we'll allow P and/or Q to be if-converted. |
| 2423 | auto IsWorthwhile = [&](BasicBlock *BB) { |
| 2424 | if (!BB) |
| 2425 | return true; |
| 2426 | // Heuristic: if the block can be if-converted/phi-folded and the |
| 2427 | // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to |
| 2428 | // thread this store. |
James Molloy | 9e959ac | 2015-11-05 08:40:19 +0000 | [diff] [blame^] | 2429 | unsigned N = 0; |
| 2430 | for (auto &I : *BB) { |
| 2431 | // Cheap instructions viable for folding. |
| 2432 | if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) || |
| 2433 | isa<StoreInst>(I)) |
| 2434 | ++N; |
| 2435 | // Free instructions. |
| 2436 | else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) || |
| 2437 | IsaBitcastOfPointerType(I)) |
| 2438 | continue; |
| 2439 | else |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2440 | return false; |
James Molloy | 9e959ac | 2015-11-05 08:40:19 +0000 | [diff] [blame^] | 2441 | } |
| 2442 | return N <= PHINodeFoldingThreshold; |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2443 | }; |
| 2444 | |
| 2445 | if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) || |
| 2446 | !IsWorthwhile(PFB) || |
| 2447 | !IsWorthwhile(QTB) || |
| 2448 | !IsWorthwhile(QFB))) |
| 2449 | return false; |
| 2450 | |
| 2451 | // For every pointer, there must be exactly two stores, one coming from |
| 2452 | // PTB or PFB, and the other from QTB or QFB. We don't support more than one |
| 2453 | // store (to any address) in PTB,PFB or QTB,QFB. |
| 2454 | // FIXME: We could relax this restriction with a bit more work and performance |
| 2455 | // testing. |
| 2456 | StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); |
| 2457 | StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); |
| 2458 | if (!PStore || !QStore) |
| 2459 | return false; |
| 2460 | |
| 2461 | // Now check the stores are compatible. |
| 2462 | if (!QStore->isUnordered() || !PStore->isUnordered()) |
| 2463 | return false; |
| 2464 | |
| 2465 | // Check that sinking the store won't cause program behavior changes. Sinking |
| 2466 | // the store out of the Q blocks won't change any behavior as we're sinking |
| 2467 | // from a block to its unconditional successor. But we're moving a store from |
| 2468 | // the P blocks down through the middle block (QBI) and past both QFB and QTB. |
| 2469 | // So we need to check that there are no aliasing loads or stores in |
| 2470 | // QBI, QTB and QFB. We also need to check there are no conflicting memory |
| 2471 | // operations between PStore and the end of its parent block. |
| 2472 | // |
| 2473 | // The ideal way to do this is to query AliasAnalysis, but we don't |
| 2474 | // preserve AA currently so that is dangerous. Be super safe and just |
| 2475 | // check there are no other memory operations at all. |
| 2476 | for (auto &I : *QFB->getSinglePredecessor()) |
| 2477 | if (I.mayReadOrWriteMemory()) |
| 2478 | return false; |
| 2479 | for (auto &I : *QFB) |
| 2480 | if (&I != QStore && I.mayReadOrWriteMemory()) |
| 2481 | return false; |
| 2482 | if (QTB) |
| 2483 | for (auto &I : *QTB) |
| 2484 | if (&I != QStore && I.mayReadOrWriteMemory()) |
| 2485 | return false; |
| 2486 | for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); |
| 2487 | I != E; ++I) |
| 2488 | if (&*I != PStore && I->mayReadOrWriteMemory()) |
| 2489 | return false; |
| 2490 | |
| 2491 | // OK, we're going to sink the stores to PostBB. The store has to be |
| 2492 | // conditional though, so first create the predicate. |
| 2493 | Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) |
| 2494 | ->getCondition(); |
| 2495 | Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) |
| 2496 | ->getCondition(); |
| 2497 | |
| 2498 | Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), |
| 2499 | PStore->getParent()); |
| 2500 | Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), |
| 2501 | QStore->getParent(), PPHI); |
| 2502 | |
| 2503 | IRBuilder<> QB(PostBB->getFirstInsertionPt()); |
| 2504 | |
| 2505 | Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); |
| 2506 | Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); |
| 2507 | |
| 2508 | if (InvertPCond) |
| 2509 | PPred = QB.CreateNot(PPred); |
| 2510 | if (InvertQCond) |
| 2511 | QPred = QB.CreateNot(QPred); |
| 2512 | Value *CombinedPred = QB.CreateOr(PPred, QPred); |
| 2513 | |
| 2514 | auto *T = SplitBlockAndInsertIfThen(CombinedPred, QB.GetInsertPoint(), false); |
| 2515 | QB.SetInsertPoint(T); |
| 2516 | StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); |
| 2517 | AAMDNodes AAMD; |
| 2518 | PStore->getAAMetadata(AAMD, /*Merge=*/false); |
| 2519 | PStore->getAAMetadata(AAMD, /*Merge=*/true); |
| 2520 | SI->setAAMetadata(AAMD); |
| 2521 | |
| 2522 | QStore->eraseFromParent(); |
| 2523 | PStore->eraseFromParent(); |
| 2524 | |
| 2525 | return true; |
| 2526 | } |
| 2527 | |
| 2528 | static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) { |
| 2529 | // The intention here is to find diamonds or triangles (see below) where each |
| 2530 | // conditional block contains a store to the same address. Both of these |
| 2531 | // stores are conditional, so they can't be unconditionally sunk. But it may |
| 2532 | // be profitable to speculatively sink the stores into one merged store at the |
| 2533 | // end, and predicate the merged store on the union of the two conditions of |
| 2534 | // PBI and QBI. |
| 2535 | // |
| 2536 | // This can reduce the number of stores executed if both of the conditions are |
| 2537 | // true, and can allow the blocks to become small enough to be if-converted. |
| 2538 | // This optimization will also chain, so that ladders of test-and-set |
| 2539 | // sequences can be if-converted away. |
| 2540 | // |
| 2541 | // We only deal with simple diamonds or triangles: |
| 2542 | // |
| 2543 | // PBI or PBI or a combination of the two |
| 2544 | // / \ | \ |
| 2545 | // PTB PFB | PFB |
| 2546 | // \ / | / |
| 2547 | // QBI QBI |
| 2548 | // / \ | \ |
| 2549 | // QTB QFB | QFB |
| 2550 | // \ / | / |
| 2551 | // PostBB PostBB |
| 2552 | // |
| 2553 | // We model triangles as a type of diamond with a nullptr "true" block. |
| 2554 | // Triangles are canonicalized so that the fallthrough edge is represented by |
| 2555 | // a true condition, as in the diagram above. |
| 2556 | // |
| 2557 | BasicBlock *PTB = PBI->getSuccessor(0); |
| 2558 | BasicBlock *PFB = PBI->getSuccessor(1); |
| 2559 | BasicBlock *QTB = QBI->getSuccessor(0); |
| 2560 | BasicBlock *QFB = QBI->getSuccessor(1); |
| 2561 | BasicBlock *PostBB = QFB->getSingleSuccessor(); |
| 2562 | |
| 2563 | bool InvertPCond = false, InvertQCond = false; |
| 2564 | // Canonicalize fallthroughs to the true branches. |
| 2565 | if (PFB == QBI->getParent()) { |
| 2566 | std::swap(PFB, PTB); |
| 2567 | InvertPCond = true; |
| 2568 | } |
| 2569 | if (QFB == PostBB) { |
| 2570 | std::swap(QFB, QTB); |
| 2571 | InvertQCond = true; |
| 2572 | } |
| 2573 | |
| 2574 | // From this point on we can assume PTB or QTB may be fallthroughs but PFB |
| 2575 | // and QFB may not. Model fallthroughs as a nullptr block. |
| 2576 | if (PTB == QBI->getParent()) |
| 2577 | PTB = nullptr; |
| 2578 | if (QTB == PostBB) |
| 2579 | QTB = nullptr; |
| 2580 | |
| 2581 | // Legality bailouts. We must have at least the non-fallthrough blocks and |
| 2582 | // the post-dominating block, and the non-fallthroughs must only have one |
| 2583 | // predecessor. |
| 2584 | auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { |
| 2585 | return BB->getSinglePredecessor() == P && |
| 2586 | BB->getSingleSuccessor() == S; |
| 2587 | }; |
| 2588 | if (!PostBB || |
| 2589 | !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || |
| 2590 | !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) |
| 2591 | return false; |
| 2592 | if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || |
| 2593 | (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) |
| 2594 | return false; |
| 2595 | if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2) |
| 2596 | return false; |
| 2597 | |
| 2598 | // OK, this is a sequence of two diamonds or triangles. |
| 2599 | // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. |
| 2600 | SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses; |
| 2601 | for (auto *BB : {PTB, PFB}) { |
| 2602 | if (!BB) |
| 2603 | continue; |
| 2604 | for (auto &I : *BB) |
| 2605 | if (StoreInst *SI = dyn_cast<StoreInst>(&I)) |
| 2606 | PStoreAddresses.insert(SI->getPointerOperand()); |
| 2607 | } |
| 2608 | for (auto *BB : {QTB, QFB}) { |
| 2609 | if (!BB) |
| 2610 | continue; |
| 2611 | for (auto &I : *BB) |
| 2612 | if (StoreInst *SI = dyn_cast<StoreInst>(&I)) |
| 2613 | QStoreAddresses.insert(SI->getPointerOperand()); |
| 2614 | } |
| 2615 | |
| 2616 | set_intersect(PStoreAddresses, QStoreAddresses); |
| 2617 | // set_intersect mutates PStoreAddresses in place. Rename it here to make it |
| 2618 | // clear what it contains. |
| 2619 | auto &CommonAddresses = PStoreAddresses; |
| 2620 | |
| 2621 | bool Changed = false; |
| 2622 | for (auto *Address : CommonAddresses) |
| 2623 | Changed |= mergeConditionalStoreToAddress( |
| 2624 | PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond); |
| 2625 | return Changed; |
| 2626 | } |
| 2627 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2628 | /// If we have a conditional branch as a predecessor of another block, |
| 2629 | /// this function tries to simplify it. We know |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2630 | /// that PBI and BI are both conditional branches, and BI is in one of the |
| 2631 | /// successor blocks of PBI - PBI branches to BI. |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 2632 | static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, |
| 2633 | const DataLayout &DL) { |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2634 | assert(PBI->isConditional() && BI->isConditional()); |
| 2635 | BasicBlock *BB = BI->getParent(); |
Dan Gohman | 5476cfd | 2009-08-12 16:23:25 +0000 | [diff] [blame] | 2636 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2637 | // If this block ends with a branch instruction, and if there is a |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2638 | // predecessor that ends on a branch of the same condition, make |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2639 | // this conditional branch redundant. |
| 2640 | if (PBI->getCondition() == BI->getCondition() && |
| 2641 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2642 | // Okay, the outcome of this conditional branch is statically |
| 2643 | // knowable. If this block had a single pred, handle specially. |
| 2644 | if (BB->getSinglePredecessor()) { |
| 2645 | // Turn this into a branch on constant. |
| 2646 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2647 | BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2648 | CondIsTrue)); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2649 | return true; // Nuke the branch on constant. |
| 2650 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2651 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2652 | // Otherwise, if there are multiple predecessors, insert a PHI that merges |
| 2653 | // in the constant and simplify the block result. Subsequent passes of |
| 2654 | // simplifycfg will thread the block. |
| 2655 | if (BlockIsSimpleEnoughToThreadThrough(BB)) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2656 | pred_iterator PB = pred_begin(BB), PE = pred_end(BB); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 2657 | PHINode *NewPN = PHINode::Create( |
| 2658 | Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), |
| 2659 | BI->getCondition()->getName() + ".pr", &BB->front()); |
Chris Lattner | 5eed372 | 2008-07-13 21:55:46 +0000 | [diff] [blame] | 2660 | // Okay, we're going to insert the PHI node. Since PBI is not the only |
| 2661 | // predecessor, compute the PHI'd conditional value for all of the preds. |
| 2662 | // Any predecessor where the condition is not computable we keep symbolic. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2663 | for (pred_iterator PI = PB; PI != PE; ++PI) { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2664 | BasicBlock *P = *PI; |
| 2665 | if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2666 | PBI != BI && PBI->isConditional() && |
| 2667 | PBI->getCondition() == BI->getCondition() && |
| 2668 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2669 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2670 | NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2671 | CondIsTrue), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2672 | } else { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2673 | NewPN->addIncoming(BI->getCondition(), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2674 | } |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2675 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2676 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2677 | BI->setCondition(NewPN); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2678 | return true; |
| 2679 | } |
| 2680 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2681 | |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 2682 | if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) |
| 2683 | if (CE->canTrap()) |
| 2684 | return false; |
| 2685 | |
Philip Reames | 846e3e4 | 2015-10-29 03:11:49 +0000 | [diff] [blame] | 2686 | // If BI is reached from the true path of PBI and PBI's condition implies |
| 2687 | // BI's condition, we know the direction of the BI branch. |
| 2688 | if (PBI->getSuccessor(0) == BI->getParent() && |
| 2689 | isImpliedCondition(PBI->getCondition(), BI->getCondition()) && |
| 2690 | PBI->getSuccessor(0) != PBI->getSuccessor(1) && |
| 2691 | BB->getSinglePredecessor()) { |
| 2692 | // Turn this into a branch on constant. |
| 2693 | auto *OldCond = BI->getCondition(); |
| 2694 | BI->setCondition(ConstantInt::getTrue(BB->getContext())); |
| 2695 | RecursivelyDeleteTriviallyDeadInstructions(OldCond); |
| 2696 | return true; // Nuke the branch on constant. |
| 2697 | } |
| 2698 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 2699 | // If both branches are conditional and both contain stores to the same |
| 2700 | // address, remove the stores from the conditionals and create a conditional |
| 2701 | // merged store at the end. |
| 2702 | if (MergeCondStores && mergeConditionalStores(PBI, BI)) |
| 2703 | return true; |
| 2704 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2705 | // If this is a conditional branch in an empty block, and if any |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2706 | // predecessors are a conditional branch to one of our destinations, |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2707 | // fold the conditions into logical ops and one cond br. |
Zhou Sheng | 264e46e | 2009-02-26 06:56:37 +0000 | [diff] [blame] | 2708 | BasicBlock::iterator BBI = BB->begin(); |
| 2709 | // Ignore dbg intrinsics. |
| 2710 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 2711 | ++BBI; |
| 2712 | if (&*BBI != BI) |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2713 | return false; |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2714 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2715 | int PBIOp, BIOp; |
| 2716 | if (PBI->getSuccessor(0) == BI->getSuccessor(0)) |
| 2717 | PBIOp = BIOp = 0; |
| 2718 | else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) |
| 2719 | PBIOp = 0, BIOp = 1; |
| 2720 | else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) |
| 2721 | PBIOp = 1, BIOp = 0; |
| 2722 | else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) |
| 2723 | PBIOp = BIOp = 1; |
| 2724 | else |
| 2725 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2726 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2727 | // Check to make sure that the other destination of this branch |
| 2728 | // isn't BB itself. If so, this is an infinite loop that will |
| 2729 | // keep getting unwound. |
| 2730 | if (PBI->getSuccessor(PBIOp) == BB) |
| 2731 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2732 | |
| 2733 | // Do not perform this transformation if it would require |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2734 | // insertion of a large number of select instructions. For targets |
| 2735 | // without predication/cmovs, this is a big pessimization. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2736 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2737 | // Also do not perform this transformation if any phi node in the common |
| 2738 | // destination block can trap when reached by BB or PBB (PR17073). In that |
| 2739 | // case, it would be unsafe to hoist the operation into a select instruction. |
| 2740 | |
| 2741 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2742 | unsigned NumPhis = 0; |
| 2743 | for (BasicBlock::iterator II = CommonDest->begin(); |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2744 | isa<PHINode>(II); ++II, ++NumPhis) { |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2745 | if (NumPhis > 2) // Disable this xform. |
| 2746 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2747 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2748 | PHINode *PN = cast<PHINode>(II); |
| 2749 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2750 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) |
| 2751 | if (CE->canTrap()) |
| 2752 | return false; |
| 2753 | |
| 2754 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2755 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2756 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) |
| 2757 | if (CE->canTrap()) |
| 2758 | return false; |
| 2759 | } |
| 2760 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2761 | // Finally, if everything is ok, fold the branches to logical ops. |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2762 | BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2763 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2764 | DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2765 | << "AND: " << *BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2766 | |
| 2767 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2768 | // If OtherDest *is* BB, then BB is a basic block with a single conditional |
| 2769 | // branch in it, where one edge (OtherDest) goes back to itself but the other |
| 2770 | // exits. We don't *know* that the program avoids the infinite loop |
| 2771 | // (even though that seems likely). If we do this xform naively, we'll end up |
| 2772 | // recursively unpeeling the loop. Since we know that (after the xform is |
| 2773 | // done) that the block *is* infinite if reached, we just make it an obviously |
| 2774 | // infinite loop with no cond branch. |
| 2775 | if (OtherDest == BB) { |
| 2776 | // Insert it at the end of the function, because it's either code, |
| 2777 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2778 | BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 2779 | "infloop", BB->getParent()); |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2780 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
| 2781 | OtherDest = InfLoopBlock; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2782 | } |
| 2783 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2784 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2785 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2786 | // BI may have other predecessors. Because of this, we leave |
| 2787 | // it alone, but modify PBI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2788 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2789 | // Make sure we get to CommonDest on True&True directions. |
| 2790 | Value *PBICond = PBI->getCondition(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2791 | IRBuilder<true, NoFolder> Builder(PBI); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2792 | if (PBIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2793 | PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not"); |
| 2794 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2795 | Value *BICond = BI->getCondition(); |
| 2796 | if (BIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2797 | BICond = Builder.CreateNot(BICond, BICond->getName()+".not"); |
| 2798 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2799 | // Merge the conditions. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2800 | Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2801 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2802 | // Modify PBI to branch on the new condition to the new dests. |
| 2803 | PBI->setCondition(Cond); |
| 2804 | PBI->setSuccessor(0, CommonDest); |
| 2805 | PBI->setSuccessor(1, OtherDest); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2806 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2807 | // Update branch weight for PBI. |
| 2808 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2809 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2810 | PredFalseWeight); |
| 2811 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2812 | SuccFalseWeight); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2813 | if (PredHasWeights && SuccHasWeights) { |
| 2814 | uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; |
| 2815 | uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight; |
| 2816 | uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; |
| 2817 | uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; |
| 2818 | // The weight to CommonDest should be PredCommon * SuccTotal + |
| 2819 | // PredOther * SuccCommon. |
| 2820 | // The weight to OtherDest should be PredOther * SuccOther. |
Benjamin Kramer | ea68a94 | 2015-02-19 15:26:17 +0000 | [diff] [blame] | 2821 | uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + |
| 2822 | PredOther * SuccCommon, |
| 2823 | PredOther * SuccOther}; |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2824 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2825 | FitWeights(NewWeights); |
| 2826 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2827 | PBI->setMetadata(LLVMContext::MD_prof, |
Benjamin Kramer | ea68a94 | 2015-02-19 15:26:17 +0000 | [diff] [blame] | 2828 | MDBuilder(BI->getContext()) |
| 2829 | .createBranchWeights(NewWeights[0], NewWeights[1])); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2830 | } |
| 2831 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2832 | // OtherDest may have phi nodes. If so, add an entry from PBI's |
| 2833 | // block that are identical to the entries for BI's block. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2834 | AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2835 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2836 | // We know that the CommonDest already had an edge from PBI to |
| 2837 | // it. If it has PHIs though, the PHIs may have different |
| 2838 | // entries for BB and PBI's BB. If so, insert a select to make |
| 2839 | // them agree. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2840 | PHINode *PN; |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2841 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 2842 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 2843 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2844 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2845 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2846 | if (BIV != PBIV) { |
| 2847 | // Insert a select in PBI to pick the right value. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2848 | Value *NV = cast<SelectInst> |
| 2849 | (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux")); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2850 | PN->setIncomingValue(PBBIdx, NV); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2851 | } |
| 2852 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2853 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2854 | DEBUG(dbgs() << "INTO: " << *PBI->getParent()); |
| 2855 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2856 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2857 | // This basic block is probably dead. We know it has at least |
| 2858 | // one fewer predecessor. |
| 2859 | return true; |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2860 | } |
| 2861 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2862 | // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is |
| 2863 | // true or to FalseBB if Cond is false. |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2864 | // Takes care of updating the successors and removing the old terminator. |
| 2865 | // Also makes sure not to introduce new successors by assuming that edges to |
| 2866 | // non-successor TrueBBs and FalseBBs aren't reachable. |
| 2867 | static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2868 | BasicBlock *TrueBB, BasicBlock *FalseBB, |
| 2869 | uint32_t TrueWeight, |
| 2870 | uint32_t FalseWeight){ |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2871 | // Remove any superfluous successor edges from the CFG. |
| 2872 | // First, figure out which successors to preserve. |
| 2873 | // If TrueBB and FalseBB are equal, only try to preserve one copy of that |
| 2874 | // successor. |
| 2875 | BasicBlock *KeepEdge1 = TrueBB; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2876 | BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2877 | |
| 2878 | // Then remove the rest. |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 2879 | for (BasicBlock *Succ : OldTerm->successors()) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2880 | // Make sure only to keep exactly one copy of each edge. |
| 2881 | if (Succ == KeepEdge1) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2882 | KeepEdge1 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2883 | else if (Succ == KeepEdge2) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2884 | KeepEdge2 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2885 | else |
David Majnemer | dc3b67b | 2015-10-21 18:22:24 +0000 | [diff] [blame] | 2886 | Succ->removePredecessor(OldTerm->getParent(), |
| 2887 | /*DontDeleteUselessPHIs=*/true); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2888 | } |
| 2889 | |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2890 | IRBuilder<> Builder(OldTerm); |
| 2891 | Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); |
| 2892 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2893 | // Insert an appropriate new terminator. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2894 | if (!KeepEdge1 && !KeepEdge2) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2895 | if (TrueBB == FalseBB) |
| 2896 | // We were only looking for one successor, and it was present. |
| 2897 | // Create an unconditional branch to it. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2898 | Builder.CreateBr(TrueBB); |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2899 | else { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2900 | // We found both of the successors we were looking for. |
| 2901 | // Create a conditional branch sharing the condition of the select. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2902 | BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); |
| 2903 | if (TrueWeight != FalseWeight) |
| 2904 | NewBI->setMetadata(LLVMContext::MD_prof, |
| 2905 | MDBuilder(OldTerm->getContext()). |
| 2906 | createBranchWeights(TrueWeight, FalseWeight)); |
| 2907 | } |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2908 | } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { |
| 2909 | // Neither of the selected blocks were successors, so this |
| 2910 | // terminator must be unreachable. |
| 2911 | new UnreachableInst(OldTerm->getContext(), OldTerm); |
| 2912 | } else { |
| 2913 | // One of the selected values was a successor, but the other wasn't. |
| 2914 | // Insert an unconditional branch to the one that was found; |
| 2915 | // the edge to the one that wasn't must be unreachable. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2916 | if (!KeepEdge1) |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2917 | // Only TrueBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2918 | Builder.CreateBr(TrueBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2919 | else |
| 2920 | // Only FalseBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2921 | Builder.CreateBr(FalseBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2922 | } |
| 2923 | |
| 2924 | EraseTerminatorInstAndDCECond(OldTerm); |
| 2925 | return true; |
| 2926 | } |
| 2927 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2928 | // Replaces |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2929 | // (switch (select cond, X, Y)) on constant X, Y |
| 2930 | // with a branch - conditional if X and Y lead to distinct BBs, |
| 2931 | // unconditional otherwise. |
| 2932 | static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { |
| 2933 | // Check for constant integer values in the select. |
| 2934 | ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); |
| 2935 | ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); |
| 2936 | if (!TrueVal || !FalseVal) |
| 2937 | return false; |
| 2938 | |
| 2939 | // Find the relevant condition and destinations. |
| 2940 | Value *Condition = Select->getCondition(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 2941 | BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); |
| 2942 | BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2943 | |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2944 | // Get weight for TrueBB and FalseBB. |
| 2945 | uint32_t TrueWeight = 0, FalseWeight = 0; |
| 2946 | SmallVector<uint64_t, 8> Weights; |
| 2947 | bool HasWeights = HasBranchWeights(SI); |
| 2948 | if (HasWeights) { |
| 2949 | GetBranchWeights(SI, Weights); |
| 2950 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 2951 | TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal). |
| 2952 | getSuccessorIndex()]; |
| 2953 | FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal). |
| 2954 | getSuccessorIndex()]; |
| 2955 | } |
| 2956 | } |
| 2957 | |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2958 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2959 | return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, |
| 2960 | TrueWeight, FalseWeight); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2961 | } |
| 2962 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2963 | // Replaces |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2964 | // (indirectbr (select cond, blockaddress(@fn, BlockA), |
| 2965 | // blockaddress(@fn, BlockB))) |
| 2966 | // with |
| 2967 | // (br cond, BlockA, BlockB). |
| 2968 | static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { |
| 2969 | // Check that both operands of the select are block addresses. |
| 2970 | BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); |
| 2971 | BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); |
| 2972 | if (!TBA || !FBA) |
| 2973 | return false; |
| 2974 | |
| 2975 | // Extract the actual blocks. |
| 2976 | BasicBlock *TrueBB = TBA->getBasicBlock(); |
| 2977 | BasicBlock *FalseBB = FBA->getBasicBlock(); |
| 2978 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2979 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2980 | return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, |
| 2981 | 0, 0); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2982 | } |
| 2983 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 2984 | /// This is called when we find an icmp instruction |
| 2985 | /// (a seteq/setne with a constant) as the only instruction in a |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2986 | /// block that ends with an uncond branch. We are looking for a very specific |
| 2987 | /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In |
| 2988 | /// this case, we merge the first two "or's of icmp" into a switch, but then the |
| 2989 | /// default value goes to an uncond block with a seteq in it, we get something |
| 2990 | /// like: |
| 2991 | /// |
| 2992 | /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] |
| 2993 | /// DEFAULT: |
| 2994 | /// %tmp = icmp eq i8 %A, 92 |
| 2995 | /// br label %end |
| 2996 | /// end: |
| 2997 | /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2998 | /// |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2999 | /// We prefer to split the edge to 'end' so that there is a true/false entry to |
| 3000 | /// the PHI, merging the third icmp into the switch. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 3001 | static bool TryToSimplifyUncondBranchWithICmpInIt( |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3002 | ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, |
| 3003 | const TargetTransformInfo &TTI, unsigned BonusInstThreshold, |
| 3004 | AssumptionCache *AC) { |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3005 | BasicBlock *BB = ICI->getParent(); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 3006 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3007 | // If the block has any PHIs in it or the icmp has multiple uses, it is too |
| 3008 | // complex. |
| 3009 | if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false; |
| 3010 | |
| 3011 | Value *V = ICI->getOperand(0); |
| 3012 | ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3013 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3014 | // The pattern we're looking for is where our only predecessor is a switch on |
| 3015 | // 'V' and this block is the default case for the switch. In this case we can |
| 3016 | // fold the compared value into the switch to simplify things. |
| 3017 | BasicBlock *Pred = BB->getSinglePredecessor(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3018 | if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3019 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3020 | SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); |
| 3021 | if (SI->getCondition() != V) |
| 3022 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3023 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3024 | // If BB is reachable on a non-default case, then we simply know the value of |
| 3025 | // V in this block. Substitute it and constant fold the icmp instruction |
| 3026 | // away. |
| 3027 | if (SI->getDefaultDest() != BB) { |
| 3028 | ConstantInt *VVal = SI->findCaseDest(BB); |
| 3029 | assert(VVal && "Should have a unique destination value"); |
| 3030 | ICI->setOperand(0, VVal); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3031 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3032 | if (Value *V = SimplifyInstruction(ICI, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3033 | ICI->replaceAllUsesWith(V); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3034 | ICI->eraseFromParent(); |
| 3035 | } |
| 3036 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3037 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3038 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3039 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3040 | // Ok, the block is reachable from the default dest. If the constant we're |
| 3041 | // comparing exists in one of the other edges, then we can constant fold ICI |
| 3042 | // and zap it. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3043 | if (SI->findCaseValue(Cst) != SI->case_default()) { |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3044 | Value *V; |
| 3045 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 3046 | V = ConstantInt::getFalse(BB->getContext()); |
| 3047 | else |
| 3048 | V = ConstantInt::getTrue(BB->getContext()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3049 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3050 | ICI->replaceAllUsesWith(V); |
| 3051 | ICI->eraseFromParent(); |
| 3052 | // BB is now empty, so it is likely to simplify away. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3053 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 3054 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3055 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3056 | // The use of the icmp has to be in the 'end' block, by the only PHI node in |
| 3057 | // the block. |
| 3058 | BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3059 | PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3060 | if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3061 | isa<PHINode>(++BasicBlock::iterator(PHIUse))) |
| 3062 | return false; |
| 3063 | |
| 3064 | // If the icmp is a SETEQ, then the default dest gets false, the new edge gets |
| 3065 | // true in the PHI. |
| 3066 | Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); |
| 3067 | Constant *NewCst = ConstantInt::getFalse(BB->getContext()); |
| 3068 | |
| 3069 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 3070 | std::swap(DefaultCst, NewCst); |
| 3071 | |
| 3072 | // Replace ICI (which is used by the PHI for the default value) with true or |
| 3073 | // false depending on if it is EQ or NE. |
| 3074 | ICI->replaceAllUsesWith(DefaultCst); |
| 3075 | ICI->eraseFromParent(); |
| 3076 | |
| 3077 | // Okay, the switch goes to this block on a default value. Add an edge from |
| 3078 | // the switch to the merge point on the compared value. |
| 3079 | BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge", |
| 3080 | BB->getParent(), BB); |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 3081 | SmallVector<uint64_t, 8> Weights; |
| 3082 | bool HasWeights = HasBranchWeights(SI); |
| 3083 | if (HasWeights) { |
| 3084 | GetBranchWeights(SI, Weights); |
| 3085 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 3086 | // Split weight for default case to case for "Cst". |
| 3087 | Weights[0] = (Weights[0]+1) >> 1; |
| 3088 | Weights.push_back(Weights[0]); |
| 3089 | |
| 3090 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 3091 | SI->setMetadata(LLVMContext::MD_prof, |
| 3092 | MDBuilder(SI->getContext()). |
| 3093 | createBranchWeights(MDWeights)); |
| 3094 | } |
| 3095 | } |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3096 | SI->addCase(Cst, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3097 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3098 | // NewBB branches to the phi block, add the uncond branch and the phi entry. |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 3099 | Builder.SetInsertPoint(NewBB); |
| 3100 | Builder.SetCurrentDebugLocation(SI->getDebugLoc()); |
| 3101 | Builder.CreateBr(SuccBlock); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 3102 | PHIUse->addIncoming(NewCst, NewBB); |
| 3103 | return true; |
| 3104 | } |
| 3105 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3106 | /// The specified branch is a conditional branch. |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3107 | /// Check to see if it is branching on an or/and chain of icmp instructions, and |
| 3108 | /// fold it into a switch instruction if so. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3109 | static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, |
| 3110 | const DataLayout &DL) { |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3111 | Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3112 | if (!Cond) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3113 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3114 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 3115 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 3116 | // 'setne's and'ed together, collect them. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3117 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 3118 | // Try to gather values from a chain of and/or to be turned into a switch |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 3119 | ConstantComparesGatherer ConstantCompare(Cond, DL); |
| 3120 | // Unpack the result |
| 3121 | SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals; |
| 3122 | Value *CompVal = ConstantCompare.CompValue; |
| 3123 | unsigned UsedICmps = ConstantCompare.UsedICmps; |
| 3124 | Value *ExtraCase = ConstantCompare.Extra; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3125 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3126 | // If we didn't have a multiply compared value, fail. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3127 | if (!CompVal) return false; |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3128 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 3129 | // Avoid turning single icmps into a switch. |
| 3130 | if (UsedICmps <= 1) |
| 3131 | return false; |
| 3132 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 3133 | bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); |
| 3134 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3135 | // There might be duplicate constants in the list, which the switch |
| 3136 | // instruction can't handle, remove them now. |
| 3137 | array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); |
| 3138 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3139 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3140 | // If Extra was used, we require at least two switch values to do the |
Sanjay Patel | 5966145 | 2015-09-10 15:14:34 +0000 | [diff] [blame] | 3141 | // transformation. A switch with one value is just a conditional branch. |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3142 | if (ExtraCase && Values.size() < 2) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3143 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 3144 | // TODO: Preserve branch weight metadata, similarly to how |
| 3145 | // FoldValueComparisonIntoPredecessors preserves it. |
| 3146 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3147 | // Figure out which block is which destination. |
| 3148 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
| 3149 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 3150 | if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3151 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3152 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3153 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3154 | DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 3155 | << " cases into SWITCH. BB is:\n" << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3156 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3157 | // If there are any extra values that couldn't be folded into the switch |
| 3158 | // then we evaluate them with an explicit branch first. Split the block |
| 3159 | // right before the condbr to handle it. |
| 3160 | if (ExtraCase) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3161 | BasicBlock *NewBB = |
| 3162 | BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3163 | // Remove the uncond branch added to the old block. |
| 3164 | TerminatorInst *OldTI = BB->getTerminator(); |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3165 | Builder.SetInsertPoint(OldTI); |
| 3166 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 3167 | if (TrueWhenEqual) |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3168 | Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 3169 | else |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3170 | Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3171 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3172 | OldTI->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3173 | |
Chris Lattner | cb570f8 | 2010-12-13 05:34:18 +0000 | [diff] [blame] | 3174 | // If there are PHI nodes in EdgeBB, then we need to add a new entry to them |
| 3175 | // for the edge we just added. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 3176 | AddPredecessorToBlock(EdgeBB, BB, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3177 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3178 | DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase |
| 3179 | << "\nEXTRABB = " << *BB); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3180 | BB = NewBB; |
| 3181 | } |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3182 | |
| 3183 | Builder.SetInsertPoint(BI); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3184 | // Convert pointer to int before we switch. |
| 3185 | if (CompVal->getType()->isPointerTy()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3186 | CompVal = Builder.CreatePtrToInt( |
| 3187 | CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3188 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3189 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3190 | // Create the new switch instruction now. |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 3191 | SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 3192 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3193 | // Add all of the 'cases' to the switch instruction. |
| 3194 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 3195 | New->addCase(Values[i], EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3196 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3197 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 3198 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 3199 | // the number of edges added. |
| 3200 | for (BasicBlock::iterator BBI = EdgeBB->begin(); |
| 3201 | isa<PHINode>(BBI); ++BBI) { |
| 3202 | PHINode *PN = cast<PHINode>(BBI); |
| 3203 | Value *InVal = PN->getIncomingValueForBlock(BB); |
| 3204 | for (unsigned i = 0, e = Values.size()-1; i != e; ++i) |
| 3205 | PN->addIncoming(InVal, BB); |
| 3206 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3207 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3208 | // Erase the old branch instruction. |
| 3209 | EraseTerminatorInstAndDCECond(BI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3210 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3211 | DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 3212 | return true; |
| 3213 | } |
| 3214 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3215 | bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { |
| 3216 | // If this is a trivial landing pad that just continues unwinding the caught |
| 3217 | // exception then zap the landing pad, turning its invokes into calls. |
| 3218 | BasicBlock *BB = RI->getParent(); |
| 3219 | LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3220 | if (RI->getValue() != LPInst) |
| 3221 | // Not a landing pad, or the resume is not unwinding the exception that |
| 3222 | // caused control to branch here. |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3223 | return false; |
| 3224 | |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3225 | // Check that there are no other instructions except for debug intrinsics. |
| 3226 | BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator(); |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3227 | while (++I != E) |
| 3228 | if (!isa<DbgInfoIntrinsic>(I)) |
| 3229 | return false; |
| 3230 | |
Chen Li | c6e2878 | 2015-10-22 20:48:38 +0000 | [diff] [blame] | 3231 | // Turn all invokes that unwind here into calls and delete the basic block. |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3232 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 3233 | BasicBlock *Pred = *PI++; |
| 3234 | removeUnwindEdge(Pred); |
Chen Li | c6e2878 | 2015-10-22 20:48:38 +0000 | [diff] [blame] | 3235 | } |
| 3236 | |
Chen Li | 7009cd3 | 2015-10-23 21:13:01 +0000 | [diff] [blame] | 3237 | // The landingpad is now unreachable. Zap it. |
| 3238 | BB->eraseFromParent(); |
| 3239 | return true; |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 3240 | } |
| 3241 | |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3242 | bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { |
| 3243 | // If this is a trivial cleanup pad that executes no instructions, it can be |
| 3244 | // eliminated. If the cleanup pad continues to the caller, any predecessor |
| 3245 | // that is an EH pad will be updated to continue to the caller and any |
| 3246 | // predecessor that terminates with an invoke instruction will have its invoke |
| 3247 | // instruction converted to a call instruction. If the cleanup pad being |
| 3248 | // simplified does not continue to the caller, each predecessor will be |
| 3249 | // updated to continue to the unwind destination of the cleanup pad being |
| 3250 | // simplified. |
| 3251 | BasicBlock *BB = RI->getParent(); |
| 3252 | Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI()); |
| 3253 | if (!CPInst) |
| 3254 | // This isn't an empty cleanup. |
| 3255 | return false; |
| 3256 | |
| 3257 | // Check that there are no other instructions except for debug intrinsics. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3258 | BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3259 | while (++I != E) |
| 3260 | if (!isa<DbgInfoIntrinsic>(I)) |
| 3261 | return false; |
| 3262 | |
| 3263 | // If the cleanup return we are simplifying unwinds to the caller, this |
| 3264 | // will set UnwindDest to nullptr. |
| 3265 | BasicBlock *UnwindDest = RI->getUnwindDest(); |
| 3266 | |
| 3267 | // We're about to remove BB from the control flow. Before we do, sink any |
| 3268 | // PHINodes into the unwind destination. Doing this before changing the |
| 3269 | // control flow avoids some potentially slow checks, since we can currently |
| 3270 | // be certain that UnwindDest and BB have no common predecessors (since they |
| 3271 | // are both EH pads). |
| 3272 | if (UnwindDest) { |
| 3273 | // First, go through the PHI nodes in UnwindDest and update any nodes that |
| 3274 | // reference the block we are removing |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3275 | for (BasicBlock::iterator I = UnwindDest->begin(), |
| 3276 | IE = UnwindDest->getFirstNonPHI()->getIterator(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3277 | I != IE; ++I) { |
| 3278 | PHINode *DestPN = cast<PHINode>(I); |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 3279 | |
Andrew Kaylor | 2a9a6d8 | 2015-09-05 01:00:51 +0000 | [diff] [blame] | 3280 | int Idx = DestPN->getBasicBlockIndex(BB); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3281 | // Since BB unwinds to UnwindDest, it has to be in the PHI node. |
Craig Topper | 02a55d7 | 2015-09-05 04:49:44 +0000 | [diff] [blame] | 3282 | assert(Idx != -1); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3283 | // This PHI node has an incoming value that corresponds to a control |
| 3284 | // path through the cleanup pad we are removing. If the incoming |
| 3285 | // value is in the cleanup pad, it must be a PHINode (because we |
| 3286 | // verified above that the block is otherwise empty). Otherwise, the |
| 3287 | // value is either a constant or a value that dominates the cleanup |
| 3288 | // pad being removed. |
| 3289 | // |
| 3290 | // Because BB and UnwindDest are both EH pads, all of their |
| 3291 | // predecessors must unwind to these blocks, and since no instruction |
| 3292 | // can have multiple unwind destinations, there will be no overlap in |
| 3293 | // incoming blocks between SrcPN and DestPN. |
| 3294 | Value *SrcVal = DestPN->getIncomingValue(Idx); |
| 3295 | PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); |
| 3296 | |
| 3297 | // Remove the entry for the block we are deleting. |
| 3298 | DestPN->removeIncomingValue(Idx, false); |
| 3299 | |
| 3300 | if (SrcPN && SrcPN->getParent() == BB) { |
| 3301 | // If the incoming value was a PHI node in the cleanup pad we are |
| 3302 | // removing, we need to merge that PHI node's incoming values into |
| 3303 | // DestPN. |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 3304 | for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3305 | SrcIdx != SrcE; ++SrcIdx) { |
| 3306 | DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), |
| 3307 | SrcPN->getIncomingBlock(SrcIdx)); |
| 3308 | } |
| 3309 | } else { |
| 3310 | // Otherwise, the incoming value came from above BB and |
| 3311 | // so we can just reuse it. We must associate all of BB's |
| 3312 | // predecessors with this value. |
| 3313 | for (auto *pred : predecessors(BB)) { |
| 3314 | DestPN->addIncoming(SrcVal, pred); |
| 3315 | } |
| 3316 | } |
| 3317 | } |
| 3318 | |
| 3319 | // Sink any remaining PHI nodes directly into UnwindDest. |
| 3320 | Instruction *InsertPt = UnwindDest->getFirstNonPHI(); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3321 | for (BasicBlock::iterator I = BB->begin(), |
| 3322 | IE = BB->getFirstNonPHI()->getIterator(); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3323 | I != IE;) { |
| 3324 | // The iterator must be incremented here because the instructions are |
| 3325 | // being moved to another block. |
| 3326 | PHINode *PN = cast<PHINode>(I++); |
| 3327 | if (PN->use_empty()) |
| 3328 | // If the PHI node has no uses, just leave it. It will be erased |
| 3329 | // when we erase BB below. |
| 3330 | continue; |
| 3331 | |
| 3332 | // Otherwise, sink this PHI node into UnwindDest. |
| 3333 | // Any predecessors to UnwindDest which are not already represented |
| 3334 | // must be back edges which inherit the value from the path through |
| 3335 | // BB. In this case, the PHI value must reference itself. |
| 3336 | for (auto *pred : predecessors(UnwindDest)) |
| 3337 | if (pred != BB) |
| 3338 | PN->addIncoming(PN, pred); |
| 3339 | PN->moveBefore(InsertPt); |
| 3340 | } |
| 3341 | } |
| 3342 | |
| 3343 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 3344 | // The iterator must be updated here because we are removing this pred. |
| 3345 | BasicBlock *PredBB = *PI++; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3346 | if (UnwindDest == nullptr) { |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3347 | removeUnwindEdge(PredBB); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3348 | } else { |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3349 | TerminatorInst *TI = PredBB->getTerminator(); |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3350 | TI->replaceUsesOfWith(BB, UnwindDest); |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 3351 | } |
| 3352 | } |
| 3353 | |
| 3354 | // The cleanup pad is now unreachable. Zap it. |
| 3355 | BB->eraseFromParent(); |
| 3356 | return true; |
| 3357 | } |
| 3358 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3359 | bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3360 | BasicBlock *BB = RI->getParent(); |
| 3361 | if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3362 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3363 | // Find predecessors that end with branches. |
| 3364 | SmallVector<BasicBlock*, 8> UncondBranchPreds; |
| 3365 | SmallVector<BranchInst*, 8> CondBranchPreds; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 3366 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 3367 | BasicBlock *P = *PI; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3368 | TerminatorInst *PTI = P->getTerminator(); |
| 3369 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { |
| 3370 | if (BI->isUnconditional()) |
| 3371 | UncondBranchPreds.push_back(P); |
| 3372 | else |
| 3373 | CondBranchPreds.push_back(BI); |
| 3374 | } |
| 3375 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3376 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3377 | // If we found some, do the transformation! |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3378 | if (!UncondBranchPreds.empty() && DupRet) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3379 | while (!UncondBranchPreds.empty()) { |
| 3380 | BasicBlock *Pred = UncondBranchPreds.pop_back_val(); |
| 3381 | DEBUG(dbgs() << "FOLDING: " << *BB |
| 3382 | << "INTO UNCOND BRANCH PRED: " << *Pred); |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3383 | (void)FoldReturnIntoUncondBranch(RI, BB, Pred); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3384 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3385 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3386 | // If we eliminated all predecessors of the block, delete the block now. |
Ramkumar Ramachandra | 40c3e03 | 2015-01-13 03:46:47 +0000 | [diff] [blame] | 3387 | if (pred_empty(BB)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3388 | // We know there are no successors, so just nuke the block. |
| 3389 | BB->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3390 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3391 | return true; |
| 3392 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3393 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3394 | // Check out all of the conditional branches going to this return |
| 3395 | // instruction. If any of them just select between returns, change the |
| 3396 | // branch itself into a select/return pair. |
| 3397 | while (!CondBranchPreds.empty()) { |
| 3398 | BranchInst *BI = CondBranchPreds.pop_back_val(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3399 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3400 | // Check to see if the non-BB successor is also a return block. |
| 3401 | if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && |
| 3402 | isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3403 | SimplifyCondBranchToTwoReturns(BI, Builder)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3404 | return true; |
| 3405 | } |
| 3406 | return false; |
| 3407 | } |
| 3408 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3409 | bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { |
| 3410 | BasicBlock *BB = UI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3411 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3412 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3413 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3414 | // If there are any instructions immediately before the unreachable that can |
| 3415 | // be removed, do so. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3416 | while (UI->getIterator() != BB->begin()) { |
| 3417 | BasicBlock::iterator BBI = UI->getIterator(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3418 | --BBI; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3419 | // Do not delete instructions that can have side effects which might cause |
| 3420 | // the unreachable to not be reachable; specifically, calls and volatile |
| 3421 | // operations may have this effect. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3422 | if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3423 | |
| 3424 | if (BBI->mayHaveSideEffects()) { |
| 3425 | if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { |
| 3426 | if (SI->isVolatile()) |
| 3427 | break; |
| 3428 | } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { |
| 3429 | if (LI->isVolatile()) |
| 3430 | break; |
| 3431 | } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { |
| 3432 | if (RMWI->isVolatile()) |
| 3433 | break; |
| 3434 | } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { |
| 3435 | if (CXI->isVolatile()) |
| 3436 | break; |
| 3437 | } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && |
| 3438 | !isa<LandingPadInst>(BBI)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3439 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3440 | } |
Bill Wendling | 55d875f | 2011-08-16 20:41:17 +0000 | [diff] [blame] | 3441 | // Note that deleting LandingPad's here is in fact okay, although it |
| 3442 | // involves a bit of subtle reasoning. If this inst is a LandingPad, |
| 3443 | // all the predecessors of this block will be the unwind edges of Invokes, |
| 3444 | // and we can therefore guarantee this block will be erased. |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3445 | } |
| 3446 | |
Eli Friedman | aac35b3 | 2011-03-09 00:48:33 +0000 | [diff] [blame] | 3447 | // Delete this instruction (any uses are guaranteed to be dead) |
| 3448 | if (!BBI->use_empty()) |
| 3449 | BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3450 | BBI->eraseFromParent(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3451 | Changed = true; |
| 3452 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3453 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3454 | // If the unreachable instruction is the first in the block, take a gander |
| 3455 | // at all of the predecessors of this instruction, and simplify them. |
| 3456 | if (&BB->front() != UI) return Changed; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3457 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3458 | SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); |
| 3459 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 3460 | TerminatorInst *TI = Preds[i]->getTerminator(); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3461 | IRBuilder<> Builder(TI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3462 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 3463 | if (BI->isUnconditional()) { |
| 3464 | if (BI->getSuccessor(0) == BB) { |
| 3465 | new UnreachableInst(TI->getContext(), TI); |
| 3466 | TI->eraseFromParent(); |
| 3467 | Changed = true; |
| 3468 | } |
| 3469 | } else { |
| 3470 | if (BI->getSuccessor(0) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3471 | Builder.CreateBr(BI->getSuccessor(1)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3472 | EraseTerminatorInstAndDCECond(BI); |
| 3473 | } else if (BI->getSuccessor(1) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3474 | Builder.CreateBr(BI->getSuccessor(0)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3475 | EraseTerminatorInstAndDCECond(BI); |
| 3476 | Changed = true; |
| 3477 | } |
| 3478 | } |
| 3479 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3480 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3481 | i != e; ++i) |
| 3482 | if (i.getCaseSuccessor() == BB) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3483 | BB->removePredecessor(SI->getParent()); |
| 3484 | SI->removeCase(i); |
| 3485 | --i; --e; |
| 3486 | Changed = true; |
| 3487 | } |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3488 | } else if ((isa<InvokeInst>(TI) && |
| 3489 | cast<InvokeInst>(TI)->getUnwindDest() == BB) || |
| 3490 | isa<CatchEndPadInst>(TI) || isa<TerminatePadInst>(TI)) { |
| 3491 | removeUnwindEdge(TI->getParent()); |
| 3492 | Changed = true; |
David Majnemer | 4929370 | 2015-10-27 22:43:56 +0000 | [diff] [blame] | 3493 | } else if (isa<CleanupReturnInst>(TI) || isa<CleanupEndPadInst>(TI)) { |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3494 | new UnreachableInst(TI->getContext(), TI); |
| 3495 | TI->eraseFromParent(); |
| 3496 | Changed = true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3497 | } |
Joseph Tremoulet | 09af67a | 2015-09-27 01:47:46 +0000 | [diff] [blame] | 3498 | // TODO: If TI is a CatchPadInst, then (BB must be its normal dest and) |
| 3499 | // we can eliminate it, redirecting its preds to its unwind successor, |
| 3500 | // or to the next outer handler if the removed catch is the last for its |
| 3501 | // catchendpad. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3502 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3503 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3504 | // If this block is now dead, remove it. |
Ramkumar Ramachandra | 40c3e03 | 2015-01-13 03:46:47 +0000 | [diff] [blame] | 3505 | if (pred_empty(BB) && |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3506 | BB != &BB->getParent()->getEntryBlock()) { |
| 3507 | // We know there are no successors, so just nuke the block. |
| 3508 | BB->eraseFromParent(); |
| 3509 | return true; |
| 3510 | } |
| 3511 | |
| 3512 | return Changed; |
| 3513 | } |
| 3514 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3515 | static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { |
| 3516 | assert(Cases.size() >= 1); |
| 3517 | |
| 3518 | array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); |
| 3519 | for (size_t I = 1, E = Cases.size(); I != E; ++I) { |
| 3520 | if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) |
| 3521 | return false; |
| 3522 | } |
| 3523 | return true; |
| 3524 | } |
| 3525 | |
| 3526 | /// Turn a switch with two reachable destinations into an integer range |
| 3527 | /// comparison and branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 3528 | static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3529 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3530 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3531 | bool HasDefault = |
| 3532 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3533 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3534 | // Partition the cases into two sets with different destinations. |
| 3535 | BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; |
| 3536 | BasicBlock *DestB = nullptr; |
| 3537 | SmallVector <ConstantInt *, 16> CasesA; |
| 3538 | SmallVector <ConstantInt *, 16> CasesB; |
| 3539 | |
| 3540 | for (SwitchInst::CaseIt I : SI->cases()) { |
| 3541 | BasicBlock *Dest = I.getCaseSuccessor(); |
| 3542 | if (!DestA) DestA = Dest; |
| 3543 | if (Dest == DestA) { |
| 3544 | CasesA.push_back(I.getCaseValue()); |
| 3545 | continue; |
| 3546 | } |
| 3547 | if (!DestB) DestB = Dest; |
| 3548 | if (Dest == DestB) { |
| 3549 | CasesB.push_back(I.getCaseValue()); |
| 3550 | continue; |
| 3551 | } |
| 3552 | return false; // More than two destinations. |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3553 | } |
| 3554 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3555 | assert(DestA && DestB && "Single-destination switch should have been folded."); |
| 3556 | assert(DestA != DestB); |
| 3557 | assert(DestB != SI->getDefaultDest()); |
| 3558 | assert(!CasesB.empty() && "There must be non-default cases."); |
| 3559 | assert(!CasesA.empty() || HasDefault); |
| 3560 | |
| 3561 | // Figure out if one of the sets of cases form a contiguous range. |
| 3562 | SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; |
| 3563 | BasicBlock *ContiguousDest = nullptr; |
| 3564 | BasicBlock *OtherDest = nullptr; |
| 3565 | if (!CasesA.empty() && CasesAreContiguous(CasesA)) { |
| 3566 | ContiguousCases = &CasesA; |
| 3567 | ContiguousDest = DestA; |
| 3568 | OtherDest = DestB; |
| 3569 | } else if (CasesAreContiguous(CasesB)) { |
| 3570 | ContiguousCases = &CasesB; |
| 3571 | ContiguousDest = DestB; |
| 3572 | OtherDest = DestA; |
| 3573 | } else |
| 3574 | return false; |
| 3575 | |
| 3576 | // Start building the compare and branch. |
| 3577 | |
| 3578 | Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); |
| 3579 | Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size()); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3580 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 3581 | Value *Sub = SI->getCondition(); |
| 3582 | if (!Offset->isNullValue()) |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3583 | Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); |
| 3584 | |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 3585 | Value *Cmp; |
| 3586 | // If NumCases overflowed, then all possible values jump to the successor. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3587 | if (NumCases->isNullValue() && !ContiguousCases->empty()) |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 3588 | Cmp = ConstantInt::getTrue(SI->getContext()); |
| 3589 | else |
| 3590 | Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3591 | BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3592 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3593 | // Update weight for the newly-created conditional branch. |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3594 | if (HasBranchWeights(SI)) { |
| 3595 | SmallVector<uint64_t, 8> Weights; |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3596 | GetBranchWeights(SI, Weights); |
| 3597 | if (Weights.size() == 1 + SI->getNumCases()) { |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3598 | uint64_t TrueWeight = 0; |
| 3599 | uint64_t FalseWeight = 0; |
| 3600 | for (size_t I = 0, E = Weights.size(); I != E; ++I) { |
| 3601 | if (SI->getSuccessor(I) == ContiguousDest) |
| 3602 | TrueWeight += Weights[I]; |
| 3603 | else |
| 3604 | FalseWeight += Weights[I]; |
| 3605 | } |
| 3606 | while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { |
| 3607 | TrueWeight /= 2; |
| 3608 | FalseWeight /= 2; |
| 3609 | } |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3610 | NewBI->setMetadata(LLVMContext::MD_prof, |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3611 | MDBuilder(SI->getContext()).createBranchWeights( |
| 3612 | (uint32_t)TrueWeight, (uint32_t)FalseWeight)); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3613 | } |
| 3614 | } |
| 3615 | |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3616 | // Prune obsolete incoming values off the successors' PHI nodes. |
| 3617 | for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 3618 | unsigned PreviousEdges = ContiguousCases->size(); |
| 3619 | if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges; |
| 3620 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3621 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 3622 | } |
Hans Wennborg | 6800008 | 2015-01-26 19:52:32 +0000 | [diff] [blame] | 3623 | for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { |
| 3624 | unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); |
| 3625 | if (OtherDest == SI->getDefaultDest()) ++PreviousEdges; |
| 3626 | for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) |
| 3627 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 3628 | } |
| 3629 | |
| 3630 | // Drop the switch. |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3631 | SI->eraseFromParent(); |
| 3632 | |
| 3633 | return true; |
| 3634 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3635 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3636 | /// Compute masked bits for the condition of a switch |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3637 | /// and use it to remove dead cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3638 | static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, |
| 3639 | const DataLayout &DL) { |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3640 | Value *Cond = SI->getCondition(); |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 3641 | unsigned Bits = Cond->getType()->getIntegerBitWidth(); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3642 | APInt KnownZero(Bits, 0), KnownOne(Bits, 0); |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 3643 | computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3644 | |
| 3645 | // Gather dead cases. |
| 3646 | SmallVector<ConstantInt*, 8> DeadCases; |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3647 | for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3648 | if ((I.getCaseValue()->getValue() & KnownZero) != 0 || |
| 3649 | (I.getCaseValue()->getValue() & KnownOne) != KnownOne) { |
| 3650 | DeadCases.push_back(I.getCaseValue()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3651 | DEBUG(dbgs() << "SimplifyCFG: switch case '" |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3652 | << I.getCaseValue() << "' is dead.\n"); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3653 | } |
| 3654 | } |
| 3655 | |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 3656 | // If we can prove that the cases must cover all possible values, the |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 3657 | // default destination becomes dead and we can remove it. If we know some |
| 3658 | // of the bits in the value, we can use that to more precisely compute the |
| 3659 | // number of possible unique case values. |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 3660 | bool HasDefault = |
| 3661 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 3662 | const unsigned NumUnknownBits = Bits - |
| 3663 | (KnownZero.Or(KnownOne)).countPopulation(); |
Filipe Cabecinhas | 48b090a | 2015-09-10 22:34:39 +0000 | [diff] [blame] | 3664 | assert(NumUnknownBits <= Bits); |
Philip Reames | 0537013 | 2015-09-10 17:44:47 +0000 | [diff] [blame] | 3665 | if (HasDefault && DeadCases.empty() && |
| 3666 | NumUnknownBits < 64 /* avoid overflow */ && |
| 3667 | SI->getNumCases() == (1ULL << NumUnknownBits)) { |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 3668 | DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); |
| 3669 | BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(), |
| 3670 | SI->getParent(), ""); |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3671 | SI->setDefaultDest(&*NewDefault); |
| 3672 | SplitBlock(&*NewDefault, &NewDefault->front()); |
Philip Reames | 98a2dab | 2015-08-26 23:56:46 +0000 | [diff] [blame] | 3673 | auto *OldTI = NewDefault->getTerminator(); |
| 3674 | new UnreachableInst(SI->getContext(), OldTI); |
| 3675 | EraseTerminatorInstAndDCECond(OldTI); |
| 3676 | return true; |
| 3677 | } |
| 3678 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3679 | SmallVector<uint64_t, 8> Weights; |
| 3680 | bool HasWeight = HasBranchWeights(SI); |
| 3681 | if (HasWeight) { |
| 3682 | GetBranchWeights(SI, Weights); |
| 3683 | HasWeight = (Weights.size() == 1 + SI->getNumCases()); |
| 3684 | } |
| 3685 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3686 | // Remove dead cases from the switch. |
| 3687 | for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3688 | SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]); |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3689 | assert(Case != SI->case_default() && |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3690 | "Case was not found. Probably mistake in DeadCases forming."); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3691 | if (HasWeight) { |
| 3692 | std::swap(Weights[Case.getCaseIndex()+1], Weights.back()); |
| 3693 | Weights.pop_back(); |
| 3694 | } |
| 3695 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3696 | // Prune unused values from PHI nodes. |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3697 | Case.getCaseSuccessor()->removePredecessor(SI->getParent()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3698 | SI->removeCase(Case); |
| 3699 | } |
Justin Bogner | 0ba3f21 | 2013-12-20 08:21:30 +0000 | [diff] [blame] | 3700 | if (HasWeight && Weights.size() >= 2) { |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3701 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 3702 | SI->setMetadata(LLVMContext::MD_prof, |
| 3703 | MDBuilder(SI->getParent()->getContext()). |
| 3704 | createBranchWeights(MDWeights)); |
| 3705 | } |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3706 | |
| 3707 | return !DeadCases.empty(); |
| 3708 | } |
| 3709 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3710 | /// If BB would be eligible for simplification by |
| 3711 | /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3712 | /// by an unconditional branch), look at the phi node for BB in the successor |
| 3713 | /// block and see if the incoming value is equal to CaseValue. If so, return |
| 3714 | /// the phi node, and set PhiIndex to BB's index in the phi node. |
| 3715 | static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, |
| 3716 | BasicBlock *BB, |
| 3717 | int *PhiIndex) { |
| 3718 | if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3719 | return nullptr; // BB must be empty to be a candidate for simplification. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3720 | if (!BB->getSinglePredecessor()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3721 | return nullptr; // BB must be dominated by the switch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3722 | |
| 3723 | BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3724 | if (!Branch || !Branch->isUnconditional()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3725 | return nullptr; // Terminator must be unconditional branch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3726 | |
| 3727 | BasicBlock *Succ = Branch->getSuccessor(0); |
| 3728 | |
| 3729 | BasicBlock::iterator I = Succ->begin(); |
| 3730 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3731 | int Idx = PHI->getBasicBlockIndex(BB); |
| 3732 | assert(Idx >= 0 && "PHI has no entry for predecessor?"); |
| 3733 | |
| 3734 | Value *InValue = PHI->getIncomingValue(Idx); |
| 3735 | if (InValue != CaseValue) continue; |
| 3736 | |
| 3737 | *PhiIndex = Idx; |
| 3738 | return PHI; |
| 3739 | } |
| 3740 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3741 | return nullptr; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3742 | } |
| 3743 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3744 | /// Try to forward the condition of a switch instruction to a phi node |
| 3745 | /// dominated by the switch, if that would mean that some of the destination |
| 3746 | /// blocks of the switch can be folded away. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3747 | /// Returns true if a change is made. |
| 3748 | static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { |
| 3749 | typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap; |
| 3750 | ForwardingNodesMap ForwardingNodes; |
| 3751 | |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3752 | for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3753 | ConstantInt *CaseValue = I.getCaseValue(); |
| 3754 | BasicBlock *CaseDest = I.getCaseSuccessor(); |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3755 | |
| 3756 | int PhiIndex; |
| 3757 | PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest, |
| 3758 | &PhiIndex); |
| 3759 | if (!PHI) continue; |
| 3760 | |
| 3761 | ForwardingNodes[PHI].push_back(PhiIndex); |
| 3762 | } |
| 3763 | |
| 3764 | bool Changed = false; |
| 3765 | |
| 3766 | for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), |
| 3767 | E = ForwardingNodes.end(); I != E; ++I) { |
| 3768 | PHINode *Phi = I->first; |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3769 | SmallVectorImpl<int> &Indexes = I->second; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3770 | |
| 3771 | if (Indexes.size() < 2) continue; |
| 3772 | |
| 3773 | for (size_t I = 0, E = Indexes.size(); I != E; ++I) |
| 3774 | Phi->setIncomingValue(Indexes[I], SI->getCondition()); |
| 3775 | Changed = true; |
| 3776 | } |
| 3777 | |
| 3778 | return Changed; |
| 3779 | } |
| 3780 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3781 | /// Return true if the backend will be able to handle |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3782 | /// initializing an array of constants like C. |
Hans Wennborg | 08238ad | 2012-09-07 08:22:57 +0000 | [diff] [blame] | 3783 | static bool ValidLookupTableConstant(Constant *C) { |
Hans Wennborg | 4dc8951 | 2014-06-20 00:38:12 +0000 | [diff] [blame] | 3784 | if (C->isThreadDependent()) |
| 3785 | return false; |
| 3786 | if (C->isDLLImportDependent()) |
| 3787 | return false; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3788 | |
Hans Wennborg | b03ebfb | 2014-06-26 00:30:52 +0000 | [diff] [blame] | 3789 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) |
| 3790 | return CE->isGEPWithNoNotionalOverIndexing(); |
| 3791 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3792 | return isa<ConstantFP>(C) || |
| 3793 | isa<ConstantInt>(C) || |
| 3794 | isa<ConstantPointerNull>(C) || |
| 3795 | isa<GlobalValue>(C) || |
| 3796 | isa<UndefValue>(C); |
| 3797 | } |
| 3798 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3799 | /// If V is a Constant, return it. Otherwise, try to look up |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3800 | /// its constant value in ConstantPool, returning 0 if it's not there. |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3801 | static Constant *LookupConstant(Value *V, |
| 3802 | const SmallDenseMap<Value*, Constant*>& ConstantPool) { |
| 3803 | if (Constant *C = dyn_cast<Constant>(V)) |
| 3804 | return C; |
| 3805 | return ConstantPool.lookup(V); |
| 3806 | } |
| 3807 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3808 | /// Try to fold instruction I into a constant. This works for |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3809 | /// simple instructions such as binary operations where both operands are |
| 3810 | /// constant or can be replaced by constants from the ConstantPool. Returns the |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3811 | /// resulting constant on success, 0 otherwise. |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3812 | static Constant * |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3813 | ConstantFold(Instruction *I, const DataLayout &DL, |
| 3814 | const SmallDenseMap<Value *, Constant *> &ConstantPool) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3815 | if (SelectInst *Select = dyn_cast<SelectInst>(I)) { |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3816 | Constant *A = LookupConstant(Select->getCondition(), ConstantPool); |
| 3817 | if (!A) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3818 | return nullptr; |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3819 | if (A->isAllOnesValue()) |
| 3820 | return LookupConstant(Select->getTrueValue(), ConstantPool); |
| 3821 | if (A->isNullValue()) |
| 3822 | return LookupConstant(Select->getFalseValue(), ConstantPool); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3823 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3824 | } |
| 3825 | |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3826 | SmallVector<Constant *, 4> COps; |
| 3827 | for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { |
| 3828 | if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) |
| 3829 | COps.push_back(A); |
| 3830 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3831 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3832 | } |
| 3833 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3834 | if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3835 | return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], |
| 3836 | COps[1], DL); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3837 | } |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3838 | |
| 3839 | return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3840 | } |
| 3841 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3842 | /// Try to determine the resulting constant values in phi nodes |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3843 | /// at the common destination basic block, *CommonDest, for one of the case |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3844 | /// destionations CaseDest corresponding to value CaseVal (0 for the default |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3845 | /// case), of a switch instruction SI. |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3846 | static bool |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3847 | GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3848 | BasicBlock **CommonDest, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3849 | SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, |
| 3850 | const DataLayout &DL) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3851 | // The block from which we enter the common destination. |
| 3852 | BasicBlock *Pred = SI->getParent(); |
| 3853 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3854 | // If CaseDest is empty except for some side-effect free instructions through |
| 3855 | // which we can constant-propagate the CaseVal, continue to its successor. |
| 3856 | SmallDenseMap<Value*, Constant*> ConstantPool; |
| 3857 | ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); |
| 3858 | for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; |
| 3859 | ++I) { |
| 3860 | if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { |
| 3861 | // If the terminator is a simple branch, continue to the next block. |
| 3862 | if (T->getNumSuccessors() != 1) |
| 3863 | return false; |
| 3864 | Pred = CaseDest; |
| 3865 | CaseDest = T->getSuccessor(0); |
| 3866 | } else if (isa<DbgInfoIntrinsic>(I)) { |
| 3867 | // Skip debug intrinsic. |
| 3868 | continue; |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3869 | } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3870 | // Instruction is side-effect free and constant. |
Hans Wennborg | dcc6e5b | 2015-01-09 22:13:31 +0000 | [diff] [blame] | 3871 | |
| 3872 | // If the instruction has uses outside this block or a phi node slot for |
| 3873 | // the block, it is not safe to bypass the instruction since it would then |
| 3874 | // no longer dominate all its uses. |
| 3875 | for (auto &Use : I->uses()) { |
| 3876 | User *User = Use.getUser(); |
| 3877 | if (Instruction *I = dyn_cast<Instruction>(User)) |
| 3878 | if (I->getParent() == CaseDest) |
| 3879 | continue; |
| 3880 | if (PHINode *Phi = dyn_cast<PHINode>(User)) |
| 3881 | if (Phi->getIncomingBlock(Use) == CaseDest) |
| 3882 | continue; |
| 3883 | return false; |
| 3884 | } |
| 3885 | |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 3886 | ConstantPool.insert(std::make_pair(&*I, C)); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3887 | } else { |
| 3888 | break; |
| 3889 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3890 | } |
| 3891 | |
| 3892 | // If we did not have a CommonDest before, use the current one. |
| 3893 | if (!*CommonDest) |
| 3894 | *CommonDest = CaseDest; |
| 3895 | // If the destination isn't the common one, abort. |
| 3896 | if (CaseDest != *CommonDest) |
| 3897 | return false; |
| 3898 | |
| 3899 | // Get the values for this case from phi nodes in the destination block. |
| 3900 | BasicBlock::iterator I = (*CommonDest)->begin(); |
| 3901 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3902 | int Idx = PHI->getBasicBlockIndex(Pred); |
| 3903 | if (Idx == -1) |
| 3904 | continue; |
| 3905 | |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3906 | Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx), |
| 3907 | ConstantPool); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3908 | if (!ConstVal) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3909 | return false; |
| 3910 | |
| 3911 | // Be conservative about which kinds of constants we support. |
| 3912 | if (!ValidLookupTableConstant(ConstVal)) |
| 3913 | return false; |
| 3914 | |
| 3915 | Res.push_back(std::make_pair(PHI, ConstVal)); |
| 3916 | } |
| 3917 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3918 | return Res.size() > 0; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3919 | } |
| 3920 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3921 | // Helper function used to add CaseVal to the list of cases that generate |
| 3922 | // Result. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3923 | static void MapCaseToResult(ConstantInt *CaseVal, |
| 3924 | SwitchCaseResultVectorTy &UniqueResults, |
| 3925 | Constant *Result) { |
| 3926 | for (auto &I : UniqueResults) { |
| 3927 | if (I.first == Result) { |
| 3928 | I.second.push_back(CaseVal); |
| 3929 | return; |
| 3930 | } |
| 3931 | } |
| 3932 | UniqueResults.push_back(std::make_pair(Result, |
| 3933 | SmallVector<ConstantInt*, 4>(1, CaseVal))); |
| 3934 | } |
| 3935 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3936 | // Helper function that initializes a map containing |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3937 | // results for the PHI node of the common destination block for a switch |
| 3938 | // instruction. Returns false if multiple PHI nodes have been found or if |
| 3939 | // there is not a common destination block for the switch. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3940 | static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, |
| 3941 | BasicBlock *&CommonDest, |
| 3942 | SwitchCaseResultVectorTy &UniqueResults, |
| 3943 | Constant *&DefaultResult, |
| 3944 | const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3945 | for (auto &I : SI->cases()) { |
| 3946 | ConstantInt *CaseVal = I.getCaseValue(); |
| 3947 | |
| 3948 | // Resulting value at phi nodes for this case value. |
| 3949 | SwitchCaseResultsTy Results; |
| 3950 | if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, |
| 3951 | DL)) |
| 3952 | return false; |
| 3953 | |
| 3954 | // Only one value per case is permitted |
| 3955 | if (Results.size() > 1) |
| 3956 | return false; |
| 3957 | MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); |
| 3958 | |
| 3959 | // Check the PHI consistency. |
| 3960 | if (!PHI) |
| 3961 | PHI = Results[0].first; |
| 3962 | else if (PHI != Results[0].first) |
| 3963 | return false; |
| 3964 | } |
| 3965 | // Find the default result value. |
| 3966 | SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; |
| 3967 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
| 3968 | GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, |
| 3969 | DL); |
| 3970 | // If the default value is not found abort unless the default destination |
| 3971 | // is unreachable. |
| 3972 | DefaultResult = |
| 3973 | DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; |
| 3974 | if ((!DefaultResult && |
| 3975 | !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) |
| 3976 | return false; |
| 3977 | |
| 3978 | return true; |
| 3979 | } |
| 3980 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 3981 | // Helper function that checks if it is possible to transform a switch with only |
| 3982 | // two cases (or two cases + default) that produces a result into a select. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3983 | // Example: |
| 3984 | // switch (a) { |
| 3985 | // case 10: %0 = icmp eq i32 %a, 10 |
| 3986 | // return 10; %1 = select i1 %0, i32 10, i32 4 |
| 3987 | // case 20: ----> %2 = icmp eq i32 %a, 20 |
| 3988 | // return 2; %3 = select i1 %2, i32 2, i32 %1 |
| 3989 | // default: |
| 3990 | // return 4; |
| 3991 | // } |
| 3992 | static Value * |
| 3993 | ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, |
| 3994 | Constant *DefaultResult, Value *Condition, |
| 3995 | IRBuilder<> &Builder) { |
| 3996 | assert(ResultVector.size() == 2 && |
| 3997 | "We should have exactly two unique results at this point"); |
| 3998 | // If we are selecting between only two cases transform into a simple |
| 3999 | // select or a two-way select if default is possible. |
| 4000 | if (ResultVector[0].second.size() == 1 && |
| 4001 | ResultVector[1].second.size() == 1) { |
| 4002 | ConstantInt *const FirstCase = ResultVector[0].second[0]; |
| 4003 | ConstantInt *const SecondCase = ResultVector[1].second[0]; |
| 4004 | |
| 4005 | bool DefaultCanTrigger = DefaultResult; |
| 4006 | Value *SelectValue = ResultVector[1].first; |
| 4007 | if (DefaultCanTrigger) { |
| 4008 | Value *const ValueCompare = |
| 4009 | Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); |
| 4010 | SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, |
| 4011 | DefaultResult, "switch.select"); |
| 4012 | } |
| 4013 | Value *const ValueCompare = |
| 4014 | Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); |
| 4015 | return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue, |
| 4016 | "switch.select"); |
| 4017 | } |
| 4018 | |
| 4019 | return nullptr; |
| 4020 | } |
| 4021 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4022 | // Helper function to cleanup a switch instruction that has been converted into |
| 4023 | // a select, fixing up PHI nodes and basic blocks. |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4024 | static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, |
| 4025 | Value *SelectValue, |
| 4026 | IRBuilder<> &Builder) { |
| 4027 | BasicBlock *SelectBB = SI->getParent(); |
| 4028 | while (PHI->getBasicBlockIndex(SelectBB) >= 0) |
| 4029 | PHI->removeIncomingValue(SelectBB); |
| 4030 | PHI->addIncoming(SelectValue, SelectBB); |
| 4031 | |
| 4032 | Builder.CreateBr(PHI->getParent()); |
| 4033 | |
| 4034 | // Remove the switch. |
| 4035 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
| 4036 | BasicBlock *Succ = SI->getSuccessor(i); |
| 4037 | |
| 4038 | if (Succ == PHI->getParent()) |
| 4039 | continue; |
| 4040 | Succ->removePredecessor(SelectBB); |
| 4041 | } |
| 4042 | SI->eraseFromParent(); |
| 4043 | } |
| 4044 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4045 | /// If the switch is only used to initialize one or more |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4046 | /// phi nodes in a common successor block with only two different |
| 4047 | /// constant values, replace the switch with select. |
| 4048 | static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4049 | AssumptionCache *AC, const DataLayout &DL) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4050 | Value *const Cond = SI->getCondition(); |
| 4051 | PHINode *PHI = nullptr; |
| 4052 | BasicBlock *CommonDest = nullptr; |
| 4053 | Constant *DefaultResult; |
| 4054 | SwitchCaseResultVectorTy UniqueResults; |
| 4055 | // Collect all the cases that will deliver the same value from the switch. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4056 | if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, |
| 4057 | DL)) |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4058 | return false; |
| 4059 | // Selects choose between maximum two values. |
| 4060 | if (UniqueResults.size() != 2) |
| 4061 | return false; |
| 4062 | assert(PHI != nullptr && "PHI for value select not found"); |
| 4063 | |
| 4064 | Builder.SetInsertPoint(SI); |
| 4065 | Value *SelectValue = ConvertTwoCaseSwitch( |
| 4066 | UniqueResults, |
| 4067 | DefaultResult, Cond, Builder); |
| 4068 | if (SelectValue) { |
| 4069 | RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); |
| 4070 | return true; |
| 4071 | } |
| 4072 | // The switch couldn't be converted into a select. |
| 4073 | return false; |
| 4074 | } |
| 4075 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4076 | namespace { |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4077 | /// This class represents a lookup table that can be used to replace a switch. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4078 | class SwitchLookupTable { |
| 4079 | public: |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4080 | /// Create a lookup table to use as a switch replacement with the contents |
| 4081 | /// of Values, using DefaultValue to fill any holes in the table. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4082 | SwitchLookupTable( |
| 4083 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 4084 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 4085 | Constant *DefaultValue, const DataLayout &DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4086 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4087 | /// Build instructions with Builder to retrieve the value at |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4088 | /// the position given by Index in the lookup table. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4089 | Value *BuildLookup(Value *Index, IRBuilder<> &Builder); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4090 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4091 | /// Return true if a table with TableSize elements of |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4092 | /// type ElementType would fit in a target-legal register. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4093 | static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 4094 | Type *ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4095 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4096 | private: |
| 4097 | // Depending on the contents of the table, it can be represented in |
| 4098 | // different ways. |
| 4099 | enum { |
| 4100 | // For tables where each element contains the same value, we just have to |
| 4101 | // store that single value and return it for each lookup. |
| 4102 | SingleValueKind, |
| 4103 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4104 | // For tables where there is a linear relationship between table index |
| 4105 | // and values. We calculate the result with a simple multiplication |
| 4106 | // and addition instead of a table lookup. |
| 4107 | LinearMapKind, |
| 4108 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4109 | // For small tables with integer elements, we can pack them into a bitmap |
| 4110 | // that fits into a target-legal register. Values are retrieved by |
| 4111 | // shift and mask operations. |
| 4112 | BitMapKind, |
| 4113 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4114 | // The table is stored as an array of values. Values are retrieved by load |
| 4115 | // instructions from the table. |
| 4116 | ArrayKind |
| 4117 | } Kind; |
| 4118 | |
| 4119 | // For SingleValueKind, this is the single value. |
| 4120 | Constant *SingleValue; |
| 4121 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4122 | // For BitMapKind, this is the bitmap. |
| 4123 | ConstantInt *BitMap; |
| 4124 | IntegerType *BitMapElementTy; |
| 4125 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4126 | // For LinearMapKind, these are the constants used to derive the value. |
| 4127 | ConstantInt *LinearOffset; |
| 4128 | ConstantInt *LinearMultiplier; |
| 4129 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4130 | // For ArrayKind, this is the array. |
| 4131 | GlobalVariable *Array; |
| 4132 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 4133 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4134 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4135 | SwitchLookupTable::SwitchLookupTable( |
| 4136 | Module &M, uint64_t TableSize, ConstantInt *Offset, |
| 4137 | const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, |
| 4138 | Constant *DefaultValue, const DataLayout &DL) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4139 | : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4140 | LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 4141 | assert(Values.size() && "Can't build lookup table without values!"); |
| 4142 | assert(TableSize >= Values.size() && "Can't fit values in table!"); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4143 | |
| 4144 | // If all values in the table are equal, this is that value. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4145 | SingleValue = Values.begin()->second; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4146 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4147 | Type *ValueType = Values.begin()->second->getType(); |
| 4148 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4149 | // Build up the table contents. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4150 | SmallVector<Constant*, 64> TableContents(TableSize); |
| 4151 | for (size_t I = 0, E = Values.size(); I != E; ++I) { |
| 4152 | ConstantInt *CaseVal = Values[I].first; |
| 4153 | Constant *CaseRes = Values[I].second; |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4154 | assert(CaseRes->getType() == ValueType); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4155 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4156 | uint64_t Idx = (CaseVal->getValue() - Offset->getValue()) |
| 4157 | .getLimitedValue(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4158 | TableContents[Idx] = CaseRes; |
| 4159 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4160 | if (CaseRes != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4161 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4162 | } |
| 4163 | |
| 4164 | // Fill in any holes in the table with the default result. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4165 | if (Values.size() < TableSize) { |
Marcello Maggioni | 89c05ad | 2014-07-03 08:29:06 +0000 | [diff] [blame] | 4166 | assert(DefaultValue && |
| 4167 | "Need a default value to fill the lookup table holes."); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4168 | assert(DefaultValue->getType() == ValueType); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4169 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 4170 | if (!TableContents[I]) |
| 4171 | TableContents[I] = DefaultValue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4172 | } |
| 4173 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4174 | if (DefaultValue != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4175 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4176 | } |
| 4177 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4178 | // If each element in the table contains the same value, we only need to store |
| 4179 | // that single value. |
| 4180 | if (SingleValue) { |
| 4181 | Kind = SingleValueKind; |
| 4182 | return; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4183 | } |
| 4184 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4185 | // Check if we can derive the value with a linear transformation from the |
| 4186 | // table index. |
| 4187 | if (isa<IntegerType>(ValueType)) { |
| 4188 | bool LinearMappingPossible = true; |
| 4189 | APInt PrevVal; |
| 4190 | APInt DistToPrev; |
| 4191 | assert(TableSize >= 2 && "Should be a SingleValue table."); |
| 4192 | // Check if there is the same distance between two consecutive values. |
| 4193 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 4194 | ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); |
| 4195 | if (!ConstVal) { |
| 4196 | // This is an undef. We could deal with it, but undefs in lookup tables |
| 4197 | // are very seldom. It's probably not worth the additional complexity. |
| 4198 | LinearMappingPossible = false; |
| 4199 | break; |
| 4200 | } |
| 4201 | APInt Val = ConstVal->getValue(); |
| 4202 | if (I != 0) { |
| 4203 | APInt Dist = Val - PrevVal; |
| 4204 | if (I == 1) { |
| 4205 | DistToPrev = Dist; |
| 4206 | } else if (Dist != DistToPrev) { |
| 4207 | LinearMappingPossible = false; |
| 4208 | break; |
| 4209 | } |
| 4210 | } |
| 4211 | PrevVal = Val; |
| 4212 | } |
| 4213 | if (LinearMappingPossible) { |
| 4214 | LinearOffset = cast<ConstantInt>(TableContents[0]); |
| 4215 | LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); |
| 4216 | Kind = LinearMapKind; |
| 4217 | ++NumLinearMaps; |
| 4218 | return; |
| 4219 | } |
| 4220 | } |
| 4221 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4222 | // If the type is integer and the table fits in a register, build a bitmap. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4223 | if (WouldFitInRegister(DL, TableSize, ValueType)) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4224 | IntegerType *IT = cast<IntegerType>(ValueType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4225 | APInt TableInt(TableSize * IT->getBitWidth(), 0); |
| 4226 | for (uint64_t I = TableSize; I > 0; --I) { |
| 4227 | TableInt <<= IT->getBitWidth(); |
Benjamin Kramer | 9fc3dc7 | 2012-10-01 11:31:48 +0000 | [diff] [blame] | 4228 | // Insert values into the bitmap. Undef values are set to zero. |
| 4229 | if (!isa<UndefValue>(TableContents[I - 1])) { |
| 4230 | ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); |
| 4231 | TableInt |= Val->getValue().zext(TableInt.getBitWidth()); |
| 4232 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4233 | } |
| 4234 | BitMap = ConstantInt::get(M.getContext(), TableInt); |
| 4235 | BitMapElementTy = IT; |
| 4236 | Kind = BitMapKind; |
| 4237 | ++NumBitMaps; |
| 4238 | return; |
| 4239 | } |
| 4240 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4241 | // Store the table in an array. |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4242 | ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4243 | Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); |
| 4244 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4245 | Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true, |
| 4246 | GlobalVariable::PrivateLinkage, |
| 4247 | Initializer, |
| 4248 | "switch.table"); |
| 4249 | Array->setUnnamedAddr(true); |
| 4250 | Kind = ArrayKind; |
| 4251 | } |
| 4252 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4253 | Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4254 | switch (Kind) { |
| 4255 | case SingleValueKind: |
| 4256 | return SingleValue; |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 4257 | case LinearMapKind: { |
| 4258 | // Derive the result value from the input value. |
| 4259 | Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), |
| 4260 | false, "switch.idx.cast"); |
| 4261 | if (!LinearMultiplier->isOne()) |
| 4262 | Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); |
| 4263 | if (!LinearOffset->isZero()) |
| 4264 | Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); |
| 4265 | return Result; |
| 4266 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4267 | case BitMapKind: { |
| 4268 | // Type of the bitmap (e.g. i59). |
| 4269 | IntegerType *MapTy = BitMap->getType(); |
| 4270 | |
| 4271 | // Cast Index to the same type as the bitmap. |
| 4272 | // Note: The Index is <= the number of elements in the table, so |
| 4273 | // truncating it to the width of the bitmask is safe. |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 4274 | Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4275 | |
| 4276 | // Multiply the shift amount by the element width. |
| 4277 | ShiftAmt = Builder.CreateMul(ShiftAmt, |
| 4278 | ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), |
| 4279 | "switch.shiftamt"); |
| 4280 | |
| 4281 | // Shift down. |
| 4282 | Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt, |
| 4283 | "switch.downshift"); |
| 4284 | // Mask off. |
| 4285 | return Builder.CreateTrunc(DownShifted, BitMapElementTy, |
| 4286 | "switch.masked"); |
| 4287 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4288 | case ArrayKind: { |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4289 | // Make sure the table index will not overflow when treated as signed. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4290 | IntegerType *IT = cast<IntegerType>(Index->getType()); |
| 4291 | uint64_t TableSize = Array->getInitializer()->getType() |
| 4292 | ->getArrayNumElements(); |
| 4293 | if (TableSize > (1ULL << (IT->getBitWidth() - 1))) |
| 4294 | Index = Builder.CreateZExt(Index, |
| 4295 | IntegerType::get(IT->getContext(), |
| 4296 | IT->getBitWidth() + 1), |
| 4297 | "switch.tableidx.zext"); |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4298 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4299 | Value *GEPIndices[] = { Builder.getInt32(0), Index }; |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 4300 | Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, |
| 4301 | GEPIndices, "switch.gep"); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4302 | return Builder.CreateLoad(GEP, "switch.load"); |
| 4303 | } |
| 4304 | } |
| 4305 | llvm_unreachable("Unknown lookup table kind!"); |
| 4306 | } |
| 4307 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4308 | bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4309 | uint64_t TableSize, |
Craig Topper | e3dcce9 | 2015-08-01 22:20:21 +0000 | [diff] [blame] | 4310 | Type *ElementType) { |
| 4311 | auto *IT = dyn_cast<IntegerType>(ElementType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4312 | if (!IT) |
| 4313 | return false; |
| 4314 | // FIXME: If the type is wider than it needs to be, e.g. i8 but all values |
| 4315 | // are <= 15, we could try to narrow the type. |
Benjamin Kramer | c2081d1 | 2012-09-27 18:29:58 +0000 | [diff] [blame] | 4316 | |
| 4317 | // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. |
| 4318 | if (TableSize >= UINT_MAX/IT->getBitWidth()) |
| 4319 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4320 | return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4321 | } |
| 4322 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4323 | /// Determine whether a lookup table should be built for this switch, based on |
| 4324 | /// the number of cases, size of the table, and the types of the results. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4325 | static bool |
| 4326 | ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, |
| 4327 | const TargetTransformInfo &TTI, const DataLayout &DL, |
| 4328 | const SmallDenseMap<PHINode *, Type *> &ResultTypes) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 4329 | if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) |
| 4330 | return false; // TableSize overflowed, or mul below might overflow. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4331 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4332 | bool AllTablesFitInRegister = true; |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4333 | bool HasIllegalType = false; |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4334 | for (const auto &I : ResultTypes) { |
| 4335 | Type *Ty = I.second; |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4336 | |
| 4337 | // Saturate this flag to true. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4338 | HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4339 | |
| 4340 | // Saturate this flag to false. |
| 4341 | AllTablesFitInRegister = AllTablesFitInRegister && |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4342 | SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 4343 | |
| 4344 | // If both flags saturate, we're done. NOTE: This *only* works with |
| 4345 | // saturating flags, and all flags have to saturate first due to the |
| 4346 | // non-deterministic behavior of iterating over a dense map. |
| 4347 | if (HasIllegalType && !AllTablesFitInRegister) |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4348 | break; |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4349 | } |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 4350 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 4351 | // If each table would fit in a register, we should build it anyway. |
| 4352 | if (AllTablesFitInRegister) |
| 4353 | return true; |
| 4354 | |
| 4355 | // Don't build a table that doesn't fit in-register if it has illegal types. |
| 4356 | if (HasIllegalType) |
| 4357 | return false; |
| 4358 | |
| 4359 | // The table density should be at least 40%. This is the same criterion as for |
| 4360 | // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. |
| 4361 | // FIXME: Find the best cut-off. |
| 4362 | return SI->getNumCases() * 10 >= TableSize * 4; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4363 | } |
| 4364 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4365 | /// Try to reuse the switch table index compare. Following pattern: |
| 4366 | /// \code |
| 4367 | /// if (idx < tablesize) |
| 4368 | /// r = table[idx]; // table does not contain default_value |
| 4369 | /// else |
| 4370 | /// r = default_value; |
| 4371 | /// if (r != default_value) |
| 4372 | /// ... |
| 4373 | /// \endcode |
| 4374 | /// Is optimized to: |
| 4375 | /// \code |
| 4376 | /// cond = idx < tablesize; |
| 4377 | /// if (cond) |
| 4378 | /// r = table[idx]; |
| 4379 | /// else |
| 4380 | /// r = default_value; |
| 4381 | /// if (cond) |
| 4382 | /// ... |
| 4383 | /// \endcode |
| 4384 | /// Jump threading will then eliminate the second if(cond). |
| 4385 | static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, |
| 4386 | BranchInst *RangeCheckBranch, Constant *DefaultValue, |
| 4387 | const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) { |
| 4388 | |
| 4389 | ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); |
| 4390 | if (!CmpInst) |
| 4391 | return; |
| 4392 | |
| 4393 | // We require that the compare is in the same block as the phi so that jump |
| 4394 | // threading can do its work afterwards. |
| 4395 | if (CmpInst->getParent() != PhiBlock) |
| 4396 | return; |
| 4397 | |
| 4398 | Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); |
| 4399 | if (!CmpOp1) |
| 4400 | return; |
| 4401 | |
| 4402 | Value *RangeCmp = RangeCheckBranch->getCondition(); |
| 4403 | Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); |
| 4404 | Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); |
| 4405 | |
| 4406 | // Check if the compare with the default value is constant true or false. |
| 4407 | Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4408 | DefaultValue, CmpOp1, true); |
| 4409 | if (DefaultConst != TrueConst && DefaultConst != FalseConst) |
| 4410 | return; |
| 4411 | |
| 4412 | // Check if the compare with the case values is distinct from the default |
| 4413 | // compare result. |
| 4414 | for (auto ValuePair : Values) { |
| 4415 | Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4416 | ValuePair.second, CmpOp1, true); |
| 4417 | if (!CaseConst || CaseConst == DefaultConst) |
| 4418 | return; |
| 4419 | assert((CaseConst == TrueConst || CaseConst == FalseConst) && |
| 4420 | "Expect true or false as compare result."); |
| 4421 | } |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 4422 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4423 | // Check if the branch instruction dominates the phi node. It's a simple |
| 4424 | // dominance check, but sufficient for our needs. |
| 4425 | // Although this check is invariant in the calling loops, it's better to do it |
| 4426 | // at this late stage. Practically we do it at most once for a switch. |
| 4427 | BasicBlock *BranchBlock = RangeCheckBranch->getParent(); |
| 4428 | for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { |
| 4429 | BasicBlock *Pred = *PI; |
| 4430 | if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) |
| 4431 | return; |
| 4432 | } |
| 4433 | |
| 4434 | if (DefaultConst == FalseConst) { |
| 4435 | // The compare yields the same result. We can replace it. |
| 4436 | CmpInst->replaceAllUsesWith(RangeCmp); |
| 4437 | ++NumTableCmpReuses; |
| 4438 | } else { |
| 4439 | // The compare yields the same result, just inverted. We can replace it. |
| 4440 | Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp, |
| 4441 | ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", |
| 4442 | RangeCheckBranch); |
| 4443 | CmpInst->replaceAllUsesWith(InvertedTableCmp); |
| 4444 | ++NumTableCmpReuses; |
| 4445 | } |
| 4446 | } |
| 4447 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 4448 | /// If the switch is only used to initialize one or more phi nodes in a common |
| 4449 | /// successor block with different constant values, replace the switch with |
| 4450 | /// lookup tables. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4451 | static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, |
| 4452 | const DataLayout &DL, |
| 4453 | const TargetTransformInfo &TTI) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4454 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4455 | |
Hans Wennborg | c3c8d95 | 2012-11-07 21:35:12 +0000 | [diff] [blame] | 4456 | // Only build lookup table when we have a target that supports it. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4457 | if (!TTI.shouldBuildLookupTables()) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4458 | return false; |
| 4459 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4460 | // FIXME: If the switch is too sparse for a lookup table, perhaps we could |
| 4461 | // split off a dense part and build a lookup table for that. |
| 4462 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4463 | // FIXME: This creates arrays of GEPs to constant strings, which means each |
| 4464 | // GEP needs a runtime relocation in PIC code. We should just build one big |
| 4465 | // string and lookup indices into that. |
| 4466 | |
Hans Wennborg | 4744ac1 | 2014-01-15 05:00:27 +0000 | [diff] [blame] | 4467 | // Ignore switches with less than three cases. Lookup tables will not make them |
| 4468 | // faster, so we don't analyze them. |
| 4469 | if (SI->getNumCases() < 3) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4470 | return false; |
| 4471 | |
| 4472 | // Figure out the corresponding result for each case value and phi node in the |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 4473 | // common destination, as well as the min and max case values. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4474 | assert(SI->case_begin() != SI->case_end()); |
| 4475 | SwitchInst::CaseIt CI = SI->case_begin(); |
| 4476 | ConstantInt *MinCaseVal = CI.getCaseValue(); |
| 4477 | ConstantInt *MaxCaseVal = CI.getCaseValue(); |
| 4478 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4479 | BasicBlock *CommonDest = nullptr; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4480 | typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4481 | SmallDenseMap<PHINode*, ResultListTy> ResultLists; |
| 4482 | SmallDenseMap<PHINode*, Constant*> DefaultResults; |
| 4483 | SmallDenseMap<PHINode*, Type*> ResultTypes; |
| 4484 | SmallVector<PHINode*, 4> PHIs; |
| 4485 | |
| 4486 | for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { |
| 4487 | ConstantInt *CaseVal = CI.getCaseValue(); |
| 4488 | if (CaseVal->getValue().slt(MinCaseVal->getValue())) |
| 4489 | MinCaseVal = CaseVal; |
| 4490 | if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) |
| 4491 | MaxCaseVal = CaseVal; |
| 4492 | |
| 4493 | // Resulting value at phi nodes for this case value. |
| 4494 | typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy; |
| 4495 | ResultsTy Results; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4496 | if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4497 | Results, DL)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4498 | return false; |
| 4499 | |
| 4500 | // Append the result from this case to the list for each phi. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4501 | for (const auto &I : Results) { |
| 4502 | PHINode *PHI = I.first; |
| 4503 | Constant *Value = I.second; |
| 4504 | if (!ResultLists.count(PHI)) |
| 4505 | PHIs.push_back(PHI); |
| 4506 | ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4507 | } |
| 4508 | } |
| 4509 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4510 | // Keep track of the result types. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4511 | for (PHINode *PHI : PHIs) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4512 | ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); |
| 4513 | } |
| 4514 | |
| 4515 | uint64_t NumResults = ResultLists[PHIs[0]].size(); |
| 4516 | APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); |
| 4517 | uint64_t TableSize = RangeSpread.getLimitedValue() + 1; |
| 4518 | bool TableHasHoles = (NumResults < TableSize); |
| 4519 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4520 | // If the table has holes, we need a constant result for the default case |
| 4521 | // or a bitmask that fits in a register. |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4522 | SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4523 | bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(), |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4524 | &CommonDest, DefaultResultsList, DL); |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4525 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4526 | bool NeedMask = (TableHasHoles && !HasDefaultResults); |
| 4527 | if (NeedMask) { |
| 4528 | // As an extra penalty for the validity test we require more cases. |
| 4529 | if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). |
| 4530 | return false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4531 | if (!DL.fitsInLegalInteger(TableSize)) |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4532 | return false; |
| 4533 | } |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4534 | |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4535 | for (const auto &I : DefaultResultsList) { |
| 4536 | PHINode *PHI = I.first; |
| 4537 | Constant *Result = I.second; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4538 | DefaultResults[PHI] = Result; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4539 | } |
| 4540 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4541 | if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4542 | return false; |
| 4543 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4544 | // Create the BB that does the lookups. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4545 | Module &Mod = *CommonDest->getParent()->getParent(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4546 | BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4547 | "switch.lookup", |
| 4548 | CommonDest->getParent(), |
| 4549 | CommonDest); |
| 4550 | |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4551 | // Compute the table index value. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4552 | Builder.SetInsertPoint(SI); |
| 4553 | Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, |
| 4554 | "switch.tableidx"); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4555 | |
| 4556 | // Compute the maximum table size representable by the integer type we are |
| 4557 | // switching upon. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4558 | unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4559 | uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4560 | assert(MaxTableSize >= TableSize && |
| 4561 | "It is impossible for a switch to have more entries than the max " |
| 4562 | "representable value of its input integer type's size."); |
| 4563 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 4564 | // If the default destination is unreachable, or if the lookup table covers |
| 4565 | // all values of the conditional variable, branch directly to the lookup table |
| 4566 | // BB. Otherwise, check that the condition is within the case range. |
| 4567 | const bool DefaultIsReachable = |
| 4568 | !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); |
| 4569 | const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4570 | BranchInst *RangeCheckBranch = nullptr; |
| 4571 | |
Hans Wennborg | b64cb27 | 2015-01-26 19:52:34 +0000 | [diff] [blame] | 4572 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4573 | Builder.CreateBr(LookupBB); |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 4574 | // Note: We call removeProdecessor later since we need to be able to get the |
| 4575 | // PHI value for the default case in case we're using a bit mask. |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4576 | } else { |
| 4577 | Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get( |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4578 | MinCaseVal->getType(), TableSize)); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4579 | RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4580 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4581 | |
| 4582 | // Populate the BB that does the lookups. |
| 4583 | Builder.SetInsertPoint(LookupBB); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4584 | |
| 4585 | if (NeedMask) { |
| 4586 | // Before doing the lookup we do the hole check. |
| 4587 | // The LookupBB is therefore re-purposed to do the hole check |
| 4588 | // and we create a new LookupBB. |
| 4589 | BasicBlock *MaskBB = LookupBB; |
| 4590 | MaskBB->setName("switch.hole_check"); |
| 4591 | LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4592 | "switch.lookup", |
| 4593 | CommonDest->getParent(), |
| 4594 | CommonDest); |
| 4595 | |
Juergen Ributzka | c9591e9 | 2014-11-17 19:39:56 +0000 | [diff] [blame] | 4596 | // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid |
| 4597 | // unnecessary illegal types. |
| 4598 | uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); |
| 4599 | APInt MaskInt(TableSizePowOf2, 0); |
| 4600 | APInt One(TableSizePowOf2, 1); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4601 | // Build bitmask; fill in a 1 bit for every case. |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4602 | const ResultListTy &ResultList = ResultLists[PHIs[0]]; |
| 4603 | for (size_t I = 0, E = ResultList.size(); I != E; ++I) { |
| 4604 | uint64_t Idx = (ResultList[I].first->getValue() - |
| 4605 | MinCaseVal->getValue()).getLimitedValue(); |
| 4606 | MaskInt |= One << Idx; |
| 4607 | } |
| 4608 | ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); |
| 4609 | |
| 4610 | // Get the TableIndex'th bit of the bitmask. |
| 4611 | // If this bit is 0 (meaning hole) jump to the default destination, |
| 4612 | // else continue with table lookup. |
| 4613 | IntegerType *MapTy = TableMask->getType(); |
| 4614 | Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy, |
| 4615 | "switch.maskindex"); |
| 4616 | Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, |
| 4617 | "switch.shifted"); |
| 4618 | Value *LoBit = Builder.CreateTrunc(Shifted, |
| 4619 | Type::getInt1Ty(Mod.getContext()), |
| 4620 | "switch.lobit"); |
| 4621 | Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); |
| 4622 | |
| 4623 | Builder.SetInsertPoint(LookupBB); |
| 4624 | AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); |
| 4625 | } |
| 4626 | |
Hans Wennborg | 86ac630 | 2015-04-24 20:57:56 +0000 | [diff] [blame] | 4627 | if (!DefaultIsReachable || GeneratingCoveredLookupTable) { |
| 4628 | // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, |
| 4629 | // do not delete PHINodes here. |
| 4630 | SI->getDefaultDest()->removePredecessor(SI->getParent(), |
| 4631 | /*DontDeleteUselessPHIs=*/true); |
| 4632 | } |
| 4633 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4634 | bool ReturnedEarly = false; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4635 | for (size_t I = 0, E = PHIs.size(); I != E; ++I) { |
| 4636 | PHINode *PHI = PHIs[I]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4637 | const ResultListTy &ResultList = ResultLists[PHI]; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4638 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4639 | // If using a bitmask, use any value to fill the lookup table holes. |
| 4640 | Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4641 | SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4642 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4643 | Value *Result = Table.BuildLookup(TableIndex, Builder); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4644 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4645 | // If the result is used to return immediately from the function, we want to |
| 4646 | // do that right here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4647 | if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && |
| 4648 | PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4649 | Builder.CreateRet(Result); |
| 4650 | ReturnedEarly = true; |
| 4651 | break; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4652 | } |
| 4653 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4654 | // Do a small peephole optimization: re-use the switch table compare if |
| 4655 | // possible. |
| 4656 | if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { |
| 4657 | BasicBlock *PhiBlock = PHI->getParent(); |
| 4658 | // Search for compare instructions which use the phi. |
| 4659 | for (auto *User : PHI->users()) { |
| 4660 | reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); |
| 4661 | } |
| 4662 | } |
| 4663 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4664 | PHI->addIncoming(Result, LookupBB); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4665 | } |
| 4666 | |
| 4667 | if (!ReturnedEarly) |
| 4668 | Builder.CreateBr(CommonDest); |
| 4669 | |
| 4670 | // Remove the switch. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4671 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4672 | BasicBlock *Succ = SI->getSuccessor(i); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4673 | |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4674 | if (Succ == SI->getDefaultDest()) |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4675 | continue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4676 | Succ->removePredecessor(SI->getParent()); |
| 4677 | } |
| 4678 | SI->eraseFromParent(); |
| 4679 | |
| 4680 | ++NumLookupTables; |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4681 | if (NeedMask) |
| 4682 | ++NumLookupTablesHoles; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4683 | return true; |
| 4684 | } |
| 4685 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4686 | bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4687 | BasicBlock *BB = SI->getParent(); |
| 4688 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4689 | if (isValueEqualityComparison(SI)) { |
| 4690 | // If we only have one predecessor, and if it is a branch on this value, |
| 4691 | // see if that predecessor totally determines the outcome of this switch. |
| 4692 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 4693 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4694 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4695 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4696 | Value *Cond = SI->getCondition(); |
| 4697 | if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) |
| 4698 | if (SimplifySwitchOnSelect(SI, Select)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4699 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4700 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4701 | // If the block only contains the switch, see if we can fold the block |
| 4702 | // away into any preds. |
| 4703 | BasicBlock::iterator BBI = BB->begin(); |
| 4704 | // Ignore dbg intrinsics. |
| 4705 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 4706 | ++BBI; |
| 4707 | if (SI == &*BBI) |
| 4708 | if (FoldValueComparisonIntoPredecessors(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4709 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4710 | } |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4711 | |
| 4712 | // Try to transform the switch into an icmp and a branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4713 | if (TurnSwitchRangeIntoICmp(SI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4714 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4715 | |
| 4716 | // Remove unreachable cases. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4717 | if (EliminateDeadSwitchCases(SI, AC, DL)) |
| 4718 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4719 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4720 | if (SwitchToSelect(SI, Builder, AC, DL)) |
| 4721 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4722 | |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4723 | if (ForwardSwitchConditionToPHI(SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4724 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4725 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4726 | if (SwitchToLookupTable(SI, Builder, DL, TTI)) |
| 4727 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4728 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4729 | return false; |
| 4730 | } |
| 4731 | |
| 4732 | bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { |
| 4733 | BasicBlock *BB = IBI->getParent(); |
| 4734 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4735 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4736 | // Eliminate redundant destinations. |
| 4737 | SmallPtrSet<Value *, 8> Succs; |
| 4738 | for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { |
| 4739 | BasicBlock *Dest = IBI->getDestination(i); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4740 | if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4741 | Dest->removePredecessor(BB); |
| 4742 | IBI->removeDestination(i); |
| 4743 | --i; --e; |
| 4744 | Changed = true; |
| 4745 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4746 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4747 | |
| 4748 | if (IBI->getNumDestinations() == 0) { |
| 4749 | // If the indirectbr has no successors, change it to unreachable. |
| 4750 | new UnreachableInst(IBI->getContext(), IBI); |
| 4751 | EraseTerminatorInstAndDCECond(IBI); |
| 4752 | return true; |
| 4753 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4754 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4755 | if (IBI->getNumDestinations() == 1) { |
| 4756 | // If the indirectbr has one successor, change it to a direct branch. |
| 4757 | BranchInst::Create(IBI->getDestination(0), IBI); |
| 4758 | EraseTerminatorInstAndDCECond(IBI); |
| 4759 | return true; |
| 4760 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4761 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4762 | if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { |
| 4763 | if (SimplifyIndirectBrOnSelect(IBI, SI)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4764 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4765 | } |
| 4766 | return Changed; |
| 4767 | } |
| 4768 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 4769 | /// Given an block with only a single landing pad and a unconditional branch |
| 4770 | /// try to find another basic block which this one can be merged with. This |
| 4771 | /// handles cases where we have multiple invokes with unique landing pads, but |
| 4772 | /// a shared handler. |
| 4773 | /// |
| 4774 | /// We specifically choose to not worry about merging non-empty blocks |
| 4775 | /// here. That is a PRE/scheduling problem and is best solved elsewhere. In |
| 4776 | /// practice, the optimizer produces empty landing pad blocks quite frequently |
| 4777 | /// when dealing with exception dense code. (see: instcombine, gvn, if-else |
| 4778 | /// sinking in this file) |
| 4779 | /// |
| 4780 | /// This is primarily a code size optimization. We need to avoid performing |
| 4781 | /// any transform which might inhibit optimization (such as our ability to |
| 4782 | /// specialize a particular handler via tail commoning). We do this by not |
| 4783 | /// merging any blocks which require us to introduce a phi. Since the same |
| 4784 | /// values are flowing through both blocks, we don't loose any ability to |
| 4785 | /// specialize. If anything, we make such specialization more likely. |
| 4786 | /// |
| 4787 | /// TODO - This transformation could remove entries from a phi in the target |
| 4788 | /// block when the inputs in the phi are the same for the two blocks being |
| 4789 | /// merged. In some cases, this could result in removal of the PHI entirely. |
| 4790 | static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, |
| 4791 | BasicBlock *BB) { |
| 4792 | auto Succ = BB->getUniqueSuccessor(); |
| 4793 | assert(Succ); |
| 4794 | // If there's a phi in the successor block, we'd likely have to introduce |
| 4795 | // a phi into the merged landing pad block. |
| 4796 | if (isa<PHINode>(*Succ->begin())) |
| 4797 | return false; |
| 4798 | |
| 4799 | for (BasicBlock *OtherPred : predecessors(Succ)) { |
| 4800 | if (BB == OtherPred) |
| 4801 | continue; |
| 4802 | BasicBlock::iterator I = OtherPred->begin(); |
| 4803 | LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); |
| 4804 | if (!LPad2 || !LPad2->isIdenticalTo(LPad)) |
| 4805 | continue; |
| 4806 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) {} |
| 4807 | BranchInst *BI2 = dyn_cast<BranchInst>(I); |
| 4808 | if (!BI2 || !BI2->isIdenticalTo(BI)) |
| 4809 | continue; |
| 4810 | |
| 4811 | // We've found an identical block. Update our predeccessors to take that |
| 4812 | // path instead and make ourselves dead. |
| 4813 | SmallSet<BasicBlock *, 16> Preds; |
| 4814 | Preds.insert(pred_begin(BB), pred_end(BB)); |
| 4815 | for (BasicBlock *Pred : Preds) { |
| 4816 | InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); |
| 4817 | assert(II->getNormalDest() != BB && |
| 4818 | II->getUnwindDest() == BB && "unexpected successor"); |
| 4819 | II->setUnwindDest(OtherPred); |
| 4820 | } |
| 4821 | |
| 4822 | // The debug info in OtherPred doesn't cover the merged control flow that |
| 4823 | // used to go through BB. We need to delete it or update it. |
| 4824 | for (auto I = OtherPred->begin(), E = OtherPred->end(); |
| 4825 | I != E;) { |
| 4826 | Instruction &Inst = *I; I++; |
| 4827 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 4828 | Inst.eraseFromParent(); |
| 4829 | } |
| 4830 | |
| 4831 | SmallSet<BasicBlock *, 16> Succs; |
| 4832 | Succs.insert(succ_begin(BB), succ_end(BB)); |
| 4833 | for (BasicBlock *Succ : Succs) { |
| 4834 | Succ->removePredecessor(BB); |
| 4835 | } |
| 4836 | |
| 4837 | IRBuilder<> Builder(BI); |
| 4838 | Builder.CreateUnreachable(); |
| 4839 | BI->eraseFromParent(); |
| 4840 | return true; |
| 4841 | } |
| 4842 | return false; |
| 4843 | } |
| 4844 | |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 4845 | bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){ |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4846 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4847 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 4848 | if (SinkCommon && SinkThenElseCodeToEnd(BI)) |
| 4849 | return true; |
| 4850 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4851 | // If the Terminator is the only non-phi instruction, simplify the block. |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 4852 | BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4853 | if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && |
| 4854 | TryToSimplifyUncondBranchFromEmptyBlock(BB)) |
| 4855 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4856 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4857 | // If the only instruction in the block is a seteq/setne comparison |
| 4858 | // against a constant, try to simplify the block. |
| 4859 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) |
| 4860 | if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { |
| 4861 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) |
| 4862 | ; |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 4863 | if (I->isTerminator() && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4864 | TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, |
| 4865 | BonusInstThreshold, AC)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4866 | return true; |
| 4867 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4868 | |
Philip Reames | 2b969d7 | 2015-03-24 22:28:45 +0000 | [diff] [blame] | 4869 | // See if we can merge an empty landing pad block with another which is |
| 4870 | // equivalent. |
| 4871 | if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { |
| 4872 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) {} |
| 4873 | if (I->isTerminator() && |
| 4874 | TryToMergeLandingPad(LPad, BI, BB)) |
| 4875 | return true; |
| 4876 | } |
| 4877 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 4878 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4879 | // branches to us and our successor, fold the comparison into the |
| 4880 | // predecessor and use logical operations to update the incoming value |
| 4881 | // for PHI nodes in common successor. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4882 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 4883 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4884 | return false; |
| 4885 | } |
| 4886 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 4887 | static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { |
| 4888 | BasicBlock *PredPred = nullptr; |
| 4889 | for (auto *P : predecessors(BB)) { |
| 4890 | BasicBlock *PPred = P->getSinglePredecessor(); |
| 4891 | if (!PPred || (PredPred && PredPred != PPred)) |
| 4892 | return nullptr; |
| 4893 | PredPred = PPred; |
| 4894 | } |
| 4895 | return PredPred; |
| 4896 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4897 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4898 | bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4899 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4900 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4901 | // Conditional branch |
| 4902 | if (isValueEqualityComparison(BI)) { |
| 4903 | // If we only have one predecessor, and if it is a branch on this value, |
| 4904 | // see if that predecessor totally determines the outcome of this |
| 4905 | // switch. |
| 4906 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4907 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4908 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4909 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4910 | // This block must be empty, except for the setcond inst, if it exists. |
| 4911 | // Ignore dbg intrinsics. |
| 4912 | BasicBlock::iterator I = BB->begin(); |
| 4913 | // Ignore dbg intrinsics. |
| 4914 | while (isa<DbgInfoIntrinsic>(I)) |
| 4915 | ++I; |
| 4916 | if (&*I == BI) { |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4917 | if (FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4918 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4919 | } else if (&*I == cast<Instruction>(BI->getCondition())){ |
| 4920 | ++I; |
| 4921 | // Ignore dbg intrinsics. |
| 4922 | while (isa<DbgInfoIntrinsic>(I)) |
| 4923 | ++I; |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4924 | if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4925 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4926 | } |
| 4927 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4928 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4929 | // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4930 | if (SimplifyBranchOnICmpChain(BI, Builder, DL)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4931 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4932 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 4933 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4934 | // branches to us and one of our successors, fold the comparison into the |
| 4935 | // predecessor and use logical operations to pick the right destination. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4936 | if (FoldBranchToCommonDest(BI, BonusInstThreshold)) |
| 4937 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4938 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4939 | // We have a conditional branch to two blocks that are only reachable |
| 4940 | // from BI. We know that the condbr dominates the two blocks, so see if |
| 4941 | // there is any identical code in the "then" and "else" blocks. If so, we |
| 4942 | // can hoist it up to the branching block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4943 | if (BI->getSuccessor(0)->getSinglePredecessor()) { |
| 4944 | if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4945 | if (HoistThenElseCodeToIf(BI, TTI)) |
| 4946 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4947 | } else { |
| 4948 | // If Successor #1 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4949 | // execute Successor #0 if it branches to Successor #1. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4950 | TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); |
| 4951 | if (Succ0TI->getNumSuccessors() == 1 && |
| 4952 | Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4953 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) |
| 4954 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4955 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4956 | } else if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4957 | // If Successor #0 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4958 | // execute Successor #1 if it branches to Successor #0. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4959 | TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); |
| 4960 | if (Succ1TI->getNumSuccessors() == 1 && |
| 4961 | Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4962 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) |
| 4963 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4964 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4965 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4966 | // If this is a branch on a phi node in the current block, thread control |
| 4967 | // through this block if any PHI node entries are constants. |
| 4968 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 4969 | if (PN->getParent() == BI->getParent()) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4970 | if (FoldCondBranchOnPHI(BI, DL)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4971 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4972 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4973 | // Scan predecessor blocks for conditional branches. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 4974 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 4975 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4976 | if (PBI != BI && PBI->isConditional()) |
Philip Reames | b42db21 | 2015-10-14 22:46:19 +0000 | [diff] [blame] | 4977 | if (SimplifyCondBranchToCondBranch(PBI, BI, DL)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4978 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4979 | |
James Molloy | 4de84dd | 2015-11-04 15:28:04 +0000 | [diff] [blame] | 4980 | // Look for diamond patterns. |
| 4981 | if (MergeCondStores) |
| 4982 | if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) |
| 4983 | if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) |
| 4984 | if (PBI != BI && PBI->isConditional()) |
| 4985 | if (mergeConditionalStores(PBI, BI)) |
| 4986 | return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; |
| 4987 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4988 | return false; |
| 4989 | } |
| 4990 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4991 | /// Check if passing a value to an instruction will cause undefined behavior. |
| 4992 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { |
| 4993 | Constant *C = dyn_cast<Constant>(V); |
| 4994 | if (!C) |
| 4995 | return false; |
| 4996 | |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 4997 | if (I->use_empty()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4998 | return false; |
| 4999 | |
| 5000 | if (C->isNullValue()) { |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 5001 | // Only look at the first use, avoid hurting compile time with long uselists |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5002 | User *Use = *I->user_begin(); |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5003 | |
| 5004 | // Now make sure that there are no instructions in between that can alter |
| 5005 | // control flow (eg. calls) |
| 5006 | for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i) |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5007 | if (i == I->getParent()->end() || i->mayHaveSideEffects()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5008 | return false; |
| 5009 | |
| 5010 | // Look through GEPs. A load from a GEP derived from NULL is still undefined |
| 5011 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) |
| 5012 | if (GEP->getPointerOperand() == I) |
| 5013 | return passingValueIsAlwaysUndefined(V, GEP); |
| 5014 | |
| 5015 | // Look through bitcasts. |
| 5016 | if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) |
| 5017 | return passingValueIsAlwaysUndefined(V, BC); |
| 5018 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5019 | // Load from null is undefined. |
| 5020 | if (LoadInst *LI = dyn_cast<LoadInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 5021 | if (!LI->isVolatile()) |
| 5022 | return LI->getPointerAddressSpace() == 0; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5023 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 5024 | // Store to null is undefined. |
| 5025 | if (StoreInst *SI = dyn_cast<StoreInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 5026 | if (!SI->isVolatile()) |
| 5027 | return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5028 | } |
| 5029 | return false; |
| 5030 | } |
| 5031 | |
| 5032 | /// If BB has an incoming value that will always trigger undefined behavior |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 5033 | /// (eg. null pointer dereference), remove the branch leading here. |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5034 | static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { |
| 5035 | for (BasicBlock::iterator i = BB->begin(); |
| 5036 | PHINode *PHI = dyn_cast<PHINode>(i); ++i) |
| 5037 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
| 5038 | if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { |
| 5039 | TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); |
| 5040 | IRBuilder<> Builder(T); |
| 5041 | if (BranchInst *BI = dyn_cast<BranchInst>(T)) { |
| 5042 | BB->removePredecessor(PHI->getIncomingBlock(i)); |
| 5043 | // Turn uncoditional branches into unreachables and remove the dead |
| 5044 | // destination from conditional branches. |
| 5045 | if (BI->isUnconditional()) |
| 5046 | Builder.CreateUnreachable(); |
| 5047 | else |
| 5048 | Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) : |
| 5049 | BI->getSuccessor(0)); |
| 5050 | BI->eraseFromParent(); |
| 5051 | return true; |
| 5052 | } |
| 5053 | // TODO: SwitchInst. |
| 5054 | } |
| 5055 | |
| 5056 | return false; |
| 5057 | } |
| 5058 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5059 | bool SimplifyCFGOpt::run(BasicBlock *BB) { |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 5060 | bool Changed = false; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5061 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 5062 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5063 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5064 | |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 5065 | // Remove basic blocks that have no predecessors (except the entry block)... |
| 5066 | // or that just have themself as a predecessor. These are unreachable. |
Ramkumar Ramachandra | 181233b | 2015-01-13 04:17:47 +0000 | [diff] [blame] | 5067 | if ((pred_empty(BB) && |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 5068 | BB != &BB->getParent()->getEntryBlock()) || |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 5069 | BB->getSinglePredecessor() == BB) { |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 5070 | DEBUG(dbgs() << "Removing BB: \n" << *BB); |
Chris Lattner | 7eb270e | 2008-12-03 06:40:52 +0000 | [diff] [blame] | 5071 | DeleteDeadBlock(BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5072 | return true; |
| 5073 | } |
| 5074 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5075 | // Check to see if we can constant propagate this terminator instruction |
| 5076 | // away... |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 5077 | Changed |= ConstantFoldTerminator(BB, true); |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5078 | |
Dan Gohman | 1a95106 | 2009-10-30 22:39:04 +0000 | [diff] [blame] | 5079 | // Check for and eliminate duplicate PHI nodes in this block. |
| 5080 | Changed |= EliminateDuplicatePHINodes(BB); |
| 5081 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 5082 | // Check for and remove branches that will always cause undefined behavior. |
| 5083 | Changed |= removeUndefIntroducingPredecessor(BB); |
| 5084 | |
Chris Lattner | 2e3832d | 2010-12-13 05:10:48 +0000 | [diff] [blame] | 5085 | // Merge basic blocks into their predecessor if there is only one distinct |
| 5086 | // pred, and if there is only one distinct successor of the predecessor, and |
| 5087 | // if there are no PHI nodes. |
| 5088 | // |
| 5089 | if (MergeBlockIntoPredecessor(BB)) |
| 5090 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 5091 | |
Devang Patel | 15ad676 | 2011-05-18 18:01:27 +0000 | [diff] [blame] | 5092 | IRBuilder<> Builder(BB); |
| 5093 | |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 5094 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 5095 | // eliminate it, do so now. |
| 5096 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 5097 | if (PN->getNumIncomingValues() == 2) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5098 | Changed |= FoldTwoEntryPHINode(PN, TTI, DL); |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 5099 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5100 | Builder.SetInsertPoint(BB->getTerminator()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 5101 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5102 | if (BI->isUnconditional()) { |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 5103 | if (SimplifyUncondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5104 | } else { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5105 | if (SimplifyCondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5106 | } |
| 5107 | } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 5108 | if (SimplifyReturn(RI, Builder)) return true; |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 5109 | } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { |
| 5110 | if (SimplifyResume(RI, Builder)) return true; |
Andrew Kaylor | 50e4e86 | 2015-09-04 23:39:40 +0000 | [diff] [blame] | 5111 | } else if (CleanupReturnInst *RI = |
| 5112 | dyn_cast<CleanupReturnInst>(BB->getTerminator())) { |
| 5113 | if (SimplifyCleanupReturn(RI)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5114 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 5115 | if (SimplifySwitch(SI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5116 | } else if (UnreachableInst *UI = |
| 5117 | dyn_cast<UnreachableInst>(BB->getTerminator())) { |
| 5118 | if (SimplifyUnreachable(UI)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 5119 | } else if (IndirectBrInst *IBI = |
| 5120 | dyn_cast<IndirectBrInst>(BB->getTerminator())) { |
| 5121 | if (SimplifyIndirectBr(IBI)) return true; |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 5122 | } |
| 5123 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 5124 | return Changed; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 5125 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5126 | |
Sanjay Patel | 09159b8f | 2015-06-24 20:40:57 +0000 | [diff] [blame] | 5127 | /// This function is used to do simplification of a CFG. |
| 5128 | /// For example, it adjusts branches to branches to eliminate the extra hop, |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5129 | /// eliminates unreachable basic blocks, and does other "peephole" optimization |
| 5130 | /// of the CFG. It returns true if a modification was made. |
| 5131 | /// |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 5132 | bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 5133 | unsigned BonusInstThreshold, AssumptionCache *AC) { |
| 5134 | return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), |
| 5135 | BonusInstThreshold, AC).run(BB); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 5136 | } |