blob: 42978e753d1666948525f84c032aa9d21def7381 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000025#include "llvm/Target/TargetAsmInfo.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000029#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000031#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chengab631522008-12-19 18:03:11 +000036#include "llvm/Support/CommandLine.h"
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000037#include "llvm/Support/Compiler.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000038#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000039#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000040#include "llvm/Support/PatternMatch.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000041using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000042using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000043
Evan Chengab631522008-12-19 18:03:11 +000044static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
46
Eric Christopher692bf6b2008-09-24 05:32:41 +000047namespace {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000048 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
49 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
Evan Chengab631522008-12-19 18:03:11 +000052
53 /// BackEdges - Keep a set of all the loop back edges.
54 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000055 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000056 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000057 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000058 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Dan Gohmanae73dc12008-09-04 17:05:41 +000059 : FunctionPass(&ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000061
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000062 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000063 bool EliminateMostlyEmptyBlocks(Function &F);
64 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000066 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000067 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000069 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70 DenseMap<Value*,Value*> &SunkAddrs);
Evan Chengbdcb7262007-12-05 23:58:20 +000071 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000072 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000073 };
74}
Devang Patel794fd752007-05-01 21:15:47 +000075
Devang Patel19974732007-05-03 01:11:54 +000076char CodeGenPrepare::ID = 0;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000077static RegisterPass<CodeGenPrepare> X("codegenprepare",
78 "Optimize for code generation");
79
80FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81 return new CodeGenPrepare(TLI);
82}
83
Evan Chengab631522008-12-19 18:03:11 +000084/// findLoopBackEdges - Do a DFS walk to find loop back edges.
85///
Mike Stumpfe095f32009-05-04 18:40:41 +000086void CodeGenPrepare::findLoopBackEdges(const Function &F) {
87 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
88 FindFunctionBackedges(F, Edges);
89
90 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +000091}
92
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000093
94bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000095 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +000096
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000097 // First pass, eliminate blocks that contain only PHI nodes and an
98 // unconditional branch.
99 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000100
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000101 // Now find loop back edges.
102 findLoopBackEdges(F);
103
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000104 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000105 while (MadeChange) {
106 MadeChange = false;
107 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
108 MadeChange |= OptimizeBlock(*BB);
109 EverMadeChange |= MadeChange;
110 }
111 return EverMadeChange;
112}
113
Dale Johannesen2d697242009-03-27 01:13:37 +0000114/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
115/// debug info directives, and an unconditional branch. Passes before isel
116/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
117/// isel. Start by eliminating these blocks so we can split them the way we
118/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
120 bool MadeChange = false;
121 // Note that this intentionally skips the entry block.
122 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
123 BasicBlock *BB = I++;
124
125 // If this block doesn't end with an uncond branch, ignore it.
126 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
127 if (!BI || !BI->isUnconditional())
128 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000129
Dale Johannesen2d697242009-03-27 01:13:37 +0000130 // If the instruction before the branch (skipping debug info) isn't a phi
131 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000132 BasicBlock::iterator BBI = BI;
133 if (BBI != BB->begin()) {
134 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000135 while (isa<DbgInfoIntrinsic>(BBI)) {
136 if (BBI == BB->begin())
137 break;
138 --BBI;
139 }
140 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
141 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000142 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000143
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000144 // Do not break infinite loops.
145 BasicBlock *DestBB = BI->getSuccessor(0);
146 if (DestBB == BB)
147 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000148
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000149 if (!CanMergeBlocks(BB, DestBB))
150 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000151
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000152 EliminateMostlyEmptyBlock(BB);
153 MadeChange = true;
154 }
155 return MadeChange;
156}
157
158/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
159/// single uncond branch between them, and BB contains no other non-phi
160/// instructions.
161bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
162 const BasicBlock *DestBB) const {
163 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
164 // the successor. If there are more complex condition (e.g. preheaders),
165 // don't mess around with them.
166 BasicBlock::const_iterator BBI = BB->begin();
167 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
168 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
169 UI != E; ++UI) {
170 const Instruction *User = cast<Instruction>(*UI);
171 if (User->getParent() != DestBB || !isa<PHINode>(User))
172 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000173 // If User is inside DestBB block and it is a PHINode then check
174 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000175 // a complex condition (e.g. preheaders) we want to avoid here.
176 if (User->getParent() == DestBB) {
177 if (const PHINode *UPN = dyn_cast<PHINode>(User))
178 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
179 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
180 if (Insn && Insn->getParent() == BB &&
181 Insn->getParent() != UPN->getIncomingBlock(I))
182 return false;
183 }
184 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000185 }
186 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000187
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000188 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
189 // and DestBB may have conflicting incoming values for the block. If so, we
190 // can't merge the block.
191 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
192 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000193
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000194 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000195 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000196 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
197 // It is faster to get preds from a PHI than with pred_iterator.
198 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
199 BBPreds.insert(BBPN->getIncomingBlock(i));
200 } else {
201 BBPreds.insert(pred_begin(BB), pred_end(BB));
202 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000203
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000204 // Walk the preds of DestBB.
205 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
206 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
207 if (BBPreds.count(Pred)) { // Common predecessor?
208 BBI = DestBB->begin();
209 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
210 const Value *V1 = PN->getIncomingValueForBlock(Pred);
211 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000212
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000213 // If V2 is a phi node in BB, look up what the mapped value will be.
214 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
215 if (V2PN->getParent() == BB)
216 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000217
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000218 // If there is a conflict, bail out.
219 if (V1 != V2) return false;
220 }
221 }
222 }
223
224 return true;
225}
226
227
228/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
229/// an unconditional branch in it.
230void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
231 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
232 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000233
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000234 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000235
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000236 // If the destination block has a single pred, then this is a trivial edge,
237 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000238 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000239 if (SinglePred != DestBB) {
240 // Remember if SinglePred was the entry block of the function. If so, we
241 // will need to move BB back to the entry position.
242 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
243 MergeBasicBlockIntoOnlyPred(DestBB);
Chris Lattner9918fb52008-11-27 19:29:14 +0000244
Chris Lattnerf5102a02008-11-28 19:54:49 +0000245 if (isEntry && BB != &BB->getParent()->getEntryBlock())
246 BB->moveBefore(&BB->getParent()->getEntryBlock());
247
248 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
249 return;
250 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000252
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000253 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
254 // to handle the new incoming edges it is about to have.
255 PHINode *PN;
256 for (BasicBlock::iterator BBI = DestBB->begin();
257 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
258 // Remove the incoming value for BB, and remember it.
259 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000260
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000261 // Two options: either the InVal is a phi node defined in BB or it is some
262 // value that dominates BB.
263 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
264 if (InValPhi && InValPhi->getParent() == BB) {
265 // Add all of the input values of the input PHI as inputs of this phi.
266 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
267 PN->addIncoming(InValPhi->getIncomingValue(i),
268 InValPhi->getIncomingBlock(i));
269 } else {
270 // Otherwise, add one instance of the dominating value for each edge that
271 // we will be adding.
272 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
273 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
274 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
275 } else {
276 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
277 PN->addIncoming(InVal, *PI);
278 }
279 }
280 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000281
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000282 // The PHIs are now updated, change everything that refers to BB to use
283 // DestBB and remove BB.
284 BB->replaceAllUsesWith(DestBB);
285 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000286
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000287 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
288}
289
290
Chris Lattnerebe80752007-12-24 19:32:55 +0000291/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000292/// successor if it will improve codegen. We only do this if the successor has
293/// phi nodes (otherwise critical edges are ok). If there is already another
294/// predecessor of the succ that is empty (and thus has no phi nodes), use it
295/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000296static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000297 SmallSet<std::pair<const BasicBlock*,
298 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000299 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000300 BasicBlock *TIBB = TI->getParent();
301 BasicBlock *Dest = TI->getSuccessor(SuccNum);
302 assert(isa<PHINode>(Dest->begin()) &&
303 "This should only be called if Dest has a PHI!");
Eric Christopher692bf6b2008-09-24 05:32:41 +0000304
Evan Chengfc0b80d2009-03-13 22:59:14 +0000305 // Do not split edges to EH landing pads.
306 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
307 if (Invoke->getSuccessor(1) == Dest)
308 return;
309 }
310
Chris Lattnerebe80752007-12-24 19:32:55 +0000311 // As a hack, never split backedges of loops. Even though the copy for any
312 // PHIs inserted on the backedge would be dead for exits from the loop, we
313 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000314 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000315 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000316
Evan Chengab631522008-12-19 18:03:11 +0000317 if (!FactorCommonPreds) {
318 /// TIPHIValues - This array is lazily computed to determine the values of
319 /// PHIs in Dest that TI would provide.
320 SmallVector<Value*, 32> TIPHIValues;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000321
Evan Chengab631522008-12-19 18:03:11 +0000322 // Check to see if Dest has any blocks that can be used as a split edge for
323 // this terminator.
324 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
325 BasicBlock *Pred = *PI;
326 // To be usable, the pred has to end with an uncond branch to the dest.
327 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000328 if (!PredBr || !PredBr->isUnconditional())
329 continue;
330 // Must be empty other than the branch and debug info.
331 BasicBlock::iterator I = Pred->begin();
332 while (isa<DbgInfoIntrinsic>(I))
333 I++;
334 if (dyn_cast<Instruction>(I) != PredBr)
335 continue;
336 // Cannot be the entry block; its label does not get emitted.
337 if (Pred == &(Dest->getParent()->getEntryBlock()))
Evan Chengab631522008-12-19 18:03:11 +0000338 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000339
Evan Chengab631522008-12-19 18:03:11 +0000340 // Finally, since we know that Dest has phi nodes in it, we have to make
Dale Johannesen6aae1d62009-03-26 01:15:07 +0000341 // sure that jumping to Pred will have the same effect as going to Dest in
Evan Chengab631522008-12-19 18:03:11 +0000342 // terms of PHI values.
343 PHINode *PN;
344 unsigned PHINo = 0;
345 bool FoundMatch = true;
346 for (BasicBlock::iterator I = Dest->begin();
347 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
348 if (PHINo == TIPHIValues.size())
349 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
Eric Christopher692bf6b2008-09-24 05:32:41 +0000350
Evan Chengab631522008-12-19 18:03:11 +0000351 // If the PHI entry doesn't work, we can't use this pred.
352 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
353 FoundMatch = false;
354 break;
355 }
356 }
357
358 // If we found a workable predecessor, change TI to branch to Succ.
359 if (FoundMatch) {
360 Dest->removePredecessor(TIBB);
361 TI->setSuccessor(SuccNum, Pred);
362 return;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000363 }
364 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000365
Evan Chengab631522008-12-19 18:03:11 +0000366 SplitCriticalEdge(TI, SuccNum, P, true);
367 return;
368 }
369
370 PHINode *PN;
371 SmallVector<Value*, 8> TIPHIValues;
372 for (BasicBlock::iterator I = Dest->begin();
373 (PN = dyn_cast<PHINode>(I)); ++I)
374 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
375
376 SmallVector<BasicBlock*, 8> IdenticalPreds;
377 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
378 BasicBlock *Pred = *PI;
379 if (BackEdges.count(std::make_pair(Pred, Dest)))
380 continue;
381 if (PI == TIBB)
382 IdenticalPreds.push_back(Pred);
383 else {
384 bool Identical = true;
385 unsigned PHINo = 0;
386 for (BasicBlock::iterator I = Dest->begin();
387 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
388 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
389 Identical = false;
390 break;
391 }
392 if (Identical)
393 IdenticalPreds.push_back(Pred);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000394 }
395 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000396
Evan Chengab631522008-12-19 18:03:11 +0000397 assert(!IdenticalPreds.empty());
398 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
399 ".critedge", P);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000400}
401
Evan Chengab631522008-12-19 18:03:11 +0000402
Chris Lattnerdd77df32007-04-13 20:30:56 +0000403/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
404/// copy (e.g. it's casting from one pointer type to another, int->uint, or
405/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000406/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000407///
408/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000409///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000410static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000411 // If this is a noop copy,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000412 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
413 MVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000414
Chris Lattnerdd77df32007-04-13 20:30:56 +0000415 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000416 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000417 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000418
Chris Lattnerdd77df32007-04-13 20:30:56 +0000419 // If this is an extension, it will be a zero or sign extension, which
420 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000421 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000422
Chris Lattnerdd77df32007-04-13 20:30:56 +0000423 // If these values will be promoted, find out what they will be promoted
424 // to. This helps us consider truncates on PPC as noop copies when they
425 // are.
426 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
427 SrcVT = TLI.getTypeToTransformTo(SrcVT);
428 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
429 DstVT = TLI.getTypeToTransformTo(DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000430
Chris Lattnerdd77df32007-04-13 20:30:56 +0000431 // If, after promotion, these are the same types, this is a noop copy.
432 if (SrcVT != DstVT)
433 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000434
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000435 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000436
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000437 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000438 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000439
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000440 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000441 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000442 UI != E; ) {
443 Use &TheUse = UI.getUse();
444 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000445
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000446 // Figure out which BB this cast is used in. For PHI's this is the
447 // appropriate predecessor block.
448 BasicBlock *UserBB = User->getParent();
449 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000450 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000451 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000452
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000453 // Preincrement use iterator so we don't invalidate it.
454 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456 // If this user is in the same block as the cast, don't change the cast.
457 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000458
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000459 // If we have already inserted a cast into this block, use it.
460 CastInst *&InsertedCast = InsertedCasts[UserBB];
461
462 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000463 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000464
465 InsertedCast =
466 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000467 InsertPt);
468 MadeChange = true;
469 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000470
Dale Johannesence0b2372007-06-12 16:50:17 +0000471 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000472 TheUse = InsertedCast;
473 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000475 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000476 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000478 MadeChange = true;
479 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000481 return MadeChange;
482}
483
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000485/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000486/// a clear win except on targets with multiple condition code registers
487/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000488///
489/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000490static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000491 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000492
Dale Johannesence0b2372007-06-12 16:50:17 +0000493 /// InsertedCmp - Only insert a cmp in each block once.
494 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000495
Dale Johannesence0b2372007-06-12 16:50:17 +0000496 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000497 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000498 UI != E; ) {
499 Use &TheUse = UI.getUse();
500 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000501
Dale Johannesence0b2372007-06-12 16:50:17 +0000502 // Preincrement use iterator so we don't invalidate it.
503 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000504
Dale Johannesence0b2372007-06-12 16:50:17 +0000505 // Don't bother for PHI nodes.
506 if (isa<PHINode>(User))
507 continue;
508
509 // Figure out which BB this cmp is used in.
510 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000511
Dale Johannesence0b2372007-06-12 16:50:17 +0000512 // If this user is in the same block as the cmp, don't change the cmp.
513 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 // If we have already inserted a cmp into this block, use it.
516 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
517
518 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000519 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000520
521 InsertedCmp =
522 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000523 CI->getOperand(1), "", InsertPt);
524 MadeChange = true;
525 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000526
Dale Johannesence0b2372007-06-12 16:50:17 +0000527 // Replace a use of the cmp with a use of the new cmp.
528 TheUse = InsertedCmp;
529 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
Dale Johannesence0b2372007-06-12 16:50:17 +0000531 // If we removed all uses, nuke the cmp.
532 if (CI->use_empty())
533 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000534
Dale Johannesence0b2372007-06-12 16:50:17 +0000535 return MadeChange;
536}
537
Chris Lattner88a5c832008-11-25 07:09:13 +0000538//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000539// Memory Optimization
540//===----------------------------------------------------------------------===//
541
Chris Lattnerdd77df32007-04-13 20:30:56 +0000542/// IsNonLocalValue - Return true if the specified values are defined in a
543/// different basic block than BB.
544static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
545 if (Instruction *I = dyn_cast<Instruction>(V))
546 return I->getParent() != BB;
547 return false;
548}
549
Chris Lattner88a5c832008-11-25 07:09:13 +0000550/// OptimizeMemoryInst - Load and Store Instructions have often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000551/// addressing modes that can do significant amounts of computation. As such,
552/// instruction selection will try to get the load or store to do as much
553/// computation as possible for the program. The problem is that isel can only
554/// see within a single block. As such, we sink as much legal addressing mode
555/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000556///
557/// This method is used to optimize both load/store and inline asms with memory
558/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000559bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000560 const Type *AccessTy,
561 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000562 // Figure out what addressing mode will be built up for this operation.
563 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000564 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
565 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000566
Chris Lattnerdd77df32007-04-13 20:30:56 +0000567 // Check to see if any of the instructions supersumed by this addr mode are
568 // non-local to I's BB.
569 bool AnyNonLocal = false;
570 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000571 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000572 AnyNonLocal = true;
573 break;
574 }
575 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000576
Chris Lattnerdd77df32007-04-13 20:30:56 +0000577 // If all the instructions matched are already in this BB, don't do anything.
578 if (!AnyNonLocal) {
579 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
580 return false;
581 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000582
Chris Lattnerdd77df32007-04-13 20:30:56 +0000583 // Insert this computation right after this user. Since our caller is
584 // scanning from the top of the BB to the bottom, reuse of the expr are
585 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000586 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000587
Chris Lattnerdd77df32007-04-13 20:30:56 +0000588 // Now that we determined the addressing expression we want to use and know
589 // that we have to sink it into this block. Check to see if we have already
590 // done this for some other load/store instr in this block. If so, reuse the
591 // computation.
592 Value *&SunkAddr = SunkAddrs[Addr];
593 if (SunkAddr) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000594 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
595 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000596 if (SunkAddr->getType() != Addr->getType())
597 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
598 } else {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000599 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
600 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000601 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000602
Chris Lattnerdd77df32007-04-13 20:30:56 +0000603 Value *Result = 0;
604 // Start with the scale value.
605 if (AddrMode.Scale) {
606 Value *V = AddrMode.ScaledReg;
607 if (V->getType() == IntPtrTy) {
608 // done.
609 } else if (isa<PointerType>(V->getType())) {
610 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
611 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
612 cast<IntegerType>(V->getType())->getBitWidth()) {
613 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
614 } else {
615 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
616 }
617 if (AddrMode.Scale != 1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000618 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Chris Lattnerdd77df32007-04-13 20:30:56 +0000619 AddrMode.Scale),
620 "sunkaddr", InsertPt);
621 Result = V;
622 }
623
624 // Add in the base register.
625 if (AddrMode.BaseReg) {
626 Value *V = AddrMode.BaseReg;
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000627 if (isa<PointerType>(V->getType()))
Chris Lattnerdd77df32007-04-13 20:30:56 +0000628 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
Dan Gohman8b0d4f62009-06-02 21:29:13 +0000629 if (V->getType() != IntPtrTy)
630 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
631 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000632 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000633 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000634 else
635 Result = V;
636 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000637
Chris Lattnerdd77df32007-04-13 20:30:56 +0000638 // Add in the BaseGV if present.
639 if (AddrMode.BaseGV) {
640 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
641 InsertPt);
642 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000643 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000644 else
645 Result = V;
646 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000647
Chris Lattnerdd77df32007-04-13 20:30:56 +0000648 // Add in the Base Offset if present.
649 if (AddrMode.BaseOffs) {
650 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
651 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000652 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000653 else
654 Result = V;
655 }
656
657 if (Result == 0)
658 SunkAddr = Constant::getNullValue(Addr->getType());
659 else
660 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
661 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000662
Chris Lattner896617b2008-11-26 03:20:37 +0000663 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000664
Chris Lattnerdd77df32007-04-13 20:30:56 +0000665 if (Addr->use_empty())
Chris Lattner3481f242008-11-27 22:57:53 +0000666 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000667 return true;
668}
669
Evan Cheng9bf12b52008-02-26 02:42:37 +0000670/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000671/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000672/// possible / profitable.
673bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
674 DenseMap<Value*,Value*> &SunkAddrs) {
675 bool MadeChange = false;
676 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
677
678 // Do a prepass over the constraints, canonicalizing them, and building up the
679 // ConstraintOperands list.
680 std::vector<InlineAsm::ConstraintInfo>
681 ConstraintInfos = IA->ParseConstraints();
682
683 /// ConstraintOperands - Information about all of the constraints.
684 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
685 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
686 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
687 ConstraintOperands.
688 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
689 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
690
691 // Compute the value type for each operand.
692 switch (OpInfo.Type) {
693 case InlineAsm::isOutput:
694 if (OpInfo.isIndirect)
695 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
696 break;
697 case InlineAsm::isInput:
698 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
699 break;
700 case InlineAsm::isClobber:
701 // Nothing to do.
702 break;
703 }
704
705 // Compute the constraint code and ConstraintType to use.
Evan Chenga7e61462008-09-24 06:48:55 +0000706 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
707 OpInfo.ConstraintType == TargetLowering::C_Memory);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000708
Eli Friedman9ec80952008-02-26 18:37:49 +0000709 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
710 OpInfo.isIndirect) {
Evan Cheng9bf12b52008-02-26 02:42:37 +0000711 Value *OpVal = OpInfo.CallOperandVal;
Chris Lattner88a5c832008-11-25 07:09:13 +0000712 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +0000713 }
714 }
715
716 return MadeChange;
717}
718
Evan Chengbdcb7262007-12-05 23:58:20 +0000719bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
720 BasicBlock *DefBB = I->getParent();
721
722 // If both result of the {s|z}xt and its source are live out, rewrite all
723 // other uses of the source with result of extension.
724 Value *Src = I->getOperand(0);
725 if (Src->hasOneUse())
726 return false;
727
Evan Cheng696e5c02007-12-13 07:50:36 +0000728 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000729 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000730 return false;
731
Evan Cheng772de512007-12-12 00:51:06 +0000732 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000733 // this block.
734 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000735 return false;
736
Evan Chengbdcb7262007-12-05 23:58:20 +0000737 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000738 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000739 UI != E; ++UI) {
740 Instruction *User = cast<Instruction>(*UI);
741
742 // Figure out which BB this ext is used in.
743 BasicBlock *UserBB = User->getParent();
744 if (UserBB == DefBB) continue;
745 DefIsLiveOut = true;
746 break;
747 }
748 if (!DefIsLiveOut)
749 return false;
750
Evan Cheng765dff22007-12-12 02:53:41 +0000751 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000752 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000753 UI != E; ++UI) {
754 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000755 BasicBlock *UserBB = User->getParent();
756 if (UserBB == DefBB) continue;
757 // Be conservative. We don't want this xform to end up introducing
758 // reloads just before load / store instructions.
759 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000760 return false;
761 }
762
Evan Chengbdcb7262007-12-05 23:58:20 +0000763 // InsertedTruncs - Only insert one trunc in each block once.
764 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
765
766 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000767 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000768 UI != E; ++UI) {
769 Use &TheUse = UI.getUse();
770 Instruction *User = cast<Instruction>(*UI);
771
772 // Figure out which BB this ext is used in.
773 BasicBlock *UserBB = User->getParent();
774 if (UserBB == DefBB) continue;
775
776 // Both src and def are live in this block. Rewrite the use.
777 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
778
779 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000780 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000781
Evan Chengbdcb7262007-12-05 23:58:20 +0000782 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
783 }
784
785 // Replace a use of the {s|z}ext source with a use of the result.
786 TheUse = InsertedTrunc;
787
788 MadeChange = true;
789 }
790
791 return MadeChange;
792}
793
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000794// In this pass we look for GEP and cast instructions that are used
795// across basic blocks and rewrite them to improve basic-block-at-a-time
796// selection.
797bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
798 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000799
Evan Chengab631522008-12-19 18:03:11 +0000800 // Split all critical edges where the dest block has a PHI.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000801 TerminatorInst *BBTI = BB.getTerminator();
802 if (BBTI->getNumSuccessors() > 1) {
Evan Chengab631522008-12-19 18:03:11 +0000803 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
804 BasicBlock *SuccBB = BBTI->getSuccessor(i);
805 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
806 SplitEdgeNicely(BBTI, i, BackEdges, this);
807 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000808 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000809
Chris Lattnerdd77df32007-04-13 20:30:56 +0000810 // Keep track of non-local addresses that have been sunk into this block.
811 // This allows us to avoid inserting duplicate code for blocks with multiple
812 // load/stores of the same address.
813 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000814
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000815 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
816 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000817
Chris Lattnerdd77df32007-04-13 20:30:56 +0000818 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000819 // If the source of the cast is a constant, then this should have
820 // already been constant folded. The only reason NOT to constant fold
821 // it is if something (e.g. LSR) was careful to place the constant
822 // evaluation in a block other than then one that uses it (e.g. to hoist
823 // the address of globals out of a loop). If this is the case, we don't
824 // want to forward-subst the cast.
825 if (isa<Constant>(CI->getOperand(0)))
826 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000827
Evan Chengbdcb7262007-12-05 23:58:20 +0000828 bool Change = false;
829 if (TLI) {
830 Change = OptimizeNoopCopyExpression(CI, *TLI);
831 MadeChange |= Change;
832 }
833
Evan Cheng55e641b2008-03-19 22:02:26 +0000834 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
Evan Chengbdcb7262007-12-05 23:58:20 +0000835 MadeChange |= OptimizeExtUses(I);
Dale Johannesence0b2372007-06-12 16:50:17 +0000836 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
837 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000838 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
839 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000840 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
841 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000842 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
843 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000844 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
845 SI->getOperand(0)->getType(),
846 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000847 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000848 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000849 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000850 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000851 GEPI->getName(), GEPI);
852 GEPI->replaceAllUsesWith(NC);
853 GEPI->eraseFromParent();
854 MadeChange = true;
855 BBI = NC;
856 }
857 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
858 // If we found an inline asm expession, and if the target knows how to
859 // lower it to normal LLVM code, do so now.
860 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
Eric Christopher692bf6b2008-09-24 05:32:41 +0000861 if (const TargetAsmInfo *TAI =
Chris Lattnerdd77df32007-04-13 20:30:56 +0000862 TLI->getTargetMachine().getTargetAsmInfo()) {
Chris Lattner65c02fb2009-02-12 06:56:08 +0000863 if (TAI->ExpandInlineAsm(CI)) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000864 BBI = BB.begin();
Chris Lattner65c02fb2009-02-12 06:56:08 +0000865 // Avoid processing instructions out of order, which could cause
866 // reuse before a value is defined.
867 SunkAddrs.clear();
868 } else
Evan Cheng9bf12b52008-02-26 02:42:37 +0000869 // Sink address computing for memory operands into the block.
870 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000871 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000872 }
873 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000874
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000875 return MadeChange;
876}