Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// |
| 2 | // |
| 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. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass munges the code in the input function to better prepare it for |
Gordon Henriksen | 829046b | 2008-05-08 17:46:35 +0000 | [diff] [blame] | 11 | // SelectionDAG-based code generation. This works around limitations in it's |
| 12 | // basic-block-at-a-time approach. It should eventually be removed. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Quentin Colombet | a349084 | 2014-02-22 00:07:45 +0000 | [diff] [blame] | 16 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 21 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 22 | #include "llvm/IR/Constants.h" |
| 23 | #include "llvm/IR/DataLayout.h" |
| 24 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 27 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/IRBuilder.h" |
| 29 | #include "llvm/IR/InlineAsm.h" |
| 30 | #include "llvm/IR/Instructions.h" |
| 31 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 32 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 33 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 34 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 35 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 36 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 37 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 38 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 39 | #include "llvm/Target/TargetLibraryInfo.h" |
| 40 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 41 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 42 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 43 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 46 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 47 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 48 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 49 | #define DEBUG_TYPE "codegenprepare" |
| 50 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 51 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 52 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 53 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 54 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 55 | "sunken Cmps"); |
| 56 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 57 | "of sunken Casts"); |
| 58 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 59 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 60 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 61 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
| 62 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 63 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 64 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 65 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 66 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 67 | static cl::opt<bool> DisableBranchOpts( |
| 68 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 69 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 70 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 71 | static cl::opt<bool> DisableSelectToBranch( |
| 72 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 73 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 74 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 75 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 76 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 77 | cl::desc("Address sinking in CGP using GEPs.")); |
| 78 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 79 | static cl::opt<bool> EnableAndCmpSinking( |
| 80 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 81 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 82 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 83 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 84 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
| 85 | typedef DenseMap<Instruction *, Type *> InstrToOrigTy; |
| 86 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 87 | class CodeGenPrepare : public FunctionPass { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 88 | /// TLI - Keep a pointer of a TargetLowering to consult for determining |
| 89 | /// transformation profitability. |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 90 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 91 | const TargetLowering *TLI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 92 | const TargetLibraryInfo *TLInfo; |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 93 | DominatorTree *DT; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 94 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 95 | /// CurInstIterator - As we scan instructions optimizing them, this is the |
| 96 | /// next instruction to optimize. Xforms that can invalidate this should |
| 97 | /// update it. |
| 98 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 99 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 100 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 101 | /// This allows us to avoid inserting duplicate code for blocks with |
| 102 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 103 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 104 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 105 | /// Keeps track of all truncates inserted for the current function. |
| 106 | SetOfInstrs InsertedTruncsSet; |
| 107 | /// Keeps track of the type of the related instruction before their |
| 108 | /// promotion for the current function. |
| 109 | InstrToOrigTy PromotedInsts; |
| 110 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 111 | /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 112 | /// be updated. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 113 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 114 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 115 | /// OptSize - True if optimizing for size. |
| 116 | bool OptSize; |
| 117 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 118 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 119 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 120 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
| 121 | : FunctionPass(ID), TM(TM), TLI(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 122 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 123 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 124 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 125 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 126 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 127 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 128 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 129 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 130 | AU.addRequired<TargetLibraryInfo>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 131 | } |
| 132 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 133 | private: |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 134 | bool EliminateFallThrough(Function &F); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 135 | bool EliminateMostlyEmptyBlocks(Function &F); |
| 136 | bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 137 | void EliminateMostlyEmptyBlock(BasicBlock *BB); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 138 | bool OptimizeBlock(BasicBlock &BB); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 139 | bool OptimizeInst(Instruction *I); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 140 | bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy); |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 141 | bool OptimizeInlineAsmInst(CallInst *CS); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 142 | bool OptimizeCallInst(CallInst *CI); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 143 | bool MoveExtToFormExtLoad(Instruction *I); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 144 | bool OptimizeExtUses(Instruction *I); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 145 | bool OptimizeSelectInst(SelectInst *SI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 146 | bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 147 | bool DupRetToEnableTailCallOpts(BasicBlock *BB); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 148 | bool PlaceDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 149 | bool sinkAndCmp(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 150 | }; |
| 151 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 152 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 153 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 154 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 155 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 156 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 157 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 158 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 159 | } |
| 160 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 161 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 162 | if (skipOptnoneFunction(F)) |
| 163 | return false; |
| 164 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 165 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 166 | // Clear per function information. |
| 167 | InsertedTruncsSet.clear(); |
| 168 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 169 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 170 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 171 | if (TM) |
| 172 | TLI = TM->getSubtargetImpl()->getTargetLowering(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 173 | TLInfo = &getAnalysis<TargetLibraryInfo>(); |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 174 | DominatorTreeWrapperPass *DTWP = |
| 175 | getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 176 | DT = DTWP ? &DTWP->getDomTree() : nullptr; |
Bill Wendling | 698e84f | 2012-12-30 10:32:01 +0000 | [diff] [blame] | 177 | OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, |
| 178 | Attribute::OptimizeForSize); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 179 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 180 | /// This optimization identifies DIV instructions that can be |
| 181 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 182 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 183 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 184 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 185 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 186 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 187 | } |
| 188 | |
| 189 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 190 | // unconditional branch. |
| 191 | EverMadeChange |= EliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 192 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 193 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 194 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 195 | // find a node corresponding to the value. |
| 196 | EverMadeChange |= PlaceDbgValues(F); |
| 197 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 198 | // If there is a mask, compare against zero, and branch that can be combined |
| 199 | // into a single target instruction, push the mask and compare into branch |
| 200 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 201 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
| 202 | if (!DisableBranchOpts) |
| 203 | EverMadeChange |= sinkAndCmp(F); |
| 204 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 205 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 206 | while (MadeChange) { |
| 207 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 208 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 209 | BasicBlock *BB = I++; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 210 | MadeChange |= OptimizeBlock(*BB); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 211 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 212 | EverMadeChange |= MadeChange; |
| 213 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 214 | |
| 215 | SunkAddrs.clear(); |
| 216 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 217 | if (!DisableBranchOpts) { |
| 218 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 219 | SmallPtrSet<BasicBlock*, 8> WorkList; |
| 220 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { |
| 221 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 222 | MadeChange |= ConstantFoldTerminator(BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 223 | if (!MadeChange) continue; |
| 224 | |
| 225 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 226 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 227 | if (pred_begin(*II) == pred_end(*II)) |
| 228 | WorkList.insert(*II); |
| 229 | } |
| 230 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 231 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 232 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 233 | while (!WorkList.empty()) { |
| 234 | BasicBlock *BB = *WorkList.begin(); |
| 235 | WorkList.erase(BB); |
| 236 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 237 | |
| 238 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 239 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 240 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 241 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 242 | if (pred_begin(*II) == pred_end(*II)) |
| 243 | WorkList.insert(*II); |
| 244 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 245 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 246 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 247 | // a single edge. |
| 248 | if (EverMadeChange || MadeChange) |
| 249 | MadeChange |= EliminateFallThrough(F); |
| 250 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 251 | if (MadeChange) |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 252 | ModifiedDT = true; |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 253 | EverMadeChange |= MadeChange; |
| 254 | } |
| 255 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 256 | if (ModifiedDT && DT) |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 257 | DT->recalculate(F); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 258 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 259 | return EverMadeChange; |
| 260 | } |
| 261 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 262 | /// EliminateFallThrough - Merge basic blocks which are connected |
| 263 | /// by a single edge, where one of the basic blocks has a single successor |
| 264 | /// pointing to the other basic block, which has a single predecessor. |
| 265 | bool CodeGenPrepare::EliminateFallThrough(Function &F) { |
| 266 | bool Changed = false; |
| 267 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 268 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 269 | BasicBlock *BB = I++; |
| 270 | // If the destination block has a single pred, then this is a trivial |
| 271 | // edge, just collapse it. |
| 272 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 273 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 274 | // Don't merge if BB's address is taken. |
| 275 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 276 | |
| 277 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 278 | if (Term && !Term->isConditional()) { |
| 279 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 280 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 281 | // Remember if SinglePred was the entry block of the function. |
| 282 | // If so, we will need to move BB back to the entry position. |
| 283 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
| 284 | MergeBasicBlockIntoOnlyPred(BB, this); |
| 285 | |
| 286 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 287 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 288 | |
| 289 | // We have erased a block. Update the iterator. |
| 290 | I = BB; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 291 | } |
| 292 | } |
| 293 | return Changed; |
| 294 | } |
| 295 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 296 | /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes, |
| 297 | /// debug info directives, and an unconditional branch. Passes before isel |
| 298 | /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for |
| 299 | /// isel. Start by eliminating these blocks so we can split them the way we |
| 300 | /// want them. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 301 | bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) { |
| 302 | bool MadeChange = false; |
| 303 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 304 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 305 | BasicBlock *BB = I++; |
| 306 | |
| 307 | // If this block doesn't end with an uncond branch, ignore it. |
| 308 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 309 | if (!BI || !BI->isUnconditional()) |
| 310 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 311 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 312 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 313 | // node, then other stuff is happening here. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 314 | BasicBlock::iterator BBI = BI; |
| 315 | if (BBI != BB->begin()) { |
| 316 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 317 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 318 | if (BBI == BB->begin()) |
| 319 | break; |
| 320 | --BBI; |
| 321 | } |
| 322 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 323 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 324 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 325 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 326 | // Do not break infinite loops. |
| 327 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 328 | if (DestBB == BB) |
| 329 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 330 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 331 | if (!CanMergeBlocks(BB, DestBB)) |
| 332 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 333 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 334 | EliminateMostlyEmptyBlock(BB); |
| 335 | MadeChange = true; |
| 336 | } |
| 337 | return MadeChange; |
| 338 | } |
| 339 | |
| 340 | /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a |
| 341 | /// single uncond branch between them, and BB contains no other non-phi |
| 342 | /// instructions. |
| 343 | bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB, |
| 344 | const BasicBlock *DestBB) const { |
| 345 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 346 | // the successor. If there are more complex condition (e.g. preheaders), |
| 347 | // don't mess around with them. |
| 348 | BasicBlock::const_iterator BBI = BB->begin(); |
| 349 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 350 | for (const User *U : PN->users()) { |
| 351 | const Instruction *UI = cast<Instruction>(U); |
| 352 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 353 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 354 | // If User is inside DestBB block and it is a PHINode then check |
| 355 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 356 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 357 | if (UI->getParent() == DestBB) { |
| 358 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 359 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 360 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 361 | if (Insn && Insn->getParent() == BB && |
| 362 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 363 | return false; |
| 364 | } |
| 365 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 366 | } |
| 367 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 368 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 369 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 370 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 371 | // can't merge the block. |
| 372 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 373 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 374 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 375 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 376 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 377 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 378 | // It is faster to get preds from a PHI than with pred_iterator. |
| 379 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 380 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 381 | } else { |
| 382 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 383 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 384 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 385 | // Walk the preds of DestBB. |
| 386 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 387 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 388 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 389 | BBI = DestBB->begin(); |
| 390 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 391 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 392 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 393 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 394 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 395 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 396 | if (V2PN->getParent() == BB) |
| 397 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 398 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 399 | // If there is a conflict, bail out. |
| 400 | if (V1 != V2) return false; |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | return true; |
| 406 | } |
| 407 | |
| 408 | |
| 409 | /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and |
| 410 | /// an unconditional branch in it. |
| 411 | void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) { |
| 412 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 413 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 414 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 415 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 416 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 417 | // If the destination block has a single pred, then this is a trivial edge, |
| 418 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 419 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 420 | if (SinglePred != DestBB) { |
| 421 | // Remember if SinglePred was the entry block of the function. If so, we |
| 422 | // will need to move BB back to the entry position. |
| 423 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 424 | MergeBasicBlockIntoOnlyPred(DestBB, this); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 425 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 426 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 427 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 428 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 429 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 430 | return; |
| 431 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 432 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 433 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 434 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 435 | // to handle the new incoming edges it is about to have. |
| 436 | PHINode *PN; |
| 437 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 438 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 439 | // Remove the incoming value for BB, and remember it. |
| 440 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 441 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 442 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 443 | // value that dominates BB. |
| 444 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 445 | if (InValPhi && InValPhi->getParent() == BB) { |
| 446 | // Add all of the input values of the input PHI as inputs of this phi. |
| 447 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 448 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 449 | InValPhi->getIncomingBlock(i)); |
| 450 | } else { |
| 451 | // Otherwise, add one instance of the dominating value for each edge that |
| 452 | // we will be adding. |
| 453 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 454 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 455 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 456 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 457 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 458 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 459 | } |
| 460 | } |
| 461 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 462 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 463 | // The PHIs are now updated, change everything that refers to BB to use |
| 464 | // DestBB and remove BB. |
| 465 | BB->replaceAllUsesWith(DestBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 466 | if (DT && !ModifiedDT) { |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 467 | BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock(); |
| 468 | BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock(); |
| 469 | BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom); |
| 470 | DT->changeImmediateDominator(DestBB, NewIDom); |
| 471 | DT->eraseNode(BB); |
| 472 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 473 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 474 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 475 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 476 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 477 | } |
| 478 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 479 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 480 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 481 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 482 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 483 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 484 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 485 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 486 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 487 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 488 | UI != E; ) { |
| 489 | Use &TheUse = UI.getUse(); |
| 490 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 491 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 492 | // Figure out which BB this cast is used in. For PHI's this is the |
| 493 | // appropriate predecessor block. |
| 494 | BasicBlock *UserBB = User->getParent(); |
| 495 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 496 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 497 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 498 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 499 | // Preincrement use iterator so we don't invalidate it. |
| 500 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 501 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 502 | // If this user is in the same block as the cast, don't change the cast. |
| 503 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 504 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 505 | // If we have already inserted a cast into this block, use it. |
| 506 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 507 | |
| 508 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 509 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 510 | InsertedCast = |
| 511 | CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 512 | InsertPt); |
| 513 | MadeChange = true; |
| 514 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 515 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 516 | // Replace a use of the cast with a use of the new cast. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 517 | TheUse = InsertedCast; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 518 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 519 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 520 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 521 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 522 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 523 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 524 | MadeChange = true; |
| 525 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 526 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 527 | return MadeChange; |
| 528 | } |
| 529 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 530 | /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop |
| 531 | /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC), |
| 532 | /// sink it into user blocks to reduce the number of virtual |
| 533 | /// registers that must be created and coalesced. |
| 534 | /// |
| 535 | /// Return true if any changes are made. |
| 536 | /// |
| 537 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){ |
| 538 | // If this is a noop copy, |
| 539 | EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType()); |
| 540 | EVT DstVT = TLI.getValueType(CI->getType()); |
| 541 | |
| 542 | // This is an fp<->int conversion? |
| 543 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 544 | return false; |
| 545 | |
| 546 | // If this is an extension, it will be a zero or sign extension, which |
| 547 | // isn't a noop. |
| 548 | if (SrcVT.bitsLT(DstVT)) return false; |
| 549 | |
| 550 | // If these values will be promoted, find out what they will be promoted |
| 551 | // to. This helps us consider truncates on PPC as noop copies when they |
| 552 | // are. |
| 553 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 554 | TargetLowering::TypePromoteInteger) |
| 555 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 556 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 557 | TargetLowering::TypePromoteInteger) |
| 558 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 559 | |
| 560 | // If, after promotion, these are the same types, this is a noop copy. |
| 561 | if (SrcVT != DstVT) |
| 562 | return false; |
| 563 | |
| 564 | return SinkCast(CI); |
| 565 | } |
| 566 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 567 | /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 568 | /// the number of virtual registers that must be created and coalesced. This is |
Chris Lattner | 2740694 | 2007-08-02 16:53:43 +0000 | [diff] [blame] | 569 | /// a clear win except on targets with multiple condition code registers |
| 570 | /// (PowerPC), where it might lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 571 | /// |
| 572 | /// Return true if any changes are made. |
Chris Lattner | 6416a6b | 2008-11-24 22:44:16 +0000 | [diff] [blame] | 573 | static bool OptimizeCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 574 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 575 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 576 | /// InsertedCmp - Only insert a cmp in each block once. |
| 577 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 578 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 579 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 580 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 581 | UI != E; ) { |
| 582 | Use &TheUse = UI.getUse(); |
| 583 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 584 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 585 | // Preincrement use iterator so we don't invalidate it. |
| 586 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 587 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 588 | // Don't bother for PHI nodes. |
| 589 | if (isa<PHINode>(User)) |
| 590 | continue; |
| 591 | |
| 592 | // Figure out which BB this cmp is used in. |
| 593 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 594 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 595 | // If this user is in the same block as the cmp, don't change the cmp. |
| 596 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 597 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 598 | // If we have already inserted a cmp into this block, use it. |
| 599 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 600 | |
| 601 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 602 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 603 | InsertedCmp = |
Dan Gohman | ad1f0a1 | 2009-08-25 23:17:54 +0000 | [diff] [blame] | 604 | CmpInst::Create(CI->getOpcode(), |
Owen Anderson | 1e5f00e | 2009-07-09 23:48:35 +0000 | [diff] [blame] | 605 | CI->getPredicate(), CI->getOperand(0), |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 606 | CI->getOperand(1), "", InsertPt); |
| 607 | MadeChange = true; |
| 608 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 609 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 610 | // Replace a use of the cmp with a use of the new cmp. |
| 611 | TheUse = InsertedCmp; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 612 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 613 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 614 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 615 | // If we removed all uses, nuke the cmp. |
| 616 | if (CI->use_empty()) |
| 617 | CI->eraseFromParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 618 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 619 | return MadeChange; |
| 620 | } |
| 621 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 622 | /// isExtractBitsCandidateUse - Check if the candidates could |
| 623 | /// be combined with shift instruction, which includes: |
| 624 | /// 1. Truncate instruction |
| 625 | /// 2. And instruction and the imm is a mask of the low bits: |
| 626 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 627 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 628 | if (!isa<TruncInst>(User)) { |
| 629 | if (User->getOpcode() != Instruction::And || |
| 630 | !isa<ConstantInt>(User->getOperand(1))) |
| 631 | return false; |
| 632 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 633 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 634 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 635 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 636 | return false; |
| 637 | } |
| 638 | return true; |
| 639 | } |
| 640 | |
| 641 | /// SinkShiftAndTruncate - sink both shift and truncate instruction |
| 642 | /// to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 643 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 644 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 645 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
| 646 | const TargetLowering &TLI) { |
| 647 | BasicBlock *UserBB = User->getParent(); |
| 648 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 649 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 650 | bool MadeChange = false; |
| 651 | |
| 652 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 653 | TruncE = TruncI->user_end(); |
| 654 | TruncUI != TruncE;) { |
| 655 | |
| 656 | Use &TruncTheUse = TruncUI.getUse(); |
| 657 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 658 | // Preincrement use iterator so we don't invalidate it. |
| 659 | |
| 660 | ++TruncUI; |
| 661 | |
| 662 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 663 | if (!ISDOpcode) |
| 664 | continue; |
| 665 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 666 | // If the use is actually a legal node, there will not be an |
| 667 | // implicit truncate. |
| 668 | // FIXME: always querying the result type is just an |
| 669 | // approximation; some nodes' legality is determined by the |
| 670 | // operand or other means. There's no good way to find out though. |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 671 | if (TLI.isOperationLegalOrCustom(ISDOpcode, |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 672 | EVT::getEVT(TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 673 | continue; |
| 674 | |
| 675 | // Don't bother for PHI nodes. |
| 676 | if (isa<PHINode>(TruncUser)) |
| 677 | continue; |
| 678 | |
| 679 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 680 | |
| 681 | if (UserBB == TruncUserBB) |
| 682 | continue; |
| 683 | |
| 684 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 685 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 686 | |
| 687 | if (!InsertedShift && !InsertedTrunc) { |
| 688 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
| 689 | // Sink the shift |
| 690 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 691 | InsertedShift = |
| 692 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 693 | else |
| 694 | InsertedShift = |
| 695 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 696 | |
| 697 | // Sink the trunc |
| 698 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 699 | TruncInsertPt++; |
| 700 | |
| 701 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
| 702 | TruncI->getType(), "", TruncInsertPt); |
| 703 | |
| 704 | MadeChange = true; |
| 705 | |
| 706 | TruncTheUse = InsertedTrunc; |
| 707 | } |
| 708 | } |
| 709 | return MadeChange; |
| 710 | } |
| 711 | |
| 712 | /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if |
| 713 | /// the uses could potentially be combined with this shift instruction and |
| 714 | /// generate BitExtract instruction. It will only be applied if the architecture |
| 715 | /// supports BitExtract instruction. Here is an example: |
| 716 | /// BB1: |
| 717 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 718 | /// BB2: |
| 719 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 720 | /// ==> |
| 721 | /// |
| 722 | /// BB2: |
| 723 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 724 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 725 | /// |
| 726 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 727 | /// instruction. |
| 728 | /// Return true if any changes are made. |
| 729 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
| 730 | const TargetLowering &TLI) { |
| 731 | BasicBlock *DefBB = ShiftI->getParent(); |
| 732 | |
| 733 | /// Only insert instructions in each block once. |
| 734 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 735 | |
| 736 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType())); |
| 737 | |
| 738 | bool MadeChange = false; |
| 739 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 740 | UI != E;) { |
| 741 | Use &TheUse = UI.getUse(); |
| 742 | Instruction *User = cast<Instruction>(*UI); |
| 743 | // Preincrement use iterator so we don't invalidate it. |
| 744 | ++UI; |
| 745 | |
| 746 | // Don't bother for PHI nodes. |
| 747 | if (isa<PHINode>(User)) |
| 748 | continue; |
| 749 | |
| 750 | if (!isExtractBitsCandidateUse(User)) |
| 751 | continue; |
| 752 | |
| 753 | BasicBlock *UserBB = User->getParent(); |
| 754 | |
| 755 | if (UserBB == DefBB) { |
| 756 | // If the shift and truncate instruction are in the same BB. The use of |
| 757 | // the truncate(TruncUse) may still introduce another truncate if not |
| 758 | // legal. In this case, we would like to sink both shift and truncate |
| 759 | // instruction to the BB of TruncUse. |
| 760 | // for example: |
| 761 | // BB1: |
| 762 | // i64 shift.result = lshr i64 opnd, imm |
| 763 | // trunc.result = trunc shift.result to i16 |
| 764 | // |
| 765 | // BB2: |
| 766 | // ----> We will have an implicit truncate here if the architecture does |
| 767 | // not have i16 compare. |
| 768 | // cmp i16 trunc.result, opnd2 |
| 769 | // |
| 770 | if (isa<TruncInst>(User) && shiftIsLegal |
| 771 | // If the type of the truncate is legal, no trucate will be |
| 772 | // introduced in other basic blocks. |
| 773 | && (!TLI.isTypeLegal(TLI.getValueType(User->getType())))) |
| 774 | MadeChange = |
| 775 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI); |
| 776 | |
| 777 | continue; |
| 778 | } |
| 779 | // If we have already inserted a shift into this block, use it. |
| 780 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 781 | |
| 782 | if (!InsertedShift) { |
| 783 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 784 | |
| 785 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 786 | InsertedShift = |
| 787 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 788 | else |
| 789 | InsertedShift = |
| 790 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 791 | |
| 792 | MadeChange = true; |
| 793 | } |
| 794 | |
| 795 | // Replace a use of the shift with a use of the new shift. |
| 796 | TheUse = InsertedShift; |
| 797 | } |
| 798 | |
| 799 | // If we removed all uses, nuke the shift. |
| 800 | if (ShiftI->use_empty()) |
| 801 | ShiftI->eraseFromParent(); |
| 802 | |
| 803 | return MadeChange; |
| 804 | } |
| 805 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 806 | namespace { |
| 807 | class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls { |
| 808 | protected: |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 809 | void replaceCall(Value *With) override { |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 810 | CI->replaceAllUsesWith(With); |
| 811 | CI->eraseFromParent(); |
| 812 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 813 | bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override { |
Gabor Greif | 6d67395 | 2010-07-16 09:38:02 +0000 | [diff] [blame] | 814 | if (ConstantInt *SizeCI = |
| 815 | dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) |
| 816 | return SizeCI->isAllOnesValue(); |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 817 | return false; |
| 818 | } |
| 819 | }; |
| 820 | } // end anonymous namespace |
| 821 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 822 | bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 823 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 824 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 825 | // Lower inline assembly if we can. |
| 826 | // If we found an inline asm expession, and if the target knows how to |
| 827 | // lower it to normal LLVM code, do so now. |
| 828 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 829 | if (TLI->ExpandInlineAsm(CI)) { |
| 830 | // Avoid invalidating the iterator. |
| 831 | CurInstIterator = BB->begin(); |
| 832 | // Avoid processing instructions out of order, which could cause |
| 833 | // reuse before a value is defined. |
| 834 | SunkAddrs.clear(); |
| 835 | return true; |
| 836 | } |
| 837 | // Sink address computing for memory operands into the block. |
| 838 | if (OptimizeInlineAsmInst(CI)) |
| 839 | return true; |
| 840 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 841 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 842 | // Lower all uses of llvm.objectsize.* |
| 843 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
| 844 | if (II && II->getIntrinsicID() == Intrinsic::objectsize) { |
Gabor Greif | 4a39b84 | 2010-06-24 00:44:01 +0000 | [diff] [blame] | 845 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 846 | Type *ReturnTy = CI->getType(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 847 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
| 848 | |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 849 | // Substituting this can cause recursive simplifications, which can |
| 850 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 851 | // happens. |
| 852 | WeakVH IterHandle(CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 853 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 854 | replaceAndRecursivelySimplify(CI, RetVal, |
| 855 | TLI ? TLI->getDataLayout() : nullptr, |
| 856 | TLInfo, ModifiedDT ? nullptr : DT); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 857 | |
| 858 | // If the iterator instruction was recursively deleted, start over at the |
| 859 | // start of the block. |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 860 | if (IterHandle != CurInstIterator) { |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 861 | CurInstIterator = BB->begin(); |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 862 | SunkAddrs.clear(); |
| 863 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 864 | return true; |
| 865 | } |
| 866 | |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 867 | if (II && TLI) { |
| 868 | SmallVector<Value*, 2> PtrOps; |
| 869 | Type *AccessTy; |
| 870 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy)) |
| 871 | while (!PtrOps.empty()) |
| 872 | if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy)) |
| 873 | return true; |
| 874 | } |
| 875 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 876 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 877 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 878 | |
Micah Villmow | cdfe20b | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 879 | // We'll need DataLayout from here on out. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 880 | const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 881 | if (!TD) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 882 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 883 | // Lower all default uses of _chk calls. This is very similar |
| 884 | // to what InstCombineCalls does, but here we are only lowering calls |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 885 | // that have the default "don't know" as the objectsize. Anything else |
| 886 | // should be left alone. |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 887 | CodeGenPrepareFortifiedLibCalls Simplifier; |
Nuno Lopes | 89702e9 | 2012-07-25 16:46:31 +0000 | [diff] [blame] | 888 | return Simplifier.fold(CI, TD, TLInfo); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 889 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 890 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 891 | /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return |
| 892 | /// instructions to the predecessor to enable tail call optimizations. The |
| 893 | /// case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 894 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 895 | /// bb0: |
| 896 | /// %tmp0 = tail call i32 @f0() |
| 897 | /// br label %return |
| 898 | /// bb1: |
| 899 | /// %tmp1 = tail call i32 @f1() |
| 900 | /// br label %return |
| 901 | /// bb2: |
| 902 | /// %tmp2 = tail call i32 @f2() |
| 903 | /// br label %return |
| 904 | /// return: |
| 905 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 906 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 907 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 908 | /// |
| 909 | /// => |
| 910 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 911 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 912 | /// bb0: |
| 913 | /// %tmp0 = tail call i32 @f0() |
| 914 | /// ret i32 %tmp0 |
| 915 | /// bb1: |
| 916 | /// %tmp1 = tail call i32 @f1() |
| 917 | /// ret i32 %tmp1 |
| 918 | /// bb2: |
| 919 | /// %tmp2 = tail call i32 @f2() |
| 920 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 921 | /// @endcode |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 922 | bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 923 | if (!TLI) |
| 924 | return false; |
| 925 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 926 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 927 | if (!RI) |
| 928 | return false; |
| 929 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 930 | PHINode *PN = nullptr; |
| 931 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 932 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 933 | if (V) { |
| 934 | BCI = dyn_cast<BitCastInst>(V); |
| 935 | if (BCI) |
| 936 | V = BCI->getOperand(0); |
| 937 | |
| 938 | PN = dyn_cast<PHINode>(V); |
| 939 | if (!PN) |
| 940 | return false; |
| 941 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 942 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 943 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 944 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 945 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 946 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 947 | // See llvm::isInTailCallPosition(). |
| 948 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 949 | AttributeSet CallerAttrs = F->getAttributes(); |
| 950 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 951 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 952 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 953 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 954 | // Make sure there are no instructions between the PHI and return, or that the |
| 955 | // return is the first instruction in the block. |
| 956 | if (PN) { |
| 957 | BasicBlock::iterator BI = BB->begin(); |
| 958 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 959 | if (&*BI == BCI) |
| 960 | // Also skip over the bitcast. |
| 961 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 962 | if (&*BI != RI) |
| 963 | return false; |
| 964 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 965 | BasicBlock::iterator BI = BB->begin(); |
| 966 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 967 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 968 | return false; |
| 969 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 970 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 971 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 972 | /// call. |
| 973 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 974 | if (PN) { |
| 975 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 976 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 977 | // Make sure the phi value is indeed produced by the tail call. |
| 978 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 979 | TLI->mayBeEmittedAsTailCall(CI)) |
| 980 | TailCalls.push_back(CI); |
| 981 | } |
| 982 | } else { |
| 983 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 984 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { |
| 985 | if (!VisitedBBs.insert(*PI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 986 | continue; |
| 987 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 988 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 989 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 990 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 991 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 992 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 993 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 994 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 995 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 996 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 997 | TailCalls.push_back(CI); |
| 998 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 999 | } |
| 1000 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1001 | bool Changed = false; |
| 1002 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1003 | CallInst *CI = TailCalls[i]; |
| 1004 | CallSite CS(CI); |
| 1005 | |
| 1006 | // Conservatively require the attributes of the call to match those of the |
| 1007 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1008 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1009 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1010 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1011 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1012 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1013 | continue; |
| 1014 | |
| 1015 | // Make sure the call instruction is followed by an unconditional branch to |
| 1016 | // the return block. |
| 1017 | BasicBlock *CallBB = CI->getParent(); |
| 1018 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1019 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1020 | continue; |
| 1021 | |
| 1022 | // Duplicate the return into CallBB. |
| 1023 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1024 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1025 | ++NumRetsDup; |
| 1026 | } |
| 1027 | |
| 1028 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1029 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1030 | BB->eraseFromParent(); |
| 1031 | |
| 1032 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1033 | } |
| 1034 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1035 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1036 | // Memory Optimization |
| 1037 | //===----------------------------------------------------------------------===// |
| 1038 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1039 | namespace { |
| 1040 | |
| 1041 | /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode |
| 1042 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1043 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1044 | Value *BaseReg; |
| 1045 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1046 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1047 | void print(raw_ostream &OS) const; |
| 1048 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1049 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1050 | bool operator==(const ExtAddrMode& O) const { |
| 1051 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 1052 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 1053 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 1054 | } |
| 1055 | }; |
| 1056 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 1057 | #ifndef NDEBUG |
| 1058 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 1059 | AM.print(OS); |
| 1060 | return OS; |
| 1061 | } |
| 1062 | #endif |
| 1063 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1064 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 1065 | bool NeedPlus = false; |
| 1066 | OS << "["; |
| 1067 | if (BaseGV) { |
| 1068 | OS << (NeedPlus ? " + " : "") |
| 1069 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1070 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1071 | NeedPlus = true; |
| 1072 | } |
| 1073 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 1074 | if (BaseOffs) { |
| 1075 | OS << (NeedPlus ? " + " : "") |
| 1076 | << BaseOffs; |
| 1077 | NeedPlus = true; |
| 1078 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1079 | |
| 1080 | if (BaseReg) { |
| 1081 | OS << (NeedPlus ? " + " : "") |
| 1082 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1083 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1084 | NeedPlus = true; |
| 1085 | } |
| 1086 | if (Scale) { |
| 1087 | OS << (NeedPlus ? " + " : "") |
| 1088 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1089 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1090 | } |
| 1091 | |
| 1092 | OS << ']'; |
| 1093 | } |
| 1094 | |
| 1095 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1096 | void ExtAddrMode::dump() const { |
| 1097 | print(dbgs()); |
| 1098 | dbgs() << '\n'; |
| 1099 | } |
| 1100 | #endif |
| 1101 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1102 | /// \brief This class provides transaction based operation on the IR. |
| 1103 | /// Every change made through this class is recorded in the internal state and |
| 1104 | /// can be undone (rollback) until commit is called. |
| 1105 | class TypePromotionTransaction { |
| 1106 | |
| 1107 | /// \brief This represents the common interface of the individual transaction. |
| 1108 | /// Each class implements the logic for doing one specific modification on |
| 1109 | /// the IR via the TypePromotionTransaction. |
| 1110 | class TypePromotionAction { |
| 1111 | protected: |
| 1112 | /// The Instruction modified. |
| 1113 | Instruction *Inst; |
| 1114 | |
| 1115 | public: |
| 1116 | /// \brief Constructor of the action. |
| 1117 | /// The constructor performs the related action on the IR. |
| 1118 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 1119 | |
| 1120 | virtual ~TypePromotionAction() {} |
| 1121 | |
| 1122 | /// \brief Undo the modification done by this action. |
| 1123 | /// When this method is called, the IR must be in the same state as it was |
| 1124 | /// before this action was applied. |
| 1125 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 1126 | /// state as it was directly after this action was applied. |
| 1127 | virtual void undo() = 0; |
| 1128 | |
| 1129 | /// \brief Advocate every change made by this action. |
| 1130 | /// When the results on the IR of the action are to be kept, it is important |
| 1131 | /// to call this function, otherwise hidden information may be kept forever. |
| 1132 | virtual void commit() { |
| 1133 | // Nothing to be done, this action is not doing anything. |
| 1134 | } |
| 1135 | }; |
| 1136 | |
| 1137 | /// \brief Utility to remember the position of an instruction. |
| 1138 | class InsertionHandler { |
| 1139 | /// Position of an instruction. |
| 1140 | /// Either an instruction: |
| 1141 | /// - Is the first in a basic block: BB is used. |
| 1142 | /// - Has a previous instructon: PrevInst is used. |
| 1143 | union { |
| 1144 | Instruction *PrevInst; |
| 1145 | BasicBlock *BB; |
| 1146 | } Point; |
| 1147 | /// Remember whether or not the instruction had a previous instruction. |
| 1148 | bool HasPrevInstruction; |
| 1149 | |
| 1150 | public: |
| 1151 | /// \brief Record the position of \p Inst. |
| 1152 | InsertionHandler(Instruction *Inst) { |
| 1153 | BasicBlock::iterator It = Inst; |
| 1154 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 1155 | if (HasPrevInstruction) |
| 1156 | Point.PrevInst = --It; |
| 1157 | else |
| 1158 | Point.BB = Inst->getParent(); |
| 1159 | } |
| 1160 | |
| 1161 | /// \brief Insert \p Inst at the recorded position. |
| 1162 | void insert(Instruction *Inst) { |
| 1163 | if (HasPrevInstruction) { |
| 1164 | if (Inst->getParent()) |
| 1165 | Inst->removeFromParent(); |
| 1166 | Inst->insertAfter(Point.PrevInst); |
| 1167 | } else { |
| 1168 | Instruction *Position = Point.BB->getFirstInsertionPt(); |
| 1169 | if (Inst->getParent()) |
| 1170 | Inst->moveBefore(Position); |
| 1171 | else |
| 1172 | Inst->insertBefore(Position); |
| 1173 | } |
| 1174 | } |
| 1175 | }; |
| 1176 | |
| 1177 | /// \brief Move an instruction before another. |
| 1178 | class InstructionMoveBefore : public TypePromotionAction { |
| 1179 | /// Original position of the instruction. |
| 1180 | InsertionHandler Position; |
| 1181 | |
| 1182 | public: |
| 1183 | /// \brief Move \p Inst before \p Before. |
| 1184 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 1185 | : TypePromotionAction(Inst), Position(Inst) { |
| 1186 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 1187 | Inst->moveBefore(Before); |
| 1188 | } |
| 1189 | |
| 1190 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1191 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1192 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 1193 | Position.insert(Inst); |
| 1194 | } |
| 1195 | }; |
| 1196 | |
| 1197 | /// \brief Set the operand of an instruction with a new value. |
| 1198 | class OperandSetter : public TypePromotionAction { |
| 1199 | /// Original operand of the instruction. |
| 1200 | Value *Origin; |
| 1201 | /// Index of the modified instruction. |
| 1202 | unsigned Idx; |
| 1203 | |
| 1204 | public: |
| 1205 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 1206 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 1207 | : TypePromotionAction(Inst), Idx(Idx) { |
| 1208 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 1209 | << "for:" << *Inst << "\n" |
| 1210 | << "with:" << *NewVal << "\n"); |
| 1211 | Origin = Inst->getOperand(Idx); |
| 1212 | Inst->setOperand(Idx, NewVal); |
| 1213 | } |
| 1214 | |
| 1215 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1216 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1217 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 1218 | << "for: " << *Inst << "\n" |
| 1219 | << "with: " << *Origin << "\n"); |
| 1220 | Inst->setOperand(Idx, Origin); |
| 1221 | } |
| 1222 | }; |
| 1223 | |
| 1224 | /// \brief Hide the operands of an instruction. |
| 1225 | /// Do as if this instruction was not using any of its operands. |
| 1226 | class OperandsHider : public TypePromotionAction { |
| 1227 | /// The list of original operands. |
| 1228 | SmallVector<Value *, 4> OriginalValues; |
| 1229 | |
| 1230 | public: |
| 1231 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 1232 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 1233 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 1234 | unsigned NumOpnds = Inst->getNumOperands(); |
| 1235 | OriginalValues.reserve(NumOpnds); |
| 1236 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 1237 | // Save the current operand. |
| 1238 | Value *Val = Inst->getOperand(It); |
| 1239 | OriginalValues.push_back(Val); |
| 1240 | // Set a dummy one. |
| 1241 | // We could use OperandSetter here, but that would implied an overhead |
| 1242 | // that we are not willing to pay. |
| 1243 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 1244 | } |
| 1245 | } |
| 1246 | |
| 1247 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1248 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1249 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 1250 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 1251 | Inst->setOperand(It, OriginalValues[It]); |
| 1252 | } |
| 1253 | }; |
| 1254 | |
| 1255 | /// \brief Build a truncate instruction. |
| 1256 | class TruncBuilder : public TypePromotionAction { |
| 1257 | public: |
| 1258 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 1259 | /// result. |
| 1260 | /// trunc Opnd to Ty. |
| 1261 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 1262 | IRBuilder<> Builder(Opnd); |
| 1263 | Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted")); |
| 1264 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n"); |
| 1265 | } |
| 1266 | |
| 1267 | /// \brief Get the built instruction. |
| 1268 | Instruction *getBuiltInstruction() { return Inst; } |
| 1269 | |
| 1270 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1271 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1272 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n"); |
| 1273 | Inst->eraseFromParent(); |
| 1274 | } |
| 1275 | }; |
| 1276 | |
| 1277 | /// \brief Build a sign extension instruction. |
| 1278 | class SExtBuilder : public TypePromotionAction { |
| 1279 | public: |
| 1280 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 1281 | /// result. |
| 1282 | /// sext Opnd to Ty. |
| 1283 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
| 1284 | : TypePromotionAction(Inst) { |
| 1285 | IRBuilder<> Builder(InsertPt); |
| 1286 | Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted")); |
| 1287 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n"); |
| 1288 | } |
| 1289 | |
| 1290 | /// \brief Get the built instruction. |
| 1291 | Instruction *getBuiltInstruction() { return Inst; } |
| 1292 | |
| 1293 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1294 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1295 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n"); |
| 1296 | Inst->eraseFromParent(); |
| 1297 | } |
| 1298 | }; |
| 1299 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1300 | /// \brief Build a zero extension instruction. |
| 1301 | class ZExtBuilder : public TypePromotionAction { |
| 1302 | public: |
| 1303 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 1304 | /// result. |
| 1305 | /// zext Opnd to Ty. |
| 1306 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
| 1307 | : TypePromotionAction(Inst) { |
| 1308 | IRBuilder<> Builder(InsertPt); |
| 1309 | Inst = cast<Instruction>(Builder.CreateZExt(Opnd, Ty, "promoted")); |
| 1310 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Inst << "\n"); |
| 1311 | } |
| 1312 | |
| 1313 | /// \brief Get the built instruction. |
| 1314 | Instruction *getBuiltInstruction() { return Inst; } |
| 1315 | |
| 1316 | /// \brief Remove the built instruction. |
| 1317 | void undo() override { |
| 1318 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Inst << "\n"); |
| 1319 | Inst->eraseFromParent(); |
| 1320 | } |
| 1321 | }; |
| 1322 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1323 | /// \brief Mutate an instruction to another type. |
| 1324 | class TypeMutator : public TypePromotionAction { |
| 1325 | /// Record the original type. |
| 1326 | Type *OrigTy; |
| 1327 | |
| 1328 | public: |
| 1329 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 1330 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 1331 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 1332 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 1333 | << "\n"); |
| 1334 | Inst->mutateType(NewTy); |
| 1335 | } |
| 1336 | |
| 1337 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1338 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1339 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 1340 | << "\n"); |
| 1341 | Inst->mutateType(OrigTy); |
| 1342 | } |
| 1343 | }; |
| 1344 | |
| 1345 | /// \brief Replace the uses of an instruction by another instruction. |
| 1346 | class UsesReplacer : public TypePromotionAction { |
| 1347 | /// Helper structure to keep track of the replaced uses. |
| 1348 | struct InstructionAndIdx { |
| 1349 | /// The instruction using the instruction. |
| 1350 | Instruction *Inst; |
| 1351 | /// The index where this instruction is used for Inst. |
| 1352 | unsigned Idx; |
| 1353 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 1354 | : Inst(Inst), Idx(Idx) {} |
| 1355 | }; |
| 1356 | |
| 1357 | /// Keep track of the original uses (pair Instruction, Index). |
| 1358 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 1359 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 1360 | |
| 1361 | public: |
| 1362 | /// \brief Replace all the use of \p Inst by \p New. |
| 1363 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 1364 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 1365 | << "\n"); |
| 1366 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1367 | for (Use &U : Inst->uses()) { |
| 1368 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1369 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1370 | } |
| 1371 | // Now, we can replace the uses. |
| 1372 | Inst->replaceAllUsesWith(New); |
| 1373 | } |
| 1374 | |
| 1375 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1376 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1377 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 1378 | for (use_iterator UseIt = OriginalUses.begin(), |
| 1379 | EndIt = OriginalUses.end(); |
| 1380 | UseIt != EndIt; ++UseIt) { |
| 1381 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 1382 | } |
| 1383 | } |
| 1384 | }; |
| 1385 | |
| 1386 | /// \brief Remove an instruction from the IR. |
| 1387 | class InstructionRemover : public TypePromotionAction { |
| 1388 | /// Original position of the instruction. |
| 1389 | InsertionHandler Inserter; |
| 1390 | /// Helper structure to hide all the link to the instruction. In other |
| 1391 | /// words, this helps to do as if the instruction was removed. |
| 1392 | OperandsHider Hider; |
| 1393 | /// Keep track of the uses replaced, if any. |
| 1394 | UsesReplacer *Replacer; |
| 1395 | |
| 1396 | public: |
| 1397 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 1398 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1399 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 1400 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1401 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1402 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1403 | if (New) |
| 1404 | Replacer = new UsesReplacer(Inst, New); |
| 1405 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 1406 | Inst->removeFromParent(); |
| 1407 | } |
| 1408 | |
| 1409 | ~InstructionRemover() { delete Replacer; } |
| 1410 | |
| 1411 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1412 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1413 | |
| 1414 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 1415 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1416 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1417 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 1418 | Inserter.insert(Inst); |
| 1419 | if (Replacer) |
| 1420 | Replacer->undo(); |
| 1421 | Hider.undo(); |
| 1422 | } |
| 1423 | }; |
| 1424 | |
| 1425 | public: |
| 1426 | /// Restoration point. |
| 1427 | /// The restoration point is a pointer to an action instead of an iterator |
| 1428 | /// because the iterator may be invalidated but not the pointer. |
| 1429 | typedef const TypePromotionAction *ConstRestorationPt; |
| 1430 | /// Advocate every changes made in that transaction. |
| 1431 | void commit(); |
| 1432 | /// Undo all the changes made after the given point. |
| 1433 | void rollback(ConstRestorationPt Point); |
| 1434 | /// Get the current restoration point. |
| 1435 | ConstRestorationPt getRestorationPoint() const; |
| 1436 | |
| 1437 | /// \name API for IR modification with state keeping to support rollback. |
| 1438 | /// @{ |
| 1439 | /// Same as Instruction::setOperand. |
| 1440 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 1441 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1442 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1443 | /// Same as Value::replaceAllUsesWith. |
| 1444 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 1445 | /// Same as Value::mutateType. |
| 1446 | void mutateType(Instruction *Inst, Type *NewTy); |
| 1447 | /// Same as IRBuilder::createTrunc. |
| 1448 | Instruction *createTrunc(Instruction *Opnd, Type *Ty); |
| 1449 | /// Same as IRBuilder::createSExt. |
| 1450 | Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1451 | /// Same as IRBuilder::createZExt. |
| 1452 | Instruction *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1453 | /// Same as Instruction::moveBefore. |
| 1454 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 1455 | /// @} |
| 1456 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1457 | private: |
| 1458 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1459 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 1460 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1461 | }; |
| 1462 | |
| 1463 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 1464 | Value *NewVal) { |
| 1465 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1466 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1467 | } |
| 1468 | |
| 1469 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 1470 | Value *NewVal) { |
| 1471 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1472 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1473 | } |
| 1474 | |
| 1475 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 1476 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1477 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1478 | } |
| 1479 | |
| 1480 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1481 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1482 | } |
| 1483 | |
| 1484 | Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 1485 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1486 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
| 1487 | Instruction *I = Ptr->getBuiltInstruction(); |
| 1488 | Actions.push_back(std::move(Ptr)); |
| 1489 | return I; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1490 | } |
| 1491 | |
| 1492 | Instruction *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 1493 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1494 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
| 1495 | Instruction *I = Ptr->getBuiltInstruction(); |
| 1496 | Actions.push_back(std::move(Ptr)); |
| 1497 | return I; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1498 | } |
| 1499 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1500 | Instruction *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 1501 | Value *Opnd, Type *Ty) { |
| 1502 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
| 1503 | Instruction *I = Ptr->getBuiltInstruction(); |
| 1504 | Actions.push_back(std::move(Ptr)); |
| 1505 | return I; |
| 1506 | } |
| 1507 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1508 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 1509 | Instruction *Before) { |
| 1510 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1511 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1512 | } |
| 1513 | |
| 1514 | TypePromotionTransaction::ConstRestorationPt |
| 1515 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1516 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1517 | } |
| 1518 | |
| 1519 | void TypePromotionTransaction::commit() { |
| 1520 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1521 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1522 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1523 | Actions.clear(); |
| 1524 | } |
| 1525 | |
| 1526 | void TypePromotionTransaction::rollback( |
| 1527 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1528 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 1529 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1530 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1531 | } |
| 1532 | } |
| 1533 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1534 | /// \brief A helper class for matching addressing modes. |
| 1535 | /// |
| 1536 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 1537 | class AddressingModeMatcher { |
| 1538 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 1539 | const TargetLowering &TLI; |
| 1540 | |
| 1541 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 1542 | /// the memory instruction that we're computing this address for. |
| 1543 | Type *AccessTy; |
| 1544 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1545 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1546 | /// AddrMode - This is the addressing mode that we're building up. This is |
| 1547 | /// part of the return value of this addressing mode matching stuff. |
| 1548 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1549 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1550 | /// The truncate instruction inserted by other CodeGenPrepare optimizations. |
| 1551 | const SetOfInstrs &InsertedTruncs; |
| 1552 | /// A map from the instructions to their type before promotion. |
| 1553 | InstrToOrigTy &PromotedInsts; |
| 1554 | /// The ongoing transaction where every action should be registered. |
| 1555 | TypePromotionTransaction &TPT; |
| 1556 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1557 | /// IgnoreProfitability - This is set to true when we should not do |
| 1558 | /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode |
| 1559 | /// always returns true. |
| 1560 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1561 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1562 | AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI, |
| 1563 | const TargetLowering &T, Type *AT, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1564 | Instruction *MI, ExtAddrMode &AM, |
| 1565 | const SetOfInstrs &InsertedTruncs, |
| 1566 | InstrToOrigTy &PromotedInsts, |
| 1567 | TypePromotionTransaction &TPT) |
| 1568 | : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM), |
| 1569 | InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1570 | IgnoreProfitability = false; |
| 1571 | } |
| 1572 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1573 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1574 | /// Match - Find the maximal addressing mode that a load/store of V can fold, |
| 1575 | /// give an access type of AccessTy. This returns a list of involved |
| 1576 | /// instructions in AddrModeInsts. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1577 | /// \p InsertedTruncs The truncate instruction inserted by other |
| 1578 | /// CodeGenPrepare |
| 1579 | /// optimizations. |
| 1580 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1581 | /// \p The ongoing transaction where every action should be registered. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1582 | static ExtAddrMode Match(Value *V, Type *AccessTy, |
| 1583 | Instruction *MemoryInst, |
| 1584 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1585 | const TargetLowering &TLI, |
| 1586 | const SetOfInstrs &InsertedTruncs, |
| 1587 | InstrToOrigTy &PromotedInsts, |
| 1588 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1589 | ExtAddrMode Result; |
| 1590 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1591 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy, |
| 1592 | MemoryInst, Result, InsertedTruncs, |
| 1593 | PromotedInsts, TPT).MatchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1594 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 1595 | return Result; |
| 1596 | } |
| 1597 | private: |
| 1598 | bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 1599 | bool MatchAddr(Value *V, unsigned Depth); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1600 | bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1601 | bool *MovedAway = nullptr); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1602 | bool IsProfitableToFoldIntoAddressingMode(Instruction *I, |
| 1603 | ExtAddrMode &AMBefore, |
| 1604 | ExtAddrMode &AMAfter); |
| 1605 | bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1606 | bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion, |
| 1607 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1608 | }; |
| 1609 | |
| 1610 | /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode. |
| 1611 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 1612 | /// false if not. |
| 1613 | bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale, |
| 1614 | unsigned Depth) { |
| 1615 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 1616 | // mode. Just process that directly. |
| 1617 | if (Scale == 1) |
| 1618 | return MatchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1619 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1620 | // If the scale is 0, it takes nothing to add this. |
| 1621 | if (Scale == 0) |
| 1622 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1623 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1624 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 1625 | // need an available scale field. |
| 1626 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 1627 | return false; |
| 1628 | |
| 1629 | ExtAddrMode TestAddrMode = AddrMode; |
| 1630 | |
| 1631 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 1632 | // [A+B + A*7] -> [B+A*8]. |
| 1633 | TestAddrMode.Scale += Scale; |
| 1634 | TestAddrMode.ScaledReg = ScaleReg; |
| 1635 | |
| 1636 | // If the new address isn't legal, bail out. |
| 1637 | if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) |
| 1638 | return false; |
| 1639 | |
| 1640 | // It was legal, so commit it. |
| 1641 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1642 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1643 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 1644 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 1645 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1646 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1647 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 1648 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 1649 | TestAddrMode.ScaledReg = AddLHS; |
| 1650 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1651 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1652 | // If this addressing mode is legal, commit it and remember that we folded |
| 1653 | // this instruction. |
| 1654 | if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) { |
| 1655 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 1656 | AddrMode = TestAddrMode; |
| 1657 | return true; |
| 1658 | } |
| 1659 | } |
| 1660 | |
| 1661 | // Otherwise, not (x+c)*scale, just return what we have. |
| 1662 | return true; |
| 1663 | } |
| 1664 | |
| 1665 | /// MightBeFoldableInst - This is a little filter, which returns true if an |
| 1666 | /// addressing computation involving I might be folded into a load/store |
| 1667 | /// accessing it. This doesn't need to be perfect, but needs to accept at least |
| 1668 | /// the set of instructions that MatchOperationAddr can. |
| 1669 | static bool MightBeFoldableInst(Instruction *I) { |
| 1670 | switch (I->getOpcode()) { |
| 1671 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 1672 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1673 | // Don't touch identity bitcasts. |
| 1674 | if (I->getType() == I->getOperand(0)->getType()) |
| 1675 | return false; |
| 1676 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 1677 | case Instruction::PtrToInt: |
| 1678 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 1679 | return true; |
| 1680 | case Instruction::IntToPtr: |
| 1681 | // We know the input is intptr_t, so this is foldable. |
| 1682 | return true; |
| 1683 | case Instruction::Add: |
| 1684 | return true; |
| 1685 | case Instruction::Mul: |
| 1686 | case Instruction::Shl: |
| 1687 | // Can only handle X*C and X << C. |
| 1688 | return isa<ConstantInt>(I->getOperand(1)); |
| 1689 | case Instruction::GetElementPtr: |
| 1690 | return true; |
| 1691 | default: |
| 1692 | return false; |
| 1693 | } |
| 1694 | } |
| 1695 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1696 | /// \brief Hepler class to perform type promotion. |
| 1697 | class TypePromotionHelper { |
| 1698 | /// \brief Utility function to check whether or not a sign extension of |
| 1699 | /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either |
| 1700 | /// using the operands of \p Inst or promoting \p Inst. |
| 1701 | /// In other words, check if: |
| 1702 | /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType. |
| 1703 | /// #1 Promotion applies: |
| 1704 | /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...). |
| 1705 | /// #2 Operand reuses: |
| 1706 | /// sext opnd1 to ConsideredSExtType. |
| 1707 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1708 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType, |
| 1709 | const InstrToOrigTy &PromotedInsts); |
| 1710 | |
| 1711 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 1712 | /// promoting \p Inst. |
| 1713 | static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) { |
| 1714 | if (isa<SelectInst>(Inst) && OpIdx == 0) |
| 1715 | return false; |
| 1716 | return true; |
| 1717 | } |
| 1718 | |
| 1719 | /// \brief Utility function to promote the operand of \p SExt when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1720 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1721 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1722 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
| 1723 | /// created to promote the operand of SExt. |
| 1724 | /// Should never be called directly. |
| 1725 | /// \return The promoted value which is used instead of SExt. |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1726 | static Value *promoteOperandForTruncAndAnyExt(Instruction *SExt, |
| 1727 | TypePromotionTransaction &TPT, |
| 1728 | InstrToOrigTy &PromotedInsts, |
| 1729 | unsigned &CreatedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1730 | |
| 1731 | /// \brief Utility function to promote the operand of \p SExt when this |
| 1732 | /// operand is promotable and is not a supported trunc or sext. |
| 1733 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1734 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
| 1735 | /// created to promote the operand of SExt. |
| 1736 | /// Should never be called directly. |
| 1737 | /// \return The promoted value which is used instead of SExt. |
| 1738 | static Value *promoteOperandForOther(Instruction *SExt, |
| 1739 | TypePromotionTransaction &TPT, |
| 1740 | InstrToOrigTy &PromotedInsts, |
| 1741 | unsigned &CreatedInsts); |
| 1742 | |
| 1743 | public: |
| 1744 | /// Type for the utility function that promotes the operand of SExt. |
| 1745 | typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT, |
| 1746 | InstrToOrigTy &PromotedInsts, |
| 1747 | unsigned &CreatedInsts); |
| 1748 | /// \brief Given a sign extend instruction \p SExt, return the approriate |
| 1749 | /// action to promote the operand of \p SExt instead of using SExt. |
| 1750 | /// \return NULL if no promotable action is possible with the current |
| 1751 | /// sign extension. |
| 1752 | /// \p InsertedTruncs keeps track of all the truncate instructions inserted by |
| 1753 | /// the others CodeGenPrepare optimizations. This information is important |
| 1754 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 1755 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 1756 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1757 | static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs, |
| 1758 | const TargetLowering &TLI, |
| 1759 | const InstrToOrigTy &PromotedInsts); |
| 1760 | }; |
| 1761 | |
| 1762 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
| 1763 | Type *ConsideredSExtType, |
| 1764 | const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1765 | // We can always get through sext or zext. |
| 1766 | if (isa<SExtInst>(Inst) || isa<ZExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1767 | return true; |
| 1768 | |
| 1769 | // We can get through binary operator, if it is legal. In other words, the |
| 1770 | // binary operator must have a nuw or nsw flag. |
| 1771 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 1772 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
| 1773 | (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap())) |
| 1774 | return true; |
| 1775 | |
| 1776 | // Check if we can do the following simplification. |
| 1777 | // sext(trunc(sext)) --> sext |
| 1778 | if (!isa<TruncInst>(Inst)) |
| 1779 | return false; |
| 1780 | |
| 1781 | Value *OpndVal = Inst->getOperand(0); |
| 1782 | // Check if we can use this operand in the sext. |
| 1783 | // If the type is larger than the result type of the sign extension, |
| 1784 | // we cannot. |
| 1785 | if (OpndVal->getType()->getIntegerBitWidth() > |
| 1786 | ConsideredSExtType->getIntegerBitWidth()) |
| 1787 | return false; |
| 1788 | |
| 1789 | // If the operand of the truncate is not an instruction, we will not have |
| 1790 | // any information on the dropped bits. |
| 1791 | // (Actually we could for constant but it is not worth the extra logic). |
| 1792 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 1793 | if (!Opnd) |
| 1794 | return false; |
| 1795 | |
| 1796 | // Check if the source of the type is narrow enough. |
| 1797 | // I.e., check that trunc just drops sign extended bits. |
| 1798 | // #1 get the type of the operand. |
| 1799 | const Type *OpndType; |
| 1800 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
| 1801 | if (It != PromotedInsts.end()) |
| 1802 | OpndType = It->second; |
| 1803 | else if (isa<SExtInst>(Opnd)) |
| 1804 | OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType(); |
| 1805 | else |
| 1806 | return false; |
| 1807 | |
| 1808 | // #2 check that the truncate just drop sign extended bits. |
| 1809 | if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth()) |
| 1810 | return true; |
| 1811 | |
| 1812 | return false; |
| 1813 | } |
| 1814 | |
| 1815 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
| 1816 | Instruction *SExt, const SetOfInstrs &InsertedTruncs, |
| 1817 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
| 1818 | Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0)); |
| 1819 | Type *SExtTy = SExt->getType(); |
| 1820 | // If the operand of the sign extension is not an instruction, we cannot |
| 1821 | // get through. |
| 1822 | // If it, check we can get through. |
| 1823 | if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1824 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1825 | |
| 1826 | // Do not promote if the operand has been added by codegenprepare. |
| 1827 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 1828 | // redone, thus causing potential infinite loop. |
| 1829 | if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1830 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1831 | |
| 1832 | // SExt or Trunc instructions. |
| 1833 | // Return the related handler. |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1834 | if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd) || |
| 1835 | isa<ZExtInst>(SExtOpnd)) |
| 1836 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1837 | |
| 1838 | // Regular instruction. |
| 1839 | // Abort early if we will have to insert non-free instructions. |
| 1840 | if (!SExtOpnd->hasOneUse() && |
| 1841 | !TLI.isTruncateFree(SExtTy, SExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1842 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1843 | return promoteOperandForOther; |
| 1844 | } |
| 1845 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1846 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1847 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
| 1848 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) { |
| 1849 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 1850 | // get through it and this method should not be called. |
| 1851 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame^] | 1852 | if (isa<ZExtInst>(SExtOpnd)) { |
| 1853 | // Replace sext(zext(opnd)) |
| 1854 | // => zext(opnd). |
| 1855 | Instruction *ZExt = |
| 1856 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 1857 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 1858 | TPT.eraseInstruction(SExt); |
| 1859 | } else { |
| 1860 | // Replace sext(trunc(opnd)) or sext(sext(opnd)) |
| 1861 | // => sext(opnd). |
| 1862 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 1863 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1864 | CreatedInsts = 0; |
| 1865 | |
| 1866 | // Remove dead code. |
| 1867 | if (SExtOpnd->use_empty()) |
| 1868 | TPT.eraseInstruction(SExtOpnd); |
| 1869 | |
| 1870 | // Check if the sext is still needed. |
| 1871 | if (SExt->getType() != SExt->getOperand(0)->getType()) |
| 1872 | return SExt; |
| 1873 | |
| 1874 | // At this point we have: sext ty opnd to ty. |
| 1875 | // Reassign the uses of SExt to the opnd and remove SExt. |
| 1876 | Value *NextVal = SExt->getOperand(0); |
| 1877 | TPT.eraseInstruction(SExt, NextVal); |
| 1878 | return NextVal; |
| 1879 | } |
| 1880 | |
| 1881 | Value * |
| 1882 | TypePromotionHelper::promoteOperandForOther(Instruction *SExt, |
| 1883 | TypePromotionTransaction &TPT, |
| 1884 | InstrToOrigTy &PromotedInsts, |
| 1885 | unsigned &CreatedInsts) { |
| 1886 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 1887 | // get through it and this method should not be called. |
| 1888 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
| 1889 | CreatedInsts = 0; |
| 1890 | if (!SExtOpnd->hasOneUse()) { |
| 1891 | // SExtOpnd will be promoted. |
| 1892 | // All its uses, but SExt, will need to use a truncated value of the |
| 1893 | // promoted version. |
| 1894 | // Create the truncate now. |
| 1895 | Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType()); |
| 1896 | Trunc->removeFromParent(); |
| 1897 | // Insert it just after the definition. |
| 1898 | Trunc->insertAfter(SExtOpnd); |
| 1899 | |
| 1900 | TPT.replaceAllUsesWith(SExtOpnd, Trunc); |
| 1901 | // Restore the operand of SExt (which has been replace by the previous call |
| 1902 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
| 1903 | TPT.setOperand(SExt, 0, SExtOpnd); |
| 1904 | } |
| 1905 | |
| 1906 | // Get through the Instruction: |
| 1907 | // 1. Update its type. |
| 1908 | // 2. Replace the uses of SExt by Inst. |
| 1909 | // 3. Sign extend each operand that needs to be sign extended. |
| 1910 | |
| 1911 | // Remember the original type of the instruction before promotion. |
| 1912 | // This is useful to know that the high bits are sign extended bits. |
| 1913 | PromotedInsts.insert( |
| 1914 | std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType())); |
| 1915 | // Step #1. |
| 1916 | TPT.mutateType(SExtOpnd, SExt->getType()); |
| 1917 | // Step #2. |
| 1918 | TPT.replaceAllUsesWith(SExt, SExtOpnd); |
| 1919 | // Step #3. |
| 1920 | Instruction *SExtForOpnd = SExt; |
| 1921 | |
| 1922 | DEBUG(dbgs() << "Propagate SExt to operands\n"); |
| 1923 | for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
| 1924 | ++OpIdx) { |
| 1925 | DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n'); |
| 1926 | if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() || |
| 1927 | !shouldSExtOperand(SExtOpnd, OpIdx)) { |
| 1928 | DEBUG(dbgs() << "No need to propagate\n"); |
| 1929 | continue; |
| 1930 | } |
| 1931 | // Check if we can statically sign extend the operand. |
| 1932 | Value *Opnd = SExtOpnd->getOperand(OpIdx); |
| 1933 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
| 1934 | DEBUG(dbgs() << "Statically sign extend\n"); |
| 1935 | TPT.setOperand( |
| 1936 | SExtOpnd, OpIdx, |
| 1937 | ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue())); |
| 1938 | continue; |
| 1939 | } |
| 1940 | // UndefValue are typed, so we have to statically sign extend them. |
| 1941 | if (isa<UndefValue>(Opnd)) { |
| 1942 | DEBUG(dbgs() << "Statically sign extend\n"); |
| 1943 | TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType())); |
| 1944 | continue; |
| 1945 | } |
| 1946 | |
| 1947 | // Otherwise we have to explicity sign extend the operand. |
| 1948 | // Check if SExt was reused to sign extend an operand. |
| 1949 | if (!SExtForOpnd) { |
| 1950 | // If yes, create a new one. |
| 1951 | DEBUG(dbgs() << "More operands to sext\n"); |
| 1952 | SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType()); |
| 1953 | ++CreatedInsts; |
| 1954 | } |
| 1955 | |
| 1956 | TPT.setOperand(SExtForOpnd, 0, Opnd); |
| 1957 | |
| 1958 | // Move the sign extension before the insertion point. |
| 1959 | TPT.moveBefore(SExtForOpnd, SExtOpnd); |
| 1960 | TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd); |
| 1961 | // If more sext are required, new instructions will have to be created. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1962 | SExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1963 | } |
| 1964 | if (SExtForOpnd == SExt) { |
| 1965 | DEBUG(dbgs() << "Sign extension is useless now\n"); |
| 1966 | TPT.eraseInstruction(SExt); |
| 1967 | } |
| 1968 | return SExtOpnd; |
| 1969 | } |
| 1970 | |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1971 | /// IsPromotionProfitable - Check whether or not promoting an instruction |
| 1972 | /// to a wider type was profitable. |
| 1973 | /// \p MatchedSize gives the number of instructions that have been matched |
| 1974 | /// in the addressing mode after the promotion was applied. |
| 1975 | /// \p SizeWithPromotion gives the number of created instructions for |
| 1976 | /// the promotion plus the number of instructions that have been |
| 1977 | /// matched in the addressing mode before the promotion. |
| 1978 | /// \p PromotedOperand is the value that has been promoted. |
| 1979 | /// \return True if the promotion is profitable, false otherwise. |
| 1980 | bool |
| 1981 | AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize, |
| 1982 | unsigned SizeWithPromotion, |
| 1983 | Value *PromotedOperand) const { |
| 1984 | // We folded less instructions than what we created to promote the operand. |
| 1985 | // This is not profitable. |
| 1986 | if (MatchedSize < SizeWithPromotion) |
| 1987 | return false; |
| 1988 | if (MatchedSize > SizeWithPromotion) |
| 1989 | return true; |
| 1990 | // The promotion is neutral but it may help folding the sign extension in |
| 1991 | // loads for instance. |
| 1992 | // Check that we did not create an illegal instruction. |
| 1993 | Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand); |
| 1994 | if (!PromotedInst) |
| 1995 | return false; |
Quentin Colombet | 1627a41 | 2014-02-22 01:06:41 +0000 | [diff] [blame] | 1996 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 1997 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 1998 | if (!ISDOpcode) |
| 1999 | return true; |
| 2000 | // Otherwise, check if the promoted instruction is legal or not. |
| 2001 | return TLI.isOperationLegalOrCustom(ISDOpcode, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2002 | EVT::getEVT(PromotedInst->getType())); |
| 2003 | } |
| 2004 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2005 | /// MatchOperationAddr - Given an instruction or constant expr, see if we can |
| 2006 | /// fold the operation into the addressing mode. If so, update the addressing |
| 2007 | /// mode and return true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2008 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 2009 | /// not AddrInst has to be folded into the addressing mode on success. |
| 2010 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 2011 | /// because it has been moved away. |
| 2012 | /// Thus AddrInst must not be added in the matched instructions. |
| 2013 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 2014 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 2015 | /// not be referenced anymore. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2016 | bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2017 | unsigned Depth, |
| 2018 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2019 | // Avoid exponential behavior on extremely deep expression trees. |
| 2020 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2021 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2022 | // By default, all matched instructions stay in place. |
| 2023 | if (MovedAway) |
| 2024 | *MovedAway = false; |
| 2025 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2026 | switch (Opcode) { |
| 2027 | case Instruction::PtrToInt: |
| 2028 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2029 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2030 | case Instruction::IntToPtr: |
| 2031 | // This inttoptr is a no-op if the integer type is pointer sized. |
| 2032 | if (TLI.getValueType(AddrInst->getOperand(0)->getType()) == |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2033 | TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace())) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2034 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2035 | return false; |
| 2036 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2037 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2038 | // BitCast is always a noop, and we can handle it as long as it is |
| 2039 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 2040 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 2041 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 2042 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 2043 | // and we don't want to mess around with them. Assume it knows what it |
| 2044 | // is doing. |
| 2045 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
| 2046 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2047 | return false; |
| 2048 | case Instruction::Add: { |
| 2049 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 2050 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2051 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2052 | // Start a transaction at this point. |
| 2053 | // The LHS may match but not the RHS. |
| 2054 | // Therefore, we need a higher level restoration point to undo partially |
| 2055 | // matched operation. |
| 2056 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2057 | TPT.getRestorationPoint(); |
| 2058 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2059 | if (MatchAddr(AddrInst->getOperand(1), Depth+1) && |
| 2060 | MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2061 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2062 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2063 | // Restore the old addr mode info. |
| 2064 | AddrMode = BackupAddrMode; |
| 2065 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2066 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2067 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2068 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
| 2069 | if (MatchAddr(AddrInst->getOperand(0), Depth+1) && |
| 2070 | MatchAddr(AddrInst->getOperand(1), Depth+1)) |
| 2071 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2072 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2073 | // Otherwise we definitely can't merge the ADD in. |
| 2074 | AddrMode = BackupAddrMode; |
| 2075 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2076 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2077 | break; |
| 2078 | } |
| 2079 | //case Instruction::Or: |
| 2080 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 2081 | //break; |
| 2082 | case Instruction::Mul: |
| 2083 | case Instruction::Shl: { |
| 2084 | // Can only handle X*C and X << C. |
| 2085 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2086 | if (!RHS) |
| 2087 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2088 | int64_t Scale = RHS->getSExtValue(); |
| 2089 | if (Opcode == Instruction::Shl) |
| 2090 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2091 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2092 | return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
| 2093 | } |
| 2094 | case Instruction::GetElementPtr: { |
| 2095 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 2096 | // one variable offset. |
| 2097 | int VariableOperand = -1; |
| 2098 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2099 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2100 | int64_t ConstantOffset = 0; |
| 2101 | const DataLayout *TD = TLI.getDataLayout(); |
| 2102 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 2103 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 2104 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 2105 | const StructLayout *SL = TD->getStructLayout(STy); |
| 2106 | unsigned Idx = |
| 2107 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 2108 | ConstantOffset += SL->getElementOffset(Idx); |
| 2109 | } else { |
| 2110 | uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType()); |
| 2111 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 2112 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 2113 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 2114 | // We only allow one variable index at the moment. |
| 2115 | if (VariableOperand != -1) |
| 2116 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2117 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2118 | // Remember the variable index. |
| 2119 | VariableOperand = i; |
| 2120 | VariableScale = TypeSize; |
| 2121 | } |
| 2122 | } |
| 2123 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2124 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2125 | // A common case is for the GEP to only do a constant offset. In this case, |
| 2126 | // just add it to the disp field and check validity. |
| 2127 | if (VariableOperand == -1) { |
| 2128 | AddrMode.BaseOffs += ConstantOffset; |
| 2129 | if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){ |
| 2130 | // Check to see if we can fold the base pointer in too. |
| 2131 | if (MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2132 | return true; |
| 2133 | } |
| 2134 | AddrMode.BaseOffs -= ConstantOffset; |
| 2135 | return false; |
| 2136 | } |
| 2137 | |
| 2138 | // Save the valid addressing mode in case we can't match. |
| 2139 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2140 | unsigned OldSize = AddrModeInsts.size(); |
| 2141 | |
| 2142 | // See if the scale and offset amount is valid for this target. |
| 2143 | AddrMode.BaseOffs += ConstantOffset; |
| 2144 | |
| 2145 | // Match the base operand of the GEP. |
| 2146 | if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) { |
| 2147 | // If it couldn't be matched, just stuff the value in a register. |
| 2148 | if (AddrMode.HasBaseReg) { |
| 2149 | AddrMode = BackupAddrMode; |
| 2150 | AddrModeInsts.resize(OldSize); |
| 2151 | return false; |
| 2152 | } |
| 2153 | AddrMode.HasBaseReg = true; |
| 2154 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2155 | } |
| 2156 | |
| 2157 | // Match the remaining variable portion of the GEP. |
| 2158 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
| 2159 | Depth)) { |
| 2160 | // If it couldn't be matched, try stuffing the base into a register |
| 2161 | // instead of matching it, and retrying the match of the scale. |
| 2162 | AddrMode = BackupAddrMode; |
| 2163 | AddrModeInsts.resize(OldSize); |
| 2164 | if (AddrMode.HasBaseReg) |
| 2165 | return false; |
| 2166 | AddrMode.HasBaseReg = true; |
| 2167 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2168 | AddrMode.BaseOffs += ConstantOffset; |
| 2169 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), |
| 2170 | VariableScale, Depth)) { |
| 2171 | // If even that didn't work, bail. |
| 2172 | AddrMode = BackupAddrMode; |
| 2173 | AddrModeInsts.resize(OldSize); |
| 2174 | return false; |
| 2175 | } |
| 2176 | } |
| 2177 | |
| 2178 | return true; |
| 2179 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2180 | case Instruction::SExt: { |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2181 | Instruction *SExt = dyn_cast<Instruction>(AddrInst); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2182 | if (!SExt) |
| 2183 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2184 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2185 | // Try to move this sext out of the way of the addressing mode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2186 | // Ask for a method for doing so. |
| 2187 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
| 2188 | SExt, InsertedTruncs, TLI, PromotedInsts); |
| 2189 | if (!TPH) |
| 2190 | return false; |
| 2191 | |
| 2192 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2193 | TPT.getRestorationPoint(); |
| 2194 | unsigned CreatedInsts = 0; |
| 2195 | Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts); |
| 2196 | // SExt has been moved away. |
| 2197 | // Thus either it will be rematched later in the recursive calls or it is |
| 2198 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 2199 | // E.g., |
| 2200 | // op = add opnd, 1 |
| 2201 | // idx = sext op |
| 2202 | // addr = gep base, idx |
| 2203 | // is now: |
| 2204 | // promotedOpnd = sext opnd <- no match here |
| 2205 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 2206 | // addr = gep base, op <- match |
| 2207 | if (MovedAway) |
| 2208 | *MovedAway = true; |
| 2209 | |
| 2210 | assert(PromotedOperand && |
| 2211 | "TypePromotionHelper should have filtered out those cases"); |
| 2212 | |
| 2213 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2214 | unsigned OldSize = AddrModeInsts.size(); |
| 2215 | |
| 2216 | if (!MatchAddr(PromotedOperand, Depth) || |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2217 | !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts, |
| 2218 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2219 | AddrMode = BackupAddrMode; |
| 2220 | AddrModeInsts.resize(OldSize); |
| 2221 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 2222 | TPT.rollback(LastKnownGood); |
| 2223 | return false; |
| 2224 | } |
| 2225 | return true; |
| 2226 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2227 | } |
| 2228 | return false; |
| 2229 | } |
| 2230 | |
| 2231 | /// MatchAddr - If we can, try to add the value of 'Addr' into the current |
| 2232 | /// addressing mode. If Addr can't be added to AddrMode this returns false and |
| 2233 | /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type |
| 2234 | /// or intptr_t for the target. |
| 2235 | /// |
| 2236 | bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2237 | // Start a transaction at this point that we will rollback if the matching |
| 2238 | // fails. |
| 2239 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2240 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2241 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 2242 | // Fold in immediates if legal for the target. |
| 2243 | AddrMode.BaseOffs += CI->getSExtValue(); |
| 2244 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2245 | return true; |
| 2246 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 2247 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 2248 | // If this is a global variable, try to fold it into the addressing mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2249 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2250 | AddrMode.BaseGV = GV; |
| 2251 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2252 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2253 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2254 | } |
| 2255 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 2256 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2257 | unsigned OldSize = AddrModeInsts.size(); |
| 2258 | |
| 2259 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2260 | bool MovedAway = false; |
| 2261 | if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
| 2262 | // This instruction may have been move away. If so, there is nothing |
| 2263 | // to check here. |
| 2264 | if (MovedAway) |
| 2265 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2266 | // Okay, it's possible to fold this. Check to see if it is actually |
| 2267 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 2268 | // register pressure too much. |
| 2269 | if (I->hasOneUse() || |
| 2270 | IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
| 2271 | AddrModeInsts.push_back(I); |
| 2272 | return true; |
| 2273 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2274 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2275 | // It isn't profitable to do this, roll back. |
| 2276 | //cerr << "NOT FOLDING: " << *I; |
| 2277 | AddrMode = BackupAddrMode; |
| 2278 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2279 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2280 | } |
| 2281 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
| 2282 | if (MatchOperationAddr(CE, CE->getOpcode(), Depth)) |
| 2283 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2284 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2285 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 2286 | // Null pointer gets folded without affecting the addressing mode. |
| 2287 | return true; |
| 2288 | } |
| 2289 | |
| 2290 | // Worse case, the target should support [reg] addressing modes. :) |
| 2291 | if (!AddrMode.HasBaseReg) { |
| 2292 | AddrMode.HasBaseReg = true; |
| 2293 | AddrMode.BaseReg = Addr; |
| 2294 | // Still check for legality in case the target supports [imm] but not [i+r]. |
| 2295 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2296 | return true; |
| 2297 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2298 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2299 | } |
| 2300 | |
| 2301 | // If the base register is already taken, see if we can do [r+r]. |
| 2302 | if (AddrMode.Scale == 0) { |
| 2303 | AddrMode.Scale = 1; |
| 2304 | AddrMode.ScaledReg = Addr; |
| 2305 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2306 | return true; |
| 2307 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2308 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2309 | } |
| 2310 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2311 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2312 | return false; |
| 2313 | } |
| 2314 | |
| 2315 | /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified |
| 2316 | /// inline asm call are due to memory operands. If so, return true, otherwise |
| 2317 | /// return false. |
| 2318 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
| 2319 | const TargetLowering &TLI) { |
| 2320 | TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI)); |
| 2321 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2322 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2323 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2324 | // Compute the constraint code and ConstraintType to use. |
| 2325 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
| 2326 | |
| 2327 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 2328 | // operand, we can't fold it! |
| 2329 | if (OpInfo.CallOperandVal == OpVal && |
| 2330 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 2331 | !OpInfo.isIndirect)) |
| 2332 | return false; |
| 2333 | } |
| 2334 | |
| 2335 | return true; |
| 2336 | } |
| 2337 | |
| 2338 | /// FindAllMemoryUses - Recursively walk all the uses of I until we find a |
| 2339 | /// memory use. If we find an obviously non-foldable instruction, return true. |
| 2340 | /// Add the ultimately found memory instructions to MemoryUses. |
| 2341 | static bool FindAllMemoryUses(Instruction *I, |
| 2342 | SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 2343 | SmallPtrSetImpl<Instruction*> &ConsideredInsts, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2344 | const TargetLowering &TLI) { |
| 2345 | // If we already considered this instruction, we're done. |
| 2346 | if (!ConsideredInsts.insert(I)) |
| 2347 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2348 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2349 | // If this is an obviously unfoldable instruction, bail out. |
| 2350 | if (!MightBeFoldableInst(I)) |
| 2351 | return true; |
| 2352 | |
| 2353 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2354 | for (Use &U : I->uses()) { |
| 2355 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2356 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2357 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 2358 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2359 | continue; |
| 2360 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2361 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2362 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 2363 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2364 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 2365 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 2366 | continue; |
| 2367 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2368 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2369 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2370 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 2371 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2372 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2373 | // If this is a memory operand, we're cool, otherwise bail out. |
| 2374 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI)) |
| 2375 | return true; |
| 2376 | continue; |
| 2377 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2378 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2379 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2380 | return true; |
| 2381 | } |
| 2382 | |
| 2383 | return false; |
| 2384 | } |
| 2385 | |
| 2386 | /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at |
| 2387 | /// the use site that we're folding it into. If so, there is no cost to |
| 2388 | /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values |
| 2389 | /// that we know are live at the instruction already. |
| 2390 | bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
| 2391 | Value *KnownLive2) { |
| 2392 | // If Val is either of the known-live values, we know it is live! |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2393 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2394 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2395 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2396 | // All values other than instructions and arguments (e.g. constants) are live. |
| 2397 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2398 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2399 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 2400 | // true because it is just a reference to the stack/frame pointer, which is |
| 2401 | // live for the whole function. |
| 2402 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 2403 | if (AI->isStaticAlloca()) |
| 2404 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2405 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2406 | // Check to see if this value is already used in the memory instruction's |
| 2407 | // block. If so, it's already live into the block at the very least, so we |
| 2408 | // can reasonably fold it. |
| 2409 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 2410 | } |
| 2411 | |
| 2412 | /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing |
| 2413 | /// mode of the machine to fold the specified instruction into a load or store |
| 2414 | /// that ultimately uses it. However, the specified instruction has multiple |
| 2415 | /// uses. Given this, it may actually increase register pressure to fold it |
| 2416 | /// into the load. For example, consider this code: |
| 2417 | /// |
| 2418 | /// X = ... |
| 2419 | /// Y = X+1 |
| 2420 | /// use(Y) -> nonload/store |
| 2421 | /// Z = Y+1 |
| 2422 | /// load Z |
| 2423 | /// |
| 2424 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 2425 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 2426 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 2427 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 2428 | /// number of computations either. |
| 2429 | /// |
| 2430 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 2431 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 2432 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 2433 | bool AddressingModeMatcher:: |
| 2434 | IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
| 2435 | ExtAddrMode &AMAfter) { |
| 2436 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2437 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2438 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 2439 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 2440 | // the set of registers referenced by AMAfter and subtract out those |
| 2441 | // referenced by AMBefore: this is the set of values which folding in this |
| 2442 | // address extends the lifetime of. |
| 2443 | // |
| 2444 | // Note that there are only two potential values being referenced here, |
| 2445 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 2446 | // folded immediates). |
| 2447 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2448 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2449 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 2450 | // lifetime wasn't extended by adding this instruction. |
| 2451 | if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2452 | BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2453 | if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2454 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2455 | |
| 2456 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 2457 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2458 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2459 | return true; |
| 2460 | |
| 2461 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 2462 | // check to see if their addressing modes will include this instruction. If |
| 2463 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 2464 | // uses. |
| 2465 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 2466 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
| 2467 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI)) |
| 2468 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2469 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2470 | // Now that we know that all uses of this instruction are part of a chain of |
| 2471 | // computation involving only operations that could theoretically be folded |
| 2472 | // into a memory use, loop over each of these uses and see if they could |
| 2473 | // *actually* fold the instruction. |
| 2474 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 2475 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 2476 | Instruction *User = MemoryUses[i].first; |
| 2477 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2478 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2479 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 2480 | // know what it accesses. |
| 2481 | Value *Address = User->getOperand(OpNo); |
| 2482 | if (!Address->getType()->isPointerTy()) |
| 2483 | return false; |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 2484 | Type *AddressAccessTy = Address->getType()->getPointerElementType(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2485 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2486 | // Do a match against the root of this address, ignoring profitability. This |
| 2487 | // will tell us if the addressing mode for the memory operation will |
| 2488 | // *actually* cover the shared instruction. |
| 2489 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2490 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2491 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2492 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2493 | MemoryInst, Result, InsertedTruncs, |
| 2494 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2495 | Matcher.IgnoreProfitability = true; |
| 2496 | bool Success = Matcher.MatchAddr(Address, 0); |
| 2497 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2498 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2499 | // The match was to check the profitability, the changes made are not |
| 2500 | // part of the original matcher. Therefore, they should be dropped |
| 2501 | // otherwise the original matcher will not present the right state. |
| 2502 | TPT.rollback(LastKnownGood); |
| 2503 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2504 | // If the match didn't cover I, then it won't be shared by it. |
| 2505 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 2506 | I) == MatchedAddrModeInsts.end()) |
| 2507 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2508 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2509 | MatchedAddrModeInsts.clear(); |
| 2510 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2511 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2512 | return true; |
| 2513 | } |
| 2514 | |
| 2515 | } // end anonymous namespace |
| 2516 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2517 | /// IsNonLocalValue - Return true if the specified values are defined in a |
| 2518 | /// different basic block than BB. |
| 2519 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 2520 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 2521 | return I->getParent() != BB; |
| 2522 | return false; |
| 2523 | } |
| 2524 | |
Bob Wilson | 53bdae3 | 2009-12-03 21:47:07 +0000 | [diff] [blame] | 2525 | /// OptimizeMemoryInst - Load and Store Instructions often have |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2526 | /// addressing modes that can do significant amounts of computation. As such, |
| 2527 | /// instruction selection will try to get the load or store to do as much |
| 2528 | /// computation as possible for the program. The problem is that isel can only |
| 2529 | /// see within a single block. As such, we sink as much legal addressing mode |
| 2530 | /// stuff into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2531 | /// |
| 2532 | /// This method is used to optimize both load/store and inline asms with memory |
| 2533 | /// operands. |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2534 | bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2535 | Type *AccessTy) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2536 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2537 | |
| 2538 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2539 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 2540 | SmallVector<Value*, 8> worklist; |
| 2541 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2542 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2543 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2544 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 2545 | // the addressing mode obtained from the non-PHI roots of the graph |
| 2546 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2547 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2548 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2549 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2550 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 2551 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2552 | TypePromotionTransaction TPT; |
| 2553 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2554 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2555 | while (!worklist.empty()) { |
| 2556 | Value *V = worklist.back(); |
| 2557 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2558 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2559 | // Break use-def graph loops. |
Nick Lewycky | a3e7ffd | 2011-09-29 23:40:12 +0000 | [diff] [blame] | 2560 | if (!Visited.insert(V)) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2561 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2562 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2563 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2564 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2565 | // For a PHI node, push all of its incoming values. |
| 2566 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
| 2567 | for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) |
| 2568 | worklist.push_back(P->getIncomingValue(i)); |
| 2569 | continue; |
| 2570 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2571 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2572 | // For non-PHIs, determine the addressing mode being computed. |
| 2573 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2574 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
| 2575 | V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet, |
| 2576 | PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2577 | |
| 2578 | // This check is broken into two cases with very similar code to avoid using |
| 2579 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 2580 | // calling getNumUses() unconditionally caused a significant compile-time |
| 2581 | // regression. |
| 2582 | if (!Consensus) { |
| 2583 | Consensus = V; |
| 2584 | AddrMode = NewAddrMode; |
| 2585 | AddrModeInsts = NewAddrModeInsts; |
| 2586 | continue; |
| 2587 | } else if (NewAddrMode == AddrMode) { |
| 2588 | if (!IsNumUsesConsensusValid) { |
| 2589 | NumUsesConsensus = Consensus->getNumUses(); |
| 2590 | IsNumUsesConsensusValid = true; |
| 2591 | } |
| 2592 | |
| 2593 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 2594 | // for all other roots of the PHI traversal. Also, when choosing one |
| 2595 | // such root as representative, select the one with the most uses in order |
| 2596 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 2597 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2598 | unsigned NumUses = V->getNumUses(); |
| 2599 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2600 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2601 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2602 | AddrModeInsts = NewAddrModeInsts; |
| 2603 | } |
| 2604 | continue; |
| 2605 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2606 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2607 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2608 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2609 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2610 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2611 | // If the addressing mode couldn't be determined, or if multiple different |
| 2612 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2613 | if (!Consensus) { |
| 2614 | TPT.rollback(LastKnownGood); |
| 2615 | return false; |
| 2616 | } |
| 2617 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2618 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2619 | // Check to see if any of the instructions supersumed by this addr mode are |
| 2620 | // non-local to I's BB. |
| 2621 | bool AnyNonLocal = false; |
| 2622 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2623 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2624 | AnyNonLocal = true; |
| 2625 | break; |
| 2626 | } |
| 2627 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2628 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2629 | // If all the instructions matched are already in this BB, don't do anything. |
| 2630 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2631 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2632 | return false; |
| 2633 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2634 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2635 | // Insert this computation right after this user. Since our caller is |
| 2636 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 2637 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2638 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2639 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2640 | // Now that we determined the addressing expression we want to use and know |
| 2641 | // that we have to sink it into this block. Check to see if we have already |
| 2642 | // done this for some other load/store instr in this block. If so, reuse the |
| 2643 | // computation. |
| 2644 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 2645 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2646 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2647 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2648 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 2649 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2650 | } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && |
| 2651 | TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) { |
| 2652 | // By default, we use the GEP-based method when AA is used later. This |
| 2653 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 2654 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2655 | << *MemoryInst << "\n"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2656 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2657 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2658 | |
| 2659 | // First, find the pointer. |
| 2660 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 2661 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2662 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2663 | } |
| 2664 | |
| 2665 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 2666 | // We can't add more than one pointer together, nor can we scale a |
| 2667 | // pointer (both of which seem meaningless). |
| 2668 | if (ResultPtr || AddrMode.Scale != 1) |
| 2669 | return false; |
| 2670 | |
| 2671 | ResultPtr = AddrMode.ScaledReg; |
| 2672 | AddrMode.Scale = 0; |
| 2673 | } |
| 2674 | |
| 2675 | if (AddrMode.BaseGV) { |
| 2676 | if (ResultPtr) |
| 2677 | return false; |
| 2678 | |
| 2679 | ResultPtr = AddrMode.BaseGV; |
| 2680 | } |
| 2681 | |
| 2682 | // If the real base value actually came from an inttoptr, then the matcher |
| 2683 | // will look through it and provide only the integer value. In that case, |
| 2684 | // use it here. |
| 2685 | if (!ResultPtr && AddrMode.BaseReg) { |
| 2686 | ResultPtr = |
| 2687 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2688 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2689 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 2690 | ResultPtr = |
| 2691 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 2692 | AddrMode.Scale = 0; |
| 2693 | } |
| 2694 | |
| 2695 | if (!ResultPtr && |
| 2696 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 2697 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 2698 | } else if (!ResultPtr) { |
| 2699 | return false; |
| 2700 | } else { |
| 2701 | Type *I8PtrTy = |
| 2702 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 2703 | |
| 2704 | // Start with the base register. Do this first so that subsequent address |
| 2705 | // matching finds it last, which will prevent it from trying to match it |
| 2706 | // as the scaled value in case it happens to be a mul. That would be |
| 2707 | // problematic if we've sunk a different mul for the scale, because then |
| 2708 | // we'd end up sinking both muls. |
| 2709 | if (AddrMode.BaseReg) { |
| 2710 | Value *V = AddrMode.BaseReg; |
| 2711 | if (V->getType() != IntPtrTy) |
| 2712 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 2713 | |
| 2714 | ResultIndex = V; |
| 2715 | } |
| 2716 | |
| 2717 | // Add the scale value. |
| 2718 | if (AddrMode.Scale) { |
| 2719 | Value *V = AddrMode.ScaledReg; |
| 2720 | if (V->getType() == IntPtrTy) { |
| 2721 | // done. |
| 2722 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2723 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 2724 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 2725 | } else { |
| 2726 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2727 | // required to create it did not overflow before we extend it. Since |
| 2728 | // the original IR value was tossed in favor of a constant back when |
| 2729 | // the AddrMode was created we need to bail out gracefully if widths |
| 2730 | // do not match instead of extending it. |
| 2731 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 2732 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 2733 | I->eraseFromParent(); |
| 2734 | return false; |
| 2735 | } |
| 2736 | |
| 2737 | if (AddrMode.Scale != 1) |
| 2738 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2739 | "sunkaddr"); |
| 2740 | if (ResultIndex) |
| 2741 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 2742 | else |
| 2743 | ResultIndex = V; |
| 2744 | } |
| 2745 | |
| 2746 | // Add in the Base Offset if present. |
| 2747 | if (AddrMode.BaseOffs) { |
| 2748 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 2749 | if (ResultIndex) { |
| 2750 | // We need to add this separately from the scale above to help with |
| 2751 | // SDAG consecutive load/store merging. |
| 2752 | if (ResultPtr->getType() != I8PtrTy) |
| 2753 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2754 | ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2755 | } |
| 2756 | |
| 2757 | ResultIndex = V; |
| 2758 | } |
| 2759 | |
| 2760 | if (!ResultIndex) { |
| 2761 | SunkAddr = ResultPtr; |
| 2762 | } else { |
| 2763 | if (ResultPtr->getType() != I8PtrTy) |
| 2764 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2765 | SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2766 | } |
| 2767 | |
| 2768 | if (SunkAddr->getType() != Addr->getType()) |
| 2769 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 2770 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2771 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2772 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2773 | << *MemoryInst << "\n"); |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2774 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2775 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2776 | |
| 2777 | // Start with the base register. Do this first so that subsequent address |
| 2778 | // matching finds it last, which will prevent it from trying to match it |
| 2779 | // as the scaled value in case it happens to be a mul. That would be |
| 2780 | // problematic if we've sunk a different mul for the scale, because then |
| 2781 | // we'd end up sinking both muls. |
| 2782 | if (AddrMode.BaseReg) { |
| 2783 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2784 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2785 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2786 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2787 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2788 | Result = V; |
| 2789 | } |
| 2790 | |
| 2791 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2792 | if (AddrMode.Scale) { |
| 2793 | Value *V = AddrMode.ScaledReg; |
| 2794 | if (V->getType() == IntPtrTy) { |
| 2795 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2796 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2797 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2798 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2799 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2800 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2801 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2802 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2803 | // required to create it did not overflow before we extend it. Since |
| 2804 | // the original IR value was tossed in favor of a constant back when |
| 2805 | // the AddrMode was created we need to bail out gracefully if widths |
| 2806 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 2807 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 2808 | if (I && (Result != AddrMode.BaseReg)) |
| 2809 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2810 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2811 | } |
| 2812 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2813 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2814 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2815 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2816 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2817 | else |
| 2818 | Result = V; |
| 2819 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2820 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2821 | // Add in the BaseGV if present. |
| 2822 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2823 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2824 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2825 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2826 | else |
| 2827 | Result = V; |
| 2828 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2829 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2830 | // Add in the Base Offset if present. |
| 2831 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 2832 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2833 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2834 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2835 | else |
| 2836 | Result = V; |
| 2837 | } |
| 2838 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2839 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 2840 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2841 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2842 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2843 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2844 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2845 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2846 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2847 | // If we have no uses, recursively delete the value and all dead instructions |
| 2848 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2849 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2850 | // This can cause recursive deletion, which can invalidate our iterator. |
| 2851 | // Use a WeakVH to hold onto it in case this happens. |
| 2852 | WeakVH IterHandle(CurInstIterator); |
| 2853 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2854 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 2855 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2856 | |
| 2857 | if (IterHandle != CurInstIterator) { |
| 2858 | // If the iterator instruction was recursively deleted, start over at the |
| 2859 | // start of the block. |
| 2860 | CurInstIterator = BB->begin(); |
| 2861 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2862 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 2863 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2864 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2865 | return true; |
| 2866 | } |
| 2867 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2868 | /// OptimizeInlineAsmInst - If there are any memory operands, use |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2869 | /// OptimizeMemoryInst to sink their address computing into the block when |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2870 | /// possible / profitable. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2871 | bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2872 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2873 | |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2874 | TargetLowering::AsmOperandInfoVector |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2875 | TargetConstraints = TLI->ParseConstraints(CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2876 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 2877 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2878 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2879 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2880 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 2881 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2882 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 2883 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 2884 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2885 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 2886 | MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType()); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2887 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 2888 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2889 | } |
| 2890 | |
| 2891 | return MadeChange; |
| 2892 | } |
| 2893 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2894 | /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same |
| 2895 | /// basic block as the load, unless conditions are unfavorable. This allows |
| 2896 | /// SelectionDAG to fold the extend into the load. |
| 2897 | /// |
| 2898 | bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) { |
| 2899 | // Look for a load being extended. |
| 2900 | LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0)); |
| 2901 | if (!LI) return false; |
| 2902 | |
| 2903 | // If they're already in the same block, there's nothing to do. |
| 2904 | if (LI->getParent() == I->getParent()) |
| 2905 | return false; |
| 2906 | |
| 2907 | // If the load has other users and the truncate is not free, this probably |
| 2908 | // isn't worthwhile. |
| 2909 | if (!LI->hasOneUse() && |
Bob Wilson | b6832a4 | 2010-09-22 18:44:56 +0000 | [diff] [blame] | 2910 | TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) || |
| 2911 | !TLI->isTypeLegal(TLI->getValueType(I->getType()))) && |
Bob Wilson | 4ddcb6a | 2010-09-21 21:54:27 +0000 | [diff] [blame] | 2912 | !TLI->isTruncateFree(I->getType(), LI->getType())) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2913 | return false; |
| 2914 | |
| 2915 | // Check whether the target supports casts folded into loads. |
| 2916 | unsigned LType; |
| 2917 | if (isa<ZExtInst>(I)) |
| 2918 | LType = ISD::ZEXTLOAD; |
| 2919 | else { |
| 2920 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 2921 | LType = ISD::SEXTLOAD; |
| 2922 | } |
Patrik Hagglund | e98b7a0 | 2012-12-11 11:14:33 +0000 | [diff] [blame] | 2923 | if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType()))) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2924 | return false; |
| 2925 | |
| 2926 | // Move the extend into the same block as the load, so that SelectionDAG |
| 2927 | // can fold it. |
| 2928 | I->removeFromParent(); |
| 2929 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2930 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2931 | return true; |
| 2932 | } |
| 2933 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2934 | bool CodeGenPrepare::OptimizeExtUses(Instruction *I) { |
| 2935 | BasicBlock *DefBB = I->getParent(); |
| 2936 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 2937 | // If the result of a {s|z}ext and its source are both live out, rewrite all |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2938 | // other uses of the source with result of extension. |
| 2939 | Value *Src = I->getOperand(0); |
| 2940 | if (Src->hasOneUse()) |
| 2941 | return false; |
| 2942 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 2943 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 2944 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 2945 | return false; |
| 2946 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 2947 | // Only safe to perform the optimization if the source is also defined in |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 2948 | // this block. |
| 2949 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 2950 | return false; |
| 2951 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2952 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2953 | for (User *U : I->users()) { |
| 2954 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2955 | |
| 2956 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2957 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2958 | if (UserBB == DefBB) continue; |
| 2959 | DefIsLiveOut = true; |
| 2960 | break; |
| 2961 | } |
| 2962 | if (!DefIsLiveOut) |
| 2963 | return false; |
| 2964 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 2965 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2966 | for (User *U : Src->users()) { |
| 2967 | Instruction *UI = cast<Instruction>(U); |
| 2968 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 2969 | if (UserBB == DefBB) continue; |
| 2970 | // Be conservative. We don't want this xform to end up introducing |
| 2971 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2972 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 2973 | return false; |
| 2974 | } |
| 2975 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2976 | // InsertedTruncs - Only insert one trunc in each block once. |
| 2977 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 2978 | |
| 2979 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2980 | for (Use &U : Src->uses()) { |
| 2981 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2982 | |
| 2983 | // Figure out which BB this ext is used in. |
| 2984 | BasicBlock *UserBB = User->getParent(); |
| 2985 | if (UserBB == DefBB) continue; |
| 2986 | |
| 2987 | // Both src and def are live in this block. Rewrite the use. |
| 2988 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 2989 | |
| 2990 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 2991 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2992 | InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2993 | InsertedTruncsSet.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2994 | } |
| 2995 | |
| 2996 | // Replace a use of the {s|z}ext source with a use of the result. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2997 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2998 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2999 | MadeChange = true; |
| 3000 | } |
| 3001 | |
| 3002 | return MadeChange; |
| 3003 | } |
| 3004 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3005 | /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be |
| 3006 | /// turned into an explicit branch. |
| 3007 | static bool isFormingBranchFromSelectProfitable(SelectInst *SI) { |
| 3008 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 3009 | // whether a select is better represented as a branch. This requires that |
| 3010 | // branch probability metadata is preserved for the select, which is not the |
| 3011 | // case currently. |
| 3012 | |
| 3013 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 3014 | |
| 3015 | // If the branch is predicted right, an out of order CPU can avoid blocking on |
| 3016 | // the compare. Emit cmovs on compares with a memory operand as branches to |
| 3017 | // avoid stalls on the load from memory. If the compare has more than one use |
| 3018 | // there's probably another cmov or setcc around so it's not worth emitting a |
| 3019 | // branch. |
| 3020 | if (!Cmp) |
| 3021 | return false; |
| 3022 | |
| 3023 | Value *CmpOp0 = Cmp->getOperand(0); |
| 3024 | Value *CmpOp1 = Cmp->getOperand(1); |
| 3025 | |
| 3026 | // We check that the memory operand has one use to avoid uses of the loaded |
| 3027 | // value directly after the compare, making branches unprofitable. |
| 3028 | return Cmp->hasOneUse() && |
| 3029 | ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 3030 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())); |
| 3031 | } |
| 3032 | |
| 3033 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3034 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 3035 | /// turn it into a branch. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3036 | bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3037 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 3038 | |
| 3039 | // Can we convert the 'select' to CF ? |
| 3040 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3041 | return false; |
| 3042 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3043 | TargetLowering::SelectSupportKind SelectKind; |
| 3044 | if (VectorCond) |
| 3045 | SelectKind = TargetLowering::VectorMaskSelect; |
| 3046 | else if (SI->getType()->isVectorTy()) |
| 3047 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 3048 | else |
| 3049 | SelectKind = TargetLowering::ScalarValSelect; |
| 3050 | |
| 3051 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 3052 | if (TLI->isSelectSupported(SelectKind)) { |
| 3053 | // We have efficient codegen support for the select instruction. |
| 3054 | // Check if it is profitable to keep this 'select'. |
| 3055 | if (!TLI->isPredictableSelectExpensive() || |
| 3056 | !isFormingBranchFromSelectProfitable(SI)) |
| 3057 | return false; |
| 3058 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3059 | |
| 3060 | ModifiedDT = true; |
| 3061 | |
| 3062 | // First, we split the block containing the select into 2 blocks. |
| 3063 | BasicBlock *StartBlock = SI->getParent(); |
| 3064 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
| 3065 | BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
| 3066 | |
| 3067 | // Create a new block serving as the landing pad for the branch. |
| 3068 | BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid", |
| 3069 | NextBlock->getParent(), NextBlock); |
| 3070 | |
| 3071 | // Move the unconditional branch from the block with the select in it into our |
| 3072 | // landing pad block. |
| 3073 | StartBlock->getTerminator()->eraseFromParent(); |
| 3074 | BranchInst::Create(NextBlock, SmallBlock); |
| 3075 | |
| 3076 | // Insert the real conditional branch based on the original condition. |
| 3077 | BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI); |
| 3078 | |
| 3079 | // The select itself is replaced with a PHI Node. |
| 3080 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin()); |
| 3081 | PN->takeName(SI); |
| 3082 | PN->addIncoming(SI->getTrueValue(), StartBlock); |
| 3083 | PN->addIncoming(SI->getFalseValue(), SmallBlock); |
| 3084 | SI->replaceAllUsesWith(PN); |
| 3085 | SI->eraseFromParent(); |
| 3086 | |
| 3087 | // Instruct OptimizeBlock to skip to the next block. |
| 3088 | CurInstIterator = StartBlock->end(); |
| 3089 | ++NumSelectsExpanded; |
| 3090 | return true; |
| 3091 | } |
| 3092 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 3093 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3094 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 3095 | int SplatElem = -1; |
| 3096 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 3097 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 3098 | return false; |
| 3099 | SplatElem = Mask[i]; |
| 3100 | } |
| 3101 | |
| 3102 | return true; |
| 3103 | } |
| 3104 | |
| 3105 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 3106 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 3107 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 3108 | /// codegen can spot all lanes are identical. |
| 3109 | bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
| 3110 | BasicBlock *DefBB = SVI->getParent(); |
| 3111 | |
| 3112 | // Only do this xform if variable vector shifts are particularly expensive. |
| 3113 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 3114 | return false; |
| 3115 | |
| 3116 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 3117 | // constant splat. |
| 3118 | if (!isBroadcastShuffle(SVI)) |
| 3119 | return false; |
| 3120 | |
| 3121 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 3122 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 3123 | |
| 3124 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3125 | for (User *U : SVI->users()) { |
| 3126 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3127 | |
| 3128 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3129 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3130 | if (UserBB == DefBB) continue; |
| 3131 | |
| 3132 | // For now only apply this when the splat is used by a shift instruction. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3133 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3134 | |
| 3135 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 3136 | // already have a copy. |
| 3137 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 3138 | |
| 3139 | if (!InsertedShuffle) { |
| 3140 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 3141 | InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0), |
| 3142 | SVI->getOperand(1), |
| 3143 | SVI->getOperand(2), "", InsertPt); |
| 3144 | } |
| 3145 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3146 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3147 | MadeChange = true; |
| 3148 | } |
| 3149 | |
| 3150 | // If we removed all uses, nuke the shuffle. |
| 3151 | if (SVI->use_empty()) { |
| 3152 | SVI->eraseFromParent(); |
| 3153 | MadeChange = true; |
| 3154 | } |
| 3155 | |
| 3156 | return MadeChange; |
| 3157 | } |
| 3158 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3159 | bool CodeGenPrepare::OptimizeInst(Instruction *I) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3160 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 3161 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 3162 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 3163 | // trivial PHI, go ahead and zap it here. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3164 | if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr, |
Benjamin Kramer | 30d249a | 2013-09-24 16:37:40 +0000 | [diff] [blame] | 3165 | TLInfo, DT)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3166 | P->replaceAllUsesWith(V); |
| 3167 | P->eraseFromParent(); |
| 3168 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3169 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3170 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3171 | return false; |
| 3172 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3173 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3174 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3175 | // If the source of the cast is a constant, then this should have |
| 3176 | // already been constant folded. The only reason NOT to constant fold |
| 3177 | // it is if something (e.g. LSR) was careful to place the constant |
| 3178 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 3179 | // the address of globals out of a loop). If this is the case, we don't |
| 3180 | // want to forward-subst the cast. |
| 3181 | if (isa<Constant>(CI->getOperand(0))) |
| 3182 | return false; |
| 3183 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3184 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI)) |
| 3185 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3186 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3187 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 3188 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 3189 | /// fit in one register |
| 3190 | if (TLI && TLI->getTypeAction(CI->getContext(), |
| 3191 | TLI->getValueType(CI->getType())) == |
| 3192 | TargetLowering::TypeExpandInteger) { |
| 3193 | return SinkCast(CI); |
| 3194 | } else { |
| 3195 | bool MadeChange = MoveExtToFormExtLoad(I); |
| 3196 | return MadeChange | OptimizeExtUses(I); |
| 3197 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3198 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3199 | return false; |
| 3200 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3201 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3202 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 3203 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 3204 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3205 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3206 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3207 | if (TLI) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 3208 | return OptimizeMemoryInst(I, I->getOperand(0), LI->getType()); |
| 3209 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3210 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3211 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3212 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3213 | if (TLI) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3214 | return OptimizeMemoryInst(I, SI->getOperand(1), |
| 3215 | SI->getOperand(0)->getType()); |
| 3216 | return false; |
| 3217 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3218 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 3219 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 3220 | |
| 3221 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 3222 | BinOp->getOpcode() == Instruction::LShr)) { |
| 3223 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 3224 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
| 3225 | return OptimizeExtractBits(BinOp, CI, *TLI); |
| 3226 | |
| 3227 | return false; |
| 3228 | } |
| 3229 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3230 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3231 | if (GEPI->hasAllZeroIndices()) { |
| 3232 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 3233 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 3234 | GEPI->getName(), GEPI); |
| 3235 | GEPI->replaceAllUsesWith(NC); |
| 3236 | GEPI->eraseFromParent(); |
| 3237 | ++NumGEPsElim; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3238 | OptimizeInst(NC); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3239 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3240 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3241 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3242 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3243 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3244 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
| 3245 | return OptimizeCallInst(CI); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3246 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3247 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
| 3248 | return OptimizeSelectInst(SI); |
| 3249 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3250 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
| 3251 | return OptimizeShuffleVectorInst(SVI); |
| 3252 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3253 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3254 | } |
| 3255 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3256 | // In this pass we look for GEP and cast instructions that are used |
| 3257 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 3258 | // selection. |
| 3259 | bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 3260 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 3261 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3262 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3263 | CurInstIterator = BB.begin(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 3264 | while (CurInstIterator != BB.end()) |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 3265 | MadeChange |= OptimizeInst(CurInstIterator++); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3266 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 3267 | MadeChange |= DupRetToEnableTailCallOpts(&BB); |
| 3268 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3269 | return MadeChange; |
| 3270 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3271 | |
| 3272 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3273 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3274 | // find a node corresponding to the value. |
| 3275 | bool CodeGenPrepare::PlaceDbgValues(Function &F) { |
| 3276 | bool MadeChange = false; |
| 3277 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3278 | Instruction *PrevNonDbgInst = nullptr; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3279 | for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) { |
| 3280 | Instruction *Insn = BI; ++BI; |
| 3281 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 3282 | // Leave dbg.values that refer to an alloca alone. These |
| 3283 | // instrinsics describe the address of a variable (= the alloca) |
| 3284 | // being taken. They should not be moved next to the alloca |
| 3285 | // (and to the beginning of the scope), but rather stay close to |
| 3286 | // where said address is used. |
| 3287 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3288 | PrevNonDbgInst = Insn; |
| 3289 | continue; |
| 3290 | } |
| 3291 | |
| 3292 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 3293 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
| 3294 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 3295 | DVI->removeFromParent(); |
| 3296 | if (isa<PHINode>(VI)) |
| 3297 | DVI->insertBefore(VI->getParent()->getFirstInsertionPt()); |
| 3298 | else |
| 3299 | DVI->insertAfter(VI); |
| 3300 | MadeChange = true; |
| 3301 | ++NumDbgValueMoved; |
| 3302 | } |
| 3303 | } |
| 3304 | } |
| 3305 | return MadeChange; |
| 3306 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 3307 | |
| 3308 | // If there is a sequence that branches based on comparing a single bit |
| 3309 | // against zero that can be combined into a single instruction, and the |
| 3310 | // target supports folding these into a single instruction, sink the |
| 3311 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 3312 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 3313 | // searched for. |
| 3314 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 3315 | if (!EnableAndCmpSinking) |
| 3316 | return false; |
| 3317 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 3318 | return false; |
| 3319 | bool MadeChange = false; |
| 3320 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
| 3321 | BasicBlock *BB = I++; |
| 3322 | |
| 3323 | // Does this BB end with the following? |
| 3324 | // %andVal = and %val, #single-bit-set |
| 3325 | // %icmpVal = icmp %andResult, 0 |
| 3326 | // br i1 %cmpVal label %dest1, label %dest2" |
| 3327 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3328 | if (!Brcc || !Brcc->isConditional()) |
| 3329 | continue; |
| 3330 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 3331 | if (!Cmp || Cmp->getParent() != BB) |
| 3332 | continue; |
| 3333 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 3334 | if (!Zero || !Zero->isZero()) |
| 3335 | continue; |
| 3336 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 3337 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 3338 | continue; |
| 3339 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 3340 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 3341 | continue; |
| 3342 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 3343 | |
| 3344 | // Push the "and; icmp" for any users that are conditional branches. |
| 3345 | // Since there can only be one branch use per BB, we don't need to keep |
| 3346 | // track of which BBs we insert into. |
| 3347 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 3348 | UI != E; ) { |
| 3349 | Use &TheUse = *UI; |
| 3350 | // Find brcc use. |
| 3351 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 3352 | ++UI; |
| 3353 | if (!BrccUser || !BrccUser->isConditional()) |
| 3354 | continue; |
| 3355 | BasicBlock *UserBB = BrccUser->getParent(); |
| 3356 | if (UserBB == BB) continue; |
| 3357 | DEBUG(dbgs() << "found Brcc use\n"); |
| 3358 | |
| 3359 | // Sink the "and; icmp" to use. |
| 3360 | MadeChange = true; |
| 3361 | BinaryOperator *NewAnd = |
| 3362 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 3363 | BrccUser); |
| 3364 | CmpInst *NewCmp = |
| 3365 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 3366 | "", BrccUser); |
| 3367 | TheUse = NewCmp; |
| 3368 | ++NumAndCmpsMoved; |
| 3369 | DEBUG(BrccUser->getParent()->dump()); |
| 3370 | } |
| 3371 | } |
| 3372 | return MadeChange; |
| 3373 | } |