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