Implement splitting of PHI nodes, allowing block extraction of BB's that have
[oota-llvm.git] / lib / Transforms / Utils / CodeExtractor.cpp
1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interface to tear out a code region, such as an
11 // individual loop or a parallel section, into a new function, replacing it with
12 // a call to the new function.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Utils/FunctionUtils.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/Verifier.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
27 #include "Support/CommandLine.h"
28 #include "Support/Debug.h"
29 #include "Support/StringExtras.h"
30 #include <algorithm>
31 #include <set>
32 using namespace llvm;
33
34 // Provide a command-line option to aggregate function arguments into a struct
35 // for functions produced by the code extrator. This is useful when converting
36 // extracted functions to pthread-based code, as only one argument (void*) can
37 // be passed in to pthread_create().
38 static cl::opt<bool>
39 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
40                  cl::desc("Aggregate arguments to code-extracted functions"));
41
42 namespace {
43   class CodeExtractor {
44     typedef std::vector<Value*> Values;
45     std::set<BasicBlock*> BlocksToExtract;
46     DominatorSet *DS;
47     bool AggregateArgs;
48     unsigned NumExitBlocks;
49     const Type *RetTy;
50   public:
51     CodeExtractor(DominatorSet *ds = 0, bool AggArgs = false)
52       : DS(ds), AggregateArgs(AggregateArgsOpt), NumExitBlocks(~0U) {}
53
54     Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
55
56     bool isEligible(const std::vector<BasicBlock*> &code);
57
58   private:
59     /// definedInRegion - Return true if the specified value is defined in the
60     /// extracted region.
61     bool definedInRegion(Value *V) const {
62       if (Instruction *I = dyn_cast<Instruction>(V))
63         if (BlocksToExtract.count(I->getParent()))
64           return true;
65       return false;
66     }
67     
68     /// definedInCaller - Return true if the specified value is defined in the
69     /// function being code extracted, but not in the region being extracted.
70     /// These values must be passed in as live-ins to the function.
71     bool definedInCaller(Value *V) const {
72       if (isa<Argument>(V)) return true;
73       if (Instruction *I = dyn_cast<Instruction>(V))
74         if (!BlocksToExtract.count(I->getParent()))
75           return true;
76       return false;
77     }
78
79     void severSplitPHINodes(BasicBlock *&Header);
80     void findInputsOutputs(Values &inputs, Values &outputs);
81
82     Function *constructFunction(const Values &inputs,
83                                 const Values &outputs,
84                                 BasicBlock *header,
85                                 BasicBlock *newRootNode, BasicBlock *newHeader,
86                                 Function *oldFunction, Module *M);
87
88     void moveCodeToFunction(Function *newFunction);
89
90     void emitCallAndSwitchStatement(Function *newFunction,
91                                     BasicBlock *newHeader,
92                                     Values &inputs,
93                                     Values &outputs);
94
95   };
96 }
97
98 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
99 /// region, we need to split the entry block of the region so that the PHI node
100 /// is easier to deal with.
101 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
102   bool HasPredsFromRegion = false;
103   unsigned NumPredsOutsideRegion = 0;
104
105   if (Header != &Header->getParent()->front()) {
106     PHINode *PN = dyn_cast<PHINode>(Header->begin());
107     if (!PN) return;  // No PHI nodes.
108
109     // If the header node contains any PHI nodes, check to see if there is more
110     // than one entry from outside the region.  If so, we need to sever the
111     // header block into two.
112     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
113       if (BlocksToExtract.count(PN->getIncomingBlock(i)))
114         HasPredsFromRegion = true;
115       else
116         ++NumPredsOutsideRegion;
117
118     // If there is one (or fewer) predecessor from outside the region, we don't
119     // need to do anything special.
120     if (NumPredsOutsideRegion <= 1) return;
121   }
122
123   // Otherwise, we need to split the header block into two pieces: one
124   // containing PHI nodes merging values from outside of the region, and a
125   // second that contains all of the code for the block and merges back any
126   // incoming values from inside of the region.
127   BasicBlock::iterator AfterPHIs = Header->begin();
128   while (isa<PHINode>(AfterPHIs)) ++AfterPHIs;
129   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
130                                               Header->getName()+".ce");
131
132   // We only want to code extract the second block now, and it becomes the new
133   // header of the region.
134   BasicBlock *OldPred = Header;
135   BlocksToExtract.erase(OldPred);
136   BlocksToExtract.insert(NewBB);
137   Header = NewBB;
138
139   // Okay, update dominator sets. The blocks that dominate the new one are the
140   // blocks that dominate TIBB plus the new block itself.
141   if (DS) {
142     DominatorSet::DomSetType DomSet = DS->getDominators(OldPred);
143     DomSet.insert(NewBB);  // A block always dominates itself.
144     DS->addBasicBlock(NewBB, DomSet);
145
146     // Additionally, NewBB dominates all blocks in the function that are
147     // dominated by OldPred.
148     Function *F = Header->getParent();
149     for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
150       if (DS->properlyDominates(OldPred, I))
151         DS->addDominator(I, NewBB);
152   }
153
154   // Okay, now we need to adjust the PHI nodes and any branches from within the
155   // region to go to the new header block instead of the old header block.
156   if (HasPredsFromRegion) {
157     PHINode *PN = cast<PHINode>(OldPred->begin());
158     // Loop over all of the predecessors of OldPred that are in the region,
159     // changing them to branch to NewBB instead.
160     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
161       if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
162         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
163         TI->replaceUsesOfWith(OldPred, NewBB);
164       }
165
166     // Okay, everthing within the region is now branching to the right block, we
167     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
168     for (AfterPHIs = OldPred->begin();
169          PHINode *PN = dyn_cast<PHINode>(AfterPHIs); ++AfterPHIs) {
170       // Create a new PHI node in the new region, which has an incoming value
171       // from OldPred of PN.
172       PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".ce",
173                                    NewBB->begin());
174       NewPN->addIncoming(PN, OldPred);
175
176       // Loop over all of the incoming value in PN, moving them to NewPN if they
177       // are from the extracted region.
178       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
179         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
180           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
181           PN->removeIncomingValue(i);
182           --i;
183         }
184       }
185     }
186   }
187
188   verifyFunction(*NewBB->getParent());
189 }
190
191 // findInputsOutputs - Find inputs to, outputs from the code region.
192 //
193 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
194   std::set<BasicBlock*> ExitBlocks;
195   for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(), 
196        ce = BlocksToExtract.end(); ci != ce; ++ci) {
197     BasicBlock *BB = *ci;
198
199     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
200       // If a used value is defined outside the region, it's an input.  If an
201       // instruction is used outside the region, it's an output.
202       for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
203         if (definedInCaller(*O))
204           inputs.push_back(*O);
205       
206       // Consider uses of this instruction (outputs).
207       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
208            UI != E; ++UI)
209         if (!definedInRegion(*UI)) {
210           outputs.push_back(I);
211           break;
212         }
213     } // for: insts
214
215     // Keep track of the exit blocks from the region.
216     TerminatorInst *TI = BB->getTerminator();
217     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
218       if (!BlocksToExtract.count(TI->getSuccessor(i)))
219         ExitBlocks.insert(TI->getSuccessor(i));
220   } // for: basic blocks
221
222   NumExitBlocks = ExitBlocks.size();
223 }
224
225 /// constructFunction - make a function based on inputs and outputs, as follows:
226 /// f(in0, ..., inN, out0, ..., outN)
227 ///
228 Function *CodeExtractor::constructFunction(const Values &inputs,
229                                            const Values &outputs,
230                                            BasicBlock *header,
231                                            BasicBlock *newRootNode,
232                                            BasicBlock *newHeader,
233                                            Function *oldFunction,
234                                            Module *M) {
235   DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
236   DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
237
238   // This function returns unsigned, outputs will go back by reference.
239   switch (NumExitBlocks) {
240   case 0:
241   case 1: RetTy = Type::VoidTy; break;
242   case 2: RetTy = Type::BoolTy; break;
243   default: RetTy = Type::UShortTy; break;
244   }
245
246   std::vector<const Type*> paramTy;
247
248   // Add the types of the input values to the function's argument list
249   for (Values::const_iterator i = inputs.begin(),
250          e = inputs.end(); i != e; ++i) {
251     const Value *value = *i;
252     DEBUG(std::cerr << "value used in func: " << value << "\n");
253     paramTy.push_back(value->getType());
254   }
255
256   // Add the types of the output values to the function's argument list.
257   for (Values::const_iterator I = outputs.begin(), E = outputs.end();
258        I != E; ++I) {
259     DEBUG(std::cerr << "instr used in func: " << *I << "\n");
260     if (AggregateArgs)
261       paramTy.push_back((*I)->getType());
262     else
263       paramTy.push_back(PointerType::get((*I)->getType()));
264   }
265
266   DEBUG(std::cerr << "Function type: " << RetTy << " f(");
267   DEBUG(for (std::vector<const Type*>::iterator i = paramTy.begin(),
268                e = paramTy.end(); i != e; ++i) std::cerr << *i << ", ");
269   DEBUG(std::cerr << ")\n");
270
271   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
272     PointerType *StructPtr = PointerType::get(StructType::get(paramTy));
273     paramTy.clear();
274     paramTy.push_back(StructPtr);
275   }
276   const FunctionType *funcType = FunctionType::get(RetTy, paramTy, false);
277
278   // Create the new function
279   Function *newFunction = new Function(funcType,
280                                        GlobalValue::InternalLinkage,
281                                        oldFunction->getName() + "_code", M);
282   newFunction->getBasicBlockList().push_back(newRootNode);
283
284   // Create an iterator to name all of the arguments we inserted.
285   Function::aiterator AI = newFunction->abegin();
286
287   // Rewrite all users of the inputs in the extracted region to use the
288   // arguments (or appropriate addressing into struct) instead.
289   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
290     Value *RewriteVal;
291     if (AggregateArgs) {
292       std::vector<Value*> Indices;
293       Indices.push_back(Constant::getNullValue(Type::UIntTy));
294       Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
295       std::string GEPname = "gep_" + inputs[i]->getName();
296       TerminatorInst *TI = newFunction->begin()->getTerminator();
297       GetElementPtrInst *GEP = new GetElementPtrInst(AI, Indices, GEPname, TI);
298       RewriteVal = new LoadInst(GEP, "load" + GEPname, TI);
299     } else
300       RewriteVal = AI++;
301
302     std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
303     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
304          use != useE; ++use)
305       if (Instruction* inst = dyn_cast<Instruction>(*use))
306         if (BlocksToExtract.count(inst->getParent()))
307           inst->replaceUsesOfWith(inputs[i], RewriteVal);
308   }
309
310   // Set names for input and output arguments.
311   if (!AggregateArgs) {
312     AI = newFunction->abegin();
313     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
314       AI->setName(inputs[i]->getName());
315     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
316       AI->setName(outputs[i]->getName()+".out");  
317   }
318
319   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
320   // within the new function. This must be done before we lose track of which
321   // blocks were originally in the code region.
322   std::vector<User*> Users(header->use_begin(), header->use_end());
323   for (unsigned i = 0, e = Users.size(); i != e; ++i)
324     // The BasicBlock which contains the branch is not in the region
325     // modify the branch target to a new block
326     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
327       if (!BlocksToExtract.count(TI->getParent()) &&
328           TI->getParent()->getParent() == oldFunction)
329         TI->replaceUsesOfWith(header, newHeader);
330
331   return newFunction;
332 }
333
334 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
335 /// the call instruction, splitting any PHI nodes in the header block as
336 /// necessary.
337 void CodeExtractor::
338 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
339                            Values &inputs, Values &outputs) {
340   // Emit a call to the new function, passing in: *pointer to struct (if
341   // aggregating parameters), or plan inputs and allocated memory for outputs
342   std::vector<Value*> params, StructValues, ReloadOutputs;
343
344   // Add inputs as params, or to be filled into the struct
345   for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
346     if (AggregateArgs)
347       StructValues.push_back(*i);
348     else
349       params.push_back(*i);
350
351   // Create allocas for the outputs
352   for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
353     if (AggregateArgs) {
354       StructValues.push_back(*i);
355     } else {
356       AllocaInst *alloca =
357         new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
358                        codeReplacer->getParent()->begin()->begin());
359       ReloadOutputs.push_back(alloca);
360       params.push_back(alloca);
361     }
362   }
363
364   AllocaInst *Struct = 0;
365   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
366     std::vector<const Type*> ArgTypes;
367     for (Values::iterator v = StructValues.begin(),
368            ve = StructValues.end(); v != ve; ++v)
369       ArgTypes.push_back((*v)->getType());
370
371     // Allocate a struct at the beginning of this function
372     Type *StructArgTy = StructType::get(ArgTypes);
373     Struct = 
374       new AllocaInst(StructArgTy, 0, "structArg", 
375                      codeReplacer->getParent()->begin()->begin());
376     params.push_back(Struct);
377
378     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
379       std::vector<Value*> Indices;
380       Indices.push_back(Constant::getNullValue(Type::UIntTy));
381       Indices.push_back(ConstantUInt::get(Type::UIntTy, i));
382       GetElementPtrInst *GEP =
383         new GetElementPtrInst(Struct, Indices,
384                               "gep_" + StructValues[i]->getName(), 0);
385       codeReplacer->getInstList().push_back(GEP);
386       StoreInst *SI = new StoreInst(StructValues[i], GEP);
387       codeReplacer->getInstList().push_back(SI);
388     }
389   } 
390
391   // Emit the call to the function
392   CallInst *call = new CallInst(newFunction, params,
393                                 NumExitBlocks > 1 ? "targetBlock": "");
394   codeReplacer->getInstList().push_back(call);
395
396   Function::aiterator OutputArgBegin = newFunction->abegin();
397   unsigned FirstOut = inputs.size();
398   if (!AggregateArgs)
399     std::advance(OutputArgBegin, inputs.size());
400
401   // Reload the outputs passed in by reference
402   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
403     Value *Output = 0;
404     if (AggregateArgs) {
405       std::vector<Value*> Indices;
406       Indices.push_back(Constant::getNullValue(Type::UIntTy));
407       Indices.push_back(ConstantUInt::get(Type::UIntTy, FirstOut + i));
408       GetElementPtrInst *GEP 
409         = new GetElementPtrInst(Struct, Indices,
410                                 "gep_reload_" + outputs[i]->getName(), 0);
411       codeReplacer->getInstList().push_back(GEP);
412       Output = GEP;
413     } else {
414       Output = ReloadOutputs[i];
415     }
416     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
417     codeReplacer->getInstList().push_back(load);
418     std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
419     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
420       Instruction *inst = cast<Instruction>(Users[u]);
421       if (!BlocksToExtract.count(inst->getParent()))
422         inst->replaceUsesOfWith(outputs[i], load);
423     }
424   }
425
426   // Now we can emit a switch statement using the call as a value.
427   SwitchInst *TheSwitch =
428     new SwitchInst(ConstantUInt::getNullValue(Type::UShortTy),
429                    codeReplacer, codeReplacer);
430
431   // Since there may be multiple exits from the original region, make the new
432   // function return an unsigned, switch on that number.  This loop iterates
433   // over all of the blocks in the extracted region, updating any terminator
434   // instructions in the to-be-extracted region that branch to blocks that are
435   // not in the region to be extracted.
436   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
437
438   unsigned switchVal = 0;
439   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
440          e = BlocksToExtract.end(); i != e; ++i) {
441     TerminatorInst *TI = (*i)->getTerminator();
442     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
443       if (!BlocksToExtract.count(TI->getSuccessor(i))) {
444         BasicBlock *OldTarget = TI->getSuccessor(i);
445         // add a new basic block which returns the appropriate value
446         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
447         if (!NewTarget) {
448           // If we don't already have an exit stub for this non-extracted
449           // destination, create one now!
450           NewTarget = new BasicBlock(OldTarget->getName() + ".exitStub",
451                                      newFunction);
452           unsigned SuccNum = switchVal++;
453
454           Value *brVal = 0;
455           switch (NumExitBlocks) {
456           case 0:
457           case 1: break;  // No value needed.
458           case 2:         // Conditional branch, return a bool
459             brVal = SuccNum ? ConstantBool::False : ConstantBool::True;
460             break;
461           default:
462             brVal = ConstantUInt::get(Type::UShortTy, SuccNum);
463             break;
464           }
465
466           ReturnInst *NTRet = new ReturnInst(brVal, NewTarget);
467
468           // Update the switch instruction.
469           TheSwitch->addCase(ConstantUInt::get(Type::UShortTy, SuccNum),
470                              OldTarget);
471
472           // Restore values just before we exit
473           Function::aiterator OAI = OutputArgBegin;
474           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
475             // For an invoke, the normal destination is the only one that is
476             // dominated by the result of the invocation
477             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
478             if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out]))
479               DefBlock = Invoke->getNormalDest();
480             if (!DS || DS->dominates(DefBlock, TI->getParent()))
481               if (AggregateArgs) {
482                 std::vector<Value*> Indices;
483                 Indices.push_back(Constant::getNullValue(Type::UIntTy));
484                 Indices.push_back(ConstantUInt::get(Type::UIntTy,FirstOut+out));
485                 GetElementPtrInst *GEP =
486                   new GetElementPtrInst(OAI, Indices,
487                                         "gep_" + outputs[out]->getName(), 
488                                         NTRet);
489                 new StoreInst(outputs[out], GEP, NTRet);
490               } else
491                 new StoreInst(outputs[out], OAI, NTRet);
492             // Advance output iterator even if we don't emit a store
493             if (!AggregateArgs) ++OAI;
494           }
495         }
496
497         // rewrite the original branch instruction with this new target
498         TI->setSuccessor(i, NewTarget);
499       }
500   }
501
502   // Now that we've done the deed, simplify the switch instruction.
503   switch (NumExitBlocks) {
504   case 0:
505     // There is only 1 successor (the block containing the switch itself), which
506     // means that previously this was the last part of the function, and hence
507     // this should be rewritten as a `ret'
508     
509     // Check if the function should return a value
510     if (TheSwitch->getParent()->getParent()->getReturnType() != Type::VoidTy &&
511         TheSwitch->getParent()->getParent()->getReturnType() ==
512         TheSwitch->getCondition()->getType())
513       // return what we have
514       new ReturnInst(TheSwitch->getCondition(), TheSwitch);
515     else
516       // just return
517       new ReturnInst(0, TheSwitch);
518
519     TheSwitch->getParent()->getInstList().erase(TheSwitch);
520     break;
521   case 1:
522     // Only a single destination, change the switch into an unconditional
523     // branch.
524     new BranchInst(TheSwitch->getSuccessor(1), TheSwitch);
525     TheSwitch->getParent()->getInstList().erase(TheSwitch);
526     break;
527   case 2:
528     new BranchInst(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
529                    call, TheSwitch);
530     TheSwitch->getParent()->getInstList().erase(TheSwitch);
531     break;
532   default:
533     // Otherwise, make the default destination of the switch instruction be one
534     // of the other successors.
535     TheSwitch->setOperand(0, call);
536     TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
537     TheSwitch->removeCase(NumExitBlocks);  // Remove redundant case
538     break;
539   }
540 }
541
542 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
543   Function *oldFunc = (*BlocksToExtract.begin())->getParent();
544   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
545   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
546
547   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
548          e = BlocksToExtract.end(); i != e; ++i) {
549     // Delete the basic block from the old function, and the list of blocks
550     oldBlocks.remove(*i);
551
552     // Insert this basic block into the new function
553     newBlocks.push_back(*i);
554   }
555 }
556
557 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
558 /// new function. Returns pointer to the new function.
559 ///
560 /// algorithm:
561 ///
562 /// find inputs and outputs for the region
563 ///
564 /// for inputs: add to function as args, map input instr* to arg# 
565 /// for outputs: add allocas for scalars, 
566 ///             add to func as args, map output instr* to arg#
567 ///
568 /// rewrite func to use argument #s instead of instr*
569 ///
570 /// for each scalar output in the function: at every exit, store intermediate 
571 /// computed result back into memory.
572 ///
573 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
574 {
575   if (!isEligible(code))
576     return 0;
577
578   // 1) Find inputs, outputs
579   // 2) Construct new function
580   //  * Add allocas for defs, pass as args by reference
581   //  * Pass in uses as args
582   // 3) Move code region, add call instr to func
583   //
584   BlocksToExtract.insert(code.begin(), code.end());
585
586   Values inputs, outputs;
587
588   // Assumption: this is a single-entry code region, and the header is the first
589   // block in the region.
590   BasicBlock *header = code[0];
591
592   for (unsigned i = 1, e = code.size(); i != e; ++i)
593     for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
594          PI != E; ++PI)
595       assert(BlocksToExtract.count(*PI) &&
596              "No blocks in this region may have entries from outside the region"
597              " except for the first block!");
598   
599   // If we have to split PHI nodes, do so now.
600   severSplitPHINodes(header);
601
602   Function *oldFunction = header->getParent();
603
604   // This takes place of the original loop
605   BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
606
607   // The new function needs a root node because other nodes can branch to the
608   // head of the region, but the entry node of a function cannot have preds.
609   BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
610   newFuncRoot->getInstList().push_back(new BranchInst(header));
611
612   // Find inputs to, outputs from the code region.
613   findInputsOutputs(inputs, outputs);
614
615   // Construct new function based on inputs/outputs & add allocas for all defs.
616   Function *newFunction = constructFunction(inputs, outputs, header,
617                                             newFuncRoot, 
618                                             codeReplacer, oldFunction,
619                                             oldFunction->getParent());
620
621   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
622
623   moveCodeToFunction(newFunction);
624
625   // Loop over all of the PHI nodes in the header block, and change any
626   // references to the old incoming edge to be the new incoming edge.
627   for (BasicBlock::iterator I = header->begin();
628        PHINode *PN = dyn_cast<PHINode>(I); ++I)
629     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
630       if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
631         PN->setIncomingBlock(i, newFuncRoot);
632
633   // Look at all successors of the codeReplacer block.  If any of these blocks
634   // had PHI nodes in them, we need to update the "from" block to be the code
635   // replacer, not the original block in the extracted region.
636   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
637                                  succ_end(codeReplacer));
638   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
639     for (BasicBlock::iterator I = Succs[i]->begin();
640          PHINode *PN = dyn_cast<PHINode>(I); ++I)
641       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
642         if (BlocksToExtract.count(PN->getIncomingBlock(i)))
643           PN->setIncomingBlock(i, codeReplacer);
644   
645   //std::cerr << "NEW FUNCTION: " << *newFunction;
646   //  verifyFunction(*newFunction);
647
648   //  std::cerr << "OLD FUNCTION: " << *oldFunction;
649   //  verifyFunction(*oldFunction);
650
651   DEBUG(if (verifyFunction(*newFunction)) abort());
652   return newFunction;
653 }
654
655 bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
656   // Deny code region if it contains allocas or vastarts.
657   for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
658        BB != e; ++BB)
659     for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
660          I != Ie; ++I)
661       if (isa<AllocaInst>(*I))
662         return false;
663       else if (const CallInst *CI = dyn_cast<CallInst>(I))
664         if (const Function *F = CI->getCalledFunction())
665           if (F->getIntrinsicID() == Intrinsic::vastart)
666             return false;
667   return true;
668 }
669
670
671 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
672 /// function
673 ///
674 Function* llvm::ExtractCodeRegion(DominatorSet &DS,
675                                   const std::vector<BasicBlock*> &code,
676                                   bool AggregateArgs) {
677   return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(code);
678 }
679
680 /// ExtractBasicBlock - slurp a natural loop into a brand new function
681 ///
682 Function* llvm::ExtractLoop(DominatorSet &DS, Loop *L, bool AggregateArgs) {
683   return CodeExtractor(&DS, AggregateArgs).ExtractCodeRegion(L->getBlocks());
684 }
685
686 /// ExtractBasicBlock - slurp a basic block into a brand new function
687 ///
688 Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
689   std::vector<BasicBlock*> Blocks;
690   Blocks.push_back(BB);
691   return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);  
692 }