Quotes should be printed before private prefix; some code clean up.
[llvm/msp430.git] / lib / Transforms / Scalar / CodeGenPrepare.cpp
blob342b1e563d0e9c9686e718218859b2f4c44ba381
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
14 //===----------------------------------------------------------------------===//
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"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/Assembly/Writer.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
41 using namespace llvm;
42 using namespace llvm::PatternMatch;
44 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
47 namespace {
48 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;
53 /// BackEdges - Keep a set of all the loop back edges.
54 ///
55 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
56 public:
57 static char ID; // Pass identification, replacement for typeid
58 explicit CodeGenPrepare(const TargetLowering *tli = 0)
59 : FunctionPass(&ID), TLI(tli) {}
60 bool runOnFunction(Function &F);
62 private:
63 bool EliminateMostlyEmptyBlocks(Function &F);
64 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65 void EliminateMostlyEmptyBlock(BasicBlock *BB);
66 bool OptimizeBlock(BasicBlock &BB);
67 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68 DenseMap<Value*,Value*> &SunkAddrs);
69 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70 DenseMap<Value*,Value*> &SunkAddrs);
71 bool OptimizeExtUses(Instruction *I);
72 void findLoopBackEdges(const Function &F);
76 char CodeGenPrepare::ID = 0;
77 static RegisterPass<CodeGenPrepare> X("codegenprepare",
78 "Optimize for code generation");
80 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81 return new CodeGenPrepare(TLI);
84 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
85 ///
86 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
87 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
88 FindFunctionBackedges(F, Edges);
90 BackEdges.insert(Edges.begin(), Edges.end());
94 bool CodeGenPrepare::runOnFunction(Function &F) {
95 bool EverMadeChange = false;
97 // First pass, eliminate blocks that contain only PHI nodes and an
98 // unconditional branch.
99 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
101 // Now find loop back edges.
102 findLoopBackEdges(F);
104 bool MadeChange = true;
105 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;
111 return EverMadeChange;
114 /// 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.
119 bool 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++;
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;
130 // If the instruction before the branch (skipping debug info) isn't a phi
131 // node, then other stuff is happening here.
132 BasicBlock::iterator BBI = BI;
133 if (BBI != BB->begin()) {
134 --BBI;
135 while (isa<DbgInfoIntrinsic>(BBI)) {
136 if (BBI == BB->begin())
137 break;
138 --BBI;
140 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
141 continue;
144 // Do not break infinite loops.
145 BasicBlock *DestBB = BI->getSuccessor(0);
146 if (DestBB == BB)
147 continue;
149 if (!CanMergeBlocks(BB, DestBB))
150 continue;
152 EliminateMostlyEmptyBlock(BB);
153 MadeChange = true;
155 return MadeChange;
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.
161 bool 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;
173 // 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
175 // 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;
188 // 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.
194 // Collect the preds of BB.
195 SmallPtrSet<const BasicBlock*, 16> BBPreds;
196 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));
204 // 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);
213 // 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);
218 // If there is a conflict, bail out.
219 if (V1 != V2) return false;
224 return true;
228 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
229 /// an unconditional branch in it.
230 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
231 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
232 BasicBlock *DestBB = BI->getSuccessor(0);
234 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
236 // If the destination block has a single pred, then this is a trivial edge,
237 // just collapse it.
238 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
239 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);
245 if (isEntry && BB != &BB->getParent()->getEntryBlock())
246 BB->moveBefore(&BB->getParent()->getEntryBlock());
248 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
249 return;
253 // 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);
261 // 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);
282 // 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();
287 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
291 /// SplitEdgeNicely - Split the critical edge from TI to its specified
292 /// 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.
296 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
297 SmallSet<std::pair<const BasicBlock*,
298 const BasicBlock*>, 8> &BackEdges,
299 Pass *P) {
300 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!");
305 // Do not split edges to EH landing pads.
306 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
307 if (Invoke->getSuccessor(1) == Dest)
308 return;
311 // 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.
314 if (BackEdges.count(std::make_pair(TIBB, Dest)))
315 return;
317 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;
322 // 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());
328 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()))
338 continue;
340 // Finally, since we know that Dest has phi nodes in it, we have to make
341 // sure that jumping to Pred will have the same effect as going to Dest in
342 // 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));
351 // 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;
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;
366 SplitCriticalEdge(TI, SuccNum, P, true);
367 return;
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));
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;
392 if (Identical)
393 IdenticalPreds.push_back(Pred);
397 assert(!IdenticalPreds.empty());
398 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
399 ".critedge", P);
403 /// 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
406 /// registers that must be created and coalesced.
408 /// Return true if any changes are made.
410 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
411 // If this is a noop copy,
412 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
413 MVT DstVT = TLI.getValueType(CI->getType());
415 // This is an fp<->int conversion?
416 if (SrcVT.isInteger() != DstVT.isInteger())
417 return false;
419 // If this is an extension, it will be a zero or sign extension, which
420 // isn't a noop.
421 if (SrcVT.bitsLT(DstVT)) return false;
423 // 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);
431 // If, after promotion, these are the same types, this is a noop copy.
432 if (SrcVT != DstVT)
433 return false;
435 BasicBlock *DefBB = CI->getParent();
437 /// InsertedCasts - Only insert a cast in each block once.
438 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
440 bool MadeChange = false;
441 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
442 UI != E; ) {
443 Use &TheUse = UI.getUse();
444 Instruction *User = cast<Instruction>(*UI);
446 // 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)) {
450 UserBB = PN->getIncomingBlock(UI);
453 // Preincrement use iterator so we don't invalidate it.
454 ++UI;
456 // If this user is in the same block as the cast, don't change the cast.
457 if (UserBB == DefBB) continue;
459 // If we have already inserted a cast into this block, use it.
460 CastInst *&InsertedCast = InsertedCasts[UserBB];
462 if (!InsertedCast) {
463 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
465 InsertedCast =
466 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
467 InsertPt);
468 MadeChange = true;
471 // Replace a use of the cast with a use of the new cast.
472 TheUse = InsertedCast;
475 // If we removed all uses, nuke the cast.
476 if (CI->use_empty()) {
477 CI->eraseFromParent();
478 MadeChange = true;
481 return MadeChange;
484 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
485 /// the number of virtual registers that must be created and coalesced. This is
486 /// a clear win except on targets with multiple condition code registers
487 /// (PowerPC), where it might lose; some adjustment may be wanted there.
489 /// Return true if any changes are made.
490 static bool OptimizeCmpExpression(CmpInst *CI) {
491 BasicBlock *DefBB = CI->getParent();
493 /// InsertedCmp - Only insert a cmp in each block once.
494 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
496 bool MadeChange = false;
497 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
498 UI != E; ) {
499 Use &TheUse = UI.getUse();
500 Instruction *User = cast<Instruction>(*UI);
502 // Preincrement use iterator so we don't invalidate it.
503 ++UI;
505 // Don't bother for PHI nodes.
506 if (isa<PHINode>(User))
507 continue;
509 // Figure out which BB this cmp is used in.
510 BasicBlock *UserBB = User->getParent();
512 // If this user is in the same block as the cmp, don't change the cmp.
513 if (UserBB == DefBB) continue;
515 // If we have already inserted a cmp into this block, use it.
516 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
518 if (!InsertedCmp) {
519 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
521 InsertedCmp =
522 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
523 CI->getOperand(1), "", InsertPt);
524 MadeChange = true;
527 // Replace a use of the cmp with a use of the new cmp.
528 TheUse = InsertedCmp;
531 // If we removed all uses, nuke the cmp.
532 if (CI->use_empty())
533 CI->eraseFromParent();
535 return MadeChange;
538 //===----------------------------------------------------------------------===//
539 // Memory Optimization
540 //===----------------------------------------------------------------------===//
542 /// IsNonLocalValue - Return true if the specified values are defined in a
543 /// different basic block than BB.
544 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
545 if (Instruction *I = dyn_cast<Instruction>(V))
546 return I->getParent() != BB;
547 return false;
550 /// OptimizeMemoryInst - Load and Store Instructions have often have
551 /// 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.
557 /// This method is used to optimize both load/store and inline asms with memory
558 /// operands.
559 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
560 const Type *AccessTy,
561 DenseMap<Value*,Value*> &SunkAddrs) {
562 // Figure out what addressing mode will be built up for this operation.
563 SmallVector<Instruction*, 16> AddrModeInsts;
564 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
565 AddrModeInsts, *TLI);
567 // 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) {
571 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
572 AnyNonLocal = true;
573 break;
577 // 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;
583 // 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.
586 BasicBlock::iterator InsertPt = MemoryInst;
588 // 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) {
594 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
595 << *MemoryInst);
596 if (SunkAddr->getType() != Addr->getType())
597 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
598 } else {
599 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
600 << *MemoryInst);
601 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
603 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);
617 if (AddrMode.Scale != 1)
618 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
619 AddrMode.Scale),
620 "sunkaddr", InsertPt);
621 Result = V;
624 // Add in the base register.
625 if (AddrMode.BaseReg) {
626 Value *V = AddrMode.BaseReg;
627 if (V->getType() != IntPtrTy)
628 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
629 if (Result)
630 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
631 else
632 Result = V;
635 // Add in the BaseGV if present.
636 if (AddrMode.BaseGV) {
637 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
638 InsertPt);
639 if (Result)
640 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
641 else
642 Result = V;
645 // Add in the Base Offset if present.
646 if (AddrMode.BaseOffs) {
647 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
648 if (Result)
649 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
650 else
651 Result = V;
654 if (Result == 0)
655 SunkAddr = Constant::getNullValue(Addr->getType());
656 else
657 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
660 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
662 if (Addr->use_empty())
663 RecursivelyDeleteTriviallyDeadInstructions(Addr);
664 return true;
667 /// OptimizeInlineAsmInst - If there are any memory operands, use
668 /// OptimizeMemoryInst to sink their address computing into the block when
669 /// possible / profitable.
670 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
671 DenseMap<Value*,Value*> &SunkAddrs) {
672 bool MadeChange = false;
673 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
675 // Do a prepass over the constraints, canonicalizing them, and building up the
676 // ConstraintOperands list.
677 std::vector<InlineAsm::ConstraintInfo>
678 ConstraintInfos = IA->ParseConstraints();
680 /// ConstraintOperands - Information about all of the constraints.
681 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
682 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
683 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
684 ConstraintOperands.
685 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
686 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
688 // Compute the value type for each operand.
689 switch (OpInfo.Type) {
690 case InlineAsm::isOutput:
691 if (OpInfo.isIndirect)
692 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
693 break;
694 case InlineAsm::isInput:
695 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
696 break;
697 case InlineAsm::isClobber:
698 // Nothing to do.
699 break;
702 // Compute the constraint code and ConstraintType to use.
703 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
704 OpInfo.ConstraintType == TargetLowering::C_Memory);
706 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
707 OpInfo.isIndirect) {
708 Value *OpVal = OpInfo.CallOperandVal;
709 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
713 return MadeChange;
716 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
717 BasicBlock *DefBB = I->getParent();
719 // If both result of the {s|z}xt and its source are live out, rewrite all
720 // other uses of the source with result of extension.
721 Value *Src = I->getOperand(0);
722 if (Src->hasOneUse())
723 return false;
725 // Only do this xform if truncating is free.
726 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
727 return false;
729 // Only safe to perform the optimization if the source is also defined in
730 // this block.
731 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
732 return false;
734 bool DefIsLiveOut = false;
735 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
736 UI != E; ++UI) {
737 Instruction *User = cast<Instruction>(*UI);
739 // Figure out which BB this ext is used in.
740 BasicBlock *UserBB = User->getParent();
741 if (UserBB == DefBB) continue;
742 DefIsLiveOut = true;
743 break;
745 if (!DefIsLiveOut)
746 return false;
748 // Make sure non of the uses are PHI nodes.
749 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
750 UI != E; ++UI) {
751 Instruction *User = cast<Instruction>(*UI);
752 BasicBlock *UserBB = User->getParent();
753 if (UserBB == DefBB) continue;
754 // Be conservative. We don't want this xform to end up introducing
755 // reloads just before load / store instructions.
756 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
757 return false;
760 // InsertedTruncs - Only insert one trunc in each block once.
761 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
763 bool MadeChange = false;
764 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
765 UI != E; ++UI) {
766 Use &TheUse = UI.getUse();
767 Instruction *User = cast<Instruction>(*UI);
769 // Figure out which BB this ext is used in.
770 BasicBlock *UserBB = User->getParent();
771 if (UserBB == DefBB) continue;
773 // Both src and def are live in this block. Rewrite the use.
774 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
776 if (!InsertedTrunc) {
777 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
779 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
782 // Replace a use of the {s|z}ext source with a use of the result.
783 TheUse = InsertedTrunc;
785 MadeChange = true;
788 return MadeChange;
791 // In this pass we look for GEP and cast instructions that are used
792 // across basic blocks and rewrite them to improve basic-block-at-a-time
793 // selection.
794 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
795 bool MadeChange = false;
797 // Split all critical edges where the dest block has a PHI.
798 TerminatorInst *BBTI = BB.getTerminator();
799 if (BBTI->getNumSuccessors() > 1) {
800 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
801 BasicBlock *SuccBB = BBTI->getSuccessor(i);
802 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
803 SplitEdgeNicely(BBTI, i, BackEdges, this);
807 // Keep track of non-local addresses that have been sunk into this block.
808 // This allows us to avoid inserting duplicate code for blocks with multiple
809 // load/stores of the same address.
810 DenseMap<Value*, Value*> SunkAddrs;
812 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
813 Instruction *I = BBI++;
815 if (CastInst *CI = dyn_cast<CastInst>(I)) {
816 // If the source of the cast is a constant, then this should have
817 // already been constant folded. The only reason NOT to constant fold
818 // it is if something (e.g. LSR) was careful to place the constant
819 // evaluation in a block other than then one that uses it (e.g. to hoist
820 // the address of globals out of a loop). If this is the case, we don't
821 // want to forward-subst the cast.
822 if (isa<Constant>(CI->getOperand(0)))
823 continue;
825 bool Change = false;
826 if (TLI) {
827 Change = OptimizeNoopCopyExpression(CI, *TLI);
828 MadeChange |= Change;
831 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
832 MadeChange |= OptimizeExtUses(I);
833 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
834 MadeChange |= OptimizeCmpExpression(CI);
835 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
836 if (TLI)
837 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
838 SunkAddrs);
839 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
840 if (TLI)
841 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
842 SI->getOperand(0)->getType(),
843 SunkAddrs);
844 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
845 if (GEPI->hasAllZeroIndices()) {
846 /// The GEP operand must be a pointer, so must its result -> BitCast
847 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
848 GEPI->getName(), GEPI);
849 GEPI->replaceAllUsesWith(NC);
850 GEPI->eraseFromParent();
851 MadeChange = true;
852 BBI = NC;
854 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
855 // If we found an inline asm expession, and if the target knows how to
856 // lower it to normal LLVM code, do so now.
857 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
858 if (const TargetAsmInfo *TAI =
859 TLI->getTargetMachine().getTargetAsmInfo()) {
860 if (TAI->ExpandInlineAsm(CI)) {
861 BBI = BB.begin();
862 // Avoid processing instructions out of order, which could cause
863 // reuse before a value is defined.
864 SunkAddrs.clear();
865 } else
866 // Sink address computing for memory operands into the block.
867 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
872 return MadeChange;