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