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