1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This 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/CodeExtractor.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/Analysis/BlockFrequencyInfo.h" 21 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 22 #include "llvm/Analysis/BranchProbabilityInfo.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/Analysis/RegionInfo.h" 25 #include "llvm/Analysis/RegionIterator.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/IR/MDBuilder.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Verifier.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/BlockFrequency.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 42 #include <algorithm> 43 #include <set> 44 using namespace llvm; 45 46 #define DEBUG_TYPE "code-extractor" 47 48 // Provide a command-line option to aggregate function arguments into a struct 49 // for functions produced by the code extractor. This is useful when converting 50 // extracted functions to pthread-based code, as only one argument (void*) can 51 // be passed in to pthread_create(). 52 static cl::opt<bool> 53 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, 54 cl::desc("Aggregate arguments to code-extracted functions")); 55 56 /// \brief Test whether a block is valid for extraction. 57 bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) { 58 // Landing pads must be in the function where they were inserted for cleanup. 59 if (BB.isEHPad()) 60 return false; 61 62 // Don't hoist code containing allocas, invokes, or vastarts. 63 for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { 64 if (isa<AllocaInst>(I) || isa<InvokeInst>(I)) 65 return false; 66 if (const CallInst *CI = dyn_cast<CallInst>(I)) 67 if (const Function *F = CI->getCalledFunction()) 68 if (F->getIntrinsicID() == Intrinsic::vastart) 69 return false; 70 } 71 72 return true; 73 } 74 75 /// \brief Build a set of blocks to extract if the input blocks are viable. 76 template <typename IteratorT> 77 static SetVector<BasicBlock *> buildExtractionBlockSet(IteratorT BBBegin, 78 IteratorT BBEnd) { 79 SetVector<BasicBlock *> Result; 80 81 assert(BBBegin != BBEnd); 82 83 // Loop over the blocks, adding them to our set-vector, and aborting with an 84 // empty set if we encounter invalid blocks. 85 do { 86 if (!Result.insert(*BBBegin)) 87 llvm_unreachable("Repeated basic blocks in extraction input"); 88 89 if (!CodeExtractor::isBlockValidForExtraction(**BBBegin)) { 90 Result.clear(); 91 return Result; 92 } 93 } while (++BBBegin != BBEnd); 94 95 #ifndef NDEBUG 96 for (SetVector<BasicBlock *>::iterator I = std::next(Result.begin()), 97 E = Result.end(); 98 I != E; ++I) 99 for (pred_iterator PI = pred_begin(*I), PE = pred_end(*I); 100 PI != PE; ++PI) 101 assert(Result.count(*PI) && 102 "No blocks in this region may have entries from outside the region" 103 " except for the first block!"); 104 #endif 105 106 return Result; 107 } 108 109 /// \brief Helper to call buildExtractionBlockSet with an ArrayRef. 110 static SetVector<BasicBlock *> 111 buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs) { 112 return buildExtractionBlockSet(BBs.begin(), BBs.end()); 113 } 114 115 CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, 116 bool AggregateArgs, BlockFrequencyInfo *BFI, 117 BranchProbabilityInfo *BPI) 118 : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 119 BPI(BPI), Blocks(buildExtractionBlockSet(BBs)), NumExitBlocks(~0U) {} 120 121 CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, 122 BlockFrequencyInfo *BFI, 123 BranchProbabilityInfo *BPI) 124 : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), 125 BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks())), 126 NumExitBlocks(~0U) {} 127 128 /// definedInRegion - Return true if the specified value is defined in the 129 /// extracted region. 130 static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { 131 if (Instruction *I = dyn_cast<Instruction>(V)) 132 if (Blocks.count(I->getParent())) 133 return true; 134 return false; 135 } 136 137 /// definedInCaller - Return true if the specified value is defined in the 138 /// function being code extracted, but not in the region being extracted. 139 /// These values must be passed in as live-ins to the function. 140 static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { 141 if (isa<Argument>(V)) return true; 142 if (Instruction *I = dyn_cast<Instruction>(V)) 143 if (!Blocks.count(I->getParent())) 144 return true; 145 return false; 146 } 147 148 void CodeExtractor::findInputsOutputs(ValueSet &Inputs, 149 ValueSet &Outputs) const { 150 for (BasicBlock *BB : Blocks) { 151 // If a used value is defined outside the region, it's an input. If an 152 // instruction is used outside the region, it's an output. 153 for (Instruction &II : *BB) { 154 for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; 155 ++OI) 156 if (definedInCaller(Blocks, *OI)) 157 Inputs.insert(*OI); 158 159 for (User *U : II.users()) 160 if (!definedInRegion(Blocks, U)) { 161 Outputs.insert(&II); 162 break; 163 } 164 } 165 } 166 } 167 168 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the 169 /// region, we need to split the entry block of the region so that the PHI node 170 /// is easier to deal with. 171 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { 172 unsigned NumPredsFromRegion = 0; 173 unsigned NumPredsOutsideRegion = 0; 174 175 if (Header != &Header->getParent()->getEntryBlock()) { 176 PHINode *PN = dyn_cast<PHINode>(Header->begin()); 177 if (!PN) return; // No PHI nodes. 178 179 // If the header node contains any PHI nodes, check to see if there is more 180 // than one entry from outside the region. If so, we need to sever the 181 // header block into two. 182 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 183 if (Blocks.count(PN->getIncomingBlock(i))) 184 ++NumPredsFromRegion; 185 else 186 ++NumPredsOutsideRegion; 187 188 // If there is one (or fewer) predecessor from outside the region, we don't 189 // need to do anything special. 190 if (NumPredsOutsideRegion <= 1) return; 191 } 192 193 // Otherwise, we need to split the header block into two pieces: one 194 // containing PHI nodes merging values from outside of the region, and a 195 // second that contains all of the code for the block and merges back any 196 // incoming values from inside of the region. 197 BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI()->getIterator(); 198 BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs, 199 Header->getName()+".ce"); 200 201 // We only want to code extract the second block now, and it becomes the new 202 // header of the region. 203 BasicBlock *OldPred = Header; 204 Blocks.remove(OldPred); 205 Blocks.insert(NewBB); 206 Header = NewBB; 207 208 // Okay, update dominator sets. The blocks that dominate the new one are the 209 // blocks that dominate TIBB plus the new block itself. 210 if (DT) 211 DT->splitBlock(NewBB); 212 213 // Okay, now we need to adjust the PHI nodes and any branches from within the 214 // region to go to the new header block instead of the old header block. 215 if (NumPredsFromRegion) { 216 PHINode *PN = cast<PHINode>(OldPred->begin()); 217 // Loop over all of the predecessors of OldPred that are in the region, 218 // changing them to branch to NewBB instead. 219 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 220 if (Blocks.count(PN->getIncomingBlock(i))) { 221 TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator(); 222 TI->replaceUsesOfWith(OldPred, NewBB); 223 } 224 225 // Okay, everything within the region is now branching to the right block, we 226 // just have to update the PHI nodes now, inserting PHI nodes into NewBB. 227 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { 228 PHINode *PN = cast<PHINode>(AfterPHIs); 229 // Create a new PHI node in the new region, which has an incoming value 230 // from OldPred of PN. 231 PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, 232 PN->getName() + ".ce", &NewBB->front()); 233 NewPN->addIncoming(PN, OldPred); 234 235 // Loop over all of the incoming value in PN, moving them to NewPN if they 236 // are from the extracted region. 237 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 238 if (Blocks.count(PN->getIncomingBlock(i))) { 239 NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); 240 PN->removeIncomingValue(i); 241 --i; 242 } 243 } 244 } 245 } 246 } 247 248 void CodeExtractor::splitReturnBlocks() { 249 for (BasicBlock *Block : Blocks) 250 if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { 251 BasicBlock *New = 252 Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); 253 if (DT) { 254 // Old dominates New. New node dominates all other nodes dominated 255 // by Old. 256 DomTreeNode *OldNode = DT->getNode(Block); 257 SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), 258 OldNode->end()); 259 260 DomTreeNode *NewNode = DT->addNewBlock(New, Block); 261 262 for (DomTreeNode *I : Children) 263 DT->changeImmediateDominator(I, NewNode); 264 } 265 } 266 } 267 268 /// constructFunction - make a function based on inputs and outputs, as follows: 269 /// f(in0, ..., inN, out0, ..., outN) 270 /// 271 Function *CodeExtractor::constructFunction(const ValueSet &inputs, 272 const ValueSet &outputs, 273 BasicBlock *header, 274 BasicBlock *newRootNode, 275 BasicBlock *newHeader, 276 Function *oldFunction, 277 Module *M) { 278 DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); 279 DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); 280 281 // This function returns unsigned, outputs will go back by reference. 282 switch (NumExitBlocks) { 283 case 0: 284 case 1: RetTy = Type::getVoidTy(header->getContext()); break; 285 case 2: RetTy = Type::getInt1Ty(header->getContext()); break; 286 default: RetTy = Type::getInt16Ty(header->getContext()); break; 287 } 288 289 std::vector<Type*> paramTy; 290 291 // Add the types of the input values to the function's argument list 292 for (Value *value : inputs) { 293 DEBUG(dbgs() << "value used in func: " << *value << "\n"); 294 paramTy.push_back(value->getType()); 295 } 296 297 // Add the types of the output values to the function's argument list. 298 for (Value *output : outputs) { 299 DEBUG(dbgs() << "instr used in func: " << *output << "\n"); 300 if (AggregateArgs) 301 paramTy.push_back(output->getType()); 302 else 303 paramTy.push_back(PointerType::getUnqual(output->getType())); 304 } 305 306 DEBUG({ 307 dbgs() << "Function type: " << *RetTy << " f("; 308 for (Type *i : paramTy) 309 dbgs() << *i << ", "; 310 dbgs() << ")\n"; 311 }); 312 313 StructType *StructTy; 314 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 315 StructTy = StructType::get(M->getContext(), paramTy); 316 paramTy.clear(); 317 paramTy.push_back(PointerType::getUnqual(StructTy)); 318 } 319 FunctionType *funcType = 320 FunctionType::get(RetTy, paramTy, false); 321 322 // Create the new function 323 Function *newFunction = Function::Create(funcType, 324 GlobalValue::InternalLinkage, 325 oldFunction->getName() + "_" + 326 header->getName(), M); 327 // If the old function is no-throw, so is the new one. 328 if (oldFunction->doesNotThrow()) 329 newFunction->setDoesNotThrow(); 330 331 // Inherit the uwtable attribute if we need to. 332 if (oldFunction->hasUWTable()) 333 newFunction->setHasUWTable(); 334 335 // Inherit all of the target dependent attributes. 336 // (e.g. If the extracted region contains a call to an x86.sse 337 // instruction we need to make sure that the extracted region has the 338 // "target-features" attribute allowing it to be lowered. 339 // FIXME: This should be changed to check to see if a specific 340 // attribute can not be inherited. 341 AttrBuilder AB(oldFunction->getAttributes().getFnAttributes()); 342 for (const auto &Attr : AB.td_attrs()) 343 newFunction->addFnAttr(Attr.first, Attr.second); 344 345 newFunction->getBasicBlockList().push_back(newRootNode); 346 347 // Create an iterator to name all of the arguments we inserted. 348 Function::arg_iterator AI = newFunction->arg_begin(); 349 350 // Rewrite all users of the inputs in the extracted region to use the 351 // arguments (or appropriate addressing into struct) instead. 352 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 353 Value *RewriteVal; 354 if (AggregateArgs) { 355 Value *Idx[2]; 356 Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); 357 Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); 358 TerminatorInst *TI = newFunction->begin()->getTerminator(); 359 GetElementPtrInst *GEP = GetElementPtrInst::Create( 360 StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); 361 RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); 362 } else 363 RewriteVal = &*AI++; 364 365 std::vector<User*> Users(inputs[i]->user_begin(), inputs[i]->user_end()); 366 for (User *use : Users) 367 if (Instruction *inst = dyn_cast<Instruction>(use)) 368 if (Blocks.count(inst->getParent())) 369 inst->replaceUsesOfWith(inputs[i], RewriteVal); 370 } 371 372 // Set names for input and output arguments. 373 if (!AggregateArgs) { 374 AI = newFunction->arg_begin(); 375 for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) 376 AI->setName(inputs[i]->getName()); 377 for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) 378 AI->setName(outputs[i]->getName()+".out"); 379 } 380 381 // Rewrite branches to basic blocks outside of the loop to new dummy blocks 382 // within the new function. This must be done before we lose track of which 383 // blocks were originally in the code region. 384 std::vector<User*> Users(header->user_begin(), header->user_end()); 385 for (unsigned i = 0, e = Users.size(); i != e; ++i) 386 // The BasicBlock which contains the branch is not in the region 387 // modify the branch target to a new block 388 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i])) 389 if (!Blocks.count(TI->getParent()) && 390 TI->getParent()->getParent() == oldFunction) 391 TI->replaceUsesOfWith(header, newHeader); 392 393 return newFunction; 394 } 395 396 /// FindPhiPredForUseInBlock - Given a value and a basic block, find a PHI 397 /// that uses the value within the basic block, and return the predecessor 398 /// block associated with that use, or return 0 if none is found. 399 static BasicBlock* FindPhiPredForUseInBlock(Value* Used, BasicBlock* BB) { 400 for (Use &U : Used->uses()) { 401 PHINode *P = dyn_cast<PHINode>(U.getUser()); 402 if (P && P->getParent() == BB) 403 return P->getIncomingBlock(U); 404 } 405 406 return nullptr; 407 } 408 409 /// emitCallAndSwitchStatement - This method sets up the caller side by adding 410 /// the call instruction, splitting any PHI nodes in the header block as 411 /// necessary. 412 void CodeExtractor:: 413 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, 414 ValueSet &inputs, ValueSet &outputs) { 415 // Emit a call to the new function, passing in: *pointer to struct (if 416 // aggregating parameters), or plan inputs and allocated memory for outputs 417 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads; 418 419 Module *M = newFunction->getParent(); 420 LLVMContext &Context = M->getContext(); 421 const DataLayout &DL = M->getDataLayout(); 422 423 // Add inputs as params, or to be filled into the struct 424 for (Value *input : inputs) 425 if (AggregateArgs) 426 StructValues.push_back(input); 427 else 428 params.push_back(input); 429 430 // Create allocas for the outputs 431 for (Value *output : outputs) { 432 if (AggregateArgs) { 433 StructValues.push_back(output); 434 } else { 435 AllocaInst *alloca = 436 new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), 437 nullptr, output->getName() + ".loc", 438 &codeReplacer->getParent()->front().front()); 439 ReloadOutputs.push_back(alloca); 440 params.push_back(alloca); 441 } 442 } 443 444 StructType *StructArgTy = nullptr; 445 AllocaInst *Struct = nullptr; 446 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { 447 std::vector<Type*> ArgTypes; 448 for (ValueSet::iterator v = StructValues.begin(), 449 ve = StructValues.end(); v != ve; ++v) 450 ArgTypes.push_back((*v)->getType()); 451 452 // Allocate a struct at the beginning of this function 453 StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); 454 Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, 455 "structArg", 456 &codeReplacer->getParent()->front().front()); 457 params.push_back(Struct); 458 459 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 460 Value *Idx[2]; 461 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 462 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); 463 GetElementPtrInst *GEP = GetElementPtrInst::Create( 464 StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); 465 codeReplacer->getInstList().push_back(GEP); 466 StoreInst *SI = new StoreInst(StructValues[i], GEP); 467 codeReplacer->getInstList().push_back(SI); 468 } 469 } 470 471 // Emit the call to the function 472 CallInst *call = CallInst::Create(newFunction, params, 473 NumExitBlocks > 1 ? "targetBlock" : ""); 474 codeReplacer->getInstList().push_back(call); 475 476 Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); 477 unsigned FirstOut = inputs.size(); 478 if (!AggregateArgs) 479 std::advance(OutputArgBegin, inputs.size()); 480 481 // Reload the outputs passed in by reference 482 for (unsigned i = 0, e = outputs.size(); i != e; ++i) { 483 Value *Output = nullptr; 484 if (AggregateArgs) { 485 Value *Idx[2]; 486 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 487 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); 488 GetElementPtrInst *GEP = GetElementPtrInst::Create( 489 StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); 490 codeReplacer->getInstList().push_back(GEP); 491 Output = GEP; 492 } else { 493 Output = ReloadOutputs[i]; 494 } 495 LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); 496 Reloads.push_back(load); 497 codeReplacer->getInstList().push_back(load); 498 std::vector<User*> Users(outputs[i]->user_begin(), outputs[i]->user_end()); 499 for (unsigned u = 0, e = Users.size(); u != e; ++u) { 500 Instruction *inst = cast<Instruction>(Users[u]); 501 if (!Blocks.count(inst->getParent())) 502 inst->replaceUsesOfWith(outputs[i], load); 503 } 504 } 505 506 // Now we can emit a switch statement using the call as a value. 507 SwitchInst *TheSwitch = 508 SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), 509 codeReplacer, 0, codeReplacer); 510 511 // Since there may be multiple exits from the original region, make the new 512 // function return an unsigned, switch on that number. This loop iterates 513 // over all of the blocks in the extracted region, updating any terminator 514 // instructions in the to-be-extracted region that branch to blocks that are 515 // not in the region to be extracted. 516 std::map<BasicBlock*, BasicBlock*> ExitBlockMap; 517 518 unsigned switchVal = 0; 519 for (BasicBlock *Block : Blocks) { 520 TerminatorInst *TI = Block->getTerminator(); 521 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 522 if (!Blocks.count(TI->getSuccessor(i))) { 523 BasicBlock *OldTarget = TI->getSuccessor(i); 524 // add a new basic block which returns the appropriate value 525 BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; 526 if (!NewTarget) { 527 // If we don't already have an exit stub for this non-extracted 528 // destination, create one now! 529 NewTarget = BasicBlock::Create(Context, 530 OldTarget->getName() + ".exitStub", 531 newFunction); 532 unsigned SuccNum = switchVal++; 533 534 Value *brVal = nullptr; 535 switch (NumExitBlocks) { 536 case 0: 537 case 1: break; // No value needed. 538 case 2: // Conditional branch, return a bool 539 brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); 540 break; 541 default: 542 brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); 543 break; 544 } 545 546 ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget); 547 548 // Update the switch instruction. 549 TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), 550 SuccNum), 551 OldTarget); 552 553 // Restore values just before we exit 554 Function::arg_iterator OAI = OutputArgBegin; 555 for (unsigned out = 0, e = outputs.size(); out != e; ++out) { 556 // For an invoke, the normal destination is the only one that is 557 // dominated by the result of the invocation 558 BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent(); 559 560 bool DominatesDef = true; 561 562 BasicBlock *NormalDest = nullptr; 563 if (auto *Invoke = dyn_cast<InvokeInst>(outputs[out])) 564 NormalDest = Invoke->getNormalDest(); 565 566 if (NormalDest) { 567 DefBlock = NormalDest; 568 569 // Make sure we are looking at the original successor block, not 570 // at a newly inserted exit block, which won't be in the dominator 571 // info. 572 for (const auto &I : ExitBlockMap) 573 if (DefBlock == I.second) { 574 DefBlock = I.first; 575 break; 576 } 577 578 // In the extract block case, if the block we are extracting ends 579 // with an invoke instruction, make sure that we don't emit a 580 // store of the invoke value for the unwind block. 581 if (!DT && DefBlock != OldTarget) 582 DominatesDef = false; 583 } 584 585 if (DT) { 586 DominatesDef = DT->dominates(DefBlock, OldTarget); 587 588 // If the output value is used by a phi in the target block, 589 // then we need to test for dominance of the phi's predecessor 590 // instead. Unfortunately, this a little complicated since we 591 // have already rewritten uses of the value to uses of the reload. 592 BasicBlock* pred = FindPhiPredForUseInBlock(Reloads[out], 593 OldTarget); 594 if (pred && DT && DT->dominates(DefBlock, pred)) 595 DominatesDef = true; 596 } 597 598 if (DominatesDef) { 599 if (AggregateArgs) { 600 Value *Idx[2]; 601 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); 602 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), 603 FirstOut+out); 604 GetElementPtrInst *GEP = GetElementPtrInst::Create( 605 StructArgTy, &*OAI, Idx, "gep_" + outputs[out]->getName(), 606 NTRet); 607 new StoreInst(outputs[out], GEP, NTRet); 608 } else { 609 new StoreInst(outputs[out], &*OAI, NTRet); 610 } 611 } 612 // Advance output iterator even if we don't emit a store 613 if (!AggregateArgs) ++OAI; 614 } 615 } 616 617 // rewrite the original branch instruction with this new target 618 TI->setSuccessor(i, NewTarget); 619 } 620 } 621 622 // Now that we've done the deed, simplify the switch instruction. 623 Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); 624 switch (NumExitBlocks) { 625 case 0: 626 // There are no successors (the block containing the switch itself), which 627 // means that previously this was the last part of the function, and hence 628 // this should be rewritten as a `ret' 629 630 // Check if the function should return a value 631 if (OldFnRetTy->isVoidTy()) { 632 ReturnInst::Create(Context, nullptr, TheSwitch); // Return void 633 } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { 634 // return what we have 635 ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); 636 } else { 637 // Otherwise we must have code extracted an unwind or something, just 638 // return whatever we want. 639 ReturnInst::Create(Context, 640 Constant::getNullValue(OldFnRetTy), TheSwitch); 641 } 642 643 TheSwitch->eraseFromParent(); 644 break; 645 case 1: 646 // Only a single destination, change the switch into an unconditional 647 // branch. 648 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); 649 TheSwitch->eraseFromParent(); 650 break; 651 case 2: 652 BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), 653 call, TheSwitch); 654 TheSwitch->eraseFromParent(); 655 break; 656 default: 657 // Otherwise, make the default destination of the switch instruction be one 658 // of the other successors. 659 TheSwitch->setCondition(call); 660 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); 661 // Remove redundant case 662 TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); 663 break; 664 } 665 } 666 667 void CodeExtractor::moveCodeToFunction(Function *newFunction) { 668 Function *oldFunc = (*Blocks.begin())->getParent(); 669 Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); 670 Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); 671 672 for (BasicBlock *Block : Blocks) { 673 // Delete the basic block from the old function, and the list of blocks 674 oldBlocks.remove(Block); 675 676 // Insert this basic block into the new function 677 newBlocks.push_back(Block); 678 } 679 } 680 681 void CodeExtractor::calculateNewCallTerminatorWeights( 682 BasicBlock *CodeReplacer, 683 DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, 684 BranchProbabilityInfo *BPI) { 685 typedef BlockFrequencyInfoImplBase::Distribution Distribution; 686 typedef BlockFrequencyInfoImplBase::BlockNode BlockNode; 687 688 // Update the branch weights for the exit block. 689 TerminatorInst *TI = CodeReplacer->getTerminator(); 690 SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); 691 692 // Block Frequency distribution with dummy node. 693 Distribution BranchDist; 694 695 // Add each of the frequencies of the successors. 696 for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { 697 BlockNode ExitNode(i); 698 uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); 699 if (ExitFreq != 0) 700 BranchDist.addExit(ExitNode, ExitFreq); 701 else 702 BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); 703 } 704 705 // Check for no total weight. 706 if (BranchDist.Total == 0) 707 return; 708 709 // Normalize the distribution so that they can fit in unsigned. 710 BranchDist.normalize(); 711 712 // Create normalized branch weights and set the metadata. 713 for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { 714 const auto &Weight = BranchDist.Weights[I]; 715 716 // Get the weight and update the current BFI. 717 BranchWeights[Weight.TargetNode.Index] = Weight.Amount; 718 BranchProbability BP(Weight.Amount, BranchDist.Total); 719 BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); 720 } 721 TI->setMetadata( 722 LLVMContext::MD_prof, 723 MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); 724 } 725 726 Function *CodeExtractor::extractCodeRegion() { 727 if (!isEligible()) 728 return nullptr; 729 730 ValueSet inputs, outputs; 731 732 // Assumption: this is a single-entry code region, and the header is the first 733 // block in the region. 734 BasicBlock *header = *Blocks.begin(); 735 736 // Calculate the entry frequency of the new function before we change the root 737 // block. 738 BlockFrequency EntryFreq; 739 if (BFI) { 740 assert(BPI && "Both BPI and BFI are required to preserve profile info"); 741 for (BasicBlock *Pred : predecessors(header)) { 742 if (Blocks.count(Pred)) 743 continue; 744 EntryFreq += 745 BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); 746 } 747 } 748 749 // If we have to split PHI nodes or the entry block, do so now. 750 severSplitPHINodes(header); 751 752 // If we have any return instructions in the region, split those blocks so 753 // that the return is not in the region. 754 splitReturnBlocks(); 755 756 Function *oldFunction = header->getParent(); 757 758 // This takes place of the original loop 759 BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 760 "codeRepl", oldFunction, 761 header); 762 763 // The new function needs a root node because other nodes can branch to the 764 // head of the region, but the entry node of a function cannot have preds. 765 BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 766 "newFuncRoot"); 767 newFuncRoot->getInstList().push_back(BranchInst::Create(header)); 768 769 // Find inputs to, outputs from the code region. 770 findInputsOutputs(inputs, outputs); 771 772 // Calculate the exit blocks for the extracted region and the total exit 773 // weights for each of those blocks. 774 DenseMap<BasicBlock *, BlockFrequency> ExitWeights; 775 SmallPtrSet<BasicBlock *, 1> ExitBlocks; 776 for (BasicBlock *Block : Blocks) { 777 for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; 778 ++SI) { 779 if (!Blocks.count(*SI)) { 780 // Update the branch weight for this successor. 781 if (BFI) { 782 BlockFrequency &BF = ExitWeights[*SI]; 783 BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); 784 } 785 ExitBlocks.insert(*SI); 786 } 787 } 788 } 789 NumExitBlocks = ExitBlocks.size(); 790 791 // Construct new function based on inputs/outputs & add allocas for all defs. 792 Function *newFunction = constructFunction(inputs, outputs, header, 793 newFuncRoot, 794 codeReplacer, oldFunction, 795 oldFunction->getParent()); 796 797 // Update the entry count of the function. 798 if (BFI) { 799 Optional<uint64_t> EntryCount = 800 BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); 801 if (EntryCount.hasValue()) 802 newFunction->setEntryCount(EntryCount.getValue()); 803 BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); 804 } 805 806 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); 807 808 moveCodeToFunction(newFunction); 809 810 // Update the branch weights for the exit block. 811 if (BFI && NumExitBlocks > 1) 812 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); 813 814 // Loop over all of the PHI nodes in the header block, and change any 815 // references to the old incoming edge to be the new incoming edge. 816 for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { 817 PHINode *PN = cast<PHINode>(I); 818 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 819 if (!Blocks.count(PN->getIncomingBlock(i))) 820 PN->setIncomingBlock(i, newFuncRoot); 821 } 822 823 // Look at all successors of the codeReplacer block. If any of these blocks 824 // had PHI nodes in them, we need to update the "from" block to be the code 825 // replacer, not the original block in the extracted region. 826 std::vector<BasicBlock*> Succs(succ_begin(codeReplacer), 827 succ_end(codeReplacer)); 828 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 829 for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) { 830 PHINode *PN = cast<PHINode>(I); 831 std::set<BasicBlock*> ProcessedPreds; 832 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 833 if (Blocks.count(PN->getIncomingBlock(i))) { 834 if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second) 835 PN->setIncomingBlock(i, codeReplacer); 836 else { 837 // There were multiple entries in the PHI for this block, now there 838 // is only one, so remove the duplicated entries. 839 PN->removeIncomingValue(i, false); 840 --i; --e; 841 } 842 } 843 } 844 845 //cerr << "NEW FUNCTION: " << *newFunction; 846 // verifyFunction(*newFunction); 847 848 // cerr << "OLD FUNCTION: " << *oldFunction; 849 // verifyFunction(*oldFunction); 850 851 DEBUG(if (verifyFunction(*newFunction)) 852 report_fatal_error("verifyFunction failed!")); 853 return newFunction; 854 } 855