LLVM API Documentation

CodeExtractor.cpp

Go to the documentation of this file.
00001 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the interface to tear out a code region, such as an
00011 // individual loop or a parallel section, into a new function, replacing it with
00012 // a call to the new function.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/Utils/FunctionUtils.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/Module.h"
00022 #include "llvm/Pass.h"
00023 #include "llvm/Analysis/Dominators.h"
00024 #include "llvm/Analysis/LoopInfo.h"
00025 #include "llvm/Analysis/Verifier.h"
00026 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Compiler.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/ADT/StringExtras.h"
00031 #include <algorithm>
00032 #include <set>
00033 using namespace llvm;
00034 
00035 // Provide a command-line option to aggregate function arguments into a struct
00036 // for functions produced by the code extractor. This is useful when converting
00037 // extracted functions to pthread-based code, as only one argument (void*) can
00038 // be passed in to pthread_create().
00039 static cl::opt<bool>
00040 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
00041                  cl::desc("Aggregate arguments to code-extracted functions"));
00042 
00043 namespace {
00044   class VISIBILITY_HIDDEN CodeExtractor {
00045     typedef std::vector<Value*> Values;
00046     std::set<BasicBlock*> BlocksToExtract;
00047     DominatorTree* DT;
00048     bool AggregateArgs;
00049     unsigned NumExitBlocks;
00050     const Type *RetTy;
00051   public:
00052     CodeExtractor(DominatorTree* dt = 0, bool AggArgs = false)
00053       : DT(dt), AggregateArgs(AggArgs||AggregateArgsOpt), NumExitBlocks(~0U) {}
00054 
00055     Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
00056 
00057     bool isEligible(const std::vector<BasicBlock*> &code);
00058 
00059   private:
00060     /// definedInRegion - Return true if the specified value is defined in the
00061     /// extracted region.
00062     bool definedInRegion(Value *V) const {
00063       if (Instruction *I = dyn_cast<Instruction>(V))
00064         if (BlocksToExtract.count(I->getParent()))
00065           return true;
00066       return false;
00067     }
00068 
00069     /// definedInCaller - Return true if the specified value is defined in the
00070     /// function being code extracted, but not in the region being extracted.
00071     /// These values must be passed in as live-ins to the function.
00072     bool definedInCaller(Value *V) const {
00073       if (isa<Argument>(V)) return true;
00074       if (Instruction *I = dyn_cast<Instruction>(V))
00075         if (!BlocksToExtract.count(I->getParent()))
00076           return true;
00077       return false;
00078     }
00079 
00080     void severSplitPHINodes(BasicBlock *&Header);
00081     void splitReturnBlocks();
00082     void findInputsOutputs(Values &inputs, Values &outputs);
00083 
00084     Function *constructFunction(const Values &inputs,
00085                                 const Values &outputs,
00086                                 BasicBlock *header,
00087                                 BasicBlock *newRootNode, BasicBlock *newHeader,
00088                                 Function *oldFunction, Module *M);
00089 
00090     void moveCodeToFunction(Function *newFunction);
00091 
00092     void emitCallAndSwitchStatement(Function *newFunction,
00093                                     BasicBlock *newHeader,
00094                                     Values &inputs,
00095                                     Values &outputs);
00096 
00097   };
00098 }
00099 
00100 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
00101 /// region, we need to split the entry block of the region so that the PHI node
00102 /// is easier to deal with.
00103 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
00104   bool HasPredsFromRegion = false;
00105   unsigned NumPredsOutsideRegion = 0;
00106 
00107   if (Header != &Header->getParent()->getEntryBlock()) {
00108     PHINode *PN = dyn_cast<PHINode>(Header->begin());
00109     if (!PN) return;  // No PHI nodes.
00110 
00111     // If the header node contains any PHI nodes, check to see if there is more
00112     // than one entry from outside the region.  If so, we need to sever the
00113     // header block into two.
00114     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00115       if (BlocksToExtract.count(PN->getIncomingBlock(i)))
00116         HasPredsFromRegion = true;
00117       else
00118         ++NumPredsOutsideRegion;
00119 
00120     // If there is one (or fewer) predecessor from outside the region, we don't
00121     // need to do anything special.
00122     if (NumPredsOutsideRegion <= 1) return;
00123   }
00124 
00125   // Otherwise, we need to split the header block into two pieces: one
00126   // containing PHI nodes merging values from outside of the region, and a
00127   // second that contains all of the code for the block and merges back any
00128   // incoming values from inside of the region.
00129   BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
00130   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
00131                                               Header->getName()+".ce");
00132 
00133   // We only want to code extract the second block now, and it becomes the new
00134   // header of the region.
00135   BasicBlock *OldPred = Header;
00136   BlocksToExtract.erase(OldPred);
00137   BlocksToExtract.insert(NewBB);
00138   Header = NewBB;
00139 
00140   // Okay, update dominator sets. The blocks that dominate the new one are the
00141   // blocks that dominate TIBB plus the new block itself.
00142   if (DT)
00143     DT->splitBlock(NewBB);
00144 
00145   // Okay, now we need to adjust the PHI nodes and any branches from within the
00146   // region to go to the new header block instead of the old header block.
00147   if (HasPredsFromRegion) {
00148     PHINode *PN = cast<PHINode>(OldPred->begin());
00149     // Loop over all of the predecessors of OldPred that are in the region,
00150     // changing them to branch to NewBB instead.
00151     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00152       if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
00153         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
00154         TI->replaceUsesOfWith(OldPred, NewBB);
00155       }
00156 
00157     // Okay, everthing within the region is now branching to the right block, we
00158     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
00159     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
00160       PHINode *PN = cast<PHINode>(AfterPHIs);
00161       // Create a new PHI node in the new region, which has an incoming value
00162       // from OldPred of PN.
00163       PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".ce",
00164                                        NewBB->begin());
00165       NewPN->addIncoming(PN, OldPred);
00166 
00167       // Loop over all of the incoming value in PN, moving them to NewPN if they
00168       // are from the extracted region.
00169       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
00170         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
00171           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
00172           PN->removeIncomingValue(i);
00173           --i;
00174         }
00175       }
00176     }
00177   }
00178 }
00179 
00180 void CodeExtractor::splitReturnBlocks() {
00181   for (std::set<BasicBlock*>::iterator I = BlocksToExtract.begin(),
00182          E = BlocksToExtract.end(); I != E; ++I)
00183     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
00184       (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
00185 }
00186 
00187 // findInputsOutputs - Find inputs to, outputs from the code region.
00188 //
00189 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
00190   std::set<BasicBlock*> ExitBlocks;
00191   for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
00192        ce = BlocksToExtract.end(); ci != ce; ++ci) {
00193     BasicBlock *BB = *ci;
00194 
00195     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00196       // If a used value is defined outside the region, it's an input.  If an
00197       // instruction is used outside the region, it's an output.
00198       for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
00199         if (definedInCaller(*O))
00200           inputs.push_back(*O);
00201 
00202       // Consider uses of this instruction (outputs).
00203       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
00204            UI != E; ++UI)
00205         if (!definedInRegion(*UI)) {
00206           outputs.push_back(I);
00207           break;
00208         }
00209     } // for: insts
00210 
00211     // Keep track of the exit blocks from the region.
00212     TerminatorInst *TI = BB->getTerminator();
00213     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00214       if (!BlocksToExtract.count(TI->getSuccessor(i)))
00215         ExitBlocks.insert(TI->getSuccessor(i));
00216   } // for: basic blocks
00217 
00218   NumExitBlocks = ExitBlocks.size();
00219 
00220   // Eliminate duplicates.
00221   std::sort(inputs.begin(), inputs.end());
00222   inputs.erase(std::unique(inputs.begin(), inputs.end()), inputs.end());
00223   std::sort(outputs.begin(), outputs.end());
00224   outputs.erase(std::unique(outputs.begin(), outputs.end()), outputs.end());
00225 }
00226 
00227 /// constructFunction - make a function based on inputs and outputs, as follows:
00228 /// f(in0, ..., inN, out0, ..., outN)
00229 ///
00230 Function *CodeExtractor::constructFunction(const Values &inputs,
00231                                            const Values &outputs,
00232                                            BasicBlock *header,
00233                                            BasicBlock *newRootNode,
00234                                            BasicBlock *newHeader,
00235                                            Function *oldFunction,
00236                                            Module *M) {
00237   DOUT << "inputs: " << inputs.size() << "\n";
00238   DOUT << "outputs: " << outputs.size() << "\n";
00239 
00240   // This function returns unsigned, outputs will go back by reference.
00241   switch (NumExitBlocks) {
00242   case 0:
00243   case 1: RetTy = Type::VoidTy; break;
00244   case 2: RetTy = Type::Int1Ty; break;
00245   default: RetTy = Type::Int16Ty; break;
00246   }
00247 
00248   std::vector<const Type*> paramTy;
00249 
00250   // Add the types of the input values to the function's argument list
00251   for (Values::const_iterator i = inputs.begin(),
00252          e = inputs.end(); i != e; ++i) {
00253     const Value *value = *i;
00254     DOUT << "value used in func: " << *value << "\n";
00255     paramTy.push_back(value->getType());
00256   }
00257 
00258   // Add the types of the output values to the function's argument list.
00259   for (Values::const_iterator I = outputs.begin(), E = outputs.end();
00260        I != E; ++I) {
00261     DOUT << "instr used in func: " << **I << "\n";
00262     if (AggregateArgs)
00263       paramTy.push_back((*I)->getType());
00264     else
00265       paramTy.push_back(PointerType::getUnqual((*I)->getType()));
00266   }
00267 
00268   DOUT << "Function type: " << *RetTy << " f(";
00269   for (std::vector<const Type*>::iterator i = paramTy.begin(),
00270          e = paramTy.end(); i != e; ++i)
00271     DOUT << **i << ", ";
00272   DOUT << ")\n";
00273 
00274   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
00275     PointerType *StructPtr = PointerType::getUnqual(StructType::get(paramTy));
00276     paramTy.clear();
00277     paramTy.push_back(StructPtr);
00278   }
00279   const FunctionType *funcType = FunctionType::get(RetTy, paramTy, false);
00280 
00281   // Create the new function
00282   Function *newFunction = Function::Create(funcType,
00283                                            GlobalValue::InternalLinkage,
00284                                            oldFunction->getName() + "_" +
00285                                            header->getName(), M);
00286   // If the old function is no-throw, so is the new one.
00287   if (oldFunction->doesNotThrow())
00288     newFunction->setDoesNotThrow(true);
00289   
00290   newFunction->getBasicBlockList().push_back(newRootNode);
00291 
00292   // Create an iterator to name all of the arguments we inserted.
00293   Function::arg_iterator AI = newFunction->arg_begin();
00294 
00295   // Rewrite all users of the inputs in the extracted region to use the
00296   // arguments (or appropriate addressing into struct) instead.
00297   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
00298     Value *RewriteVal;
00299     if (AggregateArgs) {
00300       Value *Idx[2];
00301       Idx[0] = Constant::getNullValue(Type::Int32Ty);
00302       Idx[1] = ConstantInt::get(Type::Int32Ty, i);
00303       std::string GEPname = "gep_" + inputs[i]->getName();
00304       TerminatorInst *TI = newFunction->begin()->getTerminator();
00305       GetElementPtrInst *GEP = GetElementPtrInst::Create(AI, Idx, Idx+2, 
00306                                                          GEPname, TI);
00307       RewriteVal = new LoadInst(GEP, "load" + GEPname, TI);
00308     } else
00309       RewriteVal = AI++;
00310 
00311     std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
00312     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
00313          use != useE; ++use)
00314       if (Instruction* inst = dyn_cast<Instruction>(*use))
00315         if (BlocksToExtract.count(inst->getParent()))
00316           inst->replaceUsesOfWith(inputs[i], RewriteVal);
00317   }
00318 
00319   // Set names for input and output arguments.
00320   if (!AggregateArgs) {
00321     AI = newFunction->arg_begin();
00322     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
00323       AI->setName(inputs[i]->getName());
00324     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
00325       AI->setName(outputs[i]->getName()+".out");
00326   }
00327 
00328   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
00329   // within the new function. This must be done before we lose track of which
00330   // blocks were originally in the code region.
00331   std::vector<User*> Users(header->use_begin(), header->use_end());
00332   for (unsigned i = 0, e = Users.size(); i != e; ++i)
00333     // The BasicBlock which contains the branch is not in the region
00334     // modify the branch target to a new block
00335     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
00336       if (!BlocksToExtract.count(TI->getParent()) &&
00337           TI->getParent()->getParent() == oldFunction)
00338         TI->replaceUsesOfWith(header, newHeader);
00339 
00340   return newFunction;
00341 }
00342 
00343 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
00344 /// the call instruction, splitting any PHI nodes in the header block as
00345 /// necessary.
00346 void CodeExtractor::
00347 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
00348                            Values &inputs, Values &outputs) {
00349   // Emit a call to the new function, passing in: *pointer to struct (if
00350   // aggregating parameters), or plan inputs and allocated memory for outputs
00351   std::vector<Value*> params, StructValues, ReloadOutputs;
00352 
00353   // Add inputs as params, or to be filled into the struct
00354   for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
00355     if (AggregateArgs)
00356       StructValues.push_back(*i);
00357     else
00358       params.push_back(*i);
00359 
00360   // Create allocas for the outputs
00361   for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
00362     if (AggregateArgs) {
00363       StructValues.push_back(*i);
00364     } else {
00365       AllocaInst *alloca =
00366         new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
00367                        codeReplacer->getParent()->begin()->begin());
00368       ReloadOutputs.push_back(alloca);
00369       params.push_back(alloca);
00370     }
00371   }
00372 
00373   AllocaInst *Struct = 0;
00374   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
00375     std::vector<const Type*> ArgTypes;
00376     for (Values::iterator v = StructValues.begin(),
00377            ve = StructValues.end(); v != ve; ++v)
00378       ArgTypes.push_back((*v)->getType());
00379 
00380     // Allocate a struct at the beginning of this function
00381     Type *StructArgTy = StructType::get(ArgTypes);
00382     Struct =
00383       new AllocaInst(StructArgTy, 0, "structArg",
00384                      codeReplacer->getParent()->begin()->begin());
00385     params.push_back(Struct);
00386 
00387     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
00388       Value *Idx[2];
00389       Idx[0] = Constant::getNullValue(Type::Int32Ty);
00390       Idx[1] = ConstantInt::get(Type::Int32Ty, i);
00391       GetElementPtrInst *GEP =
00392         GetElementPtrInst::Create(Struct, Idx, Idx + 2,
00393                                   "gep_" + StructValues[i]->getName());
00394       codeReplacer->getInstList().push_back(GEP);
00395       StoreInst *SI = new StoreInst(StructValues[i], GEP);
00396       codeReplacer->getInstList().push_back(SI);
00397     }
00398   }
00399 
00400   // Emit the call to the function
00401   CallInst *call = CallInst::Create(newFunction, params.begin(), params.end(),
00402                                     NumExitBlocks > 1 ? "targetBlock" : "");
00403   codeReplacer->getInstList().push_back(call);
00404 
00405   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
00406   unsigned FirstOut = inputs.size();
00407   if (!AggregateArgs)
00408     std::advance(OutputArgBegin, inputs.size());
00409 
00410   // Reload the outputs passed in by reference
00411   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
00412     Value *Output = 0;
00413     if (AggregateArgs) {
00414       Value *Idx[2];
00415       Idx[0] = Constant::getNullValue(Type::Int32Ty);
00416       Idx[1] = ConstantInt::get(Type::Int32Ty, FirstOut + i);
00417       GetElementPtrInst *GEP
00418         = GetElementPtrInst::Create(Struct, Idx, Idx + 2,
00419                                     "gep_reload_" + outputs[i]->getName());
00420       codeReplacer->getInstList().push_back(GEP);
00421       Output = GEP;
00422     } else {
00423       Output = ReloadOutputs[i];
00424     }
00425     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
00426     codeReplacer->getInstList().push_back(load);
00427     std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
00428     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
00429       Instruction *inst = cast<Instruction>(Users[u]);
00430       if (!BlocksToExtract.count(inst->getParent()))
00431         inst->replaceUsesOfWith(outputs[i], load);
00432     }
00433   }
00434 
00435   // Now we can emit a switch statement using the call as a value.
00436   SwitchInst *TheSwitch =
00437       SwitchInst::Create(ConstantInt::getNullValue(Type::Int16Ty),
00438                          codeReplacer, 0, codeReplacer);
00439 
00440   // Since there may be multiple exits from the original region, make the new
00441   // function return an unsigned, switch on that number.  This loop iterates
00442   // over all of the blocks in the extracted region, updating any terminator
00443   // instructions in the to-be-extracted region that branch to blocks that are
00444   // not in the region to be extracted.
00445   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
00446 
00447   unsigned switchVal = 0;
00448   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
00449          e = BlocksToExtract.end(); i != e; ++i) {
00450     TerminatorInst *TI = (*i)->getTerminator();
00451     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00452       if (!BlocksToExtract.count(TI->getSuccessor(i))) {
00453         BasicBlock *OldTarget = TI->getSuccessor(i);
00454         // add a new basic block which returns the appropriate value
00455         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
00456         if (!NewTarget) {
00457           // If we don't already have an exit stub for this non-extracted
00458           // destination, create one now!
00459           NewTarget = BasicBlock::Create(OldTarget->getName() + ".exitStub",
00460                                          newFunction);
00461           unsigned SuccNum = switchVal++;
00462 
00463           Value *brVal = 0;
00464           switch (NumExitBlocks) {
00465           case 0:
00466           case 1: break;  // No value needed.
00467           case 2:         // Conditional branch, return a bool
00468             brVal = ConstantInt::get(Type::Int1Ty, !SuccNum);
00469             break;
00470           default:
00471             brVal = ConstantInt::get(Type::Int16Ty, SuccNum);
00472             break;
00473           }
00474 
00475           ReturnInst *NTRet = ReturnInst::Create(brVal, NewTarget);
00476 
00477           // Update the switch instruction.
00478           TheSwitch->addCase(ConstantInt::get(Type::Int16Ty, SuccNum),
00479                              OldTarget);
00480 
00481           // Restore values just before we exit
00482           Function::arg_iterator OAI = OutputArgBegin;
00483           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
00484             // For an invoke, the normal destination is the only one that is
00485             // dominated by the result of the invocation
00486             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
00487 
00488             bool DominatesDef = true;
00489 
00490             if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
00491               DefBlock = Invoke->getNormalDest();
00492 
00493               // Make sure we are looking at the original successor block, not
00494               // at a newly inserted exit block, which won't be in the dominator
00495               // info.
00496               for (std::map<BasicBlock*, BasicBlock*>::iterator I =
00497                      ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
00498                 if (DefBlock == I->second) {
00499                   DefBlock = I->first;
00500                   break;
00501                 }
00502 
00503               // In the extract block case, if the block we are extracting ends
00504               // with an invoke instruction, make sure that we don't emit a
00505               // store of the invoke value for the unwind block.
00506               if (!DT && DefBlock != OldTarget)
00507                 DominatesDef = false;
00508             }
00509 
00510             if (DT)
00511               DominatesDef = DT->dominates(DefBlock, OldTarget);
00512 
00513             if (DominatesDef) {
00514               if (AggregateArgs) {
00515                 Value *Idx[2];
00516                 Idx[0] = Constant::getNullValue(Type::Int32Ty);
00517                 Idx[1] = ConstantInt::get(Type::Int32Ty,FirstOut+out);
00518                 GetElementPtrInst *GEP =
00519                   GetElementPtrInst::Create(OAI, Idx, Idx + 2,
00520                                             "gep_" + outputs[out]->getName(),
00521                                             NTRet);
00522                 new StoreInst(outputs[out], GEP, NTRet);
00523               } else {
00524                 new StoreInst(outputs[out], OAI, NTRet);
00525               }
00526             }
00527             // Advance output iterator even if we don't emit a store
00528             if (!AggregateArgs) ++OAI;
00529           }
00530         }
00531 
00532         // rewrite the original branch instruction with this new target
00533         TI->setSuccessor(i, NewTarget);
00534       }
00535   }
00536 
00537   // Now that we've done the deed, simplify the switch instruction.
00538   const Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
00539   switch (NumExitBlocks) {
00540   case 0:
00541     // There are no successors (the block containing the switch itself), which
00542     // means that previously this was the last part of the function, and hence
00543     // this should be rewritten as a `ret'
00544 
00545     // Check if the function should return a value
00546     if (OldFnRetTy == Type::VoidTy) {
00547       ReturnInst::Create(0, TheSwitch);  // Return void
00548     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
00549       // return what we have
00550       ReturnInst::Create(TheSwitch->getCondition(), TheSwitch);
00551     } else {
00552       // Otherwise we must have code extracted an unwind or something, just
00553       // return whatever we want.
00554       ReturnInst::Create(Constant::getNullValue(OldFnRetTy), TheSwitch);
00555     }
00556 
00557     TheSwitch->eraseFromParent();
00558     break;
00559   case 1:
00560     // Only a single destination, change the switch into an unconditional
00561     // branch.
00562     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
00563     TheSwitch->eraseFromParent();
00564     break;
00565   case 2:
00566     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
00567                        call, TheSwitch);
00568     TheSwitch->eraseFromParent();
00569     break;
00570   default:
00571     // Otherwise, make the default destination of the switch instruction be one
00572     // of the other successors.
00573     TheSwitch->setOperand(0, call);
00574     TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
00575     TheSwitch->removeCase(NumExitBlocks);  // Remove redundant case
00576     break;
00577   }
00578 }
00579 
00580 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
00581   Function *oldFunc = (*BlocksToExtract.begin())->getParent();
00582   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
00583   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
00584 
00585   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
00586          e = BlocksToExtract.end(); i != e; ++i) {
00587     // Delete the basic block from the old function, and the list of blocks
00588     oldBlocks.remove(*i);
00589 
00590     // Insert this basic block into the new function
00591     newBlocks.push_back(*i);
00592   }
00593 }
00594 
00595 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
00596 /// new function. Returns pointer to the new function.
00597 ///
00598 /// algorithm:
00599 ///
00600 /// find inputs and outputs for the region
00601 ///
00602 /// for inputs: add to function as args, map input instr* to arg#
00603 /// for outputs: add allocas for scalars,
00604 ///             add to func as args, map output instr* to arg#
00605 ///
00606 /// rewrite func to use argument #s instead of instr*
00607 ///
00608 /// for each scalar output in the function: at every exit, store intermediate
00609 /// computed result back into memory.
00610 ///
00611 Function *CodeExtractor::
00612 ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
00613   if (!isEligible(code))
00614     return 0;
00615 
00616   // 1) Find inputs, outputs
00617   // 2) Construct new function
00618   //  * Add allocas for defs, pass as args by reference
00619   //  * Pass in uses as args
00620   // 3) Move code region, add call instr to func
00621   //
00622   BlocksToExtract.insert(code.begin(), code.end());
00623 
00624   Values inputs, outputs;
00625 
00626   // Assumption: this is a single-entry code region, and the header is the first
00627   // block in the region.
00628   BasicBlock *header = code[0];
00629 
00630   for (unsigned i = 1, e = code.size(); i != e; ++i)
00631     for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
00632          PI != E; ++PI)
00633       assert(BlocksToExtract.count(*PI) &&
00634              "No blocks in this region may have entries from outside the region"
00635              " except for the first block!");
00636 
00637   // If we have to split PHI nodes or the entry block, do so now.
00638   severSplitPHINodes(header);
00639 
00640   // If we have any return instructions in the region, split those blocks so
00641   // that the return is not in the region.
00642   splitReturnBlocks();
00643 
00644   Function *oldFunction = header->getParent();
00645 
00646   // This takes place of the original loop
00647   BasicBlock *codeReplacer = BasicBlock::Create("codeRepl", oldFunction,
00648                                                 header);
00649 
00650   // The new function needs a root node because other nodes can branch to the
00651   // head of the region, but the entry node of a function cannot have preds.
00652   BasicBlock *newFuncRoot = BasicBlock::Create("newFuncRoot");
00653   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
00654 
00655   // Find inputs to, outputs from the code region.
00656   findInputsOutputs(inputs, outputs);
00657 
00658   // Construct new function based on inputs/outputs & add allocas for all defs.
00659   Function *newFunction = constructFunction(inputs, outputs, header,
00660                                             newFuncRoot,
00661                                             codeReplacer, oldFunction,
00662                                             oldFunction->getParent());
00663 
00664   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
00665 
00666   moveCodeToFunction(newFunction);
00667 
00668   // Loop over all of the PHI nodes in the header block, and change any
00669   // references to the old incoming edge to be the new incoming edge.
00670   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
00671     PHINode *PN = cast<PHINode>(I);
00672     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00673       if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
00674         PN->setIncomingBlock(i, newFuncRoot);
00675   }
00676 
00677   // Look at all successors of the codeReplacer block.  If any of these blocks
00678   // had PHI nodes in them, we need to update the "from" block to be the code
00679   // replacer, not the original block in the extracted region.
00680   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
00681                                  succ_end(codeReplacer));
00682   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
00683     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
00684       PHINode *PN = cast<PHINode>(I);
00685       std::set<BasicBlock*> ProcessedPreds;
00686       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00687         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
00688           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
00689             PN->setIncomingBlock(i, codeReplacer);
00690           else {
00691             // There were multiple entries in the PHI for this block, now there
00692             // is only one, so remove the duplicated entries.
00693             PN->removeIncomingValue(i, false);
00694             --i; --e;
00695           }
00696         }
00697     }
00698 
00699   //cerr << "NEW FUNCTION: " << *newFunction;
00700   //  verifyFunction(*newFunction);
00701 
00702   //  cerr << "OLD FUNCTION: " << *oldFunction;
00703   //  verifyFunction(*oldFunction);
00704 
00705   DEBUG(if (verifyFunction(*newFunction)) abort());
00706   return newFunction;
00707 }
00708 
00709 bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
00710   // Deny code region if it contains allocas or vastarts.
00711   for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
00712        BB != e; ++BB)
00713     for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
00714          I != Ie; ++I)
00715       if (isa<AllocaInst>(*I))
00716         return false;
00717       else if (const CallInst *CI = dyn_cast<CallInst>(I))
00718         if (const Function *F = CI->getCalledFunction())
00719           if (F->getIntrinsicID() == Intrinsic::vastart)
00720             return false;
00721   return true;
00722 }
00723 
00724 
00725 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
00726 /// function
00727 ///
00728 Function* llvm::ExtractCodeRegion(DominatorTree &DT,
00729                                   const std::vector<BasicBlock*> &code,
00730                                   bool AggregateArgs) {
00731   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(code);
00732 }
00733 
00734 /// ExtractBasicBlock - slurp a natural loop into a brand new function
00735 ///
00736 Function* llvm::ExtractLoop(DominatorTree &DT, Loop *L, bool AggregateArgs) {
00737   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(L->getBlocks());
00738 }
00739 
00740 /// ExtractBasicBlock - slurp a basic block into a brand new function
00741 ///
00742 Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
00743   std::vector<BasicBlock*> Blocks;
00744   Blocks.push_back(BB);
00745   return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
00746 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.