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" |
| 17 | #include "llvm/ADT/SetVector.h" |
| 18 | #include "llvm/ADT/SmallPtrSet.h" |
| 19 | #include "llvm/ADT/SmallVector.h" |
| 20 | #include "llvm/ADT/Statistic.h" |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | d3e7355 | 2013-01-07 03:08:10 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 25 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 26 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Constants.h" |
| 28 | #include "llvm/IR/DataLayout.h" |
| 29 | #include "llvm/IR/DerivedTypes.h" |
| 30 | #include "llvm/IR/GlobalVariable.h" |
| 31 | #include "llvm/IR/IRBuilder.h" |
| 32 | #include "llvm/IR/Instructions.h" |
| 33 | #include "llvm/IR/IntrinsicInst.h" |
| 34 | #include "llvm/IR/LLVMContext.h" |
| 35 | #include "llvm/IR/MDBuilder.h" |
| 36 | #include "llvm/IR/Metadata.h" |
| 37 | #include "llvm/IR/Module.h" |
Chandler Carruth | 64396b0 | 2014-03-04 12:05:47 +0000 | [diff] [blame] | 38 | #include "llvm/IR/NoFolder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 40 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 41 | #include "llvm/IR/Type.h" |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 42 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 43 | #include "llvm/Support/Debug.h" |
| 44 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/Local.h" |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 48 | #include <algorithm> |
Chris Lattner | 5edb2f3 | 2004-10-18 04:07:22 +0000 | [diff] [blame] | 49 | #include <map> |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 50 | #include <set> |
Chris Lattner | df3c342 | 2004-01-09 06:12:26 +0000 | [diff] [blame] | 51 | using namespace llvm; |
Benjamin Kramer | 3717222 | 2013-07-04 14:22:02 +0000 | [diff] [blame] | 52 | using namespace PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 53 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 54 | #define DEBUG_TYPE "simplifycfg" |
| 55 | |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 56 | static cl::opt<unsigned> |
| 57 | PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1), |
| 58 | cl::desc("Control the amount of phi node folding to perform (default = 1)")); |
| 59 | |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 60 | static cl::opt<bool> |
| 61 | DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), |
| 62 | cl::desc("Duplicate return instructions into unconditional branches")); |
| 63 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 64 | static cl::opt<bool> |
| 65 | SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), |
| 66 | cl::desc("Sink common instructions down to the end block")); |
| 67 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 68 | static cl::opt<bool> HoistCondStores( |
| 69 | "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), |
| 70 | cl::desc("Hoist conditional stores if an unconditional store precedes")); |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 71 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 72 | STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 73 | STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 74 | STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables"); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 75 | STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)"); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 76 | STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 77 | STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block"); |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 78 | STATISTIC(NumSpeculations, "Number of speculative executed instructions"); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 79 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 80 | namespace { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 81 | // The first field contains the value that the switch produces when a certain |
| 82 | // case group is selected, and the second field is a vector containing the cases |
| 83 | // composing the case group. |
| 84 | typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2> |
| 85 | SwitchCaseResultVectorTy; |
| 86 | // The first field contains the phi node that generates a result of the switch |
| 87 | // and the second field contains the value generated for a certain case in the switch |
| 88 | // for that PHI. |
| 89 | typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy; |
| 90 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 91 | /// ValueEqualityComparisonCase - Represents a case of a switch. |
| 92 | struct ValueEqualityComparisonCase { |
| 93 | ConstantInt *Value; |
| 94 | BasicBlock *Dest; |
| 95 | |
| 96 | ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) |
| 97 | : Value(Value), Dest(Dest) {} |
| 98 | |
| 99 | bool operator<(ValueEqualityComparisonCase RHS) const { |
| 100 | // Comparing pointers is ok as we only rely on the order for uniquing. |
| 101 | return Value < RHS.Value; |
| 102 | } |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 103 | |
| 104 | bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 105 | }; |
| 106 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 107 | class SimplifyCFGOpt { |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 108 | const TargetTransformInfo &TTI; |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 109 | unsigned BonusInstThreshold; |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 110 | const DataLayout *const DL; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 111 | AssumptionCache *AC; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 112 | Value *isValueEqualityComparison(TerminatorInst *TI); |
| 113 | BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 114 | std::vector<ValueEqualityComparisonCase> &Cases); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 115 | bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 116 | BasicBlock *Pred, |
| 117 | IRBuilder<> &Builder); |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 118 | bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 119 | IRBuilder<> &Builder); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 120 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 121 | bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 122 | bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 123 | bool SimplifyUnreachable(UnreachableInst *UI); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 124 | bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 125 | bool SimplifyIndirectBr(IndirectBrInst *IBI); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 126 | bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder); |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 127 | bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 128 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 129 | public: |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 130 | SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 131 | const DataLayout *DL, AssumptionCache *AC) |
| 132 | : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AC(AC) {} |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 133 | bool run(BasicBlock *BB); |
| 134 | }; |
| 135 | } |
| 136 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 137 | /// SafeToMergeTerminators - Return true if it is safe to merge these two |
| 138 | /// terminator instructions together. |
| 139 | /// |
| 140 | static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) { |
| 141 | if (SI1 == SI2) return false; // Can't merge with self! |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 142 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 143 | // It is not safe to merge these two switch instructions if they have a common |
| 144 | // successor, and if that successor has a PHI node, and if *that* PHI node has |
| 145 | // conflicting incoming values from the two switch blocks. |
| 146 | BasicBlock *SI1BB = SI1->getParent(); |
| 147 | BasicBlock *SI2BB = SI2->getParent(); |
Chris Lattner | b7b7514 | 2007-04-02 01:44:59 +0000 | [diff] [blame] | 148 | SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 149 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 150 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 151 | if (SI1Succs.count(*I)) |
| 152 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 153 | isa<PHINode>(BBI); ++BBI) { |
| 154 | PHINode *PN = cast<PHINode>(BBI); |
| 155 | if (PN->getIncomingValueForBlock(SI1BB) != |
| 156 | PN->getIncomingValueForBlock(SI2BB)) |
| 157 | return false; |
| 158 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 159 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 160 | return true; |
| 161 | } |
| 162 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 163 | /// isProfitableToFoldUnconditional - Return true if it is safe and profitable |
| 164 | /// to merge these two terminator instructions together, where SI1 is an |
| 165 | /// unconditional branch. PhiNodes will store all PHI nodes in common |
| 166 | /// successors. |
| 167 | /// |
| 168 | static bool isProfitableToFoldUnconditional(BranchInst *SI1, |
| 169 | BranchInst *SI2, |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 170 | Instruction *Cond, |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 171 | SmallVectorImpl<PHINode*> &PhiNodes) { |
| 172 | if (SI1 == SI2) return false; // Can't merge with self! |
| 173 | assert(SI1->isUnconditional() && SI2->isConditional()); |
| 174 | |
| 175 | // 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] | 176 | // common successors: |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 177 | // 1> We have a constant incoming value for the conditional branch; |
| 178 | // 2> We have "Cond" as the incoming value for the unconditional branch; |
| 179 | // 3> SI2->getCondition() and Cond have same operands. |
| 180 | CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); |
| 181 | if (!Ci2) return false; |
| 182 | if (!(Cond->getOperand(0) == Ci2->getOperand(0) && |
| 183 | Cond->getOperand(1) == Ci2->getOperand(1)) && |
| 184 | !(Cond->getOperand(0) == Ci2->getOperand(1) && |
| 185 | Cond->getOperand(1) == Ci2->getOperand(0))) |
| 186 | return false; |
| 187 | |
| 188 | BasicBlock *SI1BB = SI1->getParent(); |
| 189 | BasicBlock *SI2BB = SI2->getParent(); |
| 190 | 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] | 191 | for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I) |
| 192 | if (SI1Succs.count(*I)) |
| 193 | for (BasicBlock::iterator BBI = (*I)->begin(); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 194 | isa<PHINode>(BBI); ++BBI) { |
| 195 | PHINode *PN = cast<PHINode>(BBI); |
| 196 | if (PN->getIncomingValueForBlock(SI1BB) != Cond || |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 197 | !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 198 | return false; |
| 199 | PhiNodes.push_back(PN); |
| 200 | } |
| 201 | return true; |
| 202 | } |
| 203 | |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 204 | /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will |
| 205 | /// now be entries in it from the 'NewPred' block. The values that will be |
| 206 | /// flowing into the PHI nodes will be the same as those coming in from |
| 207 | /// ExistPred, an existing predecessor of Succ. |
| 208 | static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, |
| 209 | BasicBlock *ExistPred) { |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 210 | if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 211 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 212 | PHINode *PN; |
| 213 | for (BasicBlock::iterator I = Succ->begin(); |
| 214 | (PN = dyn_cast<PHINode>(I)); ++I) |
| 215 | PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); |
Chris Lattner | 76dc204 | 2005-08-03 00:19:45 +0000 | [diff] [blame] | 216 | } |
| 217 | |
David Majnemer | 91142c4 | 2013-06-01 19:43:23 +0000 | [diff] [blame] | 218 | /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 219 | /// given instruction, which is assumed to be safe to speculate. 1 means |
| 220 | /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 221 | static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) { |
| 222 | assert(isSafeToSpeculativelyExecute(I, DL) && |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 223 | "Instruction is not safe to speculatively execute!"); |
| 224 | switch (Operator::getOpcode(I)) { |
| 225 | default: |
| 226 | // In doubt, be conservative. |
| 227 | return UINT_MAX; |
| 228 | case Instruction::GetElementPtr: |
| 229 | // GEPs are cheap if all indices are constant. |
| 230 | if (!cast<GEPOperator>(I)->hasAllConstantIndices()) |
| 231 | return UINT_MAX; |
| 232 | return 1; |
Louis Gerbarg | 1f54b82 | 2014-05-09 17:02:46 +0000 | [diff] [blame] | 233 | case Instruction::ExtractValue: |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 234 | case Instruction::Load: |
| 235 | case Instruction::Add: |
| 236 | case Instruction::Sub: |
| 237 | case Instruction::And: |
| 238 | case Instruction::Or: |
| 239 | case Instruction::Xor: |
| 240 | case Instruction::Shl: |
| 241 | case Instruction::LShr: |
| 242 | case Instruction::AShr: |
| 243 | case Instruction::ICmp: |
| 244 | case Instruction::Trunc: |
| 245 | case Instruction::ZExt: |
| 246 | case Instruction::SExt: |
Matt Arsenault | c8fc08c | 2014-05-30 18:34:43 +0000 | [diff] [blame] | 247 | case Instruction::BitCast: |
| 248 | case Instruction::ExtractElement: |
| 249 | case Instruction::InsertElement: |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 250 | return 1; // These are all cheap. |
| 251 | |
| 252 | case Instruction::Call: |
| 253 | case Instruction::Select: |
| 254 | return 2; |
| 255 | } |
| 256 | } |
| 257 | |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 258 | /// DominatesMergePoint - If we have a merge point of an "if condition" as |
| 259 | /// accepted above, return true if the specified value dominates the block. We |
| 260 | /// don't handle the true generality of domination here, just a special case |
| 261 | /// which works well enough for us. |
| 262 | /// |
| 263 | /// 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] | 264 | /// see if V (which must be an instruction) and its recursive operands |
| 265 | /// that do not dominate BB have a combined cost lower than CostRemaining and |
| 266 | /// are non-trapping. If both are true, the instruction is inserted into the |
| 267 | /// set and true is returned. |
| 268 | /// |
| 269 | /// The cost for most non-trapping instructions is defined as 1 except for |
| 270 | /// Select whose cost is 2. |
| 271 | /// |
| 272 | /// After this function returns, CostRemaining is decreased by the cost of |
| 273 | /// V plus its non-dominating operands. If that cost is greater than |
| 274 | /// CostRemaining, false is returned and CostRemaining is undefined. |
Chris Lattner | 45c35b1 | 2004-10-14 05:13:36 +0000 | [diff] [blame] | 275 | static bool DominatesMergePoint(Value *V, BasicBlock *BB, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 276 | SmallPtrSetImpl<Instruction*> *AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 277 | unsigned &CostRemaining, |
| 278 | const DataLayout *DL) { |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 279 | Instruction *I = dyn_cast<Instruction>(V); |
Chris Lattner | b8b1159 | 2006-10-20 00:42:07 +0000 | [diff] [blame] | 280 | if (!I) { |
| 281 | // Non-instructions all dominate instructions, but not all constantexprs |
| 282 | // can be executed unconditionally. |
| 283 | if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) |
| 284 | if (C->canTrap()) |
| 285 | return false; |
| 286 | return true; |
| 287 | } |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 288 | BasicBlock *PBB = I->getParent(); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 289 | |
Chris Lattner | 0ce80cd | 2005-02-27 06:18:25 +0000 | [diff] [blame] | 290 | // 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] | 291 | // the bottom of this block. |
| 292 | if (PBB == BB) return false; |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 293 | |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 294 | // If this instruction is defined in a block that contains an unconditional |
| 295 | // 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] | 296 | // statement". If not, it definitely dominates the region. |
| 297 | BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 298 | if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 299 | return true; |
Eli Friedman | b8f6a4f | 2009-07-17 04:28:42 +0000 | [diff] [blame] | 300 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 301 | // If we aren't allowing aggressive promotion anymore, then don't consider |
| 302 | // instructions in the 'if region'. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 303 | if (!AggressiveInsts) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 304 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 305 | // If we have seen this instruction before, don't count it again. |
| 306 | if (AggressiveInsts->count(I)) return true; |
| 307 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 308 | // Okay, it looks like the instruction IS in the "condition". Check to |
| 309 | // see if it's a cheap instruction to unconditionally compute, and if it |
| 310 | // only uses stuff defined outside of the condition. If so, hoist it out. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 311 | if (!isSafeToSpeculativelyExecute(I, DL)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 312 | return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 313 | |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 314 | unsigned Cost = ComputeSpeculationCost(I, DL); |
Chris Lattner | 0aa5656 | 2004-04-09 22:50:22 +0000 | [diff] [blame] | 315 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 316 | if (Cost > CostRemaining) |
| 317 | return false; |
| 318 | |
| 319 | CostRemaining -= Cost; |
| 320 | |
| 321 | // Okay, we can only really hoist these out if their operands do |
| 322 | // not take us over the cost threshold. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 323 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 324 | if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL)) |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 325 | return false; |
| 326 | // Okay, it's safe to do this! Remember this instruction. |
| 327 | AggressiveInsts->insert(I); |
Chris Lattner | 18d1f19 | 2004-02-11 03:36:04 +0000 | [diff] [blame] | 328 | return true; |
| 329 | } |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 330 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 331 | /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr |
| 332 | /// and PointerNullValue. Return NULL if value is not a constant int. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 333 | static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) { |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 334 | // Normal constant int. |
| 335 | ConstantInt *CI = dyn_cast<ConstantInt>(V); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 336 | if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy()) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 337 | return CI; |
| 338 | |
| 339 | // This is some kind of pointer constant. Turn it into a pointer-sized |
| 340 | // ConstantInt if possible. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 341 | IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType())); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 342 | |
| 343 | // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). |
| 344 | if (isa<ConstantPointerNull>(V)) |
| 345 | return ConstantInt::get(PtrTy, 0); |
| 346 | |
| 347 | // IntToPtr const int. |
| 348 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 349 | if (CE->getOpcode() == Instruction::IntToPtr) |
| 350 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { |
| 351 | // The constant is very likely to have the right type already. |
| 352 | if (CI->getType() == PtrTy) |
| 353 | return CI; |
| 354 | else |
| 355 | return cast<ConstantInt> |
| 356 | (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); |
| 357 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 358 | return nullptr; |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 359 | } |
| 360 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 361 | namespace { |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 362 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 363 | /// Given a chain of or (||) or and (&&) comparison of a value against a |
| 364 | /// constant, this will try to recover the information required for a switch |
| 365 | /// structure. |
| 366 | /// It will depth-first traverse the chain of comparison, seeking for patterns |
| 367 | /// like %a == 12 or %a < 4 and combine them to produce a set of integer |
| 368 | /// representing the different cases for the switch. |
| 369 | /// Note that if the chain is composed of '||' it will build the set of elements |
| 370 | /// that matches the comparisons (i.e. any of this value validate the chain) |
| 371 | /// while for a chain of '&&' it will build the set elements that make the test |
| 372 | /// fail. |
| 373 | struct ConstantComparesGatherer { |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 374 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 375 | Value *CompValue; /// Value found for the switch comparison |
| 376 | Value *Extra; /// Extra clause to be checked before the switch |
| 377 | SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch |
| 378 | unsigned UsedICmps; /// Number of comparisons matched in the and/or chain |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 379 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 380 | /// Construct and compute the result for the comparison instruction Cond |
| 381 | ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL) |
| 382 | : CompValue(nullptr), Extra(nullptr), UsedICmps(0) { |
| 383 | gather(Cond, DL); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 384 | } |
| 385 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 386 | /// Prevent copy |
| 387 | ConstantComparesGatherer(const ConstantComparesGatherer &) |
| 388 | LLVM_DELETED_FUNCTION; |
| 389 | ConstantComparesGatherer & |
| 390 | operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 391 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 392 | private: |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 393 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 394 | /// Try to set the current value used for the comparison, it succeeds only if |
| 395 | /// it wasn't set before or if the new value is the same as the old one |
| 396 | bool setValueOnce(Value *NewVal) { |
| 397 | if(CompValue && CompValue != NewVal) return false; |
| 398 | CompValue = NewVal; |
| 399 | return (CompValue != nullptr); |
| 400 | } |
| 401 | |
| 402 | /// Try to match Instruction "I" as a comparison against a constant and |
| 403 | /// populates the array Vals with the set of values that match (or do not |
| 404 | /// match depending on isEQ). |
| 405 | /// Return false on failure. On success, the Value the comparison matched |
| 406 | /// against is placed in CompValue. |
| 407 | /// If CompValue is already set, the function is expected to fail if a match |
| 408 | /// is found but the value compared to is different. |
| 409 | bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) { |
| 410 | // If this is an icmp against a constant, handle this as one of the cases. |
| 411 | ICmpInst *ICI; |
| 412 | ConstantInt *C; |
| 413 | if (!((ICI = dyn_cast<ICmpInst>(I)) && |
| 414 | (C = GetConstantInt(I->getOperand(1), DL)))) { |
| 415 | return false; |
| 416 | } |
| 417 | |
| 418 | Value *RHSVal; |
| 419 | ConstantInt *RHSC; |
| 420 | |
| 421 | // Pattern match a special case |
| 422 | // (x & ~2^x) == y --> x == y || x == y|2^x |
| 423 | // This undoes a transformation done by instcombine to fuse 2 compares. |
| 424 | if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) { |
| 425 | if (match(ICI->getOperand(0), |
| 426 | m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 427 | APInt Not = ~RHSC->getValue(); |
| 428 | if (Not.isPowerOf2()) { |
| 429 | // If we already have a value for the switch, it has to match! |
| 430 | if(!setValueOnce(RHSVal)) |
| 431 | return false; |
| 432 | |
| 433 | Vals.push_back(C); |
| 434 | Vals.push_back(ConstantInt::get(C->getContext(), |
| 435 | C->getValue() | Not)); |
| 436 | UsedICmps++; |
| 437 | return true; |
| 438 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 439 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 440 | |
| 441 | // If we already have a value for the switch, it has to match! |
| 442 | if(!setValueOnce(ICI->getOperand(0))) |
| 443 | return false; |
| 444 | |
| 445 | UsedICmps++; |
| 446 | Vals.push_back(C); |
| 447 | return ICI->getOperand(0); |
| 448 | } |
| 449 | |
| 450 | // If we have "x ult 3", for example, then we can add 0,1,2 to the set. |
| 451 | ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(), |
| 452 | C->getValue()); |
| 453 | |
| 454 | // Shift the range if the compare is fed by an add. This is the range |
| 455 | // compare idiom as emitted by instcombine. |
| 456 | Value *CandidateVal = I->getOperand(0); |
| 457 | if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) { |
| 458 | Span = Span.subtract(RHSC->getValue()); |
| 459 | CandidateVal = RHSVal; |
| 460 | } |
| 461 | |
| 462 | // If this is an and/!= check, then we are looking to build the set of |
| 463 | // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into |
| 464 | // x != 0 && x != 1. |
| 465 | if (!isEQ) |
| 466 | Span = Span.inverse(); |
| 467 | |
| 468 | // If there are a ton of values, we don't want to make a ginormous switch. |
| 469 | if (Span.getSetSize().ugt(8) || Span.isEmptySet()) { |
| 470 | return false; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 471 | } |
| 472 | |
| 473 | // 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] | 474 | if(!setValueOnce(CandidateVal)) |
| 475 | return false; |
| 476 | |
| 477 | // Add all values from the range to the set |
| 478 | for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) |
| 479 | Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 480 | |
| 481 | UsedICmps++; |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 482 | return true; |
| 483 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 484 | } |
| 485 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 486 | /// gather - Given a potentially 'or'd or 'and'd together collection of icmp |
| 487 | /// eq/ne/lt/gt instructions that compare a value against a constant, extract |
| 488 | /// the value being compared, and stick the list constants into the Vals |
| 489 | /// vector. |
| 490 | /// One "Extra" case is allowed to differ from the other. |
| 491 | void gather(Value *V, const DataLayout *DL) { |
| 492 | Instruction *I = dyn_cast<Instruction>(V); |
| 493 | bool isEQ = (I->getOpcode() == Instruction::Or); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 494 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 495 | // Keep a stack (SmallVector for efficiency) for depth-first traversal |
| 496 | SmallVector<Value *, 8> DFT; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 497 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 498 | // Initialize |
| 499 | DFT.push_back(V); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 500 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 501 | while(!DFT.empty()) { |
| 502 | V = DFT.pop_back_val(); |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 503 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 504 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 505 | // If it is a || (or && depending on isEQ), process the operands. |
| 506 | if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { |
| 507 | DFT.push_back(I->getOperand(1)); |
| 508 | DFT.push_back(I->getOperand(0)); |
| 509 | continue; |
| 510 | } |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 511 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 512 | // Try to match the current instruction |
| 513 | if (matchInstruction(I, DL, isEQ)) |
| 514 | // Match succeed, continue the loop |
| 515 | continue; |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 516 | } |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 517 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 518 | // One element of the sequence of || (or &&) could not be match as a |
| 519 | // comparison against the same value as the others. |
| 520 | // We allow only one "Extra" case to be checked before the switch |
| 521 | if (!Extra) { |
| 522 | Extra = V; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 523 | continue; |
| 524 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 525 | // Failed to parse a proper sequence, abort now |
| 526 | CompValue = nullptr; |
| 527 | break; |
Chris Lattner | 5a177e6 | 2010-12-13 04:26:26 +0000 | [diff] [blame] | 528 | } |
Anton Korobeynikov | 1bfd121 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 529 | } |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 530 | }; |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 531 | |
Timur Iskhodzhanov | 71526a3 | 2014-11-20 12:36:43 +0000 | [diff] [blame] | 532 | } |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 533 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 534 | static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 535 | Instruction *Cond = nullptr; |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 536 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 537 | Cond = dyn_cast<Instruction>(SI->getCondition()); |
| 538 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 539 | if (BI->isConditional()) |
| 540 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 541 | } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { |
| 542 | Cond = dyn_cast<Instruction>(IBI->getAddress()); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 543 | } |
| 544 | |
| 545 | TI->eraseFromParent(); |
| 546 | if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond); |
| 547 | } |
| 548 | |
Chris Lattner | 8e84c12 | 2008-11-27 23:25:44 +0000 | [diff] [blame] | 549 | /// isValueEqualityComparison - Return true if the specified terminator checks |
| 550 | /// to see if a value is equal to constant integer value. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 551 | Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 552 | Value *CV = nullptr; |
Chris Lattner | a64923a | 2004-03-16 19:45:22 +0000 | [diff] [blame] | 553 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 554 | // Do not permit merging of large switch instructions into their |
| 555 | // predecessors unless there is only one predecessor. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 556 | if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()), |
| 557 | pred_end(SI->getParent())) <= 128) |
| 558 | CV = SI->getCondition(); |
| 559 | } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 560 | if (BI->isConditional() && BI->getCondition()->hasOneUse()) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 561 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 562 | if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 563 | CV = ICI->getOperand(0); |
| 564 | |
| 565 | // Unwrap any lossless ptrtoint cast. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 566 | if (DL && CV) { |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 567 | if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { |
| 568 | Value *Ptr = PTII->getPointerOperand(); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 569 | if (PTII->getType() == DL->getIntPtrType(Ptr->getType())) |
Matt Arsenault | fa64659 | 2013-10-21 18:55:08 +0000 | [diff] [blame] | 570 | CV = Ptr; |
| 571 | } |
| 572 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 573 | return CV; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 574 | } |
| 575 | |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 576 | /// GetValueEqualityComparisonCases - Given a value comparison instruction, |
| 577 | /// 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] | 578 | BasicBlock *SimplifyCFGOpt:: |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 579 | GetValueEqualityComparisonCases(TerminatorInst *TI, |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 580 | std::vector<ValueEqualityComparisonCase> |
| 581 | &Cases) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 582 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 583 | Cases.reserve(SI->getNumCases()); |
| 584 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) |
| 585 | Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(), |
| 586 | i.getCaseSuccessor())); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 587 | return SI->getDefaultDest(); |
| 588 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 589 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 590 | BranchInst *BI = cast<BranchInst>(TI); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 591 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 592 | BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); |
| 593 | Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1), |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 594 | DL), |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 595 | Succ)); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 596 | return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 597 | } |
| 598 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 599 | |
| 600 | /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries |
| 601 | /// in the list that match the specified block. |
| 602 | static void EliminateBlockCases(BasicBlock *BB, |
| 603 | std::vector<ValueEqualityComparisonCase> &Cases) { |
Benjamin Kramer | c5b0678 | 2012-10-14 11:15:42 +0000 | [diff] [blame] | 604 | Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 605 | } |
| 606 | |
| 607 | /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as |
| 608 | /// well. |
| 609 | static bool |
| 610 | ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, |
| 611 | std::vector<ValueEqualityComparisonCase > &C2) { |
| 612 | std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; |
| 613 | |
| 614 | // Make V1 be smaller than V2. |
| 615 | if (V1->size() > V2->size()) |
| 616 | std::swap(V1, V2); |
| 617 | |
| 618 | if (V1->size() == 0) return false; |
| 619 | if (V1->size() == 1) { |
| 620 | // Just scan V2. |
| 621 | ConstantInt *TheVal = (*V1)[0].Value; |
| 622 | for (unsigned i = 0, e = V2->size(); i != e; ++i) |
| 623 | if (TheVal == (*V2)[i].Value) |
| 624 | return true; |
| 625 | } |
| 626 | |
| 627 | // Otherwise, just sort both lists and compare element by element. |
| 628 | array_pod_sort(V1->begin(), V1->end()); |
| 629 | array_pod_sort(V2->begin(), V2->end()); |
| 630 | unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); |
| 631 | while (i1 != e1 && i2 != e2) { |
| 632 | if ((*V1)[i1].Value == (*V2)[i2].Value) |
| 633 | return true; |
| 634 | if ((*V1)[i1].Value < (*V2)[i2].Value) |
| 635 | ++i1; |
| 636 | else |
| 637 | ++i2; |
| 638 | } |
| 639 | return false; |
| 640 | } |
| 641 | |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 642 | /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a |
| 643 | /// terminator instruction and its block is known to only have a single |
| 644 | /// predecessor block, check to see if that predecessor is also a value |
| 645 | /// comparison with the same value, and if that comparison determines the |
| 646 | /// outcome of this comparison. If so, simplify TI. This does a very limited |
| 647 | /// form of jump threading. |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 648 | bool SimplifyCFGOpt:: |
| 649 | SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 650 | BasicBlock *Pred, |
| 651 | IRBuilder<> &Builder) { |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 652 | Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); |
| 653 | if (!PredVal) return false; // Not a value comparison in predecessor. |
| 654 | |
| 655 | Value *ThisVal = isValueEqualityComparison(TI); |
| 656 | assert(ThisVal && "This isn't a value comparison!!"); |
| 657 | if (ThisVal != PredVal) return false; // Different predicates. |
| 658 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 659 | // TODO: Preserve branch weight metadata, similarly to how |
| 660 | // FoldValueComparisonIntoPredecessors preserves it. |
| 661 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 662 | // 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] | 663 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 664 | BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(), |
| 665 | PredCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 666 | EliminateBlockCases(PredDef, PredCases); // Remove default from cases. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 667 | |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 668 | // Find information about how control leaves this block. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 669 | std::vector<ValueEqualityComparisonCase> ThisCases; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 670 | BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 671 | EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 672 | |
| 673 | // If TI's block is the default block from Pred's comparison, potentially |
| 674 | // simplify TI based on this knowledge. |
| 675 | if (PredDef == TI->getParent()) { |
| 676 | // If we are here, we know that the value is none of those cases listed in |
| 677 | // PredCases. If there are any cases in ThisCases that are in PredCases, we |
| 678 | // can simplify TI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 679 | if (!ValuesOverlap(PredCases, ThisCases)) |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 680 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 681 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 682 | if (isa<BranchInst>(TI)) { |
| 683 | // Okay, one of the successors of this condbr is dead. Convert it to a |
| 684 | // uncond br. |
| 685 | assert(ThisCases.size() == 1 && "Branch can only have one case!"); |
| 686 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 687 | Instruction *NI = Builder.CreateBr(ThisDef); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 688 | (void) NI; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 689 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 690 | // Remove PHI node entries for the dead edge. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 691 | ThisCases[0].Dest->removePredecessor(TI->getParent()); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 692 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 693 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 694 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 695 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 696 | EraseTerminatorInstAndDCECond(TI); |
| 697 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 698 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 699 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 700 | SwitchInst *SI = cast<SwitchInst>(TI); |
| 701 | // Okay, TI has cases that are statically dead, prune them away. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 702 | SmallPtrSet<Constant*, 16> DeadCases; |
| 703 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 704 | DeadCases.insert(PredCases[i].Value); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 705 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 706 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 707 | << "Through successor TI: " << *TI); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 708 | |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 709 | // Collect branch weights into a vector. |
| 710 | SmallVector<uint32_t, 8> Weights; |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 711 | MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 712 | bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); |
| 713 | if (HasWeight) |
| 714 | for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; |
| 715 | ++MD_i) { |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 716 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 717 | Weights.push_back(CI->getValue().getZExtValue()); |
| 718 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 719 | for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { |
| 720 | --i; |
| 721 | if (DeadCases.count(i.getCaseValue())) { |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 722 | if (HasWeight) { |
| 723 | std::swap(Weights[i.getCaseIndex()+1], Weights.back()); |
| 724 | Weights.pop_back(); |
| 725 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 726 | i.getCaseSuccessor()->removePredecessor(TI->getParent()); |
| 727 | SI->removeCase(i); |
| 728 | } |
| 729 | } |
Manman Ren | 97c1876 | 2012-10-11 22:28:34 +0000 | [diff] [blame] | 730 | if (HasWeight && Weights.size() >= 2) |
Manman Ren | 8691e52 | 2012-09-14 21:53:06 +0000 | [diff] [blame] | 731 | SI->setMetadata(LLVMContext::MD_prof, |
| 732 | MDBuilder(SI->getParent()->getContext()). |
| 733 | createBranchWeights(Weights)); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 734 | |
| 735 | DEBUG(dbgs() << "Leaving: " << *TI << "\n"); |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 736 | return true; |
| 737 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 738 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 739 | // Otherwise, TI's block must correspond to some matched value. Find out |
| 740 | // which value (or set of values) this is. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 741 | ConstantInt *TIV = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 742 | BasicBlock *TIBB = TI->getParent(); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 743 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 744 | if (PredCases[i].Dest == TIBB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 745 | if (TIV) |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 746 | return false; // Cannot handle multiple values coming to this block. |
| 747 | TIV = PredCases[i].Value; |
| 748 | } |
| 749 | assert(TIV && "No edge from pred to succ?"); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 750 | |
| 751 | // Okay, we found the one constant that our value can be if we get into TI's |
| 752 | // BB. Find out which successor will unconditionally be branched to. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 753 | BasicBlock *TheRealDest = nullptr; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 754 | for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) |
| 755 | if (ThisCases[i].Value == TIV) { |
| 756 | TheRealDest = ThisCases[i].Dest; |
| 757 | break; |
| 758 | } |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 759 | |
| 760 | // 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] | 761 | if (!TheRealDest) TheRealDest = ThisDef; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 762 | |
| 763 | // Remove PHI node entries for dead edges. |
| 764 | BasicBlock *CheckEdge = TheRealDest; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 765 | for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI) |
| 766 | if (*SI != CheckEdge) |
| 767 | (*SI)->removePredecessor(TIBB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 768 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 769 | CheckEdge = nullptr; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 770 | |
| 771 | // Insert the new branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 772 | Instruction *NI = Builder.CreateBr(TheRealDest); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 773 | (void) NI; |
| 774 | |
| 775 | DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() |
| 776 | << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n"); |
| 777 | |
| 778 | EraseTerminatorInstAndDCECond(TI); |
| 779 | return true; |
Chris Lattner | 1cca959 | 2005-02-24 06:17:52 +0000 | [diff] [blame] | 780 | } |
| 781 | |
Dale Johannesen | 7f99d22 | 2009-03-12 21:01:11 +0000 | [diff] [blame] | 782 | namespace { |
| 783 | /// ConstantIntOrdering - This class implements a stable ordering of constant |
| 784 | /// integers that does not depend on their address. This is important for |
| 785 | /// applications that sort ConstantInt's to ensure uniqueness. |
| 786 | struct ConstantIntOrdering { |
| 787 | bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { |
| 788 | return LHS->getValue().ult(RHS->getValue()); |
| 789 | } |
| 790 | }; |
| 791 | } |
Dale Johannesen | 5a41b2d | 2009-03-12 01:00:26 +0000 | [diff] [blame] | 792 | |
Benjamin Kramer | 8817cca | 2013-09-22 14:09:50 +0000 | [diff] [blame] | 793 | static int ConstantIntSortPredicate(ConstantInt *const *P1, |
| 794 | ConstantInt *const *P2) { |
| 795 | const ConstantInt *LHS = *P1; |
| 796 | const ConstantInt *RHS = *P2; |
Chris Lattner | e893e26 | 2010-12-15 04:52:41 +0000 | [diff] [blame] | 797 | if (LHS->getValue().ult(RHS->getValue())) |
| 798 | return 1; |
| 799 | if (LHS->getValue() == RHS->getValue()) |
| 800 | return 0; |
| 801 | return -1; |
Chris Lattner | 7c8e604 | 2010-12-13 02:00:58 +0000 | [diff] [blame] | 802 | } |
| 803 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 804 | static inline bool HasBranchWeights(const Instruction* I) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 805 | MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 806 | if (ProfMD && ProfMD->getOperand(0)) |
| 807 | if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) |
| 808 | return MDS->getString().equals("branch_weights"); |
| 809 | |
| 810 | return false; |
| 811 | } |
| 812 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 813 | /// Get Weights of a given TerminatorInst, the default weight is at the front |
| 814 | /// of the vector. If TI is a conditional eq, we need to swap the branch-weight |
| 815 | /// metadata. |
| 816 | static void GetBranchWeights(TerminatorInst *TI, |
| 817 | SmallVectorImpl<uint64_t> &Weights) { |
Duncan P. N. Exon Smith | de36e80 | 2014-11-11 21:30:22 +0000 | [diff] [blame] | 818 | MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 819 | assert(MD); |
| 820 | 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] | 821 | ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 822 | Weights.push_back(CI->getValue().getZExtValue()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 823 | } |
| 824 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 825 | // If TI is a conditional eq, the default case is the false case, |
| 826 | // and the corresponding branch-weight data is at index 2. We swap the |
| 827 | // default weight to be the first entry. |
| 828 | if (BranchInst* BI = dyn_cast<BranchInst>(TI)) { |
| 829 | assert(Weights.size() == 2); |
| 830 | ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); |
| 831 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 832 | std::swap(Weights.front(), Weights.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 833 | } |
| 834 | } |
| 835 | |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 836 | /// Keep halving the weights until all can fit in uint32_t. |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 837 | static void FitWeights(MutableArrayRef<uint64_t> Weights) { |
Benjamin Kramer | 79da941 | 2014-03-09 14:42:55 +0000 | [diff] [blame] | 838 | uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); |
| 839 | if (Max > UINT_MAX) { |
| 840 | unsigned Offset = 32 - countLeadingZeros(Max); |
| 841 | for (uint64_t &I : Weights) |
| 842 | I >>= Offset; |
Manman Ren | f1cb16e | 2014-01-27 23:39:03 +0000 | [diff] [blame] | 843 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 844 | } |
| 845 | |
Bill Wendling | caf1d22 | 2009-01-19 23:43:56 +0000 | [diff] [blame] | 846 | /// FoldValueComparisonIntoPredecessors - The specified terminator is a value |
| 847 | /// equality comparison instruction (either a switch or a branch on "X == c"). |
| 848 | /// See if any of the predecessors of the terminator block are value comparisons |
| 849 | /// 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] | 850 | bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, |
| 851 | IRBuilder<> &Builder) { |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 852 | BasicBlock *BB = TI->getParent(); |
| 853 | Value *CV = isValueEqualityComparison(TI); // CondVal |
| 854 | assert(CV && "Not a comparison?"); |
| 855 | bool Changed = false; |
| 856 | |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 857 | SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 858 | while (!Preds.empty()) { |
Dan Gohman | 9a6fef0 | 2009-05-06 17:22:41 +0000 | [diff] [blame] | 859 | BasicBlock *Pred = Preds.pop_back_val(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 860 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 861 | // See if the predecessor is a comparison with the same value. |
| 862 | TerminatorInst *PTI = Pred->getTerminator(); |
| 863 | Value *PCV = isValueEqualityComparison(PTI); // PredCondVal |
| 864 | |
| 865 | if (PCV == CV && SafeToMergeTerminators(TI, PTI)) { |
| 866 | // Figure out which 'cases' to copy from SI to PSI. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 867 | std::vector<ValueEqualityComparisonCase> BBCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 868 | BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); |
| 869 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 870 | std::vector<ValueEqualityComparisonCase> PredCases; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 871 | BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); |
| 872 | |
| 873 | // Based on whether the default edge from PTI goes to BB or not, fill in |
| 874 | // PredCases and PredDefault with the new switch cases we would like to |
| 875 | // build. |
Chris Lattner | 6b39cb9 | 2008-02-18 07:42:56 +0000 | [diff] [blame] | 876 | SmallVector<BasicBlock*, 8> NewSuccessors; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 877 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 878 | // Update the branch weight metadata along the way |
| 879 | SmallVector<uint64_t, 8> Weights; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 880 | bool PredHasWeights = HasBranchWeights(PTI); |
| 881 | bool SuccHasWeights = HasBranchWeights(TI); |
| 882 | |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 883 | if (PredHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 884 | GetBranchWeights(PTI, Weights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 885 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 886 | if (Weights.size() != 1 + PredCases.size()) |
| 887 | PredHasWeights = SuccHasWeights = false; |
| 888 | } else if (SuccHasWeights) |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 889 | // If there are no predecessor weights but there are successor weights, |
| 890 | // populate Weights with 1, which will later be scaled to the sum of |
| 891 | // successor's weights |
| 892 | Weights.assign(1 + PredCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 893 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 894 | SmallVector<uint64_t, 8> SuccWeights; |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 895 | if (SuccHasWeights) { |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 896 | GetBranchWeights(TI, SuccWeights); |
Andrew Trick | 7656f6d | 2012-11-15 18:40:31 +0000 | [diff] [blame] | 897 | // branch-weight metadata is inconsistent here. |
Manman Ren | 5e5049d | 2012-09-14 19:05:19 +0000 | [diff] [blame] | 898 | if (SuccWeights.size() != 1 + BBCases.size()) |
| 899 | PredHasWeights = SuccHasWeights = false; |
| 900 | } else if (PredHasWeights) |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 901 | SuccWeights.assign(1 + BBCases.size(), 1); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 902 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 903 | if (PredDefault == BB) { |
| 904 | // If this is the default destination from PTI, only the edges in TI |
| 905 | // 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] | 906 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
| 907 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 908 | if (PredCases[i].Dest != BB) |
| 909 | PTIHandled.insert(PredCases[i].Value); |
| 910 | else { |
| 911 | // The default destination is BB, we don't need explicit targets. |
| 912 | std::swap(PredCases[i], PredCases.back()); |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 913 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 914 | if (PredHasWeights || SuccHasWeights) { |
| 915 | // Increase weight for the default case. |
| 916 | Weights[0] += Weights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 917 | std::swap(Weights[i+1], Weights.back()); |
| 918 | Weights.pop_back(); |
| 919 | } |
| 920 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 921 | PredCases.pop_back(); |
| 922 | --i; --e; |
| 923 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 924 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 925 | // Reconstruct the new switch statement we will be building. |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 926 | if (PredDefault != BBDefault) { |
| 927 | PredDefault->removePredecessor(Pred); |
| 928 | PredDefault = BBDefault; |
| 929 | NewSuccessors.push_back(BBDefault); |
| 930 | } |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 931 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 932 | unsigned CasesFromPred = Weights.size(); |
| 933 | uint64_t ValidTotalSuccWeight = 0; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 934 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 935 | if (!PTIHandled.count(BBCases[i].Value) && |
| 936 | BBCases[i].Dest != BBDefault) { |
| 937 | PredCases.push_back(BBCases[i]); |
| 938 | NewSuccessors.push_back(BBCases[i].Dest); |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 939 | if (SuccHasWeights || PredHasWeights) { |
| 940 | // The default weight is at index 0, so weight for the ith case |
| 941 | // should be at index i+1. Scale the cases from successor by |
| 942 | // PredDefaultWeight (Weights[0]). |
| 943 | Weights.push_back(Weights[0] * SuccWeights[i+1]); |
| 944 | ValidTotalSuccWeight += SuccWeights[i+1]; |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 945 | } |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 946 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 947 | |
Manman Ren | 571d9e4 | 2012-09-11 17:43:35 +0000 | [diff] [blame] | 948 | if (SuccHasWeights || PredHasWeights) { |
| 949 | ValidTotalSuccWeight += SuccWeights[0]; |
| 950 | // Scale the cases from predecessor by ValidTotalSuccWeight. |
| 951 | for (unsigned i = 1; i < CasesFromPred; ++i) |
| 952 | Weights[i] *= ValidTotalSuccWeight; |
| 953 | // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). |
| 954 | Weights[0] *= SuccWeights[0]; |
| 955 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 956 | } else { |
| 957 | // If this is not the default destination from PSI, only the edges |
| 958 | // in SI that occur in PSI with a destination of BB will be |
| 959 | // activated. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 960 | std::set<ConstantInt*, ConstantIntOrdering> PTIHandled; |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 961 | std::map<ConstantInt*, uint64_t> WeightsForHandled; |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 962 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 963 | if (PredCases[i].Dest == BB) { |
| 964 | PTIHandled.insert(PredCases[i].Value); |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 965 | |
| 966 | if (PredHasWeights || SuccHasWeights) { |
| 967 | WeightsForHandled[PredCases[i].Value] = Weights[i+1]; |
| 968 | std::swap(Weights[i+1], Weights.back()); |
| 969 | Weights.pop_back(); |
| 970 | } |
| 971 | |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 972 | std::swap(PredCases[i], PredCases.back()); |
| 973 | PredCases.pop_back(); |
| 974 | --i; --e; |
| 975 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 976 | |
| 977 | // Okay, now we know which constants were sent to BB from the |
| 978 | // predecessor. Figure out where they will all go now. |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 979 | for (unsigned i = 0, e = BBCases.size(); i != e; ++i) |
| 980 | if (PTIHandled.count(BBCases[i].Value)) { |
| 981 | // If this is one we are capable of getting... |
Manman Ren | d81b8e8 | 2012-09-14 17:29:56 +0000 | [diff] [blame] | 982 | if (PredHasWeights || SuccHasWeights) |
| 983 | Weights.push_back(WeightsForHandled[BBCases[i].Value]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 984 | PredCases.push_back(BBCases[i]); |
| 985 | NewSuccessors.push_back(BBCases[i].Dest); |
| 986 | PTIHandled.erase(BBCases[i].Value);// This constant is taken care of |
| 987 | } |
| 988 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 989 | // If there are any constants vectored to BB that TI doesn't handle, |
| 990 | // they must go to the default destination of TI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 991 | for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I = |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 992 | PTIHandled.begin(), |
| 993 | E = PTIHandled.end(); I != E; ++I) { |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 994 | if (PredHasWeights || SuccHasWeights) |
| 995 | Weights.push_back(WeightsForHandled[*I]); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 996 | PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault)); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 997 | NewSuccessors.push_back(BBDefault); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 998 | } |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 999 | } |
| 1000 | |
| 1001 | // Okay, at this point, we know which new successor Pred will get. Make |
| 1002 | // sure we update the number of entries in the PHI nodes for these |
| 1003 | // successors. |
| 1004 | for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i) |
| 1005 | AddPredecessorToBlock(NewSuccessors[i], Pred, BB); |
| 1006 | |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 1007 | Builder.SetInsertPoint(PTI); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 1008 | // Convert pointer to int before we switch. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 1009 | if (CV->getType()->isPointerTy()) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1010 | assert(DL && "Cannot switch on pointer without DataLayout"); |
| 1011 | CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()), |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 1012 | "magicptr"); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 1013 | } |
| 1014 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1015 | // Now that the successors are updated, create the new Switch instruction. |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 1016 | SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault, |
| 1017 | PredCases.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 1018 | NewSI->setDebugLoc(PTI->getDebugLoc()); |
Eric Christopher | b65acc6 | 2012-07-02 23:22:21 +0000 | [diff] [blame] | 1019 | for (unsigned i = 0, e = PredCases.size(); i != e; ++i) |
| 1020 | NewSI->addCase(PredCases[i].Value, PredCases[i].Dest); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1021 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 1022 | if (PredHasWeights || SuccHasWeights) { |
| 1023 | // Halve the weights if any of them cannot fit in an uint32_t |
| 1024 | FitWeights(Weights); |
| 1025 | |
| 1026 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 1027 | |
| 1028 | NewSI->setMetadata(LLVMContext::MD_prof, |
| 1029 | MDBuilder(BB->getContext()). |
| 1030 | createBranchWeights(MDWeights)); |
| 1031 | } |
| 1032 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1033 | EraseTerminatorInstAndDCECond(PTI); |
Chris Lattner | 3215bb6 | 2005-01-01 16:02:12 +0000 | [diff] [blame] | 1034 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1035 | // Okay, last check. If BB is still a successor of PSI, then we must |
| 1036 | // have an infinite loop case. If so, add an infinitely looping block |
| 1037 | // to handle the case to preserve the behavior of the code. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1038 | BasicBlock *InfLoopBlock = nullptr; |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1039 | for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) |
| 1040 | if (NewSI->getSuccessor(i) == BB) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1041 | if (!InfLoopBlock) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 1042 | // 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] | 1043 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1044 | InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 1045 | "infloop", BB->getParent()); |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1046 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1047 | } |
| 1048 | NewSI->setSuccessor(i, InfLoopBlock); |
| 1049 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1050 | |
Chris Lattner | d3e6ae2 | 2004-02-28 21:28:10 +0000 | [diff] [blame] | 1051 | Changed = true; |
| 1052 | } |
| 1053 | } |
| 1054 | return Changed; |
| 1055 | } |
| 1056 | |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1057 | // isSafeToHoistInvoke - If we would need to insert a select that uses the |
| 1058 | // value of this invoke (comments in HoistThenElseCodeToIf explain why we |
| 1059 | // would need to do this), we can't hoist the invoke, as there is nowhere |
| 1060 | // to put the select in this case. |
| 1061 | static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, |
| 1062 | Instruction *I1, Instruction *I2) { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1063 | 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] | 1064 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1065 | for (BasicBlock::iterator BBI = SI->begin(); |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1066 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1067 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1068 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1069 | if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) { |
| 1070 | return false; |
| 1071 | } |
| 1072 | } |
| 1073 | } |
| 1074 | return true; |
| 1075 | } |
| 1076 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1077 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); |
| 1078 | |
Chris Lattner | d683bdd | 2005-08-03 17:59:45 +0000 | [diff] [blame] | 1079 | /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1080 | /// BB2, hoist any common code in the two blocks up into the branch block. The |
| 1081 | /// caller of this function guarantees that BI's block dominates BB1 and BB2. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1082 | static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1083 | // This does very trivial matching, with limited scanning, to find identical |
| 1084 | // instructions in the two blocks. In particular, we don't want to get into |
| 1085 | // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As |
| 1086 | // such, we currently just scan for obviously identical instructions in an |
| 1087 | // identical order. |
| 1088 | BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. |
| 1089 | BasicBlock *BB2 = BI->getSuccessor(1); // The false destination |
| 1090 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1091 | BasicBlock::iterator BB1_Itr = BB1->begin(); |
| 1092 | BasicBlock::iterator BB2_Itr = BB2->begin(); |
| 1093 | |
| 1094 | Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1095 | // Skip debug info if it is not identical. |
| 1096 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1097 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1098 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1099 | while (isa<DbgInfoIntrinsic>(I1)) |
| 1100 | I1 = BB1_Itr++; |
| 1101 | while (isa<DbgInfoIntrinsic>(I2)) |
| 1102 | I2 = BB2_Itr++; |
| 1103 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1104 | if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1105 | (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1106 | return false; |
| 1107 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1108 | BasicBlock *BIParent = BI->getParent(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1109 | |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1110 | bool Changed = false; |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1111 | do { |
| 1112 | // If we are hoisting the terminator instruction, don't move one (making a |
| 1113 | // broken BB), instead clone it, and remove BI. |
| 1114 | if (isa<TerminatorInst>(I1)) |
| 1115 | goto HoistTerminator; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1116 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1117 | // For a normal instruction, we just move one to right before the branch, |
| 1118 | // then replace all uses of the other with the first. Finally, we remove |
| 1119 | // the now redundant second instruction. |
| 1120 | BIParent->getInstList().splice(BI, BB1->getInstList(), I1); |
| 1121 | if (!I2->use_empty()) |
| 1122 | I2->replaceAllUsesWith(I1); |
Dan Gohman | c8a27f2 | 2009-08-25 22:11:20 +0000 | [diff] [blame] | 1123 | I1->intersectOptionalDataWith(I2); |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1124 | unsigned KnownIDs[] = { |
| 1125 | LLVMContext::MD_tbaa, |
| 1126 | LLVMContext::MD_range, |
| 1127 | LLVMContext::MD_fpmath, |
Philip Reames | d92c2a7 | 2014-10-22 16:37:13 +0000 | [diff] [blame] | 1128 | LLVMContext::MD_invariant_load, |
| 1129 | LLVMContext::MD_nonnull |
Rafael Espindola | ea46c32 | 2014-08-15 15:46:38 +0000 | [diff] [blame] | 1130 | }; |
| 1131 | combineMetadata(I1, I2, KnownIDs); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1132 | I2->eraseFromParent(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1133 | Changed = true; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1134 | |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1135 | I1 = BB1_Itr++; |
Devang Patel | f10e287 | 2009-02-04 00:03:08 +0000 | [diff] [blame] | 1136 | I2 = BB2_Itr++; |
Devang Patel | 197c352 | 2011-04-07 17:27:36 +0000 | [diff] [blame] | 1137 | // Skip debug info if it is not identical. |
| 1138 | DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); |
| 1139 | DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); |
| 1140 | if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { |
| 1141 | while (isa<DbgInfoIntrinsic>(I1)) |
| 1142 | I1 = BB1_Itr++; |
| 1143 | while (isa<DbgInfoIntrinsic>(I2)) |
| 1144 | I2 = BB2_Itr++; |
| 1145 | } |
Devang Patel | e48ddf8 | 2011-04-07 00:30:15 +0000 | [diff] [blame] | 1146 | } while (I1->isIdenticalToWhenDefined(I2)); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1147 | |
| 1148 | return true; |
| 1149 | |
| 1150 | HoistTerminator: |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1151 | // It may not be possible to hoist an invoke. |
| 1152 | if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1153 | return Changed; |
| 1154 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1155 | 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] | 1156 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1157 | for (BasicBlock::iterator BBI = SI->begin(); |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1158 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 1159 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1160 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
| 1161 | if (BB1V == BB2V) |
| 1162 | continue; |
| 1163 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1164 | // Check for passingValueIsAlwaysUndefined here because we would rather |
| 1165 | // eliminate undefined control flow then converting it to a select. |
| 1166 | if (passingValueIsAlwaysUndefined(BB1V, PN) || |
| 1167 | passingValueIsAlwaysUndefined(BB2V, PN)) |
| 1168 | return Changed; |
| 1169 | |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1170 | if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1171 | return Changed; |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1172 | if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL)) |
David Majnemer | c82f27a | 2013-06-03 20:43:12 +0000 | [diff] [blame] | 1173 | return Changed; |
| 1174 | } |
| 1175 | } |
Dale Johannesen | 9df78ee | 2009-06-15 20:59:27 +0000 | [diff] [blame] | 1176 | |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1177 | // Okay, it is safe to hoist the terminator. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 1178 | Instruction *NT = I1->clone(); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1179 | BIParent->getInstList().insert(BI, NT); |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1180 | if (!NT->getType()->isVoidTy()) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1181 | I1->replaceAllUsesWith(NT); |
| 1182 | I2->replaceAllUsesWith(NT); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1183 | NT->takeName(I1); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1184 | } |
| 1185 | |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1186 | IRBuilder<true, NoFolder> Builder(NT); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1187 | // Hoisting one of the terminators from our successor is a great thing. |
| 1188 | // Unfortunately, the successors of the if/else blocks may have PHI nodes in |
| 1189 | // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI |
| 1190 | // nodes, so we insert select instruction to compute the final result. |
| 1191 | std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1192 | 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] | 1193 | PHINode *PN; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1194 | for (BasicBlock::iterator BBI = SI->begin(); |
Chris Lattner | 0194457 | 2004-11-30 07:47:34 +0000 | [diff] [blame] | 1195 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1196 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
| 1197 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1198 | if (BB1V == BB2V) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1199 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1200 | // These values do not agree. Insert a select instruction before NT |
| 1201 | // that determines the right value. |
| 1202 | SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1203 | if (!SI) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1204 | SI = cast<SelectInst> |
| 1205 | (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, |
| 1206 | BB1V->getName()+"."+BB2V->getName())); |
| 1207 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1208 | // Make the PHI node use the select for all incoming values for BB1/BB2 |
| 1209 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 1210 | if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) |
| 1211 | PN->setIncomingValue(i, SI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | // Update any PHI nodes in our new successors. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1216 | for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) |
| 1217 | AddPredecessorToBlock(*SI, BIParent, BB1); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1218 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1219 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 389cfac | 2004-11-30 00:29:14 +0000 | [diff] [blame] | 1220 | return true; |
| 1221 | } |
| 1222 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1223 | /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd, |
| 1224 | /// check whether BBEnd has only two predecessors and the other predecessor |
| 1225 | /// ends with an unconditional branch. If it is true, sink any common code |
| 1226 | /// in the two predecessors to BBEnd. |
| 1227 | static bool SinkThenElseCodeToEnd(BranchInst *BI1) { |
| 1228 | assert(BI1->isUnconditional()); |
| 1229 | BasicBlock *BB1 = BI1->getParent(); |
| 1230 | BasicBlock *BBEnd = BI1->getSuccessor(0); |
| 1231 | |
| 1232 | // Check that BBEnd has two predecessors and the other predecessor ends with |
| 1233 | // an unconditional branch. |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1234 | pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd); |
| 1235 | BasicBlock *Pred0 = *PI++; |
| 1236 | if (PI == PE) // Only one predecessor. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1237 | return false; |
Benjamin Kramer | f064b65 | 2012-09-30 21:03:56 +0000 | [diff] [blame] | 1238 | BasicBlock *Pred1 = *PI++; |
| 1239 | if (PI != PE) // More than two predecessors. |
| 1240 | return false; |
| 1241 | BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1242 | BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator()); |
| 1243 | if (!BI2 || !BI2->isUnconditional()) |
| 1244 | return false; |
| 1245 | |
| 1246 | // Gather the PHI nodes in BBEnd. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1247 | SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1248 | Instruction *FirstNonPhiInBBEnd = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1249 | for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) { |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1250 | if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 1251 | Value *BB1V = PN->getIncomingValueForBlock(BB1); |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1252 | Value *BB2V = PN->getIncomingValueForBlock(BB2); |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1253 | JointValueMap[std::make_pair(BB1V, BB2V)] = PN; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1254 | } else { |
| 1255 | FirstNonPhiInBBEnd = &*I; |
| 1256 | break; |
| 1257 | } |
| 1258 | } |
| 1259 | if (!FirstNonPhiInBBEnd) |
| 1260 | return false; |
Andrew Trick | 90f5029 | 2012-11-15 18:40:29 +0000 | [diff] [blame] | 1261 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1262 | // This does very trivial matching, with limited scanning, to find identical |
| 1263 | // instructions in the two blocks. We scan backward for obviously identical |
| 1264 | // instructions in an identical order. |
| 1265 | BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(), |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1266 | RE1 = BB1->getInstList().rend(), |
| 1267 | RI2 = BB2->getInstList().rbegin(), |
| 1268 | RE2 = BB2->getInstList().rend(); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1269 | // Skip debug info. |
| 1270 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1271 | if (RI1 == RE1) |
| 1272 | return false; |
| 1273 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1274 | if (RI2 == RE2) |
| 1275 | return false; |
| 1276 | // Skip the unconditional branches. |
| 1277 | ++RI1; |
| 1278 | ++RI2; |
| 1279 | |
| 1280 | bool Changed = false; |
| 1281 | while (RI1 != RE1 && RI2 != RE2) { |
| 1282 | // Skip debug info. |
| 1283 | while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1; |
| 1284 | if (RI1 == RE1) |
| 1285 | return Changed; |
| 1286 | while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2; |
| 1287 | if (RI2 == RE2) |
| 1288 | return Changed; |
| 1289 | |
| 1290 | Instruction *I1 = &*RI1, *I2 = &*RI2; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1291 | auto InstPair = std::make_pair(I1, I2); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1292 | // I1 and I2 should have a single use in the same PHI node, and they |
| 1293 | // perform the same operation. |
| 1294 | // Cannot move control-flow-involving, volatile loads, vaarg, etc. |
| 1295 | if (isa<PHINode>(I1) || isa<PHINode>(I2) || |
| 1296 | isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) || |
| 1297 | isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) || |
| 1298 | isa<AllocaInst>(I1) || isa<AllocaInst>(I2) || |
| 1299 | I1->mayHaveSideEffects() || I2->mayHaveSideEffects() || |
| 1300 | I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() || |
| 1301 | !I1->hasOneUse() || !I2->hasOneUse() || |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1302 | !JointValueMap.count(InstPair)) |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1303 | return Changed; |
| 1304 | |
| 1305 | // Check whether we should swap the operands of ICmpInst. |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1306 | // TODO: Add support of communativity. |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1307 | ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2); |
| 1308 | bool SwapOpnds = false; |
| 1309 | if (ICmp1 && ICmp2 && |
| 1310 | ICmp1->getOperand(0) != ICmp2->getOperand(0) && |
| 1311 | ICmp1->getOperand(1) != ICmp2->getOperand(1) && |
| 1312 | (ICmp1->getOperand(0) == ICmp2->getOperand(1) || |
| 1313 | ICmp1->getOperand(1) == ICmp2->getOperand(0))) { |
| 1314 | ICmp2->swapOperands(); |
| 1315 | SwapOpnds = true; |
| 1316 | } |
| 1317 | if (!I1->isSameOperationAs(I2)) { |
| 1318 | if (SwapOpnds) |
| 1319 | ICmp2->swapOperands(); |
| 1320 | return Changed; |
| 1321 | } |
| 1322 | |
| 1323 | // The operands should be either the same or they need to be generated |
| 1324 | // with a PHI node after sinking. We only handle the case where there is |
| 1325 | // a single pair of different operands. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1326 | Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1327 | unsigned Op1Idx = ~0U; |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1328 | for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) { |
| 1329 | if (I1->getOperand(I) == I2->getOperand(I)) |
| 1330 | continue; |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1331 | // Early exit if we have more-than one pair of different operands or if |
| 1332 | // we need a PHI node to replace a constant. |
| 1333 | if (Op1Idx != ~0U || |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1334 | isa<Constant>(I1->getOperand(I)) || |
| 1335 | isa<Constant>(I2->getOperand(I))) { |
| 1336 | // If we can't sink the instructions, undo the swapping. |
| 1337 | if (SwapOpnds) |
| 1338 | ICmp2->swapOperands(); |
| 1339 | return Changed; |
| 1340 | } |
| 1341 | DifferentOp1 = I1->getOperand(I); |
| 1342 | Op1Idx = I; |
| 1343 | DifferentOp2 = I2->getOperand(I); |
| 1344 | } |
| 1345 | |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1346 | DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n"); |
| 1347 | DEBUG(dbgs() << " " << *I2 << "\n"); |
| 1348 | |
| 1349 | // We insert the pair of different operands to JointValueMap and |
| 1350 | // remove (I1, I2) from JointValueMap. |
| 1351 | if (Op1Idx != ~0U) { |
| 1352 | auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)]; |
| 1353 | if (!NewPN) { |
| 1354 | NewPN = |
| 1355 | PHINode::Create(DifferentOp1->getType(), 2, |
| 1356 | DifferentOp1->getName() + ".sink", BBEnd->begin()); |
| 1357 | NewPN->addIncoming(DifferentOp1, BB1); |
| 1358 | NewPN->addIncoming(DifferentOp2, BB2); |
| 1359 | DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";); |
| 1360 | } |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1361 | // I1 should use NewPN instead of DifferentOp1. |
| 1362 | I1->setOperand(Op1Idx, NewPN); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1363 | } |
Michael Liao | 5313da3 | 2014-12-23 08:26:55 +0000 | [diff] [blame] | 1364 | PHINode *OldPN = JointValueMap[InstPair]; |
| 1365 | JointValueMap.erase(InstPair); |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1366 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1367 | // We need to update RE1 and RE2 if we are going to sink the first |
| 1368 | // instruction in the basic block down. |
| 1369 | bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin()); |
| 1370 | // Sink the instruction. |
| 1371 | BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1); |
| 1372 | if (!OldPN->use_empty()) |
| 1373 | OldPN->replaceAllUsesWith(I1); |
| 1374 | OldPN->eraseFromParent(); |
| 1375 | |
| 1376 | if (!I2->use_empty()) |
| 1377 | I2->replaceAllUsesWith(I1); |
| 1378 | I1->intersectOptionalDataWith(I2); |
Philip Reames | d92c2a7 | 2014-10-22 16:37:13 +0000 | [diff] [blame] | 1379 | // TODO: Use combineMetadata here to preserve what metadata we can |
| 1380 | // (analogous to the hoisting case above). |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 1381 | I2->eraseFromParent(); |
| 1382 | |
| 1383 | if (UpdateRE1) |
| 1384 | RE1 = BB1->getInstList().rend(); |
| 1385 | if (UpdateRE2) |
| 1386 | RE2 = BB2->getInstList().rend(); |
| 1387 | FirstNonPhiInBBEnd = I1; |
| 1388 | NumSinkCommons++; |
| 1389 | Changed = true; |
| 1390 | } |
| 1391 | return Changed; |
| 1392 | } |
| 1393 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1394 | /// \brief Determine if we can hoist sink a sole store instruction out of a |
| 1395 | /// conditional block. |
| 1396 | /// |
| 1397 | /// We are looking for code like the following: |
| 1398 | /// BrBB: |
| 1399 | /// store i32 %add, i32* %arrayidx2 |
| 1400 | /// ... // No other stores or function calls (we could be calling a memory |
| 1401 | /// ... // function). |
| 1402 | /// %cmp = icmp ult %x, %y |
| 1403 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1404 | /// ThenBB: |
| 1405 | /// store i32 %add5, i32* %arrayidx2 |
| 1406 | /// br label EndBB |
| 1407 | /// EndBB: |
| 1408 | /// ... |
| 1409 | /// We are going to transform this into: |
| 1410 | /// BrBB: |
| 1411 | /// store i32 %add, i32* %arrayidx2 |
| 1412 | /// ... // |
| 1413 | /// %cmp = icmp ult %x, %y |
| 1414 | /// %add.add5 = select i1 %cmp, i32 %add, %add5 |
| 1415 | /// store i32 %add.add5, i32* %arrayidx2 |
| 1416 | /// ... |
| 1417 | /// |
| 1418 | /// \return The pointer to the value of the previous store if the store can be |
| 1419 | /// hoisted into the predecessor block. 0 otherwise. |
Benjamin Kramer | ad5c24f | 2013-05-23 16:09:15 +0000 | [diff] [blame] | 1420 | static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, |
| 1421 | BasicBlock *StoreBB, BasicBlock *EndBB) { |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1422 | StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); |
| 1423 | if (!StoreToHoist) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1424 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1425 | |
| 1426 | // Volatile or atomic. |
| 1427 | if (!StoreToHoist->isSimple()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1428 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1429 | |
| 1430 | Value *StorePtr = StoreToHoist->getPointerOperand(); |
| 1431 | |
| 1432 | // Look for a store to the same pointer in BrBB. |
| 1433 | unsigned MaxNumInstToLookAt = 10; |
| 1434 | for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), |
| 1435 | RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) { |
| 1436 | Instruction *CurI = &*RI; |
| 1437 | |
| 1438 | // Could be calling an instruction that effects memory like free(). |
| 1439 | if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1440 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1441 | |
| 1442 | StoreInst *SI = dyn_cast<StoreInst>(CurI); |
| 1443 | // Found the previous store make sure it stores to the same location. |
| 1444 | if (SI && SI->getPointerOperand() == StorePtr) |
| 1445 | // Found the previous store, return its value operand. |
| 1446 | return SI->getValueOperand(); |
| 1447 | else if (SI) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1448 | return nullptr; // Unknown store. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1449 | } |
| 1450 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1451 | return nullptr; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1452 | } |
| 1453 | |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1454 | /// \brief Speculate a conditional basic block flattening the CFG. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1455 | /// |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1456 | /// Note that this is a very risky transform currently. Speculating |
| 1457 | /// instructions like this is most often not desirable. Instead, there is an MI |
| 1458 | /// pass which can do it with full awareness of the resource constraints. |
| 1459 | /// However, some cases are "obvious" and we should do directly. An example of |
| 1460 | /// this is speculating a single, reasonably cheap instruction. |
| 1461 | /// |
| 1462 | /// There is only one distinct advantage to flattening the CFG at the IR level: |
| 1463 | /// it makes very common but simplistic optimizations such as are common in |
| 1464 | /// instcombine and the DAG combiner more powerful by removing CFG edges and |
| 1465 | /// modeling their effects with easier to reason about SSA value graphs. |
| 1466 | /// |
| 1467 | /// |
| 1468 | /// An illustration of this transform is turning this IR: |
| 1469 | /// \code |
| 1470 | /// BB: |
| 1471 | /// %cmp = icmp ult %x, %y |
| 1472 | /// br i1 %cmp, label %EndBB, label %ThenBB |
| 1473 | /// ThenBB: |
| 1474 | /// %sub = sub %x, %y |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1475 | /// br label BB2 |
Chandler Carruth | 8a4a166 | 2013-01-24 08:05:06 +0000 | [diff] [blame] | 1476 | /// EndBB: |
| 1477 | /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] |
| 1478 | /// ... |
| 1479 | /// \endcode |
| 1480 | /// |
| 1481 | /// Into this IR: |
| 1482 | /// \code |
| 1483 | /// BB: |
| 1484 | /// %cmp = icmp ult %x, %y |
| 1485 | /// %sub = sub %x, %y |
| 1486 | /// %cond = select i1 %cmp, 0, %sub |
| 1487 | /// ... |
| 1488 | /// \endcode |
| 1489 | /// |
| 1490 | /// \returns true if the conditional block is removed. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1491 | static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, |
| 1492 | const DataLayout *DL) { |
Chandler Carruth | 1d20c02 | 2013-01-24 08:22:40 +0000 | [diff] [blame] | 1493 | // Be conservative for now. FP select instruction can often be expensive. |
| 1494 | Value *BrCond = BI->getCondition(); |
| 1495 | if (isa<FCmpInst>(BrCond)) |
| 1496 | return false; |
| 1497 | |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1498 | BasicBlock *BB = BI->getParent(); |
| 1499 | BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); |
| 1500 | |
| 1501 | // If ThenBB is actually on the false edge of the conditional branch, remember |
| 1502 | // to swap the select operands later. |
| 1503 | bool Invert = false; |
| 1504 | if (ThenBB != BI->getSuccessor(0)) { |
| 1505 | assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); |
| 1506 | Invert = true; |
| 1507 | } |
| 1508 | assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); |
| 1509 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1510 | // Keep a count of how many times instructions are used within CondBB when |
| 1511 | // they are candidates for sinking into CondBB. Specifically: |
| 1512 | // - They are defined in BB, and |
| 1513 | // - They have no side effects, and |
| 1514 | // - All of their uses are in CondBB. |
| 1515 | SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; |
| 1516 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1517 | unsigned SpeculationCost = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1518 | Value *SpeculatedStoreValue = nullptr; |
| 1519 | StoreInst *SpeculatedStore = nullptr; |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1520 | for (BasicBlock::iterator BBI = ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1521 | BBE = std::prev(ThenBB->end()); |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1522 | BBI != BBE; ++BBI) { |
| 1523 | Instruction *I = BBI; |
| 1524 | // Skip debug info. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1525 | if (isa<DbgInfoIntrinsic>(I)) |
| 1526 | continue; |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1527 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1528 | // Only speculatively execution a single instruction (not counting the |
| 1529 | // terminator) for now. |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1530 | ++SpeculationCost; |
| 1531 | if (SpeculationCost > 1) |
Devang Patel | 5aed776 | 2009-03-06 06:00:17 +0000 | [diff] [blame] | 1532 | return false; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1533 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1534 | // Don't hoist the instruction if it's unsafe or expensive. |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1535 | if (!isSafeToSpeculativelyExecute(I, DL) && |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1536 | !(HoistCondStores && |
| 1537 | (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB, |
| 1538 | EndBB)))) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1539 | return false; |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1540 | if (!SpeculatedStoreValue && |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1541 | ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1542 | return false; |
| 1543 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1544 | // Store the store speculation candidate. |
| 1545 | if (SpeculatedStoreValue) |
| 1546 | SpeculatedStore = cast<StoreInst>(I); |
| 1547 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1548 | // 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] | 1549 | // used in BB. The transformation will prevent the operand from |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1550 | // being sunk into the use block. |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1551 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1552 | i != e; ++i) { |
| 1553 | Instruction *OpI = dyn_cast<Instruction>(*i); |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1554 | if (!OpI || OpI->getParent() != BB || |
| 1555 | OpI->mayHaveSideEffects()) |
| 1556 | continue; // Not a candidate for sinking. |
| 1557 | |
| 1558 | ++SinkCandidateUseCounts[OpI]; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1559 | } |
| 1560 | } |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1561 | |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1562 | // Consider any sink candidates which are only used in CondBB as costs for |
| 1563 | // speculation. Note, while we iterate over a DenseMap here, we are summing |
| 1564 | // and so iteration order isn't significant. |
| 1565 | for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I = |
| 1566 | SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end(); |
| 1567 | I != E; ++I) |
| 1568 | if (I->first->getNumUses() == I->second) { |
Chandler Carruth | 329b590 | 2013-01-27 06:42:03 +0000 | [diff] [blame] | 1569 | ++SpeculationCost; |
| 1570 | if (SpeculationCost > 1) |
Chandler Carruth | ceff222 | 2013-01-25 05:40:09 +0000 | [diff] [blame] | 1571 | return false; |
| 1572 | } |
| 1573 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1574 | // Check that the PHI nodes can be converted to selects. |
| 1575 | bool HaveRewritablePHIs = false; |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1576 | for (BasicBlock::iterator I = EndBB->begin(); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1577 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1578 | Value *OrigV = PN->getIncomingValueForBlock(BB); |
| 1579 | Value *ThenV = PN->getIncomingValueForBlock(ThenBB); |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1580 | |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1581 | // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1582 | // Skip PHIs which are trivial. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1583 | if (ThenV == OrigV) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1584 | continue; |
| 1585 | |
Arnold Schwaighofer | d7d010e | 2014-10-10 01:27:02 +0000 | [diff] [blame] | 1586 | // Don't convert to selects if we could remove undefined behavior instead. |
| 1587 | if (passingValueIsAlwaysUndefined(OrigV, PN) || |
| 1588 | passingValueIsAlwaysUndefined(ThenV, PN)) |
| 1589 | return false; |
| 1590 | |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1591 | HaveRewritablePHIs = true; |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1592 | ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); |
| 1593 | ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); |
| 1594 | if (!OrigCE && !ThenCE) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1595 | continue; // Known safe and cheap. |
| 1596 | |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1597 | if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) || |
| 1598 | (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL))) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1599 | return false; |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1600 | unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0; |
| 1601 | unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0; |
Rafael Espindola | a5e536a | 2013-06-04 14:11:59 +0000 | [diff] [blame] | 1602 | if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold) |
Chandler Carruth | 8a21005 | 2013-01-24 11:53:01 +0000 | [diff] [blame] | 1603 | return false; |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1604 | |
Chandler Carruth | 01bffaa | 2013-01-24 12:05:17 +0000 | [diff] [blame] | 1605 | // Account for the cost of an unfolded ConstantExpr which could end up |
| 1606 | // getting expanded into Instructions. |
| 1607 | // 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] | 1608 | // constant expression. |
| 1609 | ++SpeculationCost; |
| 1610 | if (SpeculationCost > 1) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1611 | return false; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1612 | } |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1613 | |
| 1614 | // If there are no PHIs to process, bail early. This helps ensure idempotence |
| 1615 | // as well. |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1616 | if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1617 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1618 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1619 | // If we get here, we can hoist the instruction and if-convert. |
Chandler Carruth | e2a779f | 2013-01-24 09:59:39 +0000 | [diff] [blame] | 1620 | DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1621 | |
Arnold Schwaighofer | 474df6d | 2013-04-29 21:28:24 +0000 | [diff] [blame] | 1622 | // Insert a select of the value of the speculated store. |
| 1623 | if (SpeculatedStoreValue) { |
| 1624 | IRBuilder<true, NoFolder> Builder(BI); |
| 1625 | Value *TrueV = SpeculatedStore->getValueOperand(); |
| 1626 | Value *FalseV = SpeculatedStoreValue; |
| 1627 | if (Invert) |
| 1628 | std::swap(TrueV, FalseV); |
| 1629 | Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() + |
| 1630 | "." + FalseV->getName()); |
| 1631 | SpeculatedStore->setOperand(0, S); |
| 1632 | } |
| 1633 | |
Chandler Carruth | 7481ca8 | 2013-01-24 11:52:58 +0000 | [diff] [blame] | 1634 | // Hoist the instructions. |
| 1635 | BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(), |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1636 | std::prev(ThenBB->end())); |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1637 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1638 | // Insert selects and rewrite the PHI operands. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1639 | IRBuilder<true, NoFolder> Builder(BI); |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1640 | for (BasicBlock::iterator I = EndBB->begin(); |
| 1641 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
| 1642 | unsigned OrigI = PN->getBasicBlockIndex(BB); |
| 1643 | unsigned ThenI = PN->getBasicBlockIndex(ThenBB); |
| 1644 | Value *OrigV = PN->getIncomingValue(OrigI); |
| 1645 | Value *ThenV = PN->getIncomingValue(ThenI); |
| 1646 | |
| 1647 | // Skip PHIs which are trivial. |
| 1648 | if (OrigV == ThenV) |
| 1649 | continue; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1650 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1651 | // Create a select whose true value is the speculatively executed value and |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1652 | // false value is the preexisting value. Swap them if the branch |
| 1653 | // destinations were inverted. |
| 1654 | Value *TrueV = ThenV, *FalseV = OrigV; |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 1655 | if (Invert) |
Chandler Carruth | 76aacbd | 2013-01-24 10:40:51 +0000 | [diff] [blame] | 1656 | std::swap(TrueV, FalseV); |
| 1657 | Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, |
| 1658 | TrueV->getName() + "." + FalseV->getName()); |
| 1659 | PN->setIncomingValue(OrigI, V); |
| 1660 | PN->setIncomingValue(ThenI, V); |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1661 | } |
| 1662 | |
Evan Cheng | 89553cc | 2008-06-12 21:15:59 +0000 | [diff] [blame] | 1663 | ++NumSpeculations; |
Evan Cheng | 89200c9 | 2008-06-07 08:52:29 +0000 | [diff] [blame] | 1664 | return true; |
| 1665 | } |
| 1666 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1667 | /// \returns True if this block contains a CallInst with the NoDuplicate |
| 1668 | /// attribute. |
| 1669 | static bool HasNoDuplicateCall(const BasicBlock *BB) { |
| 1670 | for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 1671 | const CallInst *CI = dyn_cast<CallInst>(I); |
| 1672 | if (!CI) |
| 1673 | continue; |
| 1674 | if (CI->cannotDuplicate()) |
| 1675 | return true; |
| 1676 | } |
| 1677 | return false; |
| 1678 | } |
| 1679 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1680 | /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch |
| 1681 | /// across this block. |
| 1682 | static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { |
| 1683 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1684 | unsigned Size = 0; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1685 | |
Devang Patel | 84fceff | 2009-03-10 18:00:05 +0000 | [diff] [blame] | 1686 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1687 | if (isa<DbgInfoIntrinsic>(BBI)) |
| 1688 | continue; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1689 | if (Size > 10) return false; // Don't clone large BB's. |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1690 | ++Size; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1691 | |
Dale Johannesen | ed6f5a8 | 2009-03-12 23:18:09 +0000 | [diff] [blame] | 1692 | // We can only support instructions that do not define values that are |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1693 | // live outside of the current basic block. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1694 | for (User *U : BBI->users()) { |
| 1695 | Instruction *UI = cast<Instruction>(U); |
| 1696 | if (UI->getParent() != BB || isa<PHINode>(UI)) return false; |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1697 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1698 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1699 | // Looks ok, continue checking. |
| 1700 | } |
Chris Lattner | 6c70106 | 2005-09-20 01:48:40 +0000 | [diff] [blame] | 1701 | |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1702 | return true; |
| 1703 | } |
| 1704 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1705 | /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value |
| 1706 | /// that is defined in the same block as the branch and if any PHI entries are |
| 1707 | /// constants, thread edges corresponding to that entry to be branches to their |
| 1708 | /// ultimate destination. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1709 | static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) { |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1710 | BasicBlock *BB = BI->getParent(); |
| 1711 | PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); |
Chris Lattner | 049cb44 | 2005-09-19 23:57:04 +0000 | [diff] [blame] | 1712 | // NOTE: we currently cannot transform this case if the PHI node is used |
| 1713 | // outside of the block. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1714 | if (!PN || PN->getParent() != BB || !PN->hasOneUse()) |
| 1715 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1716 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1717 | // Degenerate case of a single entry PHI. |
| 1718 | if (PN->getNumIncomingValues() == 1) { |
Chris Lattner | dc3f6f2 | 2008-12-03 19:44:02 +0000 | [diff] [blame] | 1719 | FoldSingleEntryPHINodes(PN->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1720 | return true; |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1721 | } |
| 1722 | |
| 1723 | // Now we know that this block has multiple preds and two succs. |
Chris Lattner | f0bd8d0 | 2005-09-20 00:43:16 +0000 | [diff] [blame] | 1724 | if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1725 | |
Tom Stellard | e1631dd | 2013-10-21 20:07:30 +0000 | [diff] [blame] | 1726 | if (HasNoDuplicateCall(BB)) return false; |
| 1727 | |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1728 | // Okay, this is a simple enough basic block. See if any phi values are |
| 1729 | // constants. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1730 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1731 | ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1732 | if (!CB || !CB->getType()->isIntegerTy(1)) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1733 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1734 | // Okay, we now know that all edges from PredBB should be revectored to |
| 1735 | // branch to RealDest. |
| 1736 | BasicBlock *PredBB = PN->getIncomingBlock(i); |
| 1737 | BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1738 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1739 | if (RealDest == BB) continue; // Skip self loops. |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1740 | // Skip if the predecessor's terminator is an indirect branch. |
| 1741 | if (isa<IndirectBrInst>(PredBB->getTerminator())) continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1742 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1743 | // The dest block might have PHI nodes, other predecessors and other |
| 1744 | // difficult cases. Instead of being smart about this, just insert a new |
| 1745 | // block that jumps to the destination block, effectively splitting |
| 1746 | // the edge we are about to create. |
| 1747 | BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(), |
| 1748 | RealDest->getName()+".critedge", |
| 1749 | RealDest->getParent(), RealDest); |
| 1750 | BranchInst::Create(RealDest, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1751 | |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 1752 | // Update PHI nodes. |
| 1753 | AddPredecessorToBlock(RealDest, EdgeBB, BB); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1754 | |
| 1755 | // BB may have instructions that are being threaded over. Clone these |
| 1756 | // instructions into EdgeBB. We know that there will be no uses of the |
| 1757 | // cloned instructions outside of EdgeBB. |
| 1758 | BasicBlock::iterator InsertPt = EdgeBB->begin(); |
| 1759 | DenseMap<Value*, Value*> TranslateMap; // Track translated values. |
| 1760 | for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { |
| 1761 | if (PHINode *PN = dyn_cast<PHINode>(BBI)) { |
| 1762 | TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); |
| 1763 | continue; |
| 1764 | } |
| 1765 | // Clone the instruction. |
| 1766 | Instruction *N = BBI->clone(); |
| 1767 | if (BBI->hasName()) N->setName(BBI->getName()+".c"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1768 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1769 | // Update operands due to translation. |
| 1770 | for (User::op_iterator i = N->op_begin(), e = N->op_end(); |
| 1771 | i != e; ++i) { |
| 1772 | DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i); |
| 1773 | if (PI != TranslateMap.end()) |
| 1774 | *i = PI->second; |
| 1775 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1776 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1777 | // Check for trivial simplification. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1778 | if (Value *V = SimplifyInstruction(N, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1779 | TranslateMap[BBI] = V; |
| 1780 | delete N; // Instruction folded away, don't need actual inst |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1781 | } else { |
| 1782 | // Insert the new instruction into its new home. |
| 1783 | EdgeBB->getInstList().insert(InsertPt, N); |
| 1784 | if (!BBI->use_empty()) |
| 1785 | TranslateMap[BBI] = N; |
| 1786 | } |
| 1787 | } |
| 1788 | |
| 1789 | // Loop over all of the edges from PredBB to BB, changing them to branch |
| 1790 | // to EdgeBB instead. |
| 1791 | TerminatorInst *PredBBTI = PredBB->getTerminator(); |
| 1792 | for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) |
| 1793 | if (PredBBTI->getSuccessor(i) == BB) { |
| 1794 | BB->removePredecessor(PredBB); |
| 1795 | PredBBTI->setSuccessor(i, EdgeBB); |
| 1796 | } |
Bill Wendling | 4f163df | 2011-06-04 09:42:04 +0000 | [diff] [blame] | 1797 | |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1798 | // Recurse, simplifying any other constants. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1799 | return FoldCondBranchOnPHI(BI, DL) | true; |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1800 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1801 | |
| 1802 | return false; |
| 1803 | } |
| 1804 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1805 | /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry |
| 1806 | /// PHI node, see if we can eliminate it. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1807 | static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1808 | // Ok, this is a two entry PHI node. Check to see if this is a simple "if |
| 1809 | // statement", which has a very simple dominance structure. Basically, we |
| 1810 | // are trying to find the condition that is being branched on, which |
| 1811 | // subsequently causes this merge to happen. We really want control |
| 1812 | // dependence information for this check, but simplifycfg can't keep it up |
| 1813 | // 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] | 1814 | BasicBlock *BB = PN->getParent(); |
| 1815 | BasicBlock *IfTrue, *IfFalse; |
| 1816 | Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1817 | if (!IfCond || |
| 1818 | // Don't bother if the branch will be constant folded trivially. |
| 1819 | isa<ConstantInt>(IfCond)) |
| 1820 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1821 | |
Chris Lattner | 95adf8f1 | 2006-11-18 19:19:36 +0000 | [diff] [blame] | 1822 | // Okay, we found that we can merge this two-entry phi node into a select. |
| 1823 | // Doing so would require us to fold *all* two entry phi nodes in this block. |
| 1824 | // At some point this becomes non-profitable (particularly if the target |
| 1825 | // doesn't support cmov's). Only do this transformation if there are two or |
| 1826 | // fewer PHI nodes in this block. |
| 1827 | unsigned NumPhis = 0; |
| 1828 | for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) |
| 1829 | if (NumPhis > 2) |
| 1830 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1831 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1832 | // Loop over the PHI's seeing if we can promote them all to select |
| 1833 | // instructions. While we are at it, keep track of the instructions |
| 1834 | // that need to be moved to the dominating block. |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1835 | SmallPtrSet<Instruction*, 4> AggressiveInsts; |
Peter Collingbourne | 616044a | 2011-04-29 18:47:38 +0000 | [diff] [blame] | 1836 | unsigned MaxCostVal0 = PHINodeFoldingThreshold, |
| 1837 | MaxCostVal1 = PHINodeFoldingThreshold; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1838 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1839 | for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { |
| 1840 | PHINode *PN = cast<PHINode>(II++); |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 1841 | if (Value *V = SimplifyInstruction(PN, DL)) { |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1842 | PN->replaceAllUsesWith(V); |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1843 | PN->eraseFromParent(); |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1844 | continue; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1845 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1846 | |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1847 | if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1848 | MaxCostVal0, DL) || |
Peter Collingbourne | e3511e1 | 2011-04-29 18:47:31 +0000 | [diff] [blame] | 1849 | !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 1850 | MaxCostVal1, DL)) |
Chris Lattner | b42d293 | 2010-12-14 07:20:29 +0000 | [diff] [blame] | 1851 | return false; |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1852 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1853 | |
Sylvestre Ledru | 35521e2 | 2012-07-23 08:51:15 +0000 | [diff] [blame] | 1854 | // 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] | 1855 | // we ran out of PHIs then we simplified them all. |
| 1856 | PN = dyn_cast<PHINode>(BB->begin()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1857 | if (!PN) return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1858 | |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1859 | // Don't fold i1 branches on PHIs which contain binary operators. These can |
| 1860 | // often be turned into switches and other things. |
| 1861 | if (PN->getType()->isIntegerTy(1) && |
| 1862 | (isa<BinaryOperator>(PN->getIncomingValue(0)) || |
| 1863 | isa<BinaryOperator>(PN->getIncomingValue(1)) || |
| 1864 | isa<BinaryOperator>(IfCond))) |
| 1865 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1866 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1867 | // If we all PHI nodes are promotable, check to make sure that all |
| 1868 | // instructions in the predecessor blocks can be promoted as well. If |
| 1869 | // not, we won't be able to get rid of the control flow, so it's not |
| 1870 | // worth promoting to select instructions. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1871 | BasicBlock *DomBlock = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1872 | BasicBlock *IfBlock1 = PN->getIncomingBlock(0); |
| 1873 | BasicBlock *IfBlock2 = PN->getIncomingBlock(1); |
| 1874 | if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1875 | IfBlock1 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1876 | } else { |
| 1877 | DomBlock = *pred_begin(IfBlock1); |
| 1878 | for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I) |
Devang Patel | 2032cad | 2009-02-03 22:12:02 +0000 | [diff] [blame] | 1879 | if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1880 | // This is not an aggressive instruction that we can promote. |
| 1881 | // Because of this, we won't be able to get rid of the control |
| 1882 | // flow, so the xform is not worth it. |
| 1883 | return false; |
| 1884 | } |
| 1885 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1886 | |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1887 | if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1888 | IfBlock2 = nullptr; |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1889 | } else { |
| 1890 | DomBlock = *pred_begin(IfBlock2); |
| 1891 | for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I) |
Devang Patel | 2032cad | 2009-02-03 22:12:02 +0000 | [diff] [blame] | 1892 | if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) { |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1893 | // This is not an aggressive instruction that we can promote. |
| 1894 | // Because of this, we won't be able to get rid of the control |
| 1895 | // flow, so the xform is not worth it. |
| 1896 | return false; |
| 1897 | } |
| 1898 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1899 | |
Chris Lattner | 9fd838d | 2010-12-14 07:23:10 +0000 | [diff] [blame] | 1900 | DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " |
Chris Lattner | 9ac168d | 2010-12-14 07:41:39 +0000 | [diff] [blame] | 1901 | << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1902 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1903 | // If we can still promote the PHI nodes after this gauntlet of tests, |
| 1904 | // do all of the PHI's now. |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1905 | Instruction *InsertPt = DomBlock->getTerminator(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 1906 | IRBuilder<true, NoFolder> Builder(InsertPt); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1907 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1908 | // Move all 'aggressive' instructions, which are defined in the |
| 1909 | // conditional parts of the if's up to the dominating block. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1910 | if (IfBlock1) |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1911 | DomBlock->getInstList().splice(InsertPt, |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1912 | IfBlock1->getInstList(), IfBlock1->begin(), |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1913 | IfBlock1->getTerminator()); |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1914 | if (IfBlock2) |
Chris Lattner | 7499b45 | 2010-12-14 08:46:09 +0000 | [diff] [blame] | 1915 | DomBlock->getInstList().splice(InsertPt, |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1916 | IfBlock2->getInstList(), IfBlock2->begin(), |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1917 | IfBlock2->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1918 | |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1919 | while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { |
| 1920 | // Change the PHI node into a select instruction. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1921 | Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); |
| 1922 | Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1923 | |
| 1924 | SelectInst *NV = |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1925 | cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, "")); |
Chris Lattner | 8dd4cae | 2007-02-11 01:37:51 +0000 | [diff] [blame] | 1926 | PN->replaceAllUsesWith(NV); |
| 1927 | NV->takeName(PN); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 1928 | PN->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1929 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1930 | |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1931 | // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement |
| 1932 | // has been flattened. Change DomBlock to jump directly to our new block to |
| 1933 | // avoid other simplifycfg's kicking in on the diamond. |
| 1934 | TerminatorInst *OldTI = DomBlock->getTerminator(); |
Devang Patel | 5c810ce | 2011-05-18 18:16:44 +0000 | [diff] [blame] | 1935 | Builder.SetInsertPoint(OldTI); |
| 1936 | Builder.CreateBr(BB); |
Chris Lattner | 335f0e4 | 2010-12-14 08:01:53 +0000 | [diff] [blame] | 1937 | OldTI->eraseFromParent(); |
Chris Lattner | cc14ebc | 2005-09-23 06:39:30 +0000 | [diff] [blame] | 1938 | return true; |
| 1939 | } |
Chris Lattner | 748f903 | 2005-09-19 23:49:37 +0000 | [diff] [blame] | 1940 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1941 | /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes |
| 1942 | /// to two returning blocks, try to merge them together into one return, |
| 1943 | /// introducing a select if the return values disagree. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1944 | static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1945 | IRBuilder<> &Builder) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1946 | assert(BI->isConditional() && "Must be a conditional branch"); |
| 1947 | BasicBlock *TrueSucc = BI->getSuccessor(0); |
| 1948 | BasicBlock *FalseSucc = BI->getSuccessor(1); |
| 1949 | ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); |
| 1950 | ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1951 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1952 | // Check to ensure both blocks are empty (just a return) or optionally empty |
| 1953 | // with PHI nodes. If there are other instructions, merging would cause extra |
| 1954 | // computation on one path or the other. |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1955 | if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1956 | return false; |
Chris Lattner | 4088e2b | 2010-12-13 01:47:07 +0000 | [diff] [blame] | 1957 | if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) |
Devang Patel | 086b212 | 2009-02-05 00:30:42 +0000 | [diff] [blame] | 1958 | return false; |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1959 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1960 | Builder.SetInsertPoint(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1961 | // Okay, we found a branch that is going to two return nodes. If |
| 1962 | // there is no return value for this function, just change the |
| 1963 | // branch into a return. |
| 1964 | if (FalseRet->getNumOperands() == 0) { |
| 1965 | TrueSucc->removePredecessor(BI->getParent()); |
| 1966 | FalseSucc->removePredecessor(BI->getParent()); |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 1967 | Builder.CreateRetVoid(); |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 1968 | EraseTerminatorInstAndDCECond(BI); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1969 | return true; |
| 1970 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1971 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1972 | // Otherwise, figure out what the true and false return values are |
| 1973 | // so we can insert a new select instruction. |
| 1974 | Value *TrueValue = TrueRet->getReturnValue(); |
| 1975 | Value *FalseValue = FalseRet->getReturnValue(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1976 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1977 | // Unwrap any PHI nodes in the return blocks. |
| 1978 | if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) |
| 1979 | if (TVPN->getParent() == TrueSucc) |
| 1980 | TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); |
| 1981 | if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) |
| 1982 | if (FVPN->getParent() == FalseSucc) |
| 1983 | FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1984 | |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 1985 | // In order for this transformation to be safe, we must be able to |
| 1986 | // unconditionally execute both operands to the return. This is |
| 1987 | // normally the case, but we could have a potentially-trapping |
| 1988 | // constant expression that prevents this transformation from being |
| 1989 | // safe. |
| 1990 | if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) |
| 1991 | if (TCV->canTrap()) |
| 1992 | return false; |
| 1993 | if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) |
| 1994 | if (FCV->canTrap()) |
| 1995 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 1996 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 1997 | // Okay, we collected all the mapped values and checked them for sanity, and |
| 1998 | // defined to really do this transformation. First, update the CFG. |
| 1999 | TrueSucc->removePredecessor(BI->getParent()); |
| 2000 | FalseSucc->removePredecessor(BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2001 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2002 | // Insert select instructions where needed. |
| 2003 | Value *BrCond = BI->getCondition(); |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2004 | if (TrueValue) { |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2005 | // Insert a select if the results differ. |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2006 | if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { |
| 2007 | } else if (isa<UndefValue>(TrueValue)) { |
| 2008 | TrueValue = FalseValue; |
| 2009 | } else { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2010 | TrueValue = Builder.CreateSelect(BrCond, TrueValue, |
| 2011 | FalseValue, "retval"); |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2012 | } |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2013 | } |
| 2014 | |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2015 | Value *RI = !TrueValue ? |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2016 | Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); |
| 2017 | |
Daniel Dunbar | 5e0a58b | 2009-08-23 10:29:55 +0000 | [diff] [blame] | 2018 | (void) RI; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2019 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2020 | DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2021 | << "\n " << *BI << "NewRet = " << *RI |
| 2022 | << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2023 | |
Eli Friedman | cb61afb | 2008-12-16 20:54:32 +0000 | [diff] [blame] | 2024 | EraseTerminatorInstAndDCECond(BI); |
| 2025 | |
Chris Lattner | 86bbf33 | 2008-04-24 00:01:19 +0000 | [diff] [blame] | 2026 | return true; |
| 2027 | } |
| 2028 | |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2029 | /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the |
| 2030 | /// probabilities of the branch taking each edge. Fills in the two APInt |
| 2031 | /// parameters and return true, or returns false if no or invalid metadata was |
| 2032 | /// found. |
| 2033 | static bool ExtractBranchMetadata(BranchInst *BI, |
| 2034 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 2035 | assert(BI->isConditional() && |
| 2036 | "Looking for probabilities on unconditional branch?"); |
| 2037 | MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 2038 | if (!ProfileData || ProfileData->getNumOperands() != 3) return false; |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 2039 | ConstantInt *CITrue = |
| 2040 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 2041 | ConstantInt *CIFalse = |
| 2042 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2043 | if (!CITrue || !CIFalse) return false; |
| 2044 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 2045 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 2046 | return true; |
| 2047 | } |
| 2048 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2049 | /// checkCSEInPredecessor - Return true if the given instruction is available |
| 2050 | /// in its predecessor block. If yes, the instruction will be removed. |
| 2051 | /// |
Benjamin Kramer | abbfe69 | 2012-07-13 13:25:15 +0000 | [diff] [blame] | 2052 | static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2053 | if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) |
| 2054 | return false; |
| 2055 | for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) { |
| 2056 | Instruction *PBI = &*I; |
| 2057 | // Check whether Inst and PBI generate the same value. |
| 2058 | if (Inst->isIdenticalTo(PBI)) { |
| 2059 | Inst->replaceAllUsesWith(PBI); |
| 2060 | Inst->eraseFromParent(); |
| 2061 | return true; |
| 2062 | } |
| 2063 | } |
| 2064 | return false; |
| 2065 | } |
Nick Lewycky | 3c3feaf | 2012-01-25 09:43:14 +0000 | [diff] [blame] | 2066 | |
Chris Lattner | 7d4cdae | 2011-04-11 23:24:57 +0000 | [diff] [blame] | 2067 | /// FoldBranchToCommonDest - If this basic block is simple enough, and if a |
| 2068 | /// predecessor branches to us and one of our successors, fold the block into |
| 2069 | /// the predecessor and use logical operations to pick the right destination. |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2070 | bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL, |
| 2071 | unsigned BonusInstThreshold) { |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2072 | BasicBlock *BB = BI->getParent(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2073 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2074 | Instruction *Cond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2075 | if (BI->isConditional()) |
| 2076 | Cond = dyn_cast<Instruction>(BI->getCondition()); |
| 2077 | else { |
| 2078 | // For unconditional branch, check for a simple CFG pattern, where |
| 2079 | // BB has a single predecessor and BB's successor is also its predecessor's |
| 2080 | // successor. If such pattern exisits, check for CSE between BB and its |
| 2081 | // predecessor. |
| 2082 | if (BasicBlock *PB = BB->getSinglePredecessor()) |
| 2083 | if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) |
| 2084 | if (PBI->isConditional() && |
| 2085 | (BI->getSuccessor(0) == PBI->getSuccessor(0) || |
| 2086 | BI->getSuccessor(0) == PBI->getSuccessor(1))) { |
| 2087 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); |
| 2088 | I != E; ) { |
| 2089 | Instruction *Curr = I++; |
| 2090 | if (isa<CmpInst>(Curr)) { |
| 2091 | Cond = Curr; |
| 2092 | break; |
| 2093 | } |
| 2094 | // Quit if we can't remove this instruction. |
| 2095 | if (!checkCSEInPredecessor(Curr, PB)) |
| 2096 | return false; |
| 2097 | } |
| 2098 | } |
| 2099 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2100 | if (!Cond) |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2101 | return false; |
| 2102 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2103 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2104 | if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || |
| 2105 | Cond->getParent() != BB || !Cond->hasOneUse()) |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2106 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2107 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2108 | // Make sure the instruction after the condition is the cond branch. |
| 2109 | BasicBlock::iterator CondIt = Cond; ++CondIt; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2110 | |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 2111 | // Ignore dbg intrinsics. |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2112 | while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2113 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2114 | if (&*CondIt != BI) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2115 | return false; |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2116 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2117 | // Only allow this transformation if computing the condition doesn't involve |
| 2118 | // too many instructions and these involved instructions can be executed |
| 2119 | // unconditionally. We denote all involved instructions except the condition |
| 2120 | // as "bonus instructions", and only allow this transformation when the |
| 2121 | // number of the bonus instructions does not exceed a certain threshold. |
| 2122 | unsigned NumBonusInsts = 0; |
| 2123 | for (auto I = BB->begin(); Cond != I; ++I) { |
| 2124 | // Ignore dbg intrinsics. |
| 2125 | if (isa<DbgInfoIntrinsic>(I)) |
| 2126 | continue; |
| 2127 | if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL)) |
| 2128 | return false; |
| 2129 | // I has only one use and can be executed unconditionally. |
| 2130 | Instruction *User = dyn_cast<Instruction>(I->user_back()); |
| 2131 | if (User == nullptr || User->getParent() != BB) |
| 2132 | return false; |
| 2133 | // I is used in the same BB. Since BI uses Cond and doesn't have more slots |
| 2134 | // to use any other instruction, User must be an instruction between next(I) |
| 2135 | // and Cond. |
| 2136 | ++NumBonusInsts; |
| 2137 | // Early exits once we reach the limit. |
| 2138 | if (NumBonusInsts > BonusInstThreshold) |
| 2139 | return false; |
| 2140 | } |
| 2141 | |
Chris Lattner | ea9f1d3 | 2009-01-19 23:03:13 +0000 | [diff] [blame] | 2142 | // Cond is known to be a compare or binary operator. Check to make sure that |
| 2143 | // neither operand is a potentially-trapping constant expression. |
| 2144 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) |
| 2145 | if (CE->canTrap()) |
| 2146 | return false; |
| 2147 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) |
| 2148 | if (CE->canTrap()) |
| 2149 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2150 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2151 | // Finally, don't infinitely unroll conditional loops. |
| 2152 | BasicBlock *TrueDest = BI->getSuccessor(0); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2153 | BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2154 | if (TrueDest == BB || FalseDest == BB) |
| 2155 | return false; |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2156 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2157 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 2158 | BasicBlock *PredBlock = *PI; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2159 | BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2160 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2161 | // Check that we have two conditional branches. If there is a PHI node in |
| 2162 | // the common successor, verify that the same value flows in from both |
| 2163 | // blocks. |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2164 | SmallVector<PHINode*, 4> PHIs; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2165 | if (!PBI || PBI->isUnconditional() || |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2166 | (BI->isConditional() && |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2167 | !SafeToMergeTerminators(BI, PBI)) || |
| 2168 | (!BI->isConditional() && |
| 2169 | !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2170 | continue; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2171 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2172 | // Determine if the two branches share a common destination. |
Axel Naumann | 4a12706 | 2012-09-17 14:20:57 +0000 | [diff] [blame] | 2173 | Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2174 | bool InvertPredCond = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2175 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2176 | if (BI->isConditional()) { |
| 2177 | if (PBI->getSuccessor(0) == TrueDest) |
| 2178 | Opc = Instruction::Or; |
| 2179 | else if (PBI->getSuccessor(1) == FalseDest) |
| 2180 | Opc = Instruction::And; |
| 2181 | else if (PBI->getSuccessor(0) == FalseDest) |
| 2182 | Opc = Instruction::And, InvertPredCond = true; |
| 2183 | else if (PBI->getSuccessor(1) == TrueDest) |
| 2184 | Opc = Instruction::Or, InvertPredCond = true; |
| 2185 | else |
| 2186 | continue; |
| 2187 | } else { |
| 2188 | if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) |
| 2189 | continue; |
| 2190 | } |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2191 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2192 | DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2193 | IRBuilder<> Builder(PBI); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2194 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2195 | // If we need to invert the condition in the pred block to match, do so now. |
| 2196 | if (InvertPredCond) { |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2197 | Value *NewCond = PBI->getCondition(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2198 | |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2199 | if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { |
| 2200 | CmpInst *CI = cast<CmpInst>(NewCond); |
| 2201 | CI->setPredicate(CI->getInversePredicate()); |
| 2202 | } else { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2203 | NewCond = Builder.CreateNot(NewCond, |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2204 | PBI->getCondition()->getName()+".not"); |
Chris Lattner | fbeb558 | 2010-12-13 07:00:06 +0000 | [diff] [blame] | 2205 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2206 | |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2207 | PBI->setCondition(NewCond); |
Nick Lewycky | 8d302df | 2011-12-26 20:54:14 +0000 | [diff] [blame] | 2208 | PBI->swapSuccessors(); |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2209 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2210 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2211 | // If we have bonus instructions, clone them into the predecessor block. |
| 2212 | // Note that there may be mutliple predecessor blocks, so we cannot move |
| 2213 | // bonus instructions to a predecessor block. |
| 2214 | ValueToValueMapTy VMap; // maps original values to cloned values |
| 2215 | // We already make sure Cond is the last instruction before BI. Therefore, |
| 2216 | // every instructions before Cond other than DbgInfoIntrinsic are bonus |
| 2217 | // instructions. |
| 2218 | for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) { |
| 2219 | if (isa<DbgInfoIntrinsic>(BonusInst)) |
| 2220 | continue; |
| 2221 | Instruction *NewBonusInst = BonusInst->clone(); |
| 2222 | RemapInstruction(NewBonusInst, VMap, |
| 2223 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
| 2224 | VMap[BonusInst] = NewBonusInst; |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2225 | |
| 2226 | // If we moved a load, we cannot any longer claim any knowledge about |
| 2227 | // its potential value. The previous information might have been valid |
| 2228 | // only given the branch precondition. |
| 2229 | // For an analogous reason, we must also drop all the metadata whose |
| 2230 | // semantics we don't understand. |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2231 | NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg); |
Rafael Espindola | ab73c49 | 2014-01-28 16:56:46 +0000 | [diff] [blame] | 2232 | |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2233 | PredBlock->getInstList().insert(PBI, NewBonusInst); |
| 2234 | NewBonusInst->takeName(BonusInst); |
| 2235 | BonusInst->setName(BonusInst->getName() + ".old"); |
Owen Anderson | 2cfe913 | 2010-07-14 19:52:16 +0000 | [diff] [blame] | 2236 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2237 | |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2238 | // Clone Cond into the predecessor basic block, and or/and the |
| 2239 | // two conditions together. |
Nick Lewycky | 42fb745 | 2009-09-27 07:38:41 +0000 | [diff] [blame] | 2240 | Instruction *New = Cond->clone(); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2241 | RemapInstruction(New, VMap, |
| 2242 | RF_NoModuleLevelChanges | RF_IgnoreMissingEntries); |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2243 | PredBlock->getInstList().insert(PBI, New); |
| 2244 | New->takeName(Cond); |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 2245 | Cond->setName(New->getName() + ".old"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2246 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2247 | if (BI->isConditional()) { |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2248 | Instruction *NewCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2249 | cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(), |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2250 | New, "or.cond")); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2251 | PBI->setCondition(NewCond); |
| 2252 | |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2253 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2254 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2255 | PredFalseWeight); |
| 2256 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2257 | SuccFalseWeight); |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2258 | SmallVector<uint64_t, 8> NewWeights; |
| 2259 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2260 | if (PBI->getSuccessor(0) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2261 | if (PredHasWeights && SuccHasWeights) { |
| 2262 | // PBI: br i1 %x, BB, FalseDest |
| 2263 | // BI: br i1 %y, TrueDest, FalseDest |
| 2264 | //TrueWeight is TrueWeight for PBI * TrueWeight for BI. |
| 2265 | NewWeights.push_back(PredTrueWeight * SuccTrueWeight); |
| 2266 | //FalseWeight is FalseWeight for PBI * TotalWeight for BI + |
| 2267 | // TrueWeight for PBI * FalseWeight for BI. |
| 2268 | // We assume that total weights of a BranchInst can fit into 32 bits. |
| 2269 | // Therefore, we will not have overflow using 64-bit arithmetic. |
| 2270 | NewWeights.push_back(PredFalseWeight * (SuccFalseWeight + |
| 2271 | SuccTrueWeight) + PredTrueWeight * SuccFalseWeight); |
| 2272 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2273 | AddPredecessorToBlock(TrueDest, PredBlock, BB); |
| 2274 | PBI->setSuccessor(0, TrueDest); |
| 2275 | } |
| 2276 | if (PBI->getSuccessor(1) == BB) { |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2277 | if (PredHasWeights && SuccHasWeights) { |
| 2278 | // PBI: br i1 %x, TrueDest, BB |
| 2279 | // BI: br i1 %y, TrueDest, FalseDest |
| 2280 | //TrueWeight is TrueWeight for PBI * TotalWeight for BI + |
| 2281 | // FalseWeight for PBI * TrueWeight for BI. |
| 2282 | NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + |
| 2283 | SuccTrueWeight) + PredFalseWeight * SuccTrueWeight); |
| 2284 | //FalseWeight is FalseWeight for PBI * FalseWeight for BI. |
| 2285 | NewWeights.push_back(PredFalseWeight * SuccFalseWeight); |
| 2286 | } |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2287 | AddPredecessorToBlock(FalseDest, PredBlock, BB); |
| 2288 | PBI->setSuccessor(1, FalseDest); |
| 2289 | } |
Manman Ren | bfb9d43 | 2012-09-15 00:39:57 +0000 | [diff] [blame] | 2290 | if (NewWeights.size() == 2) { |
| 2291 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2292 | FitWeights(NewWeights); |
| 2293 | |
| 2294 | SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end()); |
| 2295 | PBI->setMetadata(LLVMContext::MD_prof, |
| 2296 | MDBuilder(BI->getContext()). |
| 2297 | createBranchWeights(MDWeights)); |
| 2298 | } else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2299 | PBI->setMetadata(LLVMContext::MD_prof, nullptr); |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2300 | } else { |
| 2301 | // Update PHI nodes in the common successors. |
| 2302 | for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { |
Nick Lewycky | 0a045bb | 2012-06-24 10:15:42 +0000 | [diff] [blame] | 2303 | ConstantInt *PBI_C = cast<ConstantInt>( |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2304 | PHIs[i]->getIncomingValueForBlock(PBI->getParent())); |
| 2305 | assert(PBI_C->getType()->isIntegerTy(1)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2306 | Instruction *MergedCond = nullptr; |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2307 | if (PBI->getSuccessor(0) == TrueDest) { |
| 2308 | // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) |
| 2309 | // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) |
| 2310 | // is false: !PBI_Cond and BI_Value |
| 2311 | Instruction *NotCond = |
| 2312 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2313 | "not.cond")); |
| 2314 | MergedCond = |
| 2315 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2316 | NotCond, New, |
| 2317 | "and.cond")); |
| 2318 | if (PBI_C->isOne()) |
| 2319 | MergedCond = |
| 2320 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2321 | PBI->getCondition(), MergedCond, |
| 2322 | "or.cond")); |
| 2323 | } else { |
| 2324 | // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) |
| 2325 | // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) |
| 2326 | // is false: PBI_Cond and BI_Value |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2327 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2328 | cast<Instruction>(Builder.CreateBinOp(Instruction::And, |
| 2329 | PBI->getCondition(), New, |
| 2330 | "and.cond")); |
| 2331 | if (PBI_C->isOne()) { |
| 2332 | Instruction *NotCond = |
| 2333 | cast<Instruction>(Builder.CreateNot(PBI->getCondition(), |
| 2334 | "not.cond")); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2335 | MergedCond = |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 2336 | cast<Instruction>(Builder.CreateBinOp(Instruction::Or, |
| 2337 | NotCond, MergedCond, |
| 2338 | "or.cond")); |
| 2339 | } |
| 2340 | } |
| 2341 | // Update PHI Node. |
| 2342 | PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), |
| 2343 | MergedCond); |
| 2344 | } |
| 2345 | // Change PBI from Conditional to Unconditional. |
| 2346 | BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); |
| 2347 | EraseTerminatorInstAndDCECond(PBI); |
| 2348 | PBI = New_PBI; |
Chris Lattner | 55eaae1 | 2008-07-13 21:20:19 +0000 | [diff] [blame] | 2349 | } |
Devang Patel | d715ec8 | 2011-04-06 22:37:20 +0000 | [diff] [blame] | 2350 | |
Nick Lewycky | c554a9b | 2011-12-27 04:31:52 +0000 | [diff] [blame] | 2351 | // TODO: If BB is reachable from all paths through PredBlock, then we |
| 2352 | // could replace PBI's branch probabilities with BI's. |
| 2353 | |
Chris Lattner | fba5cdf | 2011-04-14 02:44:53 +0000 | [diff] [blame] | 2354 | // Copy any debug value intrinsics into the end of PredBlock. |
| 2355 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 2356 | if (isa<DbgInfoIntrinsic>(*I)) |
| 2357 | I->clone()->insertBefore(PBI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2358 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2359 | return true; |
Chris Lattner | 2e25b8f | 2008-07-13 21:12:01 +0000 | [diff] [blame] | 2360 | } |
| 2361 | return false; |
| 2362 | } |
| 2363 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2364 | /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a |
| 2365 | /// predecessor of another block, this function tries to simplify it. We know |
| 2366 | /// that PBI and BI are both conditional branches, and BI is in one of the |
| 2367 | /// successor blocks of PBI - PBI branches to BI. |
| 2368 | static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { |
| 2369 | assert(PBI->isConditional() && BI->isConditional()); |
| 2370 | BasicBlock *BB = BI->getParent(); |
Dan Gohman | 5476cfd | 2009-08-12 16:23:25 +0000 | [diff] [blame] | 2371 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2372 | // 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] | 2373 | // predecessor that ends on a branch of the same condition, make |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2374 | // this conditional branch redundant. |
| 2375 | if (PBI->getCondition() == BI->getCondition() && |
| 2376 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2377 | // Okay, the outcome of this conditional branch is statically |
| 2378 | // knowable. If this block had a single pred, handle specially. |
| 2379 | if (BB->getSinglePredecessor()) { |
| 2380 | // Turn this into a branch on constant. |
| 2381 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2382 | BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2383 | CondIsTrue)); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2384 | return true; // Nuke the branch on constant. |
| 2385 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2386 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2387 | // Otherwise, if there are multiple predecessors, insert a PHI that merges |
| 2388 | // in the constant and simplify the block result. Subsequent passes of |
| 2389 | // simplifycfg will thread the block. |
| 2390 | if (BlockIsSimpleEnoughToThreadThrough(BB)) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2391 | pred_iterator PB = pred_begin(BB), PE = pred_end(BB); |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2392 | PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()), |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 2393 | std::distance(PB, PE), |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2394 | BI->getCondition()->getName() + ".pr", |
| 2395 | BB->begin()); |
Chris Lattner | 5eed372 | 2008-07-13 21:55:46 +0000 | [diff] [blame] | 2396 | // Okay, we're going to insert the PHI node. Since PBI is not the only |
| 2397 | // predecessor, compute the PHI'd conditional value for all of the preds. |
| 2398 | // Any predecessor where the condition is not computable we keep symbolic. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 2399 | for (pred_iterator PI = PB; PI != PE; ++PI) { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2400 | BasicBlock *P = *PI; |
| 2401 | if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2402 | PBI != BI && PBI->isConditional() && |
| 2403 | PBI->getCondition() == BI->getCondition() && |
| 2404 | PBI->getSuccessor(0) != PBI->getSuccessor(1)) { |
| 2405 | bool CondIsTrue = PBI->getSuccessor(0) == BB; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2406 | NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()), |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2407 | CondIsTrue), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2408 | } else { |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2409 | NewPN->addIncoming(BI->getCondition(), P); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2410 | } |
Gabor Greif | 8629f12 | 2010-07-12 10:59:23 +0000 | [diff] [blame] | 2411 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2412 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2413 | BI->setCondition(NewPN); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2414 | return true; |
| 2415 | } |
| 2416 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2417 | |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2418 | // 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] | 2419 | // predecessors are a conditional branch to one of our destinations, |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2420 | // fold the conditions into logical ops and one cond br. |
Zhou Sheng | 264e46e | 2009-02-26 06:56:37 +0000 | [diff] [blame] | 2421 | BasicBlock::iterator BBI = BB->begin(); |
| 2422 | // Ignore dbg intrinsics. |
| 2423 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 2424 | ++BBI; |
| 2425 | if (&*BBI != BI) |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2426 | return false; |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2427 | |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2428 | |
Chris Lattner | c59945b | 2009-01-20 01:15:41 +0000 | [diff] [blame] | 2429 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition())) |
| 2430 | if (CE->canTrap()) |
| 2431 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2432 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2433 | int PBIOp, BIOp; |
| 2434 | if (PBI->getSuccessor(0) == BI->getSuccessor(0)) |
| 2435 | PBIOp = BIOp = 0; |
| 2436 | else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) |
| 2437 | PBIOp = 0, BIOp = 1; |
| 2438 | else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) |
| 2439 | PBIOp = 1, BIOp = 0; |
| 2440 | else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) |
| 2441 | PBIOp = BIOp = 1; |
| 2442 | else |
| 2443 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2444 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2445 | // Check to make sure that the other destination of this branch |
| 2446 | // isn't BB itself. If so, this is an infinite loop that will |
| 2447 | // keep getting unwound. |
| 2448 | if (PBI->getSuccessor(PBIOp) == BB) |
| 2449 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2450 | |
| 2451 | // Do not perform this transformation if it would require |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2452 | // insertion of a large number of select instructions. For targets |
| 2453 | // without predication/cmovs, this is a big pessimization. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2454 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2455 | // Also do not perform this transformation if any phi node in the common |
| 2456 | // destination block can trap when reached by BB or PBB (PR17073). In that |
| 2457 | // case, it would be unsafe to hoist the operation into a select instruction. |
| 2458 | |
| 2459 | BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2460 | unsigned NumPhis = 0; |
| 2461 | for (BasicBlock::iterator II = CommonDest->begin(); |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2462 | isa<PHINode>(II); ++II, ++NumPhis) { |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2463 | if (NumPhis > 2) // Disable this xform. |
| 2464 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2465 | |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2466 | PHINode *PN = cast<PHINode>(II); |
| 2467 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2468 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) |
| 2469 | if (CE->canTrap()) |
| 2470 | return false; |
| 2471 | |
| 2472 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2473 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2474 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) |
| 2475 | if (CE->canTrap()) |
| 2476 | return false; |
| 2477 | } |
| 2478 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2479 | // Finally, if everything is ok, fold the branches to logical ops. |
Sanjay Patel | a932da8 | 2014-07-07 21:19:00 +0000 | [diff] [blame] | 2480 | BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2481 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2482 | DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2483 | << "AND: " << *BI->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2484 | |
| 2485 | |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2486 | // If OtherDest *is* BB, then BB is a basic block with a single conditional |
| 2487 | // branch in it, where one edge (OtherDest) goes back to itself but the other |
| 2488 | // exits. We don't *know* that the program avoids the infinite loop |
| 2489 | // (even though that seems likely). If we do this xform naively, we'll end up |
| 2490 | // recursively unpeeling the loop. Since we know that (after the xform is |
| 2491 | // done) that the block *is* infinite if reached, we just make it an obviously |
| 2492 | // infinite loop with no cond branch. |
| 2493 | if (OtherDest == BB) { |
| 2494 | // Insert it at the end of the function, because it's either code, |
| 2495 | // or it won't matter if it's hot. :) |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 2496 | BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(), |
| 2497 | "infloop", BB->getParent()); |
Chris Lattner | 80b03a1 | 2008-07-13 22:23:11 +0000 | [diff] [blame] | 2498 | BranchInst::Create(InfLoopBlock, InfLoopBlock); |
| 2499 | OtherDest = InfLoopBlock; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2500 | } |
| 2501 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2502 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2503 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2504 | // BI may have other predecessors. Because of this, we leave |
| 2505 | // it alone, but modify PBI. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2506 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2507 | // Make sure we get to CommonDest on True&True directions. |
| 2508 | Value *PBICond = PBI->getCondition(); |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2509 | IRBuilder<true, NoFolder> Builder(PBI); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2510 | if (PBIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2511 | PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not"); |
| 2512 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2513 | Value *BICond = BI->getCondition(); |
| 2514 | if (BIOp) |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2515 | BICond = Builder.CreateNot(BICond, BICond->getName()+".not"); |
| 2516 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2517 | // Merge the conditions. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2518 | Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2519 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2520 | // Modify PBI to branch on the new condition to the new dests. |
| 2521 | PBI->setCondition(Cond); |
| 2522 | PBI->setSuccessor(0, CommonDest); |
| 2523 | PBI->setSuccessor(1, OtherDest); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2524 | |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2525 | // Update branch weight for PBI. |
| 2526 | uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 2527 | bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight, |
| 2528 | PredFalseWeight); |
| 2529 | bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight, |
| 2530 | SuccFalseWeight); |
Manman Ren | 2d4c10f | 2012-09-17 21:30:40 +0000 | [diff] [blame] | 2531 | if (PredHasWeights && SuccHasWeights) { |
| 2532 | uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; |
| 2533 | uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight; |
| 2534 | uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; |
| 2535 | uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; |
| 2536 | // The weight to CommonDest should be PredCommon * SuccTotal + |
| 2537 | // PredOther * SuccCommon. |
| 2538 | // The weight to OtherDest should be PredOther * SuccOther. |
| 2539 | SmallVector<uint64_t, 2> NewWeights; |
| 2540 | NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) + |
| 2541 | PredOther * SuccCommon); |
| 2542 | NewWeights.push_back(PredOther * SuccOther); |
| 2543 | // Halve the weights if any of them cannot fit in an uint32_t |
| 2544 | FitWeights(NewWeights); |
| 2545 | |
| 2546 | SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end()); |
| 2547 | PBI->setMetadata(LLVMContext::MD_prof, |
| 2548 | MDBuilder(BI->getContext()). |
| 2549 | createBranchWeights(MDWeights)); |
| 2550 | } |
| 2551 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2552 | // OtherDest may have phi nodes. If so, add an entry from PBI's |
| 2553 | // block that are identical to the entries for BI's block. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2554 | AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2555 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2556 | // We know that the CommonDest already had an edge from PBI to |
| 2557 | // it. If it has PHIs though, the PHIs may have different |
| 2558 | // entries for BB and PBI's BB. If so, insert a select to make |
| 2559 | // them agree. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2560 | PHINode *PN; |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2561 | for (BasicBlock::iterator II = CommonDest->begin(); |
| 2562 | (PN = dyn_cast<PHINode>(II)); ++II) { |
| 2563 | Value *BIV = PN->getIncomingValueForBlock(BB); |
| 2564 | unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); |
| 2565 | Value *PBIV = PN->getIncomingValue(PBBIdx); |
| 2566 | if (BIV != PBIV) { |
| 2567 | // Insert a select in PBI to pick the right value. |
Devang Patel | 1407fb4 | 2011-05-19 20:52:46 +0000 | [diff] [blame] | 2568 | Value *NV = cast<SelectInst> |
| 2569 | (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux")); |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2570 | PN->setIncomingValue(PBBIdx, NV); |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2571 | } |
| 2572 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2573 | |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 2574 | DEBUG(dbgs() << "INTO: " << *PBI->getParent()); |
| 2575 | DEBUG(dbgs() << *PBI->getParent()->getParent()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2576 | |
Chris Lattner | 834ab4e | 2008-07-13 22:04:41 +0000 | [diff] [blame] | 2577 | // This basic block is probably dead. We know it has at least |
| 2578 | // one fewer predecessor. |
| 2579 | return true; |
Chris Lattner | 9aada1d | 2008-07-13 21:53:26 +0000 | [diff] [blame] | 2580 | } |
| 2581 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2582 | // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a |
| 2583 | // branch to TrueBB if Cond is true or to FalseBB if Cond is false. |
| 2584 | // Takes care of updating the successors and removing the old terminator. |
| 2585 | // Also makes sure not to introduce new successors by assuming that edges to |
| 2586 | // non-successor TrueBBs and FalseBBs aren't reachable. |
| 2587 | static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2588 | BasicBlock *TrueBB, BasicBlock *FalseBB, |
| 2589 | uint32_t TrueWeight, |
| 2590 | uint32_t FalseWeight){ |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2591 | // Remove any superfluous successor edges from the CFG. |
| 2592 | // First, figure out which successors to preserve. |
| 2593 | // If TrueBB and FalseBB are equal, only try to preserve one copy of that |
| 2594 | // successor. |
| 2595 | BasicBlock *KeepEdge1 = TrueBB; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2596 | BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2597 | |
| 2598 | // Then remove the rest. |
| 2599 | for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) { |
| 2600 | BasicBlock *Succ = OldTerm->getSuccessor(I); |
| 2601 | // Make sure only to keep exactly one copy of each edge. |
| 2602 | if (Succ == KeepEdge1) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2603 | KeepEdge1 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2604 | else if (Succ == KeepEdge2) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2605 | KeepEdge2 = nullptr; |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2606 | else |
| 2607 | Succ->removePredecessor(OldTerm->getParent()); |
| 2608 | } |
| 2609 | |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2610 | IRBuilder<> Builder(OldTerm); |
| 2611 | Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); |
| 2612 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2613 | // Insert an appropriate new terminator. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2614 | if (!KeepEdge1 && !KeepEdge2) { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2615 | if (TrueBB == FalseBB) |
| 2616 | // We were only looking for one successor, and it was present. |
| 2617 | // Create an unconditional branch to it. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2618 | Builder.CreateBr(TrueBB); |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2619 | else { |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2620 | // We found both of the successors we were looking for. |
| 2621 | // Create a conditional branch sharing the condition of the select. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2622 | BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); |
| 2623 | if (TrueWeight != FalseWeight) |
| 2624 | NewBI->setMetadata(LLVMContext::MD_prof, |
| 2625 | MDBuilder(OldTerm->getContext()). |
| 2626 | createBranchWeights(TrueWeight, FalseWeight)); |
| 2627 | } |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2628 | } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { |
| 2629 | // Neither of the selected blocks were successors, so this |
| 2630 | // terminator must be unreachable. |
| 2631 | new UnreachableInst(OldTerm->getContext(), OldTerm); |
| 2632 | } else { |
| 2633 | // One of the selected values was a successor, but the other wasn't. |
| 2634 | // Insert an unconditional branch to the one that was found; |
| 2635 | // the edge to the one that wasn't must be unreachable. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2636 | if (!KeepEdge1) |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2637 | // Only TrueBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2638 | Builder.CreateBr(TrueBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2639 | else |
| 2640 | // Only FalseBB was found. |
Devang Patel | 2c2ea22 | 2011-05-18 18:43:31 +0000 | [diff] [blame] | 2641 | Builder.CreateBr(FalseBB); |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2642 | } |
| 2643 | |
| 2644 | EraseTerminatorInstAndDCECond(OldTerm); |
| 2645 | return true; |
| 2646 | } |
| 2647 | |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2648 | // SimplifySwitchOnSelect - Replaces |
| 2649 | // (switch (select cond, X, Y)) on constant X, Y |
| 2650 | // with a branch - conditional if X and Y lead to distinct BBs, |
| 2651 | // unconditional otherwise. |
| 2652 | static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { |
| 2653 | // Check for constant integer values in the select. |
| 2654 | ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); |
| 2655 | ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); |
| 2656 | if (!TrueVal || !FalseVal) |
| 2657 | return false; |
| 2658 | |
| 2659 | // Find the relevant condition and destinations. |
| 2660 | Value *Condition = Select->getCondition(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 2661 | BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); |
| 2662 | BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2663 | |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2664 | // Get weight for TrueBB and FalseBB. |
| 2665 | uint32_t TrueWeight = 0, FalseWeight = 0; |
| 2666 | SmallVector<uint64_t, 8> Weights; |
| 2667 | bool HasWeights = HasBranchWeights(SI); |
| 2668 | if (HasWeights) { |
| 2669 | GetBranchWeights(SI, Weights); |
| 2670 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 2671 | TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal). |
| 2672 | getSuccessorIndex()]; |
| 2673 | FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal). |
| 2674 | getSuccessorIndex()]; |
| 2675 | } |
| 2676 | } |
| 2677 | |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2678 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2679 | return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, |
| 2680 | TrueWeight, FalseWeight); |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 2681 | } |
| 2682 | |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2683 | // SimplifyIndirectBrOnSelect - Replaces |
| 2684 | // (indirectbr (select cond, blockaddress(@fn, BlockA), |
| 2685 | // blockaddress(@fn, BlockB))) |
| 2686 | // with |
| 2687 | // (br cond, BlockA, BlockB). |
| 2688 | static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { |
| 2689 | // Check that both operands of the select are block addresses. |
| 2690 | BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); |
| 2691 | BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); |
| 2692 | if (!TBA || !FBA) |
| 2693 | return false; |
| 2694 | |
| 2695 | // Extract the actual blocks. |
| 2696 | BasicBlock *TrueBB = TBA->getBasicBlock(); |
| 2697 | BasicBlock *FalseBB = FBA->getBasicBlock(); |
| 2698 | |
Frits van Bommel | 8e15849 | 2011-01-11 12:52:11 +0000 | [diff] [blame] | 2699 | // Perform the actual simplification. |
Manman Ren | 774246a | 2012-09-17 22:28:55 +0000 | [diff] [blame] | 2700 | return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, |
| 2701 | 0, 0); |
Frits van Bommel | 8fb69ee | 2010-12-05 18:29:03 +0000 | [diff] [blame] | 2702 | } |
| 2703 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2704 | /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp |
| 2705 | /// instruction (a seteq/setne with a constant) as the only instruction in a |
| 2706 | /// block that ends with an uncond branch. We are looking for a very specific |
| 2707 | /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In |
| 2708 | /// this case, we merge the first two "or's of icmp" into a switch, but then the |
| 2709 | /// default value goes to an uncond block with a seteq in it, we get something |
| 2710 | /// like: |
| 2711 | /// |
| 2712 | /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] |
| 2713 | /// DEFAULT: |
| 2714 | /// %tmp = icmp eq i8 %A, 92 |
| 2715 | /// br label %end |
| 2716 | /// end: |
| 2717 | /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2718 | /// |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2719 | /// We prefer to split the edge to 'end' so that there is a true/false entry to |
| 2720 | /// the PHI, merging the third icmp into the switch. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 2721 | static bool TryToSimplifyUncondBranchWithICmpInIt( |
| 2722 | ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 2723 | unsigned BonusInstThreshold, const DataLayout *DL, AssumptionCache *AC) { |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2724 | BasicBlock *BB = ICI->getParent(); |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 2725 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2726 | // If the block has any PHIs in it or the icmp has multiple uses, it is too |
| 2727 | // complex. |
| 2728 | if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false; |
| 2729 | |
| 2730 | Value *V = ICI->getOperand(0); |
| 2731 | ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2732 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2733 | // The pattern we're looking for is where our only predecessor is a switch on |
| 2734 | // 'V' and this block is the default case for the switch. In this case we can |
| 2735 | // fold the compared value into the switch to simplify things. |
| 2736 | BasicBlock *Pred = BB->getSinglePredecessor(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2737 | if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2738 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2739 | SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); |
| 2740 | if (SI->getCondition() != V) |
| 2741 | return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2742 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2743 | // If BB is reachable on a non-default case, then we simply know the value of |
| 2744 | // V in this block. Substitute it and constant fold the icmp instruction |
| 2745 | // away. |
| 2746 | if (SI->getDefaultDest() != BB) { |
| 2747 | ConstantInt *VVal = SI->findCaseDest(BB); |
| 2748 | assert(VVal && "Should have a unique destination value"); |
| 2749 | ICI->setOperand(0, VVal); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2750 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2751 | if (Value *V = SimplifyInstruction(ICI, DL)) { |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2752 | ICI->replaceAllUsesWith(V); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2753 | ICI->eraseFromParent(); |
| 2754 | } |
| 2755 | // BB is now empty, so it is likely to simplify away. |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 2756 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2757 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2758 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2759 | // Ok, the block is reachable from the default dest. If the constant we're |
| 2760 | // comparing exists in one of the other edges, then we can constant fold ICI |
| 2761 | // and zap it. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 2762 | if (SI->findCaseValue(Cst) != SI->case_default()) { |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2763 | Value *V; |
| 2764 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 2765 | V = ConstantInt::getFalse(BB->getContext()); |
| 2766 | else |
| 2767 | V = ConstantInt::getTrue(BB->getContext()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2768 | |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2769 | ICI->replaceAllUsesWith(V); |
| 2770 | ICI->eraseFromParent(); |
| 2771 | // BB is now empty, so it is likely to simplify away. |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 2772 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 62cc76e | 2010-12-13 03:43:57 +0000 | [diff] [blame] | 2773 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2774 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2775 | // The use of the icmp has to be in the 'end' block, by the only PHI node in |
| 2776 | // the block. |
| 2777 | BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2778 | PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2779 | if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2780 | isa<PHINode>(++BasicBlock::iterator(PHIUse))) |
| 2781 | return false; |
| 2782 | |
| 2783 | // If the icmp is a SETEQ, then the default dest gets false, the new edge gets |
| 2784 | // true in the PHI. |
| 2785 | Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); |
| 2786 | Constant *NewCst = ConstantInt::getFalse(BB->getContext()); |
| 2787 | |
| 2788 | if (ICI->getPredicate() == ICmpInst::ICMP_EQ) |
| 2789 | std::swap(DefaultCst, NewCst); |
| 2790 | |
| 2791 | // Replace ICI (which is used by the PHI for the default value) with true or |
| 2792 | // false depending on if it is EQ or NE. |
| 2793 | ICI->replaceAllUsesWith(DefaultCst); |
| 2794 | ICI->eraseFromParent(); |
| 2795 | |
| 2796 | // Okay, the switch goes to this block on a default value. Add an edge from |
| 2797 | // the switch to the merge point on the compared value. |
| 2798 | BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge", |
| 2799 | BB->getParent(), BB); |
Manman Ren | ce48ea7 | 2012-09-17 23:07:43 +0000 | [diff] [blame] | 2800 | SmallVector<uint64_t, 8> Weights; |
| 2801 | bool HasWeights = HasBranchWeights(SI); |
| 2802 | if (HasWeights) { |
| 2803 | GetBranchWeights(SI, Weights); |
| 2804 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 2805 | // Split weight for default case to case for "Cst". |
| 2806 | Weights[0] = (Weights[0]+1) >> 1; |
| 2807 | Weights.push_back(Weights[0]); |
| 2808 | |
| 2809 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 2810 | SI->setMetadata(LLVMContext::MD_prof, |
| 2811 | MDBuilder(SI->getContext()). |
| 2812 | createBranchWeights(MDWeights)); |
| 2813 | } |
| 2814 | } |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2815 | SI->addCase(Cst, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2816 | |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2817 | // 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] | 2818 | Builder.SetInsertPoint(NewBB); |
| 2819 | Builder.SetCurrentDebugLocation(SI->getDebugLoc()); |
| 2820 | Builder.CreateBr(SuccBlock); |
Chris Lattner | d9bacc0 | 2010-12-13 03:18:54 +0000 | [diff] [blame] | 2821 | PHIUse->addIncoming(NewCst, NewBB); |
| 2822 | return true; |
| 2823 | } |
| 2824 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2825 | /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch. |
| 2826 | /// Check to see if it is branching on an or/and chain of icmp instructions, and |
| 2827 | /// fold it into a switch instruction if so. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2828 | static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL, |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2829 | IRBuilder<> &Builder) { |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2830 | Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2831 | if (!Cond) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2832 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2833 | // Change br (X == 0 | X == 1), T, F into a switch instruction. |
| 2834 | // If this is a bunch of seteq's or'd together, or if it's a bunch of |
| 2835 | // 'setne's and'ed together, collect them. |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2836 | |
Mehdi Amini | 9a25cb8 | 2014-11-19 20:09:11 +0000 | [diff] [blame] | 2837 | // 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] | 2838 | ConstantComparesGatherer ConstantCompare(Cond, DL); |
| 2839 | // Unpack the result |
| 2840 | SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals; |
| 2841 | Value *CompVal = ConstantCompare.CompValue; |
| 2842 | unsigned UsedICmps = ConstantCompare.UsedICmps; |
| 2843 | Value *ExtraCase = ConstantCompare.Extra; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2844 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2845 | // If we didn't have a multiply compared value, fail. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2846 | if (!CompVal) return false; |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2847 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 2848 | // Avoid turning single icmps into a switch. |
| 2849 | if (UsedICmps <= 1) |
| 2850 | return false; |
| 2851 | |
Mehdi Amini | ffd0100 | 2014-11-20 22:40:25 +0000 | [diff] [blame] | 2852 | bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); |
| 2853 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2854 | // There might be duplicate constants in the list, which the switch |
| 2855 | // instruction can't handle, remove them now. |
| 2856 | array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); |
| 2857 | Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2858 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2859 | // If Extra was used, we require at least two switch values to do the |
| 2860 | // transformation. A switch with one value is just an cond branch. |
| 2861 | if (ExtraCase && Values.size() < 2) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2862 | |
Andrew Trick | 3051aa1 | 2012-08-29 21:46:38 +0000 | [diff] [blame] | 2863 | // TODO: Preserve branch weight metadata, similarly to how |
| 2864 | // FoldValueComparisonIntoPredecessors preserves it. |
| 2865 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2866 | // Figure out which block is which destination. |
| 2867 | BasicBlock *DefaultBB = BI->getSuccessor(1); |
| 2868 | BasicBlock *EdgeBB = BI->getSuccessor(0); |
| 2869 | if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2870 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2871 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2872 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2873 | DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2874 | << " cases into SWITCH. BB is:\n" << *BB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2875 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2876 | // If there are any extra values that couldn't be folded into the switch |
| 2877 | // then we evaluate them with an explicit branch first. Split the block |
| 2878 | // right before the condbr to handle it. |
| 2879 | if (ExtraCase) { |
| 2880 | BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test"); |
| 2881 | // Remove the uncond branch added to the old block. |
| 2882 | TerminatorInst *OldTI = BB->getTerminator(); |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2883 | Builder.SetInsertPoint(OldTI); |
| 2884 | |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2885 | if (TrueWhenEqual) |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2886 | Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); |
Chris Lattner | 5a9d59d | 2010-12-14 05:57:30 +0000 | [diff] [blame] | 2887 | else |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2888 | Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2889 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2890 | OldTI->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2891 | |
Chris Lattner | cb570f8 | 2010-12-13 05:34:18 +0000 | [diff] [blame] | 2892 | // If there are PHI nodes in EdgeBB, then we need to add a new entry to them |
| 2893 | // for the edge we just added. |
Chris Lattner | 0f4d67b | 2010-12-14 07:09:42 +0000 | [diff] [blame] | 2894 | AddPredecessorToBlock(EdgeBB, BB, NewBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2895 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2896 | DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase |
| 2897 | << "\nEXTRABB = " << *BB); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2898 | BB = NewBB; |
| 2899 | } |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2900 | |
| 2901 | Builder.SetInsertPoint(BI); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2902 | // Convert pointer to int before we switch. |
| 2903 | if (CompVal->getType()->isPointerTy()) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2904 | assert(DL && "Cannot switch on pointer without DataLayout"); |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2905 | CompVal = Builder.CreatePtrToInt(CompVal, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2906 | DL->getIntPtrType(CompVal->getType()), |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2907 | "magicptr"); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2908 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2909 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2910 | // Create the new switch instruction now. |
Devang Patel | 7de6c4b | 2011-05-18 23:18:47 +0000 | [diff] [blame] | 2911 | SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); |
Devang Patel | b849cd5 | 2011-05-17 23:29:05 +0000 | [diff] [blame] | 2912 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2913 | // Add all of the 'cases' to the switch instruction. |
| 2914 | for (unsigned i = 0, e = Values.size(); i != e; ++i) |
| 2915 | New->addCase(Values[i], EdgeBB); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2916 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2917 | // We added edges from PI to the EdgeBB. As such, if there were any |
| 2918 | // PHI nodes in EdgeBB, they need entries to be added corresponding to |
| 2919 | // the number of edges added. |
| 2920 | for (BasicBlock::iterator BBI = EdgeBB->begin(); |
| 2921 | isa<PHINode>(BBI); ++BBI) { |
| 2922 | PHINode *PN = cast<PHINode>(BBI); |
| 2923 | Value *InVal = PN->getIncomingValueForBlock(BB); |
| 2924 | for (unsigned i = 0, e = Values.size()-1; i != e; ++i) |
| 2925 | PN->addIncoming(InVal, BB); |
| 2926 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2927 | |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2928 | // Erase the old branch instruction. |
| 2929 | EraseTerminatorInstAndDCECond(BI); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2930 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 2931 | DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); |
Chris Lattner | a69c443 | 2010-12-13 05:03:41 +0000 | [diff] [blame] | 2932 | return true; |
| 2933 | } |
| 2934 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2935 | bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { |
| 2936 | // If this is a trivial landing pad that just continues unwinding the caught |
| 2937 | // exception then zap the landing pad, turning its invokes into calls. |
| 2938 | BasicBlock *BB = RI->getParent(); |
| 2939 | LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); |
| 2940 | if (RI->getValue() != LPInst) |
| 2941 | // Not a landing pad, or the resume is not unwinding the exception that |
| 2942 | // caused control to branch here. |
| 2943 | return false; |
| 2944 | |
| 2945 | // Check that there are no other instructions except for debug intrinsics. |
| 2946 | BasicBlock::iterator I = LPInst, E = RI; |
| 2947 | while (++I != E) |
| 2948 | if (!isa<DbgInfoIntrinsic>(I)) |
| 2949 | return false; |
| 2950 | |
| 2951 | // Turn all invokes that unwind here into calls and delete the basic block. |
Bill Wendling | 9534d88 | 2013-03-11 20:53:00 +0000 | [diff] [blame] | 2952 | bool InvokeRequiresTableEntry = false; |
| 2953 | bool Changed = false; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2954 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { |
| 2955 | InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator()); |
Bill Wendling | 9534d88 | 2013-03-11 20:53:00 +0000 | [diff] [blame] | 2956 | |
| 2957 | if (II->hasFnAttr(Attribute::UWTable)) { |
| 2958 | // Don't remove an `invoke' instruction if the ABI requires an entry into |
| 2959 | // the table. |
| 2960 | InvokeRequiresTableEntry = true; |
| 2961 | continue; |
| 2962 | } |
| 2963 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2964 | SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3); |
Bill Wendling | 9534d88 | 2013-03-11 20:53:00 +0000 | [diff] [blame] | 2965 | |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2966 | // Insert a call instruction before the invoke. |
| 2967 | CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II); |
| 2968 | Call->takeName(II); |
| 2969 | Call->setCallingConv(II->getCallingConv()); |
| 2970 | Call->setAttributes(II->getAttributes()); |
| 2971 | Call->setDebugLoc(II->getDebugLoc()); |
| 2972 | |
| 2973 | // Anything that used the value produced by the invoke instruction now uses |
| 2974 | // the value produced by the call instruction. Note that we do this even |
| 2975 | // for void functions and calls with no uses so that the callgraph edge is |
| 2976 | // updated. |
| 2977 | II->replaceAllUsesWith(Call); |
| 2978 | BB->removePredecessor(II->getParent()); |
| 2979 | |
| 2980 | // Insert a branch to the normal destination right before the invoke. |
| 2981 | BranchInst::Create(II->getNormalDest(), II); |
| 2982 | |
| 2983 | // Finally, delete the invoke instruction! |
| 2984 | II->eraseFromParent(); |
Bill Wendling | 9534d88 | 2013-03-11 20:53:00 +0000 | [diff] [blame] | 2985 | Changed = true; |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2986 | } |
| 2987 | |
Bill Wendling | 9534d88 | 2013-03-11 20:53:00 +0000 | [diff] [blame] | 2988 | if (!InvokeRequiresTableEntry) |
| 2989 | // The landingpad is now unreachable. Zap it. |
| 2990 | BB->eraseFromParent(); |
| 2991 | |
| 2992 | return Changed; |
Duncan Sands | 29192d0 | 2011-09-05 12:57:57 +0000 | [diff] [blame] | 2993 | } |
| 2994 | |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 2995 | bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 2996 | BasicBlock *BB = RI->getParent(); |
| 2997 | if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 2998 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 2999 | // Find predecessors that end with branches. |
| 3000 | SmallVector<BasicBlock*, 8> UncondBranchPreds; |
| 3001 | SmallVector<BranchInst*, 8> CondBranchPreds; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 3002 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { |
| 3003 | BasicBlock *P = *PI; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3004 | TerminatorInst *PTI = P->getTerminator(); |
| 3005 | if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { |
| 3006 | if (BI->isUnconditional()) |
| 3007 | UncondBranchPreds.push_back(P); |
| 3008 | else |
| 3009 | CondBranchPreds.push_back(BI); |
| 3010 | } |
| 3011 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3012 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3013 | // If we found some, do the transformation! |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3014 | if (!UncondBranchPreds.empty() && DupRet) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3015 | while (!UncondBranchPreds.empty()) { |
| 3016 | BasicBlock *Pred = UncondBranchPreds.pop_back_val(); |
| 3017 | DEBUG(dbgs() << "FOLDING: " << *BB |
| 3018 | << "INTO UNCOND BRANCH PRED: " << *Pred); |
Evan Cheng | d983eba | 2011-01-29 04:46:23 +0000 | [diff] [blame] | 3019 | (void)FoldReturnIntoUncondBranch(RI, BB, Pred); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3020 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3021 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3022 | // If we eliminated all predecessors of the block, delete the block now. |
| 3023 | if (pred_begin(BB) == pred_end(BB)) |
| 3024 | // We know there are no successors, so just nuke the block. |
| 3025 | BB->eraseFromParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3026 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3027 | return true; |
| 3028 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3029 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3030 | // Check out all of the conditional branches going to this return |
| 3031 | // instruction. If any of them just select between returns, change the |
| 3032 | // branch itself into a select/return pair. |
| 3033 | while (!CondBranchPreds.empty()) { |
| 3034 | BranchInst *BI = CondBranchPreds.pop_back_val(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3035 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3036 | // Check to see if the non-BB successor is also a return block. |
| 3037 | if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && |
| 3038 | isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 3039 | SimplifyCondBranchToTwoReturns(BI, Builder)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3040 | return true; |
| 3041 | } |
| 3042 | return false; |
| 3043 | } |
| 3044 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3045 | bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { |
| 3046 | BasicBlock *BB = UI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3047 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3048 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3049 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3050 | // If there are any instructions immediately before the unreachable that can |
| 3051 | // be removed, do so. |
| 3052 | while (UI != BB->begin()) { |
| 3053 | BasicBlock::iterator BBI = UI; |
| 3054 | --BBI; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3055 | // Do not delete instructions that can have side effects which might cause |
| 3056 | // the unreachable to not be reachable; specifically, calls and volatile |
| 3057 | // operations may have this effect. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3058 | if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3059 | |
| 3060 | if (BBI->mayHaveSideEffects()) { |
| 3061 | if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { |
| 3062 | if (SI->isVolatile()) |
| 3063 | break; |
| 3064 | } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { |
| 3065 | if (LI->isVolatile()) |
| 3066 | break; |
| 3067 | } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { |
| 3068 | if (RMWI->isVolatile()) |
| 3069 | break; |
| 3070 | } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { |
| 3071 | if (CXI->isVolatile()) |
| 3072 | break; |
| 3073 | } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && |
| 3074 | !isa<LandingPadInst>(BBI)) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3075 | break; |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3076 | } |
Bill Wendling | 55d875f | 2011-08-16 20:41:17 +0000 | [diff] [blame] | 3077 | // Note that deleting LandingPad's here is in fact okay, although it |
| 3078 | // involves a bit of subtle reasoning. If this inst is a LandingPad, |
| 3079 | // all the predecessors of this block will be the unwind edges of Invokes, |
| 3080 | // and we can therefore guarantee this block will be erased. |
Eli Friedman | 0ffdf2e | 2011-08-15 23:59:28 +0000 | [diff] [blame] | 3081 | } |
| 3082 | |
Eli Friedman | aac35b3 | 2011-03-09 00:48:33 +0000 | [diff] [blame] | 3083 | // Delete this instruction (any uses are guaranteed to be dead) |
| 3084 | if (!BBI->use_empty()) |
| 3085 | BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 3086 | BBI->eraseFromParent(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3087 | Changed = true; |
| 3088 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3089 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3090 | // If the unreachable instruction is the first in the block, take a gander |
| 3091 | // at all of the predecessors of this instruction, and simplify them. |
| 3092 | if (&BB->front() != UI) return Changed; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3093 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3094 | SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB)); |
| 3095 | for (unsigned i = 0, e = Preds.size(); i != e; ++i) { |
| 3096 | TerminatorInst *TI = Preds[i]->getTerminator(); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3097 | IRBuilder<> Builder(TI); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3098 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 3099 | if (BI->isUnconditional()) { |
| 3100 | if (BI->getSuccessor(0) == BB) { |
| 3101 | new UnreachableInst(TI->getContext(), TI); |
| 3102 | TI->eraseFromParent(); |
| 3103 | Changed = true; |
| 3104 | } |
| 3105 | } else { |
| 3106 | if (BI->getSuccessor(0) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3107 | Builder.CreateBr(BI->getSuccessor(1)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3108 | EraseTerminatorInstAndDCECond(BI); |
| 3109 | } else if (BI->getSuccessor(1) == BB) { |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3110 | Builder.CreateBr(BI->getSuccessor(0)); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3111 | EraseTerminatorInstAndDCECond(BI); |
| 3112 | Changed = true; |
| 3113 | } |
| 3114 | } |
| 3115 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3116 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3117 | i != e; ++i) |
| 3118 | if (i.getCaseSuccessor() == BB) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3119 | BB->removePredecessor(SI->getParent()); |
| 3120 | SI->removeCase(i); |
| 3121 | --i; --e; |
| 3122 | Changed = true; |
| 3123 | } |
Hans Wennborg | 5bef5b5 | 2014-12-01 17:36:43 +0000 | [diff] [blame] | 3124 | // If the default value is unreachable, figure out the most popular |
| 3125 | // destination and make it the default. |
| 3126 | if (SI->getDefaultDest() == BB) { |
| 3127 | std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity; |
| 3128 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
| 3129 | i != e; ++i) { |
| 3130 | std::pair<unsigned, unsigned> &entry = |
| 3131 | Popularity[i.getCaseSuccessor()]; |
| 3132 | if (entry.first == 0) { |
| 3133 | entry.first = 1; |
| 3134 | entry.second = i.getCaseIndex(); |
| 3135 | } else { |
| 3136 | entry.first++; |
| 3137 | } |
| 3138 | } |
| 3139 | |
| 3140 | // Find the most popular block. |
| 3141 | unsigned MaxPop = 0; |
| 3142 | unsigned MaxIndex = 0; |
| 3143 | BasicBlock *MaxBlock = nullptr; |
| 3144 | for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator |
| 3145 | I = Popularity.begin(), E = Popularity.end(); I != E; ++I) { |
| 3146 | if (I->second.first > MaxPop || |
| 3147 | (I->second.first == MaxPop && MaxIndex > I->second.second)) { |
| 3148 | MaxPop = I->second.first; |
| 3149 | MaxIndex = I->second.second; |
| 3150 | MaxBlock = I->first; |
| 3151 | } |
| 3152 | } |
| 3153 | if (MaxBlock) { |
| 3154 | // Make this the new default, allowing us to delete any explicit |
| 3155 | // edges to it. |
| 3156 | SI->setDefaultDest(MaxBlock); |
| 3157 | Changed = true; |
| 3158 | |
| 3159 | // If MaxBlock has phinodes in it, remove MaxPop-1 entries from |
| 3160 | // it. |
| 3161 | if (isa<PHINode>(MaxBlock->begin())) |
| 3162 | for (unsigned i = 0; i != MaxPop-1; ++i) |
| 3163 | MaxBlock->removePredecessor(SI->getParent()); |
| 3164 | |
| 3165 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
| 3166 | i != e; ++i) |
| 3167 | if (i.getCaseSuccessor() == MaxBlock) { |
| 3168 | SI->removeCase(i); |
| 3169 | --i; --e; |
| 3170 | } |
| 3171 | } |
| 3172 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3173 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) { |
| 3174 | if (II->getUnwindDest() == BB) { |
| 3175 | // Convert the invoke to a call instruction. This would be a good |
| 3176 | // place to note that the call does not throw though. |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3177 | BranchInst *BI = Builder.CreateBr(II->getNormalDest()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3178 | II->removeFromParent(); // Take out of symbol table |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3179 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3180 | // Insert the call now... |
| 3181 | SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3); |
Devang Patel | 31458a0 | 2011-05-19 00:09:21 +0000 | [diff] [blame] | 3182 | Builder.SetInsertPoint(BI); |
| 3183 | CallInst *CI = Builder.CreateCall(II->getCalledValue(), |
Jay Foad | 5bd375a | 2011-07-15 08:37:34 +0000 | [diff] [blame] | 3184 | Args, II->getName()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3185 | CI->setCallingConv(II->getCallingConv()); |
| 3186 | CI->setAttributes(II->getAttributes()); |
| 3187 | // If the invoke produced a value, the call does now instead. |
| 3188 | II->replaceAllUsesWith(CI); |
| 3189 | delete II; |
| 3190 | Changed = true; |
| 3191 | } |
| 3192 | } |
| 3193 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 3194 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3195 | // If this block is now dead, remove it. |
| 3196 | if (pred_begin(BB) == pred_end(BB) && |
| 3197 | BB != &BB->getParent()->getEntryBlock()) { |
| 3198 | // We know there are no successors, so just nuke the block. |
| 3199 | BB->eraseFromParent(); |
| 3200 | return true; |
| 3201 | } |
| 3202 | |
| 3203 | return Changed; |
| 3204 | } |
| 3205 | |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3206 | /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a |
| 3207 | /// integer range comparison into a sub, an icmp and a branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 3208 | static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3209 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3210 | |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3211 | // Make sure all cases point to the same destination and gather the values. |
| 3212 | SmallVector<ConstantInt *, 16> Cases; |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3213 | SwitchInst::CaseIt I = SI->case_begin(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3214 | Cases.push_back(I.getCaseValue()); |
| 3215 | SwitchInst::CaseIt PrevI = I++; |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3216 | for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3217 | if (PrevI.getCaseSuccessor() != I.getCaseSuccessor()) |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3218 | return false; |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3219 | Cases.push_back(I.getCaseValue()); |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3220 | } |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3221 | assert(Cases.size() == SI->getNumCases() && "Not all cases gathered"); |
Benjamin Kramer | 62aa46b | 2011-02-03 22:51:41 +0000 | [diff] [blame] | 3222 | |
| 3223 | // Sort the case values, then check if they form a range we can transform. |
| 3224 | array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); |
| 3225 | for (unsigned I = 1, E = Cases.size(); I != E; ++I) { |
| 3226 | if (Cases[I-1]->getValue() != Cases[I]->getValue()+1) |
| 3227 | return false; |
| 3228 | } |
| 3229 | |
| 3230 | Constant *Offset = ConstantExpr::getNeg(Cases.back()); |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3231 | Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3232 | |
Benjamin Kramer | 8d6a8c1 | 2011-02-07 22:37:28 +0000 | [diff] [blame] | 3233 | Value *Sub = SI->getCondition(); |
| 3234 | if (!Offset->isNullValue()) |
Devang Patel | 3015a54 | 2011-05-19 00:13:33 +0000 | [diff] [blame] | 3235 | Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off"); |
Hans Wennborg | c9e1d99 | 2013-04-16 08:35:36 +0000 | [diff] [blame] | 3236 | Value *Cmp; |
| 3237 | // If NumCases overflowed, then all possible values jump to the successor. |
| 3238 | if (NumCases->isNullValue() && SI->getNumCases() != 0) |
| 3239 | Cmp = ConstantInt::getTrue(SI->getContext()); |
| 3240 | else |
| 3241 | Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3242 | BranchInst *NewBI = Builder.CreateCondBr( |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3243 | Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest()); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3244 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3245 | // Update weight for the newly-created conditional branch. |
| 3246 | SmallVector<uint64_t, 8> Weights; |
| 3247 | bool HasWeights = HasBranchWeights(SI); |
| 3248 | if (HasWeights) { |
| 3249 | GetBranchWeights(SI, Weights); |
| 3250 | if (Weights.size() == 1 + SI->getNumCases()) { |
| 3251 | // Combine all weights for the cases to be the true weight of NewBI. |
| 3252 | // We assume that the sum of all weights for a Terminator can fit into 32 |
| 3253 | // bits. |
| 3254 | uint32_t NewTrueWeight = 0; |
| 3255 | for (unsigned I = 1, E = Weights.size(); I != E; ++I) |
| 3256 | NewTrueWeight += (uint32_t)Weights[I]; |
| 3257 | NewBI->setMetadata(LLVMContext::MD_prof, |
| 3258 | MDBuilder(SI->getContext()). |
| 3259 | createBranchWeights(NewTrueWeight, |
| 3260 | (uint32_t)Weights[0])); |
| 3261 | } |
| 3262 | } |
| 3263 | |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3264 | // Prune obsolete incoming values off the successor's PHI nodes. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3265 | for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin(); |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3266 | isa<PHINode>(BBI); ++BBI) { |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3267 | for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I) |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 3268 | cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); |
| 3269 | } |
| 3270 | SI->eraseFromParent(); |
| 3271 | |
| 3272 | return true; |
| 3273 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 3274 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3275 | /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch |
| 3276 | /// and use it to remove dead cases. |
Hal Finkel | 60db058 | 2014-09-07 18:57:58 +0000 | [diff] [blame] | 3277 | static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 3278 | AssumptionCache *AC) { |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3279 | Value *Cond = SI->getCondition(); |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 3280 | unsigned Bits = Cond->getType()->getIntegerBitWidth(); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3281 | APInt KnownZero(Bits, 0), KnownOne(Bits, 0); |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 3282 | computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3283 | |
| 3284 | // Gather dead cases. |
| 3285 | SmallVector<ConstantInt*, 8> DeadCases; |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3286 | 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] | 3287 | if ((I.getCaseValue()->getValue() & KnownZero) != 0 || |
| 3288 | (I.getCaseValue()->getValue() & KnownOne) != KnownOne) { |
| 3289 | DeadCases.push_back(I.getCaseValue()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3290 | DEBUG(dbgs() << "SimplifyCFG: switch case '" |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3291 | << I.getCaseValue() << "' is dead.\n"); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3292 | } |
| 3293 | } |
| 3294 | |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3295 | SmallVector<uint64_t, 8> Weights; |
| 3296 | bool HasWeight = HasBranchWeights(SI); |
| 3297 | if (HasWeight) { |
| 3298 | GetBranchWeights(SI, Weights); |
| 3299 | HasWeight = (Weights.size() == 1 + SI->getNumCases()); |
| 3300 | } |
| 3301 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3302 | // Remove dead cases from the switch. |
| 3303 | for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) { |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3304 | SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]); |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3305 | assert(Case != SI->case_default() && |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 3306 | "Case was not found. Probably mistake in DeadCases forming."); |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3307 | if (HasWeight) { |
| 3308 | std::swap(Weights[Case.getCaseIndex()+1], Weights.back()); |
| 3309 | Weights.pop_back(); |
| 3310 | } |
| 3311 | |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3312 | // Prune unused values from PHI nodes. |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 3313 | Case.getCaseSuccessor()->removePredecessor(SI->getParent()); |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3314 | SI->removeCase(Case); |
| 3315 | } |
Justin Bogner | 0ba3f21 | 2013-12-20 08:21:30 +0000 | [diff] [blame] | 3316 | if (HasWeight && Weights.size() >= 2) { |
Manman Ren | 5657555 | 2012-09-18 00:47:33 +0000 | [diff] [blame] | 3317 | SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); |
| 3318 | SI->setMetadata(LLVMContext::MD_prof, |
| 3319 | MDBuilder(SI->getParent()->getContext()). |
| 3320 | createBranchWeights(MDWeights)); |
| 3321 | } |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 3322 | |
| 3323 | return !DeadCases.empty(); |
| 3324 | } |
| 3325 | |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3326 | /// FindPHIForConditionForwarding - If BB would be eligible for simplification |
| 3327 | /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated |
| 3328 | /// by an unconditional branch), look at the phi node for BB in the successor |
| 3329 | /// block and see if the incoming value is equal to CaseValue. If so, return |
| 3330 | /// the phi node, and set PhiIndex to BB's index in the phi node. |
| 3331 | static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, |
| 3332 | BasicBlock *BB, |
| 3333 | int *PhiIndex) { |
| 3334 | if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3335 | return nullptr; // BB must be empty to be a candidate for simplification. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3336 | if (!BB->getSinglePredecessor()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3337 | return nullptr; // BB must be dominated by the switch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3338 | |
| 3339 | BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3340 | if (!Branch || !Branch->isUnconditional()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3341 | return nullptr; // Terminator must be unconditional branch. |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3342 | |
| 3343 | BasicBlock *Succ = Branch->getSuccessor(0); |
| 3344 | |
| 3345 | BasicBlock::iterator I = Succ->begin(); |
| 3346 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3347 | int Idx = PHI->getBasicBlockIndex(BB); |
| 3348 | assert(Idx >= 0 && "PHI has no entry for predecessor?"); |
| 3349 | |
| 3350 | Value *InValue = PHI->getIncomingValue(Idx); |
| 3351 | if (InValue != CaseValue) continue; |
| 3352 | |
| 3353 | *PhiIndex = Idx; |
| 3354 | return PHI; |
| 3355 | } |
| 3356 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3357 | return nullptr; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3358 | } |
| 3359 | |
| 3360 | /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch |
| 3361 | /// instruction to a phi node dominated by the switch, if that would mean that |
| 3362 | /// some of the destination blocks of the switch can be folded away. |
| 3363 | /// Returns true if a change is made. |
| 3364 | static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { |
| 3365 | typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap; |
| 3366 | ForwardingNodesMap ForwardingNodes; |
| 3367 | |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 3368 | 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] | 3369 | ConstantInt *CaseValue = I.getCaseValue(); |
| 3370 | BasicBlock *CaseDest = I.getCaseSuccessor(); |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3371 | |
| 3372 | int PhiIndex; |
| 3373 | PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest, |
| 3374 | &PhiIndex); |
| 3375 | if (!PHI) continue; |
| 3376 | |
| 3377 | ForwardingNodes[PHI].push_back(PhiIndex); |
| 3378 | } |
| 3379 | |
| 3380 | bool Changed = false; |
| 3381 | |
| 3382 | for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), |
| 3383 | E = ForwardingNodes.end(); I != E; ++I) { |
| 3384 | PHINode *Phi = I->first; |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3385 | SmallVectorImpl<int> &Indexes = I->second; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 3386 | |
| 3387 | if (Indexes.size() < 2) continue; |
| 3388 | |
| 3389 | for (size_t I = 0, E = Indexes.size(); I != E; ++I) |
| 3390 | Phi->setIncomingValue(Indexes[I], SI->getCondition()); |
| 3391 | Changed = true; |
| 3392 | } |
| 3393 | |
| 3394 | return Changed; |
| 3395 | } |
| 3396 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3397 | /// ValidLookupTableConstant - Return true if the backend will be able to handle |
| 3398 | /// initializing an array of constants like C. |
Hans Wennborg | 08238ad | 2012-09-07 08:22:57 +0000 | [diff] [blame] | 3399 | static bool ValidLookupTableConstant(Constant *C) { |
Hans Wennborg | 4dc8951 | 2014-06-20 00:38:12 +0000 | [diff] [blame] | 3400 | if (C->isThreadDependent()) |
| 3401 | return false; |
| 3402 | if (C->isDLLImportDependent()) |
| 3403 | return false; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3404 | |
Hans Wennborg | b03ebfb | 2014-06-26 00:30:52 +0000 | [diff] [blame] | 3405 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) |
| 3406 | return CE->isGEPWithNoNotionalOverIndexing(); |
| 3407 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3408 | return isa<ConstantFP>(C) || |
| 3409 | isa<ConstantInt>(C) || |
| 3410 | isa<ConstantPointerNull>(C) || |
| 3411 | isa<GlobalValue>(C) || |
| 3412 | isa<UndefValue>(C); |
| 3413 | } |
| 3414 | |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3415 | /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3416 | /// its constant value in ConstantPool, returning 0 if it's not there. |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3417 | static Constant *LookupConstant(Value *V, |
| 3418 | const SmallDenseMap<Value*, Constant*>& ConstantPool) { |
| 3419 | if (Constant *C = dyn_cast<Constant>(V)) |
| 3420 | return C; |
| 3421 | return ConstantPool.lookup(V); |
| 3422 | } |
| 3423 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3424 | /// ConstantFold - Try to fold instruction I into a constant. This works for |
| 3425 | /// simple instructions such as binary operations where both operands are |
| 3426 | /// constant or can be replaced by constants from the ConstantPool. Returns the |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3427 | /// resulting constant on success, 0 otherwise. |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3428 | static Constant * |
| 3429 | ConstantFold(Instruction *I, |
| 3430 | const SmallDenseMap<Value *, Constant *> &ConstantPool, |
| 3431 | const DataLayout *DL) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3432 | if (SelectInst *Select = dyn_cast<SelectInst>(I)) { |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3433 | Constant *A = LookupConstant(Select->getCondition(), ConstantPool); |
| 3434 | if (!A) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3435 | return nullptr; |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3436 | if (A->isAllOnesValue()) |
| 3437 | return LookupConstant(Select->getTrueValue(), ConstantPool); |
| 3438 | if (A->isNullValue()) |
| 3439 | return LookupConstant(Select->getFalseValue(), ConstantPool); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3440 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3441 | } |
| 3442 | |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3443 | SmallVector<Constant *, 4> COps; |
| 3444 | for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { |
| 3445 | if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) |
| 3446 | COps.push_back(A); |
| 3447 | else |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3448 | return nullptr; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3449 | } |
| 3450 | |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3451 | if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) |
| 3452 | return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], |
| 3453 | COps[1], DL); |
| 3454 | |
| 3455 | return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3456 | } |
| 3457 | |
| 3458 | /// GetCaseResults - Try to determine the resulting constant values in phi nodes |
| 3459 | /// at the common destination basic block, *CommonDest, for one of the case |
Hans Wennborg | 4fef2fe | 2012-10-31 15:31:09 +0000 | [diff] [blame] | 3460 | /// destionations CaseDest corresponding to value CaseVal (0 for the default |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3461 | /// case), of a switch instruction SI. |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3462 | static bool |
| 3463 | GetCaseResults(SwitchInst *SI, |
| 3464 | ConstantInt *CaseVal, |
| 3465 | BasicBlock *CaseDest, |
| 3466 | BasicBlock **CommonDest, |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3467 | SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res, |
| 3468 | const DataLayout *DL) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3469 | // The block from which we enter the common destination. |
| 3470 | BasicBlock *Pred = SI->getParent(); |
| 3471 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3472 | // If CaseDest is empty except for some side-effect free instructions through |
| 3473 | // which we can constant-propagate the CaseVal, continue to its successor. |
| 3474 | SmallDenseMap<Value*, Constant*> ConstantPool; |
| 3475 | ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); |
| 3476 | for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; |
| 3477 | ++I) { |
| 3478 | if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { |
| 3479 | // If the terminator is a simple branch, continue to the next block. |
| 3480 | if (T->getNumSuccessors() != 1) |
| 3481 | return false; |
| 3482 | Pred = CaseDest; |
| 3483 | CaseDest = T->getSuccessor(0); |
| 3484 | } else if (isa<DbgInfoIntrinsic>(I)) { |
| 3485 | // Skip debug intrinsic. |
| 3486 | continue; |
Benjamin Kramer | 7c30260 | 2013-11-12 12:24:36 +0000 | [diff] [blame] | 3487 | } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) { |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3488 | // Instruction is side-effect free and constant. |
Hans Wennborg | dcc6e5b | 2015-01-09 22:13:31 +0000 | [diff] [blame^] | 3489 | |
| 3490 | // If the instruction has uses outside this block or a phi node slot for |
| 3491 | // the block, it is not safe to bypass the instruction since it would then |
| 3492 | // no longer dominate all its uses. |
| 3493 | for (auto &Use : I->uses()) { |
| 3494 | User *User = Use.getUser(); |
| 3495 | if (Instruction *I = dyn_cast<Instruction>(User)) |
| 3496 | if (I->getParent() == CaseDest) |
| 3497 | continue; |
| 3498 | if (PHINode *Phi = dyn_cast<PHINode>(User)) |
| 3499 | if (Phi->getIncomingBlock(Use) == CaseDest) |
| 3500 | continue; |
| 3501 | return false; |
| 3502 | } |
| 3503 | |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3504 | ConstantPool.insert(std::make_pair(I, C)); |
| 3505 | } else { |
| 3506 | break; |
| 3507 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3508 | } |
| 3509 | |
| 3510 | // If we did not have a CommonDest before, use the current one. |
| 3511 | if (!*CommonDest) |
| 3512 | *CommonDest = CaseDest; |
| 3513 | // If the destination isn't the common one, abort. |
| 3514 | if (CaseDest != *CommonDest) |
| 3515 | return false; |
| 3516 | |
| 3517 | // Get the values for this case from phi nodes in the destination block. |
| 3518 | BasicBlock::iterator I = (*CommonDest)->begin(); |
| 3519 | while (PHINode *PHI = dyn_cast<PHINode>(I++)) { |
| 3520 | int Idx = PHI->getBasicBlockIndex(Pred); |
| 3521 | if (Idx == -1) |
| 3522 | continue; |
| 3523 | |
Hans Wennborg | 09acdb9 | 2012-10-31 15:14:39 +0000 | [diff] [blame] | 3524 | Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx), |
| 3525 | ConstantPool); |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 3526 | if (!ConstVal) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3527 | return false; |
| 3528 | |
| 3529 | // Be conservative about which kinds of constants we support. |
| 3530 | if (!ValidLookupTableConstant(ConstVal)) |
| 3531 | return false; |
| 3532 | |
| 3533 | Res.push_back(std::make_pair(PHI, ConstVal)); |
| 3534 | } |
| 3535 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3536 | return Res.size() > 0; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3537 | } |
| 3538 | |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3539 | // MapCaseToResult - Helper function used to |
| 3540 | // add CaseVal to the list of cases that generate Result. |
| 3541 | static void MapCaseToResult(ConstantInt *CaseVal, |
| 3542 | SwitchCaseResultVectorTy &UniqueResults, |
| 3543 | Constant *Result) { |
| 3544 | for (auto &I : UniqueResults) { |
| 3545 | if (I.first == Result) { |
| 3546 | I.second.push_back(CaseVal); |
| 3547 | return; |
| 3548 | } |
| 3549 | } |
| 3550 | UniqueResults.push_back(std::make_pair(Result, |
| 3551 | SmallVector<ConstantInt*, 4>(1, CaseVal))); |
| 3552 | } |
| 3553 | |
| 3554 | // InitializeUniqueCases - Helper function that initializes a map containing |
| 3555 | // results for the PHI node of the common destination block for a switch |
| 3556 | // instruction. Returns false if multiple PHI nodes have been found or if |
| 3557 | // there is not a common destination block for the switch. |
| 3558 | static bool InitializeUniqueCases( |
| 3559 | SwitchInst *SI, const DataLayout *DL, PHINode *&PHI, |
| 3560 | BasicBlock *&CommonDest, |
| 3561 | SwitchCaseResultVectorTy &UniqueResults, |
| 3562 | Constant *&DefaultResult) { |
| 3563 | for (auto &I : SI->cases()) { |
| 3564 | ConstantInt *CaseVal = I.getCaseValue(); |
| 3565 | |
| 3566 | // Resulting value at phi nodes for this case value. |
| 3567 | SwitchCaseResultsTy Results; |
| 3568 | if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, |
| 3569 | DL)) |
| 3570 | return false; |
| 3571 | |
| 3572 | // Only one value per case is permitted |
| 3573 | if (Results.size() > 1) |
| 3574 | return false; |
| 3575 | MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); |
| 3576 | |
| 3577 | // Check the PHI consistency. |
| 3578 | if (!PHI) |
| 3579 | PHI = Results[0].first; |
| 3580 | else if (PHI != Results[0].first) |
| 3581 | return false; |
| 3582 | } |
| 3583 | // Find the default result value. |
| 3584 | SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; |
| 3585 | BasicBlock *DefaultDest = SI->getDefaultDest(); |
| 3586 | GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, |
| 3587 | DL); |
| 3588 | // If the default value is not found abort unless the default destination |
| 3589 | // is unreachable. |
| 3590 | DefaultResult = |
| 3591 | DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; |
| 3592 | if ((!DefaultResult && |
| 3593 | !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) |
| 3594 | return false; |
| 3595 | |
| 3596 | return true; |
| 3597 | } |
| 3598 | |
| 3599 | // ConvertTwoCaseSwitch - Helper function that checks if it is possible to |
| 3600 | // transform a switch with only two cases (or two cases + default) |
| 3601 | // that produces a result into a value select. |
| 3602 | // Example: |
| 3603 | // switch (a) { |
| 3604 | // case 10: %0 = icmp eq i32 %a, 10 |
| 3605 | // return 10; %1 = select i1 %0, i32 10, i32 4 |
| 3606 | // case 20: ----> %2 = icmp eq i32 %a, 20 |
| 3607 | // return 2; %3 = select i1 %2, i32 2, i32 %1 |
| 3608 | // default: |
| 3609 | // return 4; |
| 3610 | // } |
| 3611 | static Value * |
| 3612 | ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, |
| 3613 | Constant *DefaultResult, Value *Condition, |
| 3614 | IRBuilder<> &Builder) { |
| 3615 | assert(ResultVector.size() == 2 && |
| 3616 | "We should have exactly two unique results at this point"); |
| 3617 | // If we are selecting between only two cases transform into a simple |
| 3618 | // select or a two-way select if default is possible. |
| 3619 | if (ResultVector[0].second.size() == 1 && |
| 3620 | ResultVector[1].second.size() == 1) { |
| 3621 | ConstantInt *const FirstCase = ResultVector[0].second[0]; |
| 3622 | ConstantInt *const SecondCase = ResultVector[1].second[0]; |
| 3623 | |
| 3624 | bool DefaultCanTrigger = DefaultResult; |
| 3625 | Value *SelectValue = ResultVector[1].first; |
| 3626 | if (DefaultCanTrigger) { |
| 3627 | Value *const ValueCompare = |
| 3628 | Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); |
| 3629 | SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, |
| 3630 | DefaultResult, "switch.select"); |
| 3631 | } |
| 3632 | Value *const ValueCompare = |
| 3633 | Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); |
| 3634 | return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue, |
| 3635 | "switch.select"); |
| 3636 | } |
| 3637 | |
| 3638 | return nullptr; |
| 3639 | } |
| 3640 | |
| 3641 | // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch |
| 3642 | // instruction that has been converted into a select, fixing up PHI nodes and |
| 3643 | // basic blocks. |
| 3644 | static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, |
| 3645 | Value *SelectValue, |
| 3646 | IRBuilder<> &Builder) { |
| 3647 | BasicBlock *SelectBB = SI->getParent(); |
| 3648 | while (PHI->getBasicBlockIndex(SelectBB) >= 0) |
| 3649 | PHI->removeIncomingValue(SelectBB); |
| 3650 | PHI->addIncoming(SelectValue, SelectBB); |
| 3651 | |
| 3652 | Builder.CreateBr(PHI->getParent()); |
| 3653 | |
| 3654 | // Remove the switch. |
| 3655 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
| 3656 | BasicBlock *Succ = SI->getSuccessor(i); |
| 3657 | |
| 3658 | if (Succ == PHI->getParent()) |
| 3659 | continue; |
| 3660 | Succ->removePredecessor(SelectBB); |
| 3661 | } |
| 3662 | SI->eraseFromParent(); |
| 3663 | } |
| 3664 | |
| 3665 | /// SwitchToSelect - If the switch is only used to initialize one or more |
| 3666 | /// phi nodes in a common successor block with only two different |
| 3667 | /// constant values, replace the switch with select. |
| 3668 | static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 3669 | const DataLayout *DL, AssumptionCache *AC) { |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 3670 | Value *const Cond = SI->getCondition(); |
| 3671 | PHINode *PHI = nullptr; |
| 3672 | BasicBlock *CommonDest = nullptr; |
| 3673 | Constant *DefaultResult; |
| 3674 | SwitchCaseResultVectorTy UniqueResults; |
| 3675 | // Collect all the cases that will deliver the same value from the switch. |
| 3676 | if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults, |
| 3677 | DefaultResult)) |
| 3678 | return false; |
| 3679 | // Selects choose between maximum two values. |
| 3680 | if (UniqueResults.size() != 2) |
| 3681 | return false; |
| 3682 | assert(PHI != nullptr && "PHI for value select not found"); |
| 3683 | |
| 3684 | Builder.SetInsertPoint(SI); |
| 3685 | Value *SelectValue = ConvertTwoCaseSwitch( |
| 3686 | UniqueResults, |
| 3687 | DefaultResult, Cond, Builder); |
| 3688 | if (SelectValue) { |
| 3689 | RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); |
| 3690 | return true; |
| 3691 | } |
| 3692 | // The switch couldn't be converted into a select. |
| 3693 | return false; |
| 3694 | } |
| 3695 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3696 | namespace { |
| 3697 | /// SwitchLookupTable - This class represents a lookup table that can be used |
| 3698 | /// to replace a switch. |
| 3699 | class SwitchLookupTable { |
| 3700 | public: |
| 3701 | /// SwitchLookupTable - Create a lookup table to use as a switch replacement |
| 3702 | /// with the contents of Values, using DefaultValue to fill any holes in the |
| 3703 | /// table. |
| 3704 | SwitchLookupTable(Module &M, |
| 3705 | uint64_t TableSize, |
| 3706 | ConstantInt *Offset, |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3707 | const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3708 | Constant *DefaultValue, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3709 | const DataLayout *DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3710 | |
| 3711 | /// BuildLookup - Build instructions with Builder to retrieve the value at |
| 3712 | /// the position given by Index in the lookup table. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 3713 | Value *BuildLookup(Value *Index, IRBuilder<> &Builder); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3714 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3715 | /// WouldFitInRegister - Return true if a table with TableSize elements of |
| 3716 | /// type ElementType would fit in a target-legal register. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3717 | static bool WouldFitInRegister(const DataLayout *DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3718 | uint64_t TableSize, |
| 3719 | const Type *ElementType); |
| 3720 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3721 | private: |
| 3722 | // Depending on the contents of the table, it can be represented in |
| 3723 | // different ways. |
| 3724 | enum { |
| 3725 | // For tables where each element contains the same value, we just have to |
| 3726 | // store that single value and return it for each lookup. |
| 3727 | SingleValueKind, |
| 3728 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3729 | // For tables where there is a linear relationship between table index |
| 3730 | // and values. We calculate the result with a simple multiplication |
| 3731 | // and addition instead of a table lookup. |
| 3732 | LinearMapKind, |
| 3733 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3734 | // For small tables with integer elements, we can pack them into a bitmap |
| 3735 | // that fits into a target-legal register. Values are retrieved by |
| 3736 | // shift and mask operations. |
| 3737 | BitMapKind, |
| 3738 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3739 | // The table is stored as an array of values. Values are retrieved by load |
| 3740 | // instructions from the table. |
| 3741 | ArrayKind |
| 3742 | } Kind; |
| 3743 | |
| 3744 | // For SingleValueKind, this is the single value. |
| 3745 | Constant *SingleValue; |
| 3746 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3747 | // For BitMapKind, this is the bitmap. |
| 3748 | ConstantInt *BitMap; |
| 3749 | IntegerType *BitMapElementTy; |
| 3750 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3751 | // For LinearMapKind, these are the constants used to derive the value. |
| 3752 | ConstantInt *LinearOffset; |
| 3753 | ConstantInt *LinearMultiplier; |
| 3754 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3755 | // For ArrayKind, this is the array. |
| 3756 | GlobalVariable *Array; |
| 3757 | }; |
| 3758 | } |
| 3759 | |
| 3760 | SwitchLookupTable::SwitchLookupTable(Module &M, |
| 3761 | uint64_t TableSize, |
| 3762 | ConstantInt *Offset, |
Craig Topper | b94011f | 2013-07-14 04:42:23 +0000 | [diff] [blame] | 3763 | const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3764 | Constant *DefaultValue, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3765 | const DataLayout *DL) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3766 | : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3767 | LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 3768 | assert(Values.size() && "Can't build lookup table without values!"); |
| 3769 | assert(TableSize >= Values.size() && "Can't fit values in table!"); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3770 | |
| 3771 | // If all values in the table are equal, this is that value. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3772 | SingleValue = Values.begin()->second; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3773 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3774 | Type *ValueType = Values.begin()->second->getType(); |
| 3775 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3776 | // Build up the table contents. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3777 | SmallVector<Constant*, 64> TableContents(TableSize); |
| 3778 | for (size_t I = 0, E = Values.size(); I != E; ++I) { |
| 3779 | ConstantInt *CaseVal = Values[I].first; |
| 3780 | Constant *CaseRes = Values[I].second; |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3781 | assert(CaseRes->getType() == ValueType); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3782 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3783 | uint64_t Idx = (CaseVal->getValue() - Offset->getValue()) |
| 3784 | .getLimitedValue(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3785 | TableContents[Idx] = CaseRes; |
| 3786 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3787 | if (CaseRes != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3788 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3789 | } |
| 3790 | |
| 3791 | // Fill in any holes in the table with the default result. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3792 | if (Values.size() < TableSize) { |
Marcello Maggioni | 89c05ad | 2014-07-03 08:29:06 +0000 | [diff] [blame] | 3793 | assert(DefaultValue && |
| 3794 | "Need a default value to fill the lookup table holes."); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3795 | assert(DefaultValue->getType() == ValueType); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3796 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 3797 | if (!TableContents[I]) |
| 3798 | TableContents[I] = DefaultValue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3799 | } |
| 3800 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3801 | if (DefaultValue != SingleValue) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3802 | SingleValue = nullptr; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3803 | } |
| 3804 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3805 | // If each element in the table contains the same value, we only need to store |
| 3806 | // that single value. |
| 3807 | if (SingleValue) { |
| 3808 | Kind = SingleValueKind; |
| 3809 | return; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3810 | } |
| 3811 | |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3812 | // Check if we can derive the value with a linear transformation from the |
| 3813 | // table index. |
| 3814 | if (isa<IntegerType>(ValueType)) { |
| 3815 | bool LinearMappingPossible = true; |
| 3816 | APInt PrevVal; |
| 3817 | APInt DistToPrev; |
| 3818 | assert(TableSize >= 2 && "Should be a SingleValue table."); |
| 3819 | // Check if there is the same distance between two consecutive values. |
| 3820 | for (uint64_t I = 0; I < TableSize; ++I) { |
| 3821 | ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); |
| 3822 | if (!ConstVal) { |
| 3823 | // This is an undef. We could deal with it, but undefs in lookup tables |
| 3824 | // are very seldom. It's probably not worth the additional complexity. |
| 3825 | LinearMappingPossible = false; |
| 3826 | break; |
| 3827 | } |
| 3828 | APInt Val = ConstVal->getValue(); |
| 3829 | if (I != 0) { |
| 3830 | APInt Dist = Val - PrevVal; |
| 3831 | if (I == 1) { |
| 3832 | DistToPrev = Dist; |
| 3833 | } else if (Dist != DistToPrev) { |
| 3834 | LinearMappingPossible = false; |
| 3835 | break; |
| 3836 | } |
| 3837 | } |
| 3838 | PrevVal = Val; |
| 3839 | } |
| 3840 | if (LinearMappingPossible) { |
| 3841 | LinearOffset = cast<ConstantInt>(TableContents[0]); |
| 3842 | LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); |
| 3843 | Kind = LinearMapKind; |
| 3844 | ++NumLinearMaps; |
| 3845 | return; |
| 3846 | } |
| 3847 | } |
| 3848 | |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3849 | // 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] | 3850 | if (WouldFitInRegister(DL, TableSize, ValueType)) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3851 | IntegerType *IT = cast<IntegerType>(ValueType); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3852 | APInt TableInt(TableSize * IT->getBitWidth(), 0); |
| 3853 | for (uint64_t I = TableSize; I > 0; --I) { |
| 3854 | TableInt <<= IT->getBitWidth(); |
Benjamin Kramer | 9fc3dc7 | 2012-10-01 11:31:48 +0000 | [diff] [blame] | 3855 | // Insert values into the bitmap. Undef values are set to zero. |
| 3856 | if (!isa<UndefValue>(TableContents[I - 1])) { |
| 3857 | ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); |
| 3858 | TableInt |= Val->getValue().zext(TableInt.getBitWidth()); |
| 3859 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3860 | } |
| 3861 | BitMap = ConstantInt::get(M.getContext(), TableInt); |
| 3862 | BitMapElementTy = IT; |
| 3863 | Kind = BitMapKind; |
| 3864 | ++NumBitMaps; |
| 3865 | return; |
| 3866 | } |
| 3867 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3868 | // Store the table in an array. |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 3869 | ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3870 | Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); |
| 3871 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3872 | Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true, |
| 3873 | GlobalVariable::PrivateLinkage, |
| 3874 | Initializer, |
| 3875 | "switch.table"); |
| 3876 | Array->setUnnamedAddr(true); |
| 3877 | Kind = ArrayKind; |
| 3878 | } |
| 3879 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 3880 | Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3881 | switch (Kind) { |
| 3882 | case SingleValueKind: |
| 3883 | return SingleValue; |
Erik Eckstein | 105374f | 2014-11-17 09:13:57 +0000 | [diff] [blame] | 3884 | case LinearMapKind: { |
| 3885 | // Derive the result value from the input value. |
| 3886 | Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), |
| 3887 | false, "switch.idx.cast"); |
| 3888 | if (!LinearMultiplier->isOne()) |
| 3889 | Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); |
| 3890 | if (!LinearOffset->isZero()) |
| 3891 | Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); |
| 3892 | return Result; |
| 3893 | } |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3894 | case BitMapKind: { |
| 3895 | // Type of the bitmap (e.g. i59). |
| 3896 | IntegerType *MapTy = BitMap->getType(); |
| 3897 | |
| 3898 | // Cast Index to the same type as the bitmap. |
| 3899 | // Note: The Index is <= the number of elements in the table, so |
| 3900 | // truncating it to the width of the bitmask is safe. |
Hans Wennborg | cd3a11f | 2012-09-26 14:01:53 +0000 | [diff] [blame] | 3901 | Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3902 | |
| 3903 | // Multiply the shift amount by the element width. |
| 3904 | ShiftAmt = Builder.CreateMul(ShiftAmt, |
| 3905 | ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), |
| 3906 | "switch.shiftamt"); |
| 3907 | |
| 3908 | // Shift down. |
| 3909 | Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt, |
| 3910 | "switch.downshift"); |
| 3911 | // Mask off. |
| 3912 | return Builder.CreateTrunc(DownShifted, BitMapElementTy, |
| 3913 | "switch.masked"); |
| 3914 | } |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3915 | case ArrayKind: { |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 3916 | // Make sure the table index will not overflow when treated as signed. |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 3917 | IntegerType *IT = cast<IntegerType>(Index->getType()); |
| 3918 | uint64_t TableSize = Array->getInitializer()->getType() |
| 3919 | ->getArrayNumElements(); |
| 3920 | if (TableSize > (1ULL << (IT->getBitWidth() - 1))) |
| 3921 | Index = Builder.CreateZExt(Index, |
| 3922 | IntegerType::get(IT->getContext(), |
| 3923 | IT->getBitWidth() + 1), |
| 3924 | "switch.tableidx.zext"); |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 3925 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3926 | Value *GEPIndices[] = { Builder.getInt32(0), Index }; |
| 3927 | Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices, |
| 3928 | "switch.gep"); |
| 3929 | return Builder.CreateLoad(GEP, "switch.load"); |
| 3930 | } |
| 3931 | } |
| 3932 | llvm_unreachable("Unknown lookup table kind!"); |
| 3933 | } |
| 3934 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3935 | bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3936 | uint64_t TableSize, |
| 3937 | const Type *ElementType) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3938 | if (!DL) |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3939 | return false; |
| 3940 | const IntegerType *IT = dyn_cast<IntegerType>(ElementType); |
| 3941 | if (!IT) |
| 3942 | return false; |
| 3943 | // FIXME: If the type is wider than it needs to be, e.g. i8 but all values |
| 3944 | // are <= 15, we could try to narrow the type. |
Benjamin Kramer | c2081d1 | 2012-09-27 18:29:58 +0000 | [diff] [blame] | 3945 | |
| 3946 | // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. |
| 3947 | if (TableSize >= UINT_MAX/IT->getBitWidth()) |
| 3948 | return false; |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3949 | return DL->fitsInLegalInteger(TableSize * IT->getBitWidth()); |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3950 | } |
| 3951 | |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3952 | /// ShouldBuildLookupTable - Determine whether a lookup table should be built |
Hans Wennborg | 5cf30be | 2013-06-04 11:22:30 +0000 | [diff] [blame] | 3953 | /// for this switch, based on the number of cases, size of the table and the |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3954 | /// types of the results. |
| 3955 | static bool ShouldBuildLookupTable(SwitchInst *SI, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3956 | uint64_t TableSize, |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 3957 | const TargetTransformInfo &TTI, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3958 | const DataLayout *DL, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3959 | const SmallDenseMap<PHINode*, Type*>& ResultTypes) { |
Hans Wennborg | f2e2c10 | 2012-09-26 11:07:37 +0000 | [diff] [blame] | 3960 | if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) |
| 3961 | return false; // TableSize overflowed, or mul below might overflow. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 3962 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 3963 | bool AllTablesFitInRegister = true; |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 3964 | bool HasIllegalType = false; |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 3965 | for (const auto &I : ResultTypes) { |
| 3966 | Type *Ty = I.second; |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 3967 | |
| 3968 | // Saturate this flag to true. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 3969 | HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 3970 | |
| 3971 | // Saturate this flag to false. |
| 3972 | AllTablesFitInRegister = AllTablesFitInRegister && |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 3973 | SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); |
Chandler Carruth | d9ef81e | 2012-11-30 09:34:29 +0000 | [diff] [blame] | 3974 | |
| 3975 | // If both flags saturate, we're done. NOTE: This *only* works with |
| 3976 | // saturating flags, and all flags have to saturate first due to the |
| 3977 | // non-deterministic behavior of iterating over a dense map. |
| 3978 | if (HasIllegalType && !AllTablesFitInRegister) |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 3979 | break; |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 3980 | } |
Evan Cheng | 65df808 | 2012-11-30 02:02:42 +0000 | [diff] [blame] | 3981 | |
Chandler Carruth | 77d433d | 2012-11-30 09:26:25 +0000 | [diff] [blame] | 3982 | // If each table would fit in a register, we should build it anyway. |
| 3983 | if (AllTablesFitInRegister) |
| 3984 | return true; |
| 3985 | |
| 3986 | // Don't build a table that doesn't fit in-register if it has illegal types. |
| 3987 | if (HasIllegalType) |
| 3988 | return false; |
| 3989 | |
| 3990 | // The table density should be at least 40%. This is the same criterion as for |
| 3991 | // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. |
| 3992 | // FIXME: Find the best cut-off. |
| 3993 | return SI->getNumCases() * 10 >= TableSize * 4; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 3994 | } |
| 3995 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 3996 | /// Try to reuse the switch table index compare. Following pattern: |
| 3997 | /// \code |
| 3998 | /// if (idx < tablesize) |
| 3999 | /// r = table[idx]; // table does not contain default_value |
| 4000 | /// else |
| 4001 | /// r = default_value; |
| 4002 | /// if (r != default_value) |
| 4003 | /// ... |
| 4004 | /// \endcode |
| 4005 | /// Is optimized to: |
| 4006 | /// \code |
| 4007 | /// cond = idx < tablesize; |
| 4008 | /// if (cond) |
| 4009 | /// r = table[idx]; |
| 4010 | /// else |
| 4011 | /// r = default_value; |
| 4012 | /// if (cond) |
| 4013 | /// ... |
| 4014 | /// \endcode |
| 4015 | /// Jump threading will then eliminate the second if(cond). |
| 4016 | static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, |
| 4017 | BranchInst *RangeCheckBranch, Constant *DefaultValue, |
| 4018 | const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) { |
| 4019 | |
| 4020 | ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); |
| 4021 | if (!CmpInst) |
| 4022 | return; |
| 4023 | |
| 4024 | // We require that the compare is in the same block as the phi so that jump |
| 4025 | // threading can do its work afterwards. |
| 4026 | if (CmpInst->getParent() != PhiBlock) |
| 4027 | return; |
| 4028 | |
| 4029 | Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); |
| 4030 | if (!CmpOp1) |
| 4031 | return; |
| 4032 | |
| 4033 | Value *RangeCmp = RangeCheckBranch->getCondition(); |
| 4034 | Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); |
| 4035 | Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); |
| 4036 | |
| 4037 | // Check if the compare with the default value is constant true or false. |
| 4038 | Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4039 | DefaultValue, CmpOp1, true); |
| 4040 | if (DefaultConst != TrueConst && DefaultConst != FalseConst) |
| 4041 | return; |
| 4042 | |
| 4043 | // Check if the compare with the case values is distinct from the default |
| 4044 | // compare result. |
| 4045 | for (auto ValuePair : Values) { |
| 4046 | Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), |
| 4047 | ValuePair.second, CmpOp1, true); |
| 4048 | if (!CaseConst || CaseConst == DefaultConst) |
| 4049 | return; |
| 4050 | assert((CaseConst == TrueConst || CaseConst == FalseConst) && |
| 4051 | "Expect true or false as compare result."); |
| 4052 | } |
| 4053 | |
| 4054 | // Check if the branch instruction dominates the phi node. It's a simple |
| 4055 | // dominance check, but sufficient for our needs. |
| 4056 | // Although this check is invariant in the calling loops, it's better to do it |
| 4057 | // at this late stage. Practically we do it at most once for a switch. |
| 4058 | BasicBlock *BranchBlock = RangeCheckBranch->getParent(); |
| 4059 | for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { |
| 4060 | BasicBlock *Pred = *PI; |
| 4061 | if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) |
| 4062 | return; |
| 4063 | } |
| 4064 | |
| 4065 | if (DefaultConst == FalseConst) { |
| 4066 | // The compare yields the same result. We can replace it. |
| 4067 | CmpInst->replaceAllUsesWith(RangeCmp); |
| 4068 | ++NumTableCmpReuses; |
| 4069 | } else { |
| 4070 | // The compare yields the same result, just inverted. We can replace it. |
| 4071 | Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp, |
| 4072 | ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", |
| 4073 | RangeCheckBranch); |
| 4074 | CmpInst->replaceAllUsesWith(InvertedTableCmp); |
| 4075 | ++NumTableCmpReuses; |
| 4076 | } |
| 4077 | } |
| 4078 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4079 | /// SwitchToLookupTable - If the switch is only used to initialize one or more |
| 4080 | /// phi nodes in a common successor block with different constant values, |
| 4081 | /// replace the switch with lookup tables. |
| 4082 | static bool SwitchToLookupTable(SwitchInst *SI, |
Hans Wennborg | 39583b8 | 2012-09-26 09:44:49 +0000 | [diff] [blame] | 4083 | IRBuilder<> &Builder, |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4084 | const TargetTransformInfo &TTI, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4085 | const DataLayout* DL) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4086 | assert(SI->getNumCases() > 1 && "Degenerate switch?"); |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4087 | |
Hans Wennborg | c3c8d95 | 2012-11-07 21:35:12 +0000 | [diff] [blame] | 4088 | // Only build lookup table when we have a target that supports it. |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4089 | if (!TTI.shouldBuildLookupTables()) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4090 | return false; |
| 4091 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4092 | // FIXME: If the switch is too sparse for a lookup table, perhaps we could |
| 4093 | // split off a dense part and build a lookup table for that. |
| 4094 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4095 | // FIXME: This creates arrays of GEPs to constant strings, which means each |
| 4096 | // GEP needs a runtime relocation in PIC code. We should just build one big |
| 4097 | // string and lookup indices into that. |
| 4098 | |
Hans Wennborg | 4744ac1 | 2014-01-15 05:00:27 +0000 | [diff] [blame] | 4099 | // Ignore switches with less than three cases. Lookup tables will not make them |
| 4100 | // faster, so we don't analyze them. |
| 4101 | if (SI->getNumCases() < 3) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4102 | return false; |
| 4103 | |
| 4104 | // Figure out the corresponding result for each case value and phi node in the |
| 4105 | // common destination, as well as the the min and max case values. |
| 4106 | assert(SI->case_begin() != SI->case_end()); |
| 4107 | SwitchInst::CaseIt CI = SI->case_begin(); |
| 4108 | ConstantInt *MinCaseVal = CI.getCaseValue(); |
| 4109 | ConstantInt *MaxCaseVal = CI.getCaseValue(); |
| 4110 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4111 | BasicBlock *CommonDest = nullptr; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4112 | typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4113 | SmallDenseMap<PHINode*, ResultListTy> ResultLists; |
| 4114 | SmallDenseMap<PHINode*, Constant*> DefaultResults; |
| 4115 | SmallDenseMap<PHINode*, Type*> ResultTypes; |
| 4116 | SmallVector<PHINode*, 4> PHIs; |
| 4117 | |
| 4118 | for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { |
| 4119 | ConstantInt *CaseVal = CI.getCaseValue(); |
| 4120 | if (CaseVal->getValue().slt(MinCaseVal->getValue())) |
| 4121 | MinCaseVal = CaseVal; |
| 4122 | if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) |
| 4123 | MaxCaseVal = CaseVal; |
| 4124 | |
| 4125 | // Resulting value at phi nodes for this case value. |
| 4126 | typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy; |
| 4127 | ResultsTy Results; |
Hans Wennborg | 9e74dd9 | 2012-10-31 13:42:45 +0000 | [diff] [blame] | 4128 | if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4129 | Results, DL)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4130 | return false; |
| 4131 | |
| 4132 | // Append the result from this case to the list for each phi. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4133 | for (const auto &I : Results) { |
| 4134 | PHINode *PHI = I.first; |
| 4135 | Constant *Value = I.second; |
| 4136 | if (!ResultLists.count(PHI)) |
| 4137 | PHIs.push_back(PHI); |
| 4138 | ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4139 | } |
| 4140 | } |
| 4141 | |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4142 | // Keep track of the result types. |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4143 | for (PHINode *PHI : PHIs) { |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4144 | ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); |
| 4145 | } |
| 4146 | |
| 4147 | uint64_t NumResults = ResultLists[PHIs[0]].size(); |
| 4148 | APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); |
| 4149 | uint64_t TableSize = RangeSpread.getLimitedValue() + 1; |
| 4150 | bool TableHasHoles = (NumResults < TableSize); |
| 4151 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4152 | // If the table has holes, we need a constant result for the default case |
| 4153 | // or a bitmask that fits in a register. |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4154 | SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4155 | bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(), |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4156 | &CommonDest, DefaultResultsList, DL); |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4157 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4158 | bool NeedMask = (TableHasHoles && !HasDefaultResults); |
| 4159 | if (NeedMask) { |
| 4160 | // As an extra penalty for the validity test we require more cases. |
| 4161 | if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). |
| 4162 | return false; |
| 4163 | if (!(DL && DL->fitsInLegalInteger(TableSize))) |
| 4164 | return false; |
| 4165 | } |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4166 | |
Hans Wennborg | a6a11a9 | 2014-11-18 02:37:11 +0000 | [diff] [blame] | 4167 | for (const auto &I : DefaultResultsList) { |
| 4168 | PHINode *PHI = I.first; |
| 4169 | Constant *Result = I.second; |
Hans Wennborg | 7fd5c844 | 2012-09-10 07:44:22 +0000 | [diff] [blame] | 4170 | DefaultResults[PHI] = Result; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4171 | } |
| 4172 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4173 | if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4174 | return false; |
| 4175 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4176 | // Create the BB that does the lookups. |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4177 | Module &Mod = *CommonDest->getParent()->getParent(); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4178 | BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4179 | "switch.lookup", |
| 4180 | CommonDest->getParent(), |
| 4181 | CommonDest); |
| 4182 | |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4183 | // Compute the table index value. |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4184 | Builder.SetInsertPoint(SI); |
| 4185 | Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, |
| 4186 | "switch.tableidx"); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4187 | |
| 4188 | // Compute the maximum table size representable by the integer type we are |
| 4189 | // switching upon. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4190 | unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); |
Hans Wennborg | ac114a3 | 2014-01-12 00:44:41 +0000 | [diff] [blame] | 4191 | uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4192 | assert(MaxTableSize >= TableSize && |
| 4193 | "It is impossible for a switch to have more entries than the max " |
| 4194 | "representable value of its input integer type's size."); |
| 4195 | |
Hans Wennborg | 5bef5b5 | 2014-12-01 17:36:43 +0000 | [diff] [blame] | 4196 | // If we have a fully covered lookup table, unconditionally branch to the |
| 4197 | // lookup table BB. Otherwise, check if the condition value is within the case |
| 4198 | // range. If it is so, branch to the new BB. Otherwise branch to SI's default |
| 4199 | // destination. |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4200 | BranchInst *RangeCheckBranch = nullptr; |
| 4201 | |
Hans Wennborg | 5bef5b5 | 2014-12-01 17:36:43 +0000 | [diff] [blame] | 4202 | const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize; |
| 4203 | if (GeneratingCoveredLookupTable) { |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4204 | Builder.CreateBr(LookupBB); |
Manman Ren | 062f58d | 2014-08-02 23:41:54 +0000 | [diff] [blame] | 4205 | // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, |
| 4206 | // do not delete PHINodes here. |
| 4207 | SI->getDefaultDest()->removePredecessor(SI->getParent(), |
Hans Wennborg | 5bef5b5 | 2014-12-01 17:36:43 +0000 | [diff] [blame] | 4208 | true/*DontDeleteUselessPHIs*/); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4209 | } else { |
| 4210 | Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get( |
Manman Ren | edc6037 | 2014-07-23 23:13:23 +0000 | [diff] [blame] | 4211 | MinCaseVal->getType(), TableSize)); |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4212 | RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4213 | } |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4214 | |
| 4215 | // Populate the BB that does the lookups. |
| 4216 | Builder.SetInsertPoint(LookupBB); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4217 | |
| 4218 | if (NeedMask) { |
| 4219 | // Before doing the lookup we do the hole check. |
| 4220 | // The LookupBB is therefore re-purposed to do the hole check |
| 4221 | // and we create a new LookupBB. |
| 4222 | BasicBlock *MaskBB = LookupBB; |
| 4223 | MaskBB->setName("switch.hole_check"); |
| 4224 | LookupBB = BasicBlock::Create(Mod.getContext(), |
| 4225 | "switch.lookup", |
| 4226 | CommonDest->getParent(), |
| 4227 | CommonDest); |
| 4228 | |
Juergen Ributzka | c9591e9 | 2014-11-17 19:39:56 +0000 | [diff] [blame] | 4229 | // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid |
| 4230 | // unnecessary illegal types. |
| 4231 | uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); |
| 4232 | APInt MaskInt(TableSizePowOf2, 0); |
| 4233 | APInt One(TableSizePowOf2, 1); |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4234 | // Build bitmask; fill in a 1 bit for every case. |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4235 | const ResultListTy &ResultList = ResultLists[PHIs[0]]; |
| 4236 | for (size_t I = 0, E = ResultList.size(); I != E; ++I) { |
| 4237 | uint64_t Idx = (ResultList[I].first->getValue() - |
| 4238 | MinCaseVal->getValue()).getLimitedValue(); |
| 4239 | MaskInt |= One << Idx; |
| 4240 | } |
| 4241 | ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); |
| 4242 | |
| 4243 | // Get the TableIndex'th bit of the bitmask. |
| 4244 | // If this bit is 0 (meaning hole) jump to the default destination, |
| 4245 | // else continue with table lookup. |
| 4246 | IntegerType *MapTy = TableMask->getType(); |
| 4247 | Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy, |
| 4248 | "switch.maskindex"); |
| 4249 | Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, |
| 4250 | "switch.shifted"); |
| 4251 | Value *LoBit = Builder.CreateTrunc(Shifted, |
| 4252 | Type::getInt1Ty(Mod.getContext()), |
| 4253 | "switch.lobit"); |
| 4254 | Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); |
| 4255 | |
| 4256 | Builder.SetInsertPoint(LookupBB); |
| 4257 | AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); |
| 4258 | } |
| 4259 | |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4260 | bool ReturnedEarly = false; |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4261 | for (size_t I = 0, E = PHIs.size(); I != E; ++I) { |
| 4262 | PHINode *PHI = PHIs[I]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4263 | const ResultListTy &ResultList = ResultLists[PHI]; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4264 | |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4265 | // If using a bitmask, use any value to fill the lookup table holes. |
| 4266 | Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4267 | SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL); |
Hans Wennborg | 776d712 | 2012-09-26 09:34:53 +0000 | [diff] [blame] | 4268 | |
Manman Ren | 4d189fb | 2014-07-24 21:13:20 +0000 | [diff] [blame] | 4269 | Value *Result = Table.BuildLookup(TableIndex, Builder); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4270 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4271 | // If the result is used to return immediately from the function, we want to |
| 4272 | // do that right here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4273 | if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && |
| 4274 | PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4275 | Builder.CreateRet(Result); |
| 4276 | ReturnedEarly = true; |
| 4277 | break; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4278 | } |
| 4279 | |
Erik Eckstein | 0d86c76 | 2014-11-27 15:13:14 +0000 | [diff] [blame] | 4280 | // Do a small peephole optimization: re-use the switch table compare if |
| 4281 | // possible. |
| 4282 | if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { |
| 4283 | BasicBlock *PhiBlock = PHI->getParent(); |
| 4284 | // Search for compare instructions which use the phi. |
| 4285 | for (auto *User : PHI->users()) { |
| 4286 | reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); |
| 4287 | } |
| 4288 | } |
| 4289 | |
Hans Wennborg | f744fa9 | 2012-09-19 14:24:21 +0000 | [diff] [blame] | 4290 | PHI->addIncoming(Result, LookupBB); |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4291 | } |
| 4292 | |
| 4293 | if (!ReturnedEarly) |
| 4294 | Builder.CreateBr(CommonDest); |
| 4295 | |
| 4296 | // Remove the switch. |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4297 | for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4298 | BasicBlock *Succ = SI->getSuccessor(i); |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4299 | |
Michael Gottesman | 63c63ac | 2013-10-21 05:20:11 +0000 | [diff] [blame] | 4300 | if (Succ == SI->getDefaultDest()) |
Michael Gottesman | c024f32 | 2013-10-20 07:04:37 +0000 | [diff] [blame] | 4301 | continue; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4302 | Succ->removePredecessor(SI->getParent()); |
| 4303 | } |
| 4304 | SI->eraseFromParent(); |
| 4305 | |
| 4306 | ++NumLookupTables; |
Hans Wennborg | b73c0b0 | 2014-03-12 18:35:40 +0000 | [diff] [blame] | 4307 | if (NeedMask) |
| 4308 | ++NumLookupTablesHoles; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4309 | return true; |
| 4310 | } |
| 4311 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4312 | bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4313 | BasicBlock *BB = SI->getParent(); |
| 4314 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4315 | if (isValueEqualityComparison(SI)) { |
| 4316 | // If we only have one predecessor, and if it is a branch on this value, |
| 4317 | // see if that predecessor totally determines the outcome of this switch. |
| 4318 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
| 4319 | if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4320 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4321 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4322 | Value *Cond = SI->getCondition(); |
| 4323 | if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) |
| 4324 | if (SimplifySwitchOnSelect(SI, Select)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4325 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Frits van Bommel | 8ae0799 | 2011-02-28 09:44:07 +0000 | [diff] [blame] | 4326 | |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4327 | // If the block only contains the switch, see if we can fold the block |
| 4328 | // away into any preds. |
| 4329 | BasicBlock::iterator BBI = BB->begin(); |
| 4330 | // Ignore dbg intrinsics. |
| 4331 | while (isa<DbgInfoIntrinsic>(BBI)) |
| 4332 | ++BBI; |
| 4333 | if (SI == &*BBI) |
| 4334 | if (FoldValueComparisonIntoPredecessors(SI, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4335 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Jakob Stoklund Olesen | 977f41a | 2012-10-25 18:51:15 +0000 | [diff] [blame] | 4336 | } |
Benjamin Kramer | f4ea1d5 | 2011-02-02 15:56:22 +0000 | [diff] [blame] | 4337 | |
| 4338 | // Try to transform the switch into an icmp and a branch. |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4339 | if (TurnSwitchRangeIntoICmp(SI, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4340 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4341 | |
| 4342 | // Remove unreachable cases. |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4343 | if (EliminateDeadSwitchCases(SI, DL, AC)) |
| 4344 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Benjamin Kramer | d96205c | 2011-05-14 15:57:25 +0000 | [diff] [blame] | 4345 | |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4346 | if (SwitchToSelect(SI, Builder, DL, AC)) |
| 4347 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Marcello Maggioni | 5bbe3df | 2014-10-14 01:58:26 +0000 | [diff] [blame] | 4348 | |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4349 | if (ForwardSwitchConditionToPHI(SI)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4350 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Hans Wennborg | 4ab4a8e | 2011-06-18 10:28:47 +0000 | [diff] [blame] | 4351 | |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4352 | if (SwitchToLookupTable(SI, Builder, TTI, DL)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4353 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Hans Wennborg | 8a62fc5 | 2012-09-06 09:43:28 +0000 | [diff] [blame] | 4354 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4355 | return false; |
| 4356 | } |
| 4357 | |
| 4358 | bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { |
| 4359 | BasicBlock *BB = IBI->getParent(); |
| 4360 | bool Changed = false; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4361 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4362 | // Eliminate redundant destinations. |
| 4363 | SmallPtrSet<Value *, 8> Succs; |
| 4364 | for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { |
| 4365 | BasicBlock *Dest = IBI->getDestination(i); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4366 | if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4367 | Dest->removePredecessor(BB); |
| 4368 | IBI->removeDestination(i); |
| 4369 | --i; --e; |
| 4370 | Changed = true; |
| 4371 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4372 | } |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4373 | |
| 4374 | if (IBI->getNumDestinations() == 0) { |
| 4375 | // If the indirectbr has no successors, change it to unreachable. |
| 4376 | new UnreachableInst(IBI->getContext(), IBI); |
| 4377 | EraseTerminatorInstAndDCECond(IBI); |
| 4378 | return true; |
| 4379 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4380 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4381 | if (IBI->getNumDestinations() == 1) { |
| 4382 | // If the indirectbr has one successor, change it to a direct branch. |
| 4383 | BranchInst::Create(IBI->getDestination(0), IBI); |
| 4384 | EraseTerminatorInstAndDCECond(IBI); |
| 4385 | return true; |
| 4386 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4387 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4388 | if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { |
| 4389 | if (SimplifyIndirectBrOnSelect(IBI, SI)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4390 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4391 | } |
| 4392 | return Changed; |
| 4393 | } |
| 4394 | |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 4395 | bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){ |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4396 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4397 | |
Manman Ren | 93ab649 | 2012-09-20 22:37:36 +0000 | [diff] [blame] | 4398 | if (SinkCommon && SinkThenElseCodeToEnd(BI)) |
| 4399 | return true; |
| 4400 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4401 | // If the Terminator is the only non-phi instruction, simplify the block. |
Rafael Espindola | d07cf40 | 2014-07-30 21:04:00 +0000 | [diff] [blame] | 4402 | BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4403 | if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && |
| 4404 | TryToSimplifyUncondBranchFromEmptyBlock(BB)) |
| 4405 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4406 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4407 | // If the only instruction in the block is a seteq/setne comparison |
| 4408 | // against a constant, try to simplify the block. |
| 4409 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) |
| 4410 | if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { |
| 4411 | for (++I; isa<DbgInfoIntrinsic>(I); ++I) |
| 4412 | ; |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 4413 | if (I->isTerminator() && |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 4414 | TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4415 | BonusInstThreshold, DL, AC)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4416 | return true; |
| 4417 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4418 | |
Manman Ren | d33f4ef | 2012-06-13 05:43:29 +0000 | [diff] [blame] | 4419 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4420 | // branches to us and our successor, fold the comparison into the |
| 4421 | // predecessor and use logical operations to update the incoming value |
| 4422 | // for PHI nodes in common successor. |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 4423 | if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4424 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4425 | return false; |
| 4426 | } |
| 4427 | |
| 4428 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4429 | bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4430 | BasicBlock *BB = BI->getParent(); |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4431 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4432 | // Conditional branch |
| 4433 | if (isValueEqualityComparison(BI)) { |
| 4434 | // If we only have one predecessor, and if it is a branch on this value, |
| 4435 | // see if that predecessor totally determines the outcome of this |
| 4436 | // switch. |
| 4437 | if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4438 | if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4439 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4440 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4441 | // This block must be empty, except for the setcond inst, if it exists. |
| 4442 | // Ignore dbg intrinsics. |
| 4443 | BasicBlock::iterator I = BB->begin(); |
| 4444 | // Ignore dbg intrinsics. |
| 4445 | while (isa<DbgInfoIntrinsic>(I)) |
| 4446 | ++I; |
| 4447 | if (&*I == BI) { |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4448 | if (FoldValueComparisonIntoPredecessors(BI, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4449 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4450 | } else if (&*I == cast<Instruction>(BI->getCondition())){ |
| 4451 | ++I; |
| 4452 | // Ignore dbg intrinsics. |
| 4453 | while (isa<DbgInfoIntrinsic>(I)) |
| 4454 | ++I; |
Devang Patel | 5838055 | 2011-05-18 20:53:17 +0000 | [diff] [blame] | 4455 | if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4456 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4457 | } |
| 4458 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4459 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4460 | // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4461 | if (SimplifyBranchOnICmpChain(BI, DL, Builder)) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4462 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4463 | |
Dan Gohman | 5ab9c0a | 2012-01-05 23:58:56 +0000 | [diff] [blame] | 4464 | // If this basic block is ONLY a compare and a branch, and if a predecessor |
| 4465 | // branches to us and one of our successors, fold the comparison into the |
| 4466 | // predecessor and use logical operations to pick the right destination. |
Jingyue Wu | fc02967 | 2014-09-30 22:23:38 +0000 | [diff] [blame] | 4467 | if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4468 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4469 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4470 | // We have a conditional branch to two blocks that are only reachable |
| 4471 | // from BI. We know that the condbr dominates the two blocks, so see if |
| 4472 | // there is any identical code in the "then" and "else" blocks. If so, we |
| 4473 | // can hoist it up to the branching block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4474 | if (BI->getSuccessor(0)->getSinglePredecessor()) { |
| 4475 | if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 4476 | if (HoistThenElseCodeToIf(BI, DL)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4477 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4478 | } else { |
| 4479 | // If Successor #1 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4480 | // execute Successor #0 if it branches to Successor #1. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4481 | TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); |
| 4482 | if (Succ0TI->getNumSuccessors() == 1 && |
| 4483 | Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 4484 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4485 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4486 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4487 | } else if (BI->getSuccessor(1)->getSinglePredecessor()) { |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4488 | // If Successor #0 has multiple preds, we may be able to conditionally |
Sanjay Patel | 0a2ada7 | 2014-07-06 23:10:24 +0000 | [diff] [blame] | 4489 | // execute Successor #1 if it branches to Successor #0. |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4490 | TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); |
| 4491 | if (Succ1TI->getNumSuccessors() == 1 && |
| 4492 | Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) |
Hal Finkel | a995f92 | 2014-07-10 14:41:31 +0000 | [diff] [blame] | 4493 | if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4494 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4495 | } |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4496 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4497 | // If this is a branch on a phi node in the current block, thread control |
| 4498 | // through this block if any PHI node entries are constants. |
| 4499 | if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) |
| 4500 | if (PN->getParent() == BI->getParent()) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4501 | if (FoldCondBranchOnPHI(BI, DL)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4502 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4503 | |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4504 | // Scan predecessor blocks for conditional branches. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 4505 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 4506 | if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4507 | if (PBI != BI && PBI->isConditional()) |
| 4508 | if (SimplifyCondBranchToCondBranch(PBI, BI)) |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4509 | return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true; |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4510 | |
| 4511 | return false; |
| 4512 | } |
| 4513 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4514 | /// Check if passing a value to an instruction will cause undefined behavior. |
| 4515 | static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { |
| 4516 | Constant *C = dyn_cast<Constant>(V); |
| 4517 | if (!C) |
| 4518 | return false; |
| 4519 | |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 4520 | if (I->use_empty()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4521 | return false; |
| 4522 | |
| 4523 | if (C->isNullValue()) { |
Benjamin Kramer | d12e82e | 2012-10-04 16:11:49 +0000 | [diff] [blame] | 4524 | // 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] | 4525 | User *Use = *I->user_begin(); |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4526 | |
| 4527 | // Now make sure that there are no instructions in between that can alter |
| 4528 | // control flow (eg. calls) |
| 4529 | for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i) |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4530 | if (i == I->getParent()->end() || i->mayHaveSideEffects()) |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4531 | return false; |
| 4532 | |
| 4533 | // Look through GEPs. A load from a GEP derived from NULL is still undefined |
| 4534 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) |
| 4535 | if (GEP->getPointerOperand() == I) |
| 4536 | return passingValueIsAlwaysUndefined(V, GEP); |
| 4537 | |
| 4538 | // Look through bitcasts. |
| 4539 | if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) |
| 4540 | return passingValueIsAlwaysUndefined(V, BC); |
| 4541 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4542 | // Load from null is undefined. |
| 4543 | if (LoadInst *LI = dyn_cast<LoadInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 4544 | if (!LI->isVolatile()) |
| 4545 | return LI->getPointerAddressSpace() == 0; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4546 | |
Benjamin Kramer | 0655b78 | 2011-08-26 02:25:55 +0000 | [diff] [blame] | 4547 | // Store to null is undefined. |
| 4548 | if (StoreInst *SI = dyn_cast<StoreInst>(Use)) |
Andrew Trick | a0a5ca0 | 2013-03-07 01:03:35 +0000 | [diff] [blame] | 4549 | if (!SI->isVolatile()) |
| 4550 | return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I; |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4551 | } |
| 4552 | return false; |
| 4553 | } |
| 4554 | |
| 4555 | /// If BB has an incoming value that will always trigger undefined behavior |
Nick Lewycky | e87d54c | 2011-12-26 20:37:40 +0000 | [diff] [blame] | 4556 | /// (eg. null pointer dereference), remove the branch leading here. |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4557 | static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { |
| 4558 | for (BasicBlock::iterator i = BB->begin(); |
| 4559 | PHINode *PHI = dyn_cast<PHINode>(i); ++i) |
| 4560 | for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) |
| 4561 | if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { |
| 4562 | TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); |
| 4563 | IRBuilder<> Builder(T); |
| 4564 | if (BranchInst *BI = dyn_cast<BranchInst>(T)) { |
| 4565 | BB->removePredecessor(PHI->getIncomingBlock(i)); |
| 4566 | // Turn uncoditional branches into unreachables and remove the dead |
| 4567 | // destination from conditional branches. |
| 4568 | if (BI->isUnconditional()) |
| 4569 | Builder.CreateUnreachable(); |
| 4570 | else |
| 4571 | Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) : |
| 4572 | BI->getSuccessor(0)); |
| 4573 | BI->eraseFromParent(); |
| 4574 | return true; |
| 4575 | } |
| 4576 | // TODO: SwitchInst. |
| 4577 | } |
| 4578 | |
| 4579 | return false; |
| 4580 | } |
| 4581 | |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4582 | bool SimplifyCFGOpt::run(BasicBlock *BB) { |
Chris Lattner | 3f5823f | 2003-08-24 18:36:16 +0000 | [diff] [blame] | 4583 | bool Changed = false; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4584 | |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 4585 | assert(BB && BB->getParent() && "Block not embedded in function!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4586 | assert(BB->getTerminator() && "Degenerate basic block encountered!"); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4587 | |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 4588 | // Remove basic blocks that have no predecessors (except the entry block)... |
| 4589 | // or that just have themself as a predecessor. These are unreachable. |
Chris Lattner | d7beca3 | 2010-12-14 06:17:25 +0000 | [diff] [blame] | 4590 | if ((pred_begin(BB) == pred_end(BB) && |
| 4591 | BB != &BB->getParent()->getEntryBlock()) || |
Dan Gohman | 4a63fad | 2010-08-14 00:29:42 +0000 | [diff] [blame] | 4592 | BB->getSinglePredecessor() == BB) { |
David Greene | 725c7c3 | 2010-01-05 01:26:52 +0000 | [diff] [blame] | 4593 | DEBUG(dbgs() << "Removing BB: \n" << *BB); |
Chris Lattner | 7eb270e | 2008-12-03 06:40:52 +0000 | [diff] [blame] | 4594 | DeleteDeadBlock(BB); |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4595 | return true; |
| 4596 | } |
| 4597 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4598 | // Check to see if we can constant propagate this terminator instruction |
| 4599 | // away... |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 4600 | Changed |= ConstantFoldTerminator(BB, true); |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4601 | |
Dan Gohman | 1a95106 | 2009-10-30 22:39:04 +0000 | [diff] [blame] | 4602 | // Check for and eliminate duplicate PHI nodes in this block. |
| 4603 | Changed |= EliminateDuplicatePHINodes(BB); |
| 4604 | |
Benjamin Kramer | fb212a6 | 2011-08-26 01:22:29 +0000 | [diff] [blame] | 4605 | // Check for and remove branches that will always cause undefined behavior. |
| 4606 | Changed |= removeUndefIntroducingPredecessor(BB); |
| 4607 | |
Chris Lattner | 2e3832d | 2010-12-13 05:10:48 +0000 | [diff] [blame] | 4608 | // Merge basic blocks into their predecessor if there is only one distinct |
| 4609 | // pred, and if there is only one distinct successor of the predecessor, and |
| 4610 | // if there are no PHI nodes. |
| 4611 | // |
| 4612 | if (MergeBlockIntoPredecessor(BB)) |
| 4613 | return true; |
Andrew Trick | f3cf193 | 2012-08-29 21:46:36 +0000 | [diff] [blame] | 4614 | |
Devang Patel | 15ad676 | 2011-05-18 18:01:27 +0000 | [diff] [blame] | 4615 | IRBuilder<> Builder(BB); |
| 4616 | |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 4617 | // If there is a trivial two-entry PHI node in this basic block, and we can |
| 4618 | // eliminate it, do so now. |
| 4619 | if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) |
| 4620 | if (PN->getNumIncomingValues() == 2) |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 4621 | Changed |= FoldTwoEntryPHINode(PN, DL); |
Dan Gohman | 20af5a0 | 2008-03-11 21:53:06 +0000 | [diff] [blame] | 4622 | |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4623 | Builder.SetInsertPoint(BB->getTerminator()); |
Chris Lattner | 25c3af3 | 2010-12-13 06:25:44 +0000 | [diff] [blame] | 4624 | if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4625 | if (BI->isUnconditional()) { |
Devang Patel | 767f693 | 2011-05-18 18:28:48 +0000 | [diff] [blame] | 4626 | if (SimplifyUncondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4627 | } else { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4628 | if (SimplifyCondBranch(BI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4629 | } |
| 4630 | } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { |
Devang Patel | dd14e0f | 2011-05-18 21:33:11 +0000 | [diff] [blame] | 4631 | if (SimplifyReturn(RI, Builder)) return true; |
Bill Wendling | d5d95b0 | 2012-02-06 21:16:41 +0000 | [diff] [blame] | 4632 | } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { |
| 4633 | if (SimplifyResume(RI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4634 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { |
Devang Patel | a7ec47d | 2011-05-18 20:35:38 +0000 | [diff] [blame] | 4635 | if (SimplifySwitch(SI, Builder)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4636 | } else if (UnreachableInst *UI = |
| 4637 | dyn_cast<UnreachableInst>(BB->getTerminator())) { |
| 4638 | if (SimplifyUnreachable(UI)) return true; |
Chris Lattner | 1d05761 | 2010-12-13 06:36:51 +0000 | [diff] [blame] | 4639 | } else if (IndirectBrInst *IBI = |
| 4640 | dyn_cast<IndirectBrInst>(BB->getTerminator())) { |
| 4641 | if (SimplifyIndirectBr(IBI)) return true; |
Chris Lattner | e42732e | 2004-02-16 06:35:48 +0000 | [diff] [blame] | 4642 | } |
| 4643 | |
Chris Lattner | 031340a | 2003-08-17 19:41:53 +0000 | [diff] [blame] | 4644 | return Changed; |
Chris Lattner | 466a049 | 2002-05-21 20:50:24 +0000 | [diff] [blame] | 4645 | } |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4646 | |
| 4647 | /// SimplifyCFG - This function is used to do simplification of a CFG. For |
| 4648 | /// example, it adjusts branches to branches to eliminate the extra hop, it |
| 4649 | /// eliminates unreachable basic blocks, and does other "peephole" optimization |
| 4650 | /// of the CFG. It returns true if a modification was made. |
| 4651 | /// |
Chandler Carruth | 0b4ef9c | 2013-01-07 03:53:25 +0000 | [diff] [blame] | 4652 | bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4653 | unsigned BonusInstThreshold, const DataLayout *DL, |
| 4654 | AssumptionCache *AC) { |
| 4655 | return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AC).run(BB); |
Jakob Stoklund Olesen | 916f48a | 2010-02-05 22:03:18 +0000 | [diff] [blame] | 4656 | } |