1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/IRBuilder.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/ProfileInfo.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm::PatternMatch;
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
59 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
65 static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69 // FIXME: Remove this abomination once all of the tests pass without it!
70 static cl::opt<bool> DisableDeleteDeadBlocks(
71 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
74 static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
79 class CodeGenPrepare : public FunctionPass {
80 /// TLI - Keep a pointer of a TargetLowering to consult for determining
81 /// transformation profitability.
82 const TargetLowering *TLI;
83 const TargetLibraryInfo *TLInfo;
87 /// CurInstIterator - As we scan instructions optimizing them, this is the
88 /// next instruction to optimize. Xforms that can invalidate this should
90 BasicBlock::iterator CurInstIterator;
92 /// Keeps track of non-local addresses that have been sunk into a block.
93 /// This allows us to avoid inserting duplicate code for blocks with
94 /// multiple load/stores of the same address.
95 DenseMap<Value*, Value*> SunkAddrs;
97 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
101 /// OptSize - True if optimizing for size.
105 static char ID; // Pass identification, replacement for typeid
106 explicit CodeGenPrepare(const TargetLowering *tli = 0)
107 : FunctionPass(ID), TLI(tli) {
108 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
110 bool runOnFunction(Function &F);
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.addPreserved<DominatorTree>();
114 AU.addPreserved<ProfileInfo>();
115 AU.addRequired<TargetLibraryInfo>();
119 bool EliminateFallThrough(Function &F);
120 bool EliminateMostlyEmptyBlocks(Function &F);
121 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
122 void EliminateMostlyEmptyBlock(BasicBlock *BB);
123 bool OptimizeBlock(BasicBlock &BB);
124 bool OptimizeInst(Instruction *I);
125 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
126 bool OptimizeInlineAsmInst(CallInst *CS);
127 bool OptimizeCallInst(CallInst *CI);
128 bool MoveExtToFormExtLoad(Instruction *I);
129 bool OptimizeExtUses(Instruction *I);
130 bool OptimizeSelectInst(SelectInst *SI);
131 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
132 bool PlaceDbgValues(Function &F);
136 char CodeGenPrepare::ID = 0;
137 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
138 "Optimize for code generation", false, false)
139 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
140 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
141 "Optimize for code generation", false, false)
143 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
144 return new CodeGenPrepare(TLI);
147 bool CodeGenPrepare::runOnFunction(Function &F) {
148 bool EverMadeChange = false;
151 TLInfo = &getAnalysis<TargetLibraryInfo>();
152 DT = getAnalysisIfAvailable<DominatorTree>();
153 PFI = getAnalysisIfAvailable<ProfileInfo>();
154 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
156 // First pass, eliminate blocks that contain only PHI nodes and an
157 // unconditional branch.
158 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
160 // llvm.dbg.value is far away from the value then iSel may not be able
161 // handle it properly. iSel will drop llvm.dbg.value if it can not
162 // find a node corresponding to the value.
163 EverMadeChange |= PlaceDbgValues(F);
165 bool MadeChange = true;
168 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
169 BasicBlock *BB = I++;
170 MadeChange |= OptimizeBlock(*BB);
172 EverMadeChange |= MadeChange;
177 if (!DisableBranchOpts) {
179 SmallPtrSet<BasicBlock*, 8> WorkList;
180 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
181 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
182 MadeChange |= ConstantFoldTerminator(BB, true);
183 if (!MadeChange) continue;
185 for (SmallVectorImpl<BasicBlock*>::iterator
186 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
187 if (pred_begin(*II) == pred_end(*II))
188 WorkList.insert(*II);
191 if (!DisableDeleteDeadBlocks)
192 for (SmallPtrSet<BasicBlock*, 8>::iterator
193 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
196 // Merge pairs of basic blocks with unconditional branches, connected by
198 if (EverMadeChange || MadeChange)
199 MadeChange |= EliminateFallThrough(F);
203 EverMadeChange |= MadeChange;
206 if (ModifiedDT && DT)
207 DT->DT->recalculate(F);
209 return EverMadeChange;
212 /// EliminateFallThrough - Merge basic blocks which are connected
213 /// by a single edge, where one of the basic blocks has a single successor
214 /// pointing to the other basic block, which has a single predecessor.
215 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
216 bool Changed = false;
217 // Scan all of the blocks in the function, except for the entry block.
218 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
219 BasicBlock *BB = I++;
220 // If the destination block has a single pred, then this is a trivial
221 // edge, just collapse it.
222 BasicBlock *SinglePred = BB->getSinglePredecessor();
224 if (!SinglePred || SinglePred == BB) continue;
226 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
227 if (Term && !Term->isConditional()) {
229 // Remember if SinglePred was the entry block of the function.
230 // If so, we will need to move BB back to the entry position.
231 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
232 MergeBasicBlockIntoOnlyPred(BB, this);
234 if (isEntry && BB != &BB->getParent()->getEntryBlock())
235 BB->moveBefore(&BB->getParent()->getEntryBlock());
237 // We have erased a block. Update the iterator.
239 DEBUG(dbgs() << "Merged:\n"<< *SinglePred << "\n\n\n");
245 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
246 /// debug info directives, and an unconditional branch. Passes before isel
247 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
248 /// isel. Start by eliminating these blocks so we can split them the way we
250 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
251 bool MadeChange = false;
252 // Note that this intentionally skips the entry block.
253 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
254 BasicBlock *BB = I++;
256 // If this block doesn't end with an uncond branch, ignore it.
257 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
258 if (!BI || !BI->isUnconditional())
261 // If the instruction before the branch (skipping debug info) isn't a phi
262 // node, then other stuff is happening here.
263 BasicBlock::iterator BBI = BI;
264 if (BBI != BB->begin()) {
266 while (isa<DbgInfoIntrinsic>(BBI)) {
267 if (BBI == BB->begin())
271 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
275 // Do not break infinite loops.
276 BasicBlock *DestBB = BI->getSuccessor(0);
280 if (!CanMergeBlocks(BB, DestBB))
283 EliminateMostlyEmptyBlock(BB);
289 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
290 /// single uncond branch between them, and BB contains no other non-phi
292 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
293 const BasicBlock *DestBB) const {
294 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
295 // the successor. If there are more complex condition (e.g. preheaders),
296 // don't mess around with them.
297 BasicBlock::const_iterator BBI = BB->begin();
298 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
299 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
301 const Instruction *User = cast<Instruction>(*UI);
302 if (User->getParent() != DestBB || !isa<PHINode>(User))
304 // If User is inside DestBB block and it is a PHINode then check
305 // incoming value. If incoming value is not from BB then this is
306 // a complex condition (e.g. preheaders) we want to avoid here.
307 if (User->getParent() == DestBB) {
308 if (const PHINode *UPN = dyn_cast<PHINode>(User))
309 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
310 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
311 if (Insn && Insn->getParent() == BB &&
312 Insn->getParent() != UPN->getIncomingBlock(I))
319 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
320 // and DestBB may have conflicting incoming values for the block. If so, we
321 // can't merge the block.
322 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
323 if (!DestBBPN) return true; // no conflict.
325 // Collect the preds of BB.
326 SmallPtrSet<const BasicBlock*, 16> BBPreds;
327 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
328 // It is faster to get preds from a PHI than with pred_iterator.
329 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
330 BBPreds.insert(BBPN->getIncomingBlock(i));
332 BBPreds.insert(pred_begin(BB), pred_end(BB));
335 // Walk the preds of DestBB.
336 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
337 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
338 if (BBPreds.count(Pred)) { // Common predecessor?
339 BBI = DestBB->begin();
340 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
341 const Value *V1 = PN->getIncomingValueForBlock(Pred);
342 const Value *V2 = PN->getIncomingValueForBlock(BB);
344 // If V2 is a phi node in BB, look up what the mapped value will be.
345 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
346 if (V2PN->getParent() == BB)
347 V2 = V2PN->getIncomingValueForBlock(Pred);
349 // If there is a conflict, bail out.
350 if (V1 != V2) return false;
359 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
360 /// an unconditional branch in it.
361 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
362 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
363 BasicBlock *DestBB = BI->getSuccessor(0);
365 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
367 // If the destination block has a single pred, then this is a trivial edge,
369 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
370 if (SinglePred != DestBB) {
371 // Remember if SinglePred was the entry block of the function. If so, we
372 // will need to move BB back to the entry position.
373 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
374 MergeBasicBlockIntoOnlyPred(DestBB, this);
376 if (isEntry && BB != &BB->getParent()->getEntryBlock())
377 BB->moveBefore(&BB->getParent()->getEntryBlock());
379 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
384 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
385 // to handle the new incoming edges it is about to have.
387 for (BasicBlock::iterator BBI = DestBB->begin();
388 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
389 // Remove the incoming value for BB, and remember it.
390 Value *InVal = PN->removeIncomingValue(BB, false);
392 // Two options: either the InVal is a phi node defined in BB or it is some
393 // value that dominates BB.
394 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
395 if (InValPhi && InValPhi->getParent() == BB) {
396 // Add all of the input values of the input PHI as inputs of this phi.
397 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
398 PN->addIncoming(InValPhi->getIncomingValue(i),
399 InValPhi->getIncomingBlock(i));
401 // Otherwise, add one instance of the dominating value for each edge that
402 // we will be adding.
403 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
404 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
405 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
407 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
408 PN->addIncoming(InVal, *PI);
413 // The PHIs are now updated, change everything that refers to BB to use
414 // DestBB and remove BB.
415 BB->replaceAllUsesWith(DestBB);
416 if (DT && !ModifiedDT) {
417 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
418 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
419 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
420 DT->changeImmediateDominator(DestBB, NewIDom);
424 PFI->replaceAllUses(BB, DestBB);
425 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
427 BB->eraseFromParent();
430 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
433 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
434 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
435 /// sink it into user blocks to reduce the number of virtual
436 /// registers that must be created and coalesced.
438 /// Return true if any changes are made.
440 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
441 // If this is a noop copy,
442 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
443 EVT DstVT = TLI.getValueType(CI->getType());
445 // This is an fp<->int conversion?
446 if (SrcVT.isInteger() != DstVT.isInteger())
449 // If this is an extension, it will be a zero or sign extension, which
451 if (SrcVT.bitsLT(DstVT)) return false;
453 // If these values will be promoted, find out what they will be promoted
454 // to. This helps us consider truncates on PPC as noop copies when they
456 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
457 TargetLowering::TypePromoteInteger)
458 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
459 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
460 TargetLowering::TypePromoteInteger)
461 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
463 // If, after promotion, these are the same types, this is a noop copy.
467 BasicBlock *DefBB = CI->getParent();
469 /// InsertedCasts - Only insert a cast in each block once.
470 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
472 bool MadeChange = false;
473 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
475 Use &TheUse = UI.getUse();
476 Instruction *User = cast<Instruction>(*UI);
478 // Figure out which BB this cast is used in. For PHI's this is the
479 // appropriate predecessor block.
480 BasicBlock *UserBB = User->getParent();
481 if (PHINode *PN = dyn_cast<PHINode>(User)) {
482 UserBB = PN->getIncomingBlock(UI);
485 // Preincrement use iterator so we don't invalidate it.
488 // If this user is in the same block as the cast, don't change the cast.
489 if (UserBB == DefBB) continue;
491 // If we have already inserted a cast into this block, use it.
492 CastInst *&InsertedCast = InsertedCasts[UserBB];
495 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
497 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
502 // Replace a use of the cast with a use of the new cast.
503 TheUse = InsertedCast;
507 // If we removed all uses, nuke the cast.
508 if (CI->use_empty()) {
509 CI->eraseFromParent();
516 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
517 /// the number of virtual registers that must be created and coalesced. This is
518 /// a clear win except on targets with multiple condition code registers
519 /// (PowerPC), where it might lose; some adjustment may be wanted there.
521 /// Return true if any changes are made.
522 static bool OptimizeCmpExpression(CmpInst *CI) {
523 BasicBlock *DefBB = CI->getParent();
525 /// InsertedCmp - Only insert a cmp in each block once.
526 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
528 bool MadeChange = false;
529 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
531 Use &TheUse = UI.getUse();
532 Instruction *User = cast<Instruction>(*UI);
534 // Preincrement use iterator so we don't invalidate it.
537 // Don't bother for PHI nodes.
538 if (isa<PHINode>(User))
541 // Figure out which BB this cmp is used in.
542 BasicBlock *UserBB = User->getParent();
544 // If this user is in the same block as the cmp, don't change the cmp.
545 if (UserBB == DefBB) continue;
547 // If we have already inserted a cmp into this block, use it.
548 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
551 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
553 CmpInst::Create(CI->getOpcode(),
554 CI->getPredicate(), CI->getOperand(0),
555 CI->getOperand(1), "", InsertPt);
559 // Replace a use of the cmp with a use of the new cmp.
560 TheUse = InsertedCmp;
564 // If we removed all uses, nuke the cmp.
566 CI->eraseFromParent();
572 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
574 void replaceCall(Value *With) {
575 CI->replaceAllUsesWith(With);
576 CI->eraseFromParent();
578 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
579 if (ConstantInt *SizeCI =
580 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
581 return SizeCI->isAllOnesValue();
585 } // end anonymous namespace
587 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
588 BasicBlock *BB = CI->getParent();
590 // Lower inline assembly if we can.
591 // If we found an inline asm expession, and if the target knows how to
592 // lower it to normal LLVM code, do so now.
593 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
594 if (TLI->ExpandInlineAsm(CI)) {
595 // Avoid invalidating the iterator.
596 CurInstIterator = BB->begin();
597 // Avoid processing instructions out of order, which could cause
598 // reuse before a value is defined.
602 // Sink address computing for memory operands into the block.
603 if (OptimizeInlineAsmInst(CI))
607 // Lower all uses of llvm.objectsize.*
608 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
609 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
610 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
611 Type *ReturnTy = CI->getType();
612 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
614 // Substituting this can cause recursive simplifications, which can
615 // invalidate our iterator. Use a WeakVH to hold onto it in case this
617 WeakVH IterHandle(CurInstIterator);
619 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
620 TLInfo, ModifiedDT ? 0 : DT);
622 // If the iterator instruction was recursively deleted, start over at the
623 // start of the block.
624 if (IterHandle != CurInstIterator) {
625 CurInstIterator = BB->begin();
632 SmallVector<Value*, 2> PtrOps;
634 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
635 while (!PtrOps.empty())
636 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
640 // From here on out we're working with named functions.
641 if (CI->getCalledFunction() == 0) return false;
643 // We'll need TargetData from here on out.
644 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
645 if (!TD) return false;
647 // Lower all default uses of _chk calls. This is very similar
648 // to what InstCombineCalls does, but here we are only lowering calls
649 // that have the default "don't know" as the objectsize. Anything else
650 // should be left alone.
651 CodeGenPrepareFortifiedLibCalls Simplifier;
652 return Simplifier.fold(CI, TD, TLInfo);
655 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
656 /// instructions to the predecessor to enable tail call optimizations. The
657 /// case it is currently looking for is:
659 /// %tmp0 = tail call i32 @f0()
662 /// %tmp1 = tail call i32 @f1()
665 /// %tmp2 = tail call i32 @f2()
668 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
674 /// %tmp0 = tail call i32 @f0()
677 /// %tmp1 = tail call i32 @f1()
680 /// %tmp2 = tail call i32 @f2()
683 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
688 BitCastInst *BCI = 0;
689 Value *V = RI->getReturnValue();
691 BCI = dyn_cast<BitCastInst>(V);
693 V = BCI->getOperand(0);
695 PN = dyn_cast<PHINode>(V);
700 BasicBlock *BB = RI->getParent();
701 if (PN && PN->getParent() != BB)
704 // It's not safe to eliminate the sign / zero extension of the return value.
705 // See llvm::isInTailCallPosition().
706 const Function *F = BB->getParent();
707 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
708 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
711 // Make sure there are no instructions between the PHI and return, or that the
712 // return is the first instruction in the block.
714 BasicBlock::iterator BI = BB->begin();
715 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
717 // Also skip over the bitcast.
722 BasicBlock::iterator BI = BB->begin();
723 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
728 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
730 SmallVector<CallInst*, 4> TailCalls;
732 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
733 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
734 // Make sure the phi value is indeed produced by the tail call.
735 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
736 TLI->mayBeEmittedAsTailCall(CI))
737 TailCalls.push_back(CI);
740 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
741 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
742 if (!VisitedBBs.insert(*PI))
745 BasicBlock::InstListType &InstList = (*PI)->getInstList();
746 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
747 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
748 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
752 CallInst *CI = dyn_cast<CallInst>(&*RI);
753 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
754 TailCalls.push_back(CI);
758 bool Changed = false;
759 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
760 CallInst *CI = TailCalls[i];
763 // Conservatively require the attributes of the call to match those of the
764 // return. Ignore noalias because it doesn't affect the call sequence.
765 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
766 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
769 // Make sure the call instruction is followed by an unconditional branch to
771 BasicBlock *CallBB = CI->getParent();
772 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
773 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
776 // Duplicate the return into CallBB.
777 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
778 ModifiedDT = Changed = true;
782 // If we eliminated all predecessors of the block, delete the block now.
783 if (Changed && pred_begin(BB) == pred_end(BB))
784 BB->eraseFromParent();
789 //===----------------------------------------------------------------------===//
790 // Memory Optimization
791 //===----------------------------------------------------------------------===//
793 /// IsNonLocalValue - Return true if the specified values are defined in a
794 /// different basic block than BB.
795 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
796 if (Instruction *I = dyn_cast<Instruction>(V))
797 return I->getParent() != BB;
801 /// OptimizeMemoryInst - Load and Store Instructions often have
802 /// addressing modes that can do significant amounts of computation. As such,
803 /// instruction selection will try to get the load or store to do as much
804 /// computation as possible for the program. The problem is that isel can only
805 /// see within a single block. As such, we sink as much legal addressing mode
806 /// stuff into the block as possible.
808 /// This method is used to optimize both load/store and inline asms with memory
810 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
814 // Try to collapse single-value PHI nodes. This is necessary to undo
815 // unprofitable PRE transformations.
816 SmallVector<Value*, 8> worklist;
817 SmallPtrSet<Value*, 16> Visited;
818 worklist.push_back(Addr);
820 // Use a worklist to iteratively look through PHI nodes, and ensure that
821 // the addressing mode obtained from the non-PHI roots of the graph
823 Value *Consensus = 0;
824 unsigned NumUsesConsensus = 0;
825 bool IsNumUsesConsensusValid = false;
826 SmallVector<Instruction*, 16> AddrModeInsts;
827 ExtAddrMode AddrMode;
828 while (!worklist.empty()) {
829 Value *V = worklist.back();
832 // Break use-def graph loops.
833 if (!Visited.insert(V)) {
838 // For a PHI node, push all of its incoming values.
839 if (PHINode *P = dyn_cast<PHINode>(V)) {
840 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
841 worklist.push_back(P->getIncomingValue(i));
845 // For non-PHIs, determine the addressing mode being computed.
846 SmallVector<Instruction*, 16> NewAddrModeInsts;
847 ExtAddrMode NewAddrMode =
848 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
849 NewAddrModeInsts, *TLI);
851 // This check is broken into two cases with very similar code to avoid using
852 // getNumUses() as much as possible. Some values have a lot of uses, so
853 // calling getNumUses() unconditionally caused a significant compile-time
857 AddrMode = NewAddrMode;
858 AddrModeInsts = NewAddrModeInsts;
860 } else if (NewAddrMode == AddrMode) {
861 if (!IsNumUsesConsensusValid) {
862 NumUsesConsensus = Consensus->getNumUses();
863 IsNumUsesConsensusValid = true;
866 // Ensure that the obtained addressing mode is equivalent to that obtained
867 // for all other roots of the PHI traversal. Also, when choosing one
868 // such root as representative, select the one with the most uses in order
869 // to keep the cost modeling heuristics in AddressingModeMatcher
871 unsigned NumUses = V->getNumUses();
872 if (NumUses > NumUsesConsensus) {
874 NumUsesConsensus = NumUses;
875 AddrModeInsts = NewAddrModeInsts;
884 // If the addressing mode couldn't be determined, or if multiple different
885 // ones were determined, bail out now.
886 if (!Consensus) return false;
888 // Check to see if any of the instructions supersumed by this addr mode are
889 // non-local to I's BB.
890 bool AnyNonLocal = false;
891 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
892 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
898 // If all the instructions matched are already in this BB, don't do anything.
900 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
904 // Insert this computation right after this user. Since our caller is
905 // scanning from the top of the BB to the bottom, reuse of the expr are
906 // guaranteed to happen later.
907 IRBuilder<> Builder(MemoryInst);
909 // Now that we determined the addressing expression we want to use and know
910 // that we have to sink it into this block. Check to see if we have already
911 // done this for some other load/store instr in this block. If so, reuse the
913 Value *&SunkAddr = SunkAddrs[Addr];
915 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
917 if (SunkAddr->getType() != Addr->getType())
918 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
920 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
923 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
927 // Start with the base register. Do this first so that subsequent address
928 // matching finds it last, which will prevent it from trying to match it
929 // as the scaled value in case it happens to be a mul. That would be
930 // problematic if we've sunk a different mul for the scale, because then
931 // we'd end up sinking both muls.
932 if (AddrMode.BaseReg) {
933 Value *V = AddrMode.BaseReg;
934 if (V->getType()->isPointerTy())
935 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
936 if (V->getType() != IntPtrTy)
937 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
941 // Add the scale value.
942 if (AddrMode.Scale) {
943 Value *V = AddrMode.ScaledReg;
944 if (V->getType() == IntPtrTy) {
946 } else if (V->getType()->isPointerTy()) {
947 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
948 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
949 cast<IntegerType>(V->getType())->getBitWidth()) {
950 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
952 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
954 if (AddrMode.Scale != 1)
955 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
958 Result = Builder.CreateAdd(Result, V, "sunkaddr");
963 // Add in the BaseGV if present.
964 if (AddrMode.BaseGV) {
965 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
967 Result = Builder.CreateAdd(Result, V, "sunkaddr");
972 // Add in the Base Offset if present.
973 if (AddrMode.BaseOffs) {
974 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
976 Result = Builder.CreateAdd(Result, V, "sunkaddr");
982 SunkAddr = Constant::getNullValue(Addr->getType());
984 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
987 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
989 // If we have no uses, recursively delete the value and all dead instructions
991 if (Repl->use_empty()) {
992 // This can cause recursive deletion, which can invalidate our iterator.
993 // Use a WeakVH to hold onto it in case this happens.
994 WeakVH IterHandle(CurInstIterator);
995 BasicBlock *BB = CurInstIterator->getParent();
997 RecursivelyDeleteTriviallyDeadInstructions(Repl);
999 if (IterHandle != CurInstIterator) {
1000 // If the iterator instruction was recursively deleted, start over at the
1001 // start of the block.
1002 CurInstIterator = BB->begin();
1005 // This address is now available for reassignment, so erase the table
1006 // entry; we don't want to match some completely different instruction.
1007 SunkAddrs[Addr] = 0;
1014 /// OptimizeInlineAsmInst - If there are any memory operands, use
1015 /// OptimizeMemoryInst to sink their address computing into the block when
1016 /// possible / profitable.
1017 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1018 bool MadeChange = false;
1020 TargetLowering::AsmOperandInfoVector
1021 TargetConstraints = TLI->ParseConstraints(CS);
1023 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1024 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1026 // Compute the constraint code and ConstraintType to use.
1027 TLI->ComputeConstraintToUse(OpInfo, SDValue());
1029 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1030 OpInfo.isIndirect) {
1031 Value *OpVal = CS->getArgOperand(ArgNo++);
1032 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1033 } else if (OpInfo.Type == InlineAsm::isInput)
1040 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1041 /// basic block as the load, unless conditions are unfavorable. This allows
1042 /// SelectionDAG to fold the extend into the load.
1044 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1045 // Look for a load being extended.
1046 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1047 if (!LI) return false;
1049 // If they're already in the same block, there's nothing to do.
1050 if (LI->getParent() == I->getParent())
1053 // If the load has other users and the truncate is not free, this probably
1054 // isn't worthwhile.
1055 if (!LI->hasOneUse() &&
1056 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1057 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1058 !TLI->isTruncateFree(I->getType(), LI->getType()))
1061 // Check whether the target supports casts folded into loads.
1063 if (isa<ZExtInst>(I))
1064 LType = ISD::ZEXTLOAD;
1066 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1067 LType = ISD::SEXTLOAD;
1069 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1072 // Move the extend into the same block as the load, so that SelectionDAG
1074 I->removeFromParent();
1080 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1081 BasicBlock *DefBB = I->getParent();
1083 // If the result of a {s|z}ext and its source are both live out, rewrite all
1084 // other uses of the source with result of extension.
1085 Value *Src = I->getOperand(0);
1086 if (Src->hasOneUse())
1089 // Only do this xform if truncating is free.
1090 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1093 // Only safe to perform the optimization if the source is also defined in
1095 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1098 bool DefIsLiveOut = false;
1099 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1101 Instruction *User = cast<Instruction>(*UI);
1103 // Figure out which BB this ext is used in.
1104 BasicBlock *UserBB = User->getParent();
1105 if (UserBB == DefBB) continue;
1106 DefIsLiveOut = true;
1112 // Make sure non of the uses are PHI nodes.
1113 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1115 Instruction *User = cast<Instruction>(*UI);
1116 BasicBlock *UserBB = User->getParent();
1117 if (UserBB == DefBB) continue;
1118 // Be conservative. We don't want this xform to end up introducing
1119 // reloads just before load / store instructions.
1120 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1124 // InsertedTruncs - Only insert one trunc in each block once.
1125 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1127 bool MadeChange = false;
1128 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1130 Use &TheUse = UI.getUse();
1131 Instruction *User = cast<Instruction>(*UI);
1133 // Figure out which BB this ext is used in.
1134 BasicBlock *UserBB = User->getParent();
1135 if (UserBB == DefBB) continue;
1137 // Both src and def are live in this block. Rewrite the use.
1138 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1140 if (!InsertedTrunc) {
1141 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1142 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1145 // Replace a use of the {s|z}ext source with a use of the result.
1146 TheUse = InsertedTrunc;
1154 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1155 /// turned into an explicit branch.
1156 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1157 // FIXME: This should use the same heuristics as IfConversion to determine
1158 // whether a select is better represented as a branch. This requires that
1159 // branch probability metadata is preserved for the select, which is not the
1162 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1164 // If the branch is predicted right, an out of order CPU can avoid blocking on
1165 // the compare. Emit cmovs on compares with a memory operand as branches to
1166 // avoid stalls on the load from memory. If the compare has more than one use
1167 // there's probably another cmov or setcc around so it's not worth emitting a
1172 Value *CmpOp0 = Cmp->getOperand(0);
1173 Value *CmpOp1 = Cmp->getOperand(1);
1175 // We check that the memory operand has one use to avoid uses of the loaded
1176 // value directly after the compare, making branches unprofitable.
1177 return Cmp->hasOneUse() &&
1178 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1179 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1183 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1184 // If we have a SelectInst that will likely profit from branch prediction,
1185 // turn it into a branch.
1186 if (DisableSelectToBranch || OptSize || !TLI ||
1187 !TLI->isPredictableSelectExpensive())
1190 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1191 !isFormingBranchFromSelectProfitable(SI))
1196 // First, we split the block containing the select into 2 blocks.
1197 BasicBlock *StartBlock = SI->getParent();
1198 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1199 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1201 // Create a new block serving as the landing pad for the branch.
1202 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1203 NextBlock->getParent(), NextBlock);
1205 // Move the unconditional branch from the block with the select in it into our
1206 // landing pad block.
1207 StartBlock->getTerminator()->eraseFromParent();
1208 BranchInst::Create(NextBlock, SmallBlock);
1210 // Insert the real conditional branch based on the original condition.
1211 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1213 // The select itself is replaced with a PHI Node.
1214 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1216 PN->addIncoming(SI->getTrueValue(), StartBlock);
1217 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1218 SI->replaceAllUsesWith(PN);
1219 SI->eraseFromParent();
1221 // Instruct OptimizeBlock to skip to the next block.
1222 CurInstIterator = StartBlock->end();
1223 ++NumSelectsExpanded;
1227 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1228 if (PHINode *P = dyn_cast<PHINode>(I)) {
1229 // It is possible for very late stage optimizations (such as SimplifyCFG)
1230 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1231 // trivial PHI, go ahead and zap it here.
1232 if (Value *V = SimplifyInstruction(P)) {
1233 P->replaceAllUsesWith(V);
1234 P->eraseFromParent();
1241 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1242 // If the source of the cast is a constant, then this should have
1243 // already been constant folded. The only reason NOT to constant fold
1244 // it is if something (e.g. LSR) was careful to place the constant
1245 // evaluation in a block other than then one that uses it (e.g. to hoist
1246 // the address of globals out of a loop). If this is the case, we don't
1247 // want to forward-subst the cast.
1248 if (isa<Constant>(CI->getOperand(0)))
1251 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1254 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1255 bool MadeChange = MoveExtToFormExtLoad(I);
1256 return MadeChange | OptimizeExtUses(I);
1261 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1262 return OptimizeCmpExpression(CI);
1264 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1266 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1270 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1272 return OptimizeMemoryInst(I, SI->getOperand(1),
1273 SI->getOperand(0)->getType());
1277 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1278 if (GEPI->hasAllZeroIndices()) {
1279 /// The GEP operand must be a pointer, so must its result -> BitCast
1280 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1281 GEPI->getName(), GEPI);
1282 GEPI->replaceAllUsesWith(NC);
1283 GEPI->eraseFromParent();
1291 if (CallInst *CI = dyn_cast<CallInst>(I))
1292 return OptimizeCallInst(CI);
1294 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1295 return DupRetToEnableTailCallOpts(RI);
1297 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1298 return OptimizeSelectInst(SI);
1303 // In this pass we look for GEP and cast instructions that are used
1304 // across basic blocks and rewrite them to improve basic-block-at-a-time
1306 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1308 bool MadeChange = false;
1310 CurInstIterator = BB.begin();
1311 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1312 MadeChange |= OptimizeInst(CurInstIterator++);
1317 // llvm.dbg.value is far away from the value then iSel may not be able
1318 // handle it properly. iSel will drop llvm.dbg.value if it can not
1319 // find a node corresponding to the value.
1320 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1321 bool MadeChange = false;
1322 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1323 Instruction *PrevNonDbgInst = NULL;
1324 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1325 Instruction *Insn = BI; ++BI;
1326 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1328 PrevNonDbgInst = Insn;
1332 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1333 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1334 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1335 DVI->removeFromParent();
1336 if (isa<PHINode>(VI))
1337 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1339 DVI->insertAfter(VI);