1 //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 // Implementation for the IROutliner which is used by the IROutliner Pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/IROutliner.h" 15 #include "llvm/Analysis/IRSimilarityIdentifier.h" 16 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 17 #include "llvm/Analysis/TargetTransformInfo.h" 18 #include "llvm/IR/Attributes.h" 19 #include "llvm/IR/DIBuilder.h" 20 #include "llvm/IR/DebugInfo.h" 21 #include "llvm/IR/DebugInfoMetadata.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Mangler.h" 24 #include "llvm/IR/PassManager.h" 25 #include "llvm/InitializePasses.h" 26 #include "llvm/Pass.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Transforms/IPO.h" 29 #include <vector> 30 31 #define DEBUG_TYPE "iroutliner" 32 33 using namespace llvm; 34 using namespace IRSimilarity; 35 36 // A command flag to be used for debugging to exclude branches from similarity 37 // matching and outlining. 38 namespace llvm { 39 extern cl::opt<bool> DisableBranches; 40 41 // A command flag to be used for debugging to indirect calls from similarity 42 // matching and outlining. 43 extern cl::opt<bool> DisableIndirectCalls; 44 45 // A command flag to be used for debugging to exclude intrinsics from similarity 46 // matching and outlining. 47 extern cl::opt<bool> DisableIntrinsics; 48 49 } // namespace llvm 50 51 // Set to true if the user wants the ir outliner to run on linkonceodr linkage 52 // functions. This is false by default because the linker can dedupe linkonceodr 53 // functions. Since the outliner is confined to a single module (modulo LTO), 54 // this is off by default. It should, however, be the default behavior in 55 // LTO. 56 static cl::opt<bool> EnableLinkOnceODRIROutlining( 57 "enable-linkonceodr-ir-outlining", cl::Hidden, 58 cl::desc("Enable the IR outliner on linkonceodr functions"), 59 cl::init(false)); 60 61 // This is a debug option to test small pieces of code to ensure that outlining 62 // works correctly. 63 static cl::opt<bool> NoCostModel( 64 "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden, 65 cl::desc("Debug option to outline greedily, without restriction that " 66 "calculated benefit outweighs cost")); 67 68 /// The OutlinableGroup holds all the overarching information for outlining 69 /// a set of regions that are structurally similar to one another, such as the 70 /// types of the overall function, the output blocks, the sets of stores needed 71 /// and a list of the different regions. This information is used in the 72 /// deduplication of extracted regions with the same structure. 73 struct OutlinableGroup { 74 /// The sections that could be outlined 75 std::vector<OutlinableRegion *> Regions; 76 77 /// The argument types for the function created as the overall function to 78 /// replace the extracted function for each region. 79 std::vector<Type *> ArgumentTypes; 80 /// The FunctionType for the overall function. 81 FunctionType *OutlinedFunctionType = nullptr; 82 /// The Function for the collective overall function. 83 Function *OutlinedFunction = nullptr; 84 85 /// Flag for whether we should not consider this group of OutlinableRegions 86 /// for extraction. 87 bool IgnoreGroup = false; 88 89 /// The return blocks for the overall function. 90 DenseMap<Value *, BasicBlock *> EndBBs; 91 92 /// The PHIBlocks with their corresponding return block based on the return 93 /// value as the key. 94 DenseMap<Value *, BasicBlock *> PHIBlocks; 95 96 /// A set containing the different GVN store sets needed. Each array contains 97 /// a sorted list of the different values that need to be stored into output 98 /// registers. 99 DenseSet<ArrayRef<unsigned>> OutputGVNCombinations; 100 101 /// Flag for whether the \ref ArgumentTypes have been defined after the 102 /// extraction of the first region. 103 bool InputTypesSet = false; 104 105 /// The number of input values in \ref ArgumentTypes. Anything after this 106 /// index in ArgumentTypes is an output argument. 107 unsigned NumAggregateInputs = 0; 108 109 /// The mapping of the canonical numbering of the values in outlined sections 110 /// to specific arguments. 111 DenseMap<unsigned, unsigned> CanonicalNumberToAggArg; 112 113 /// The number of branches in the region target a basic block that is outside 114 /// of the region. 115 unsigned BranchesToOutside = 0; 116 117 /// Tracker counting backwards from the highest unsigned value possible to 118 /// avoid conflicting with the GVNs of assigned values. We start at -3 since 119 /// -2 and -1 are assigned by the DenseMap. 120 unsigned PHINodeGVNTracker = -3; 121 122 DenseMap<unsigned, 123 std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>> 124 PHINodeGVNToGVNs; 125 DenseMap<hash_code, unsigned> GVNsToPHINodeGVN; 126 127 /// The number of instructions that will be outlined by extracting \ref 128 /// Regions. 129 InstructionCost Benefit = 0; 130 /// The number of added instructions needed for the outlining of the \ref 131 /// Regions. 132 InstructionCost Cost = 0; 133 134 /// The argument that needs to be marked with the swifterr attribute. If not 135 /// needed, there is no value. 136 Optional<unsigned> SwiftErrorArgument; 137 138 /// For the \ref Regions, we look at every Value. If it is a constant, 139 /// we check whether it is the same in Region. 140 /// 141 /// \param [in,out] NotSame contains the global value numbers where the 142 /// constant is not always the same, and must be passed in as an argument. 143 void findSameConstants(DenseSet<unsigned> &NotSame); 144 145 /// For the regions, look at each set of GVN stores needed and account for 146 /// each combination. Add an argument to the argument types if there is 147 /// more than one combination. 148 /// 149 /// \param [in] M - The module we are outlining from. 150 void collectGVNStoreSets(Module &M); 151 }; 152 153 /// Move the contents of \p SourceBB to before the last instruction of \p 154 /// TargetBB. 155 /// \param SourceBB - the BasicBlock to pull Instructions from. 156 /// \param TargetBB - the BasicBlock to put Instruction into. 157 static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) { 158 for (Instruction &I : llvm::make_early_inc_range(SourceBB)) 159 I.moveBefore(TargetBB, TargetBB.end()); 160 } 161 162 /// A function to sort the keys of \p Map, which must be a mapping of constant 163 /// values to basic blocks and return it in \p SortedKeys 164 /// 165 /// \param SortedKeys - The vector the keys will be return in and sorted. 166 /// \param Map - The DenseMap containing keys to sort. 167 static void getSortedConstantKeys(std::vector<Value *> &SortedKeys, 168 DenseMap<Value *, BasicBlock *> &Map) { 169 for (auto &VtoBB : Map) 170 SortedKeys.push_back(VtoBB.first); 171 172 stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) { 173 const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS); 174 const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS); 175 assert(RHSC && "Not a constant integer in return value?"); 176 assert(LHSC && "Not a constant integer in return value?"); 177 178 return LHSC->getLimitedValue() < RHSC->getLimitedValue(); 179 }); 180 } 181 182 Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other, 183 Value *V) { 184 Optional<unsigned> GVN = Candidate->getGVN(V); 185 assert(GVN.hasValue() && "No GVN for incoming value"); 186 Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN); 187 Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum); 188 Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN); 189 return FoundValueOpt.getValueOr(nullptr); 190 } 191 192 BasicBlock * 193 OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other, 194 BasicBlock *BB) { 195 Instruction *FirstNonPHI = BB->getFirstNonPHI(); 196 assert(FirstNonPHI && "block is empty?"); 197 Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI); 198 if (!CorrespondingVal) 199 return nullptr; 200 BasicBlock *CorrespondingBlock = 201 cast<Instruction>(CorrespondingVal)->getParent(); 202 return CorrespondingBlock; 203 } 204 205 /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found 206 /// in \p Included to branch to BasicBlock \p Replace if they currently branch 207 /// to the BasicBlock \p Find. This is used to fix up the incoming basic blocks 208 /// when PHINodes are included in outlined regions. 209 /// 210 /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be 211 /// checked. 212 /// \param Find - The successor block to be replaced. 213 /// \param Replace - The new succesor block to branch to. 214 /// \param Included - The set of blocks about to be outlined. 215 static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find, 216 BasicBlock *Replace, 217 DenseSet<BasicBlock *> &Included) { 218 for (PHINode &PN : PHIBlock->phis()) { 219 for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd; 220 ++Idx) { 221 // Check if the incoming block is included in the set of blocks being 222 // outlined. 223 BasicBlock *Incoming = PN.getIncomingBlock(Idx); 224 if (!Included.contains(Incoming)) 225 continue; 226 227 BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator()); 228 assert(BI && "Not a branch instruction?"); 229 // Look over the branching instructions into this block to see if we 230 // used to branch to Find in this outlined block. 231 for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End; 232 Succ++) { 233 // If we have found the block to replace, we do so here. 234 if (BI->getSuccessor(Succ) != Find) 235 continue; 236 BI->setSuccessor(Succ, Replace); 237 } 238 } 239 } 240 } 241 242 243 void OutlinableRegion::splitCandidate() { 244 assert(!CandidateSplit && "Candidate already split!"); 245 246 Instruction *BackInst = Candidate->backInstruction(); 247 248 Instruction *EndInst = nullptr; 249 // Check whether the last instruction is a terminator, if it is, we do 250 // not split on the following instruction. We leave the block as it is. We 251 // also check that this is not the last instruction in the Module, otherwise 252 // the check for whether the current following instruction matches the 253 // previously recorded instruction will be incorrect. 254 if (!BackInst->isTerminator() || 255 BackInst->getParent() != &BackInst->getFunction()->back()) { 256 EndInst = Candidate->end()->Inst; 257 assert(EndInst && "Expected an end instruction?"); 258 } 259 260 // We check if the current instruction following the last instruction in the 261 // region is the same as the recorded instruction following the last 262 // instruction. If they do not match, there could be problems in rewriting 263 // the program after outlining, so we ignore it. 264 if (!BackInst->isTerminator() && 265 EndInst != BackInst->getNextNonDebugInstruction()) 266 return; 267 268 Instruction *StartInst = (*Candidate->begin()).Inst; 269 assert(StartInst && "Expected a start instruction?"); 270 StartBB = StartInst->getParent(); 271 PrevBB = StartBB; 272 273 DenseSet<BasicBlock *> BBSet; 274 Candidate->getBasicBlocks(BBSet); 275 276 // We iterate over the instructions in the region, if we find a PHINode, we 277 // check if there are predecessors outside of the region, if there are, 278 // we ignore this region since we are unable to handle the severing of the 279 // phi node right now. 280 281 // TODO: Handle extraneous inputs for PHINodes through variable number of 282 // inputs, similar to how outputs are handled. 283 BasicBlock::iterator It = StartInst->getIterator(); 284 EndBB = BackInst->getParent(); 285 BasicBlock *IBlock; 286 bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst; 287 while (PHINode *PN = dyn_cast<PHINode>(&*It)) { 288 unsigned NumPredsOutsideRegion = 0; 289 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 290 if (!BBSet.contains(PN->getIncomingBlock(i))) { 291 ++NumPredsOutsideRegion; 292 continue; 293 } 294 295 // We must consider the case there the incoming block to the PHINode is 296 // the same as the final block of the OutlinableRegion. If this is the 297 // case, the branch from this block must also be outlined to be valid. 298 IBlock = PN->getIncomingBlock(i); 299 if (IBlock == EndBB && EndBBTermAndBackInstDifferent) 300 ++NumPredsOutsideRegion; 301 } 302 303 if (NumPredsOutsideRegion > 1) 304 return; 305 306 It++; 307 } 308 309 // If the region starts with a PHINode, but is not the initial instruction of 310 // the BasicBlock, we ignore this region for now. 311 if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin()) 312 return; 313 314 // If the region ends with a PHINode, but does not contain all of the phi node 315 // instructions of the region, we ignore it for now. 316 if (isa<PHINode>(BackInst) && 317 BackInst != &*std::prev(EndBB->getFirstInsertionPt())) 318 return; 319 320 // The basic block gets split like so: 321 // block: block: 322 // inst1 inst1 323 // inst2 inst2 324 // region1 br block_to_outline 325 // region2 block_to_outline: 326 // region3 -> region1 327 // region4 region2 328 // inst3 region3 329 // inst4 region4 330 // br block_after_outline 331 // block_after_outline: 332 // inst3 333 // inst4 334 335 std::string OriginalName = PrevBB->getName().str(); 336 337 StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline"); 338 PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB); 339 340 CandidateSplit = true; 341 if (!BackInst->isTerminator()) { 342 EndBB = EndInst->getParent(); 343 FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline"); 344 EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB); 345 FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB); 346 } else { 347 EndBB = BackInst->getParent(); 348 EndsInBranch = true; 349 FollowBB = nullptr; 350 } 351 352 // Refind the basic block set. 353 BBSet.clear(); 354 Candidate->getBasicBlocks(BBSet); 355 // For the phi nodes in the new starting basic block of the region, we 356 // reassign the targets of the basic blocks branching instructions. 357 replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet); 358 if (FollowBB) 359 replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet); 360 } 361 362 void OutlinableRegion::reattachCandidate() { 363 assert(CandidateSplit && "Candidate is not split!"); 364 365 // The basic block gets reattached like so: 366 // block: block: 367 // inst1 inst1 368 // inst2 inst2 369 // br block_to_outline region1 370 // block_to_outline: -> region2 371 // region1 region3 372 // region2 region4 373 // region3 inst3 374 // region4 inst4 375 // br block_after_outline 376 // block_after_outline: 377 // inst3 378 // inst4 379 assert(StartBB != nullptr && "StartBB for Candidate is not defined!"); 380 381 assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!"); 382 PrevBB->getTerminator()->eraseFromParent(); 383 384 // If we reattaching after outlining, we iterate over the phi nodes to 385 // the initial block, and reassign the branch instructions of the incoming 386 // blocks to the block we are remerging into. 387 if (!ExtractedFunction) { 388 DenseSet<BasicBlock *> BBSet; 389 Candidate->getBasicBlocks(BBSet); 390 391 replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet); 392 if (!EndsInBranch) 393 replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet); 394 } 395 396 moveBBContents(*StartBB, *PrevBB); 397 398 BasicBlock *PlacementBB = PrevBB; 399 if (StartBB != EndBB) 400 PlacementBB = EndBB; 401 if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) { 402 assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!"); 403 assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!"); 404 PlacementBB->getTerminator()->eraseFromParent(); 405 moveBBContents(*FollowBB, *PlacementBB); 406 PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB); 407 FollowBB->eraseFromParent(); 408 } 409 410 PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB); 411 StartBB->eraseFromParent(); 412 413 // Make sure to save changes back to the StartBB. 414 StartBB = PrevBB; 415 EndBB = nullptr; 416 PrevBB = nullptr; 417 FollowBB = nullptr; 418 419 CandidateSplit = false; 420 } 421 422 /// Find whether \p V matches the Constants previously found for the \p GVN. 423 /// 424 /// \param V - The value to check for consistency. 425 /// \param GVN - The global value number assigned to \p V. 426 /// \param GVNToConstant - The mapping of global value number to Constants. 427 /// \returns true if the Value matches the Constant mapped to by V and false if 428 /// it \p V is a Constant but does not match. 429 /// \returns None if \p V is not a Constant. 430 static Optional<bool> 431 constantMatches(Value *V, unsigned GVN, 432 DenseMap<unsigned, Constant *> &GVNToConstant) { 433 // See if we have a constants 434 Constant *CST = dyn_cast<Constant>(V); 435 if (!CST) 436 return None; 437 438 // Holds a mapping from a global value number to a Constant. 439 DenseMap<unsigned, Constant *>::iterator GVNToConstantIt; 440 bool Inserted; 441 442 443 // If we have a constant, try to make a new entry in the GVNToConstant. 444 std::tie(GVNToConstantIt, Inserted) = 445 GVNToConstant.insert(std::make_pair(GVN, CST)); 446 // If it was found and is not equal, it is not the same. We do not 447 // handle this case yet, and exit early. 448 if (Inserted || (GVNToConstantIt->second == CST)) 449 return true; 450 451 return false; 452 } 453 454 InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) { 455 InstructionCost Benefit = 0; 456 457 // Estimate the benefit of outlining a specific sections of the program. We 458 // delegate mostly this task to the TargetTransformInfo so that if the target 459 // has specific changes, we can have a more accurate estimate. 460 461 // However, getInstructionCost delegates the code size calculation for 462 // arithmetic instructions to getArithmeticInstrCost in 463 // include/Analysis/TargetTransformImpl.h, where it always estimates that the 464 // code size for a division and remainder instruction to be equal to 4, and 465 // everything else to 1. This is not an accurate representation of the 466 // division instruction for targets that have a native division instruction. 467 // To be overly conservative, we only add 1 to the number of instructions for 468 // each division instruction. 469 for (IRInstructionData &ID : *Candidate) { 470 Instruction *I = ID.Inst; 471 switch (I->getOpcode()) { 472 case Instruction::FDiv: 473 case Instruction::FRem: 474 case Instruction::SDiv: 475 case Instruction::SRem: 476 case Instruction::UDiv: 477 case Instruction::URem: 478 Benefit += 1; 479 break; 480 default: 481 Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize); 482 break; 483 } 484 } 485 486 return Benefit; 487 } 488 489 /// Check the \p OutputMappings structure for value \p Input, if it exists 490 /// it has been used as an output for outlining, and has been renamed, and we 491 /// return the new value, otherwise, we return the same value. 492 /// 493 /// \param OutputMappings [in] - The mapping of values to their renamed value 494 /// after being used as an output for an outlined region. 495 /// \param Input [in] - The value to find the remapped value of, if it exists. 496 /// \return The remapped value if it has been renamed, and the same value if has 497 /// not. 498 static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings, 499 Value *Input) { 500 DenseMap<Value *, Value *>::const_iterator OutputMapping = 501 OutputMappings.find(Input); 502 if (OutputMapping != OutputMappings.end()) 503 return OutputMapping->second; 504 return Input; 505 } 506 507 /// Find whether \p Region matches the global value numbering to Constant 508 /// mapping found so far. 509 /// 510 /// \param Region - The OutlinableRegion we are checking for constants 511 /// \param GVNToConstant - The mapping of global value number to Constants. 512 /// \param NotSame - The set of global value numbers that do not have the same 513 /// constant in each region. 514 /// \returns true if all Constants are the same in every use of a Constant in \p 515 /// Region and false if not 516 static bool 517 collectRegionsConstants(OutlinableRegion &Region, 518 DenseMap<unsigned, Constant *> &GVNToConstant, 519 DenseSet<unsigned> &NotSame) { 520 bool ConstantsTheSame = true; 521 522 IRSimilarityCandidate &C = *Region.Candidate; 523 for (IRInstructionData &ID : C) { 524 525 // Iterate over the operands in an instruction. If the global value number, 526 // assigned by the IRSimilarityCandidate, has been seen before, we check if 527 // the the number has been found to be not the same value in each instance. 528 for (Value *V : ID.OperVals) { 529 Optional<unsigned> GVNOpt = C.getGVN(V); 530 assert(GVNOpt.hasValue() && "Expected a GVN for operand?"); 531 unsigned GVN = GVNOpt.getValue(); 532 533 // Check if this global value has been found to not be the same already. 534 if (NotSame.contains(GVN)) { 535 if (isa<Constant>(V)) 536 ConstantsTheSame = false; 537 continue; 538 } 539 540 // If it has been the same so far, we check the value for if the 541 // associated Constant value match the previous instances of the same 542 // global value number. If the global value does not map to a Constant, 543 // it is considered to not be the same value. 544 Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant); 545 if (ConstantMatches.hasValue()) { 546 if (ConstantMatches.getValue()) 547 continue; 548 else 549 ConstantsTheSame = false; 550 } 551 552 // While this value is a register, it might not have been previously, 553 // make sure we don't already have a constant mapped to this global value 554 // number. 555 if (GVNToConstant.find(GVN) != GVNToConstant.end()) 556 ConstantsTheSame = false; 557 558 NotSame.insert(GVN); 559 } 560 } 561 562 return ConstantsTheSame; 563 } 564 565 void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) { 566 DenseMap<unsigned, Constant *> GVNToConstant; 567 568 for (OutlinableRegion *Region : Regions) 569 collectRegionsConstants(*Region, GVNToConstant, NotSame); 570 } 571 572 void OutlinableGroup::collectGVNStoreSets(Module &M) { 573 for (OutlinableRegion *OS : Regions) 574 OutputGVNCombinations.insert(OS->GVNStores); 575 576 // We are adding an extracted argument to decide between which output path 577 // to use in the basic block. It is used in a switch statement and only 578 // needs to be an integer. 579 if (OutputGVNCombinations.size() > 1) 580 ArgumentTypes.push_back(Type::getInt32Ty(M.getContext())); 581 } 582 583 /// Get the subprogram if it exists for one of the outlined regions. 584 /// 585 /// \param [in] Group - The set of regions to find a subprogram for. 586 /// \returns the subprogram if it exists, or nullptr. 587 static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) { 588 for (OutlinableRegion *OS : Group.Regions) 589 if (Function *F = OS->Call->getFunction()) 590 if (DISubprogram *SP = F->getSubprogram()) 591 return SP; 592 593 return nullptr; 594 } 595 596 Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group, 597 unsigned FunctionNameSuffix) { 598 assert(!Group.OutlinedFunction && "Function is already defined!"); 599 600 Type *RetTy = Type::getVoidTy(M.getContext()); 601 // All extracted functions _should_ have the same return type at this point 602 // since the similarity identifier ensures that all branches outside of the 603 // region occur in the same place. 604 605 // NOTE: Should we ever move to the model that uses a switch at every point 606 // needed, meaning that we could branch within the region or out, it is 607 // possible that we will need to switch to using the most general case all of 608 // the time. 609 for (OutlinableRegion *R : Group.Regions) { 610 Type *ExtractedFuncType = R->ExtractedFunction->getReturnType(); 611 if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) || 612 (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16))) 613 RetTy = ExtractedFuncType; 614 } 615 616 Group.OutlinedFunctionType = FunctionType::get( 617 RetTy, Group.ArgumentTypes, false); 618 619 // These functions will only be called from within the same module, so 620 // we can set an internal linkage. 621 Group.OutlinedFunction = Function::Create( 622 Group.OutlinedFunctionType, GlobalValue::InternalLinkage, 623 "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M); 624 625 // Transfer the swifterr attribute to the correct function parameter. 626 if (Group.SwiftErrorArgument.hasValue()) 627 Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(), 628 Attribute::SwiftError); 629 630 Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize); 631 Group.OutlinedFunction->addFnAttr(Attribute::MinSize); 632 633 // If there's a DISubprogram associated with this outlined function, then 634 // emit debug info for the outlined function. 635 if (DISubprogram *SP = getSubprogramOrNull(Group)) { 636 Function *F = Group.OutlinedFunction; 637 // We have a DISubprogram. Get its DICompileUnit. 638 DICompileUnit *CU = SP->getUnit(); 639 DIBuilder DB(M, true, CU); 640 DIFile *Unit = SP->getFile(); 641 Mangler Mg; 642 // Get the mangled name of the function for the linkage name. 643 std::string Dummy; 644 llvm::raw_string_ostream MangledNameStream(Dummy); 645 Mg.getNameWithPrefix(MangledNameStream, F, false); 646 647 DISubprogram *OutlinedSP = DB.createFunction( 648 Unit /* Context */, F->getName(), MangledNameStream.str(), 649 Unit /* File */, 650 0 /* Line 0 is reserved for compiler-generated code. */, 651 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */ 652 0, /* Line 0 is reserved for compiler-generated code. */ 653 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 654 /* Outlined code is optimized code by definition. */ 655 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); 656 657 // Don't add any new variables to the subprogram. 658 DB.finalizeSubprogram(OutlinedSP); 659 660 // Attach subprogram to the function. 661 F->setSubprogram(OutlinedSP); 662 // We're done with the DIBuilder. 663 DB.finalize(); 664 } 665 666 return Group.OutlinedFunction; 667 } 668 669 /// Move each BasicBlock in \p Old to \p New. 670 /// 671 /// \param [in] Old - The function to move the basic blocks from. 672 /// \param [in] New - The function to move the basic blocks to. 673 /// \param [out] NewEnds - The return blocks of the new overall function. 674 static void moveFunctionData(Function &Old, Function &New, 675 DenseMap<Value *, BasicBlock *> &NewEnds) { 676 for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) { 677 CurrBB.removeFromParent(); 678 CurrBB.insertInto(&New); 679 Instruction *I = CurrBB.getTerminator(); 680 681 // For each block we find a return instruction is, it is a potential exit 682 // path for the function. We keep track of each block based on the return 683 // value here. 684 if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) 685 NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB)); 686 687 std::vector<Instruction *> DebugInsts; 688 689 for (Instruction &Val : CurrBB) { 690 // We must handle the scoping of called functions differently than 691 // other outlined instructions. 692 if (!isa<CallInst>(&Val)) { 693 // Remove the debug information for outlined functions. 694 Val.setDebugLoc(DebugLoc()); 695 696 // Loop info metadata may contain line locations. Update them to have no 697 // value in the new subprogram since the outlined code could be from 698 // several locations. 699 auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * { 700 if (DISubprogram *SP = New.getSubprogram()) 701 if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 702 return DILocation::get(New.getContext(), Loc->getLine(), 703 Loc->getColumn(), SP, nullptr); 704 return MD; 705 }; 706 updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc); 707 continue; 708 } 709 710 // From this point we are only handling call instructions. 711 CallInst *CI = cast<CallInst>(&Val); 712 713 // We add any debug statements here, to be removed after. Since the 714 // instructions originate from many different locations in the program, 715 // it will cause incorrect reporting from a debugger if we keep the 716 // same debug instructions. 717 if (isa<DbgInfoIntrinsic>(CI)) { 718 DebugInsts.push_back(&Val); 719 continue; 720 } 721 722 // Edit the scope of called functions inside of outlined functions. 723 if (DISubprogram *SP = New.getSubprogram()) { 724 DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP); 725 Val.setDebugLoc(DI); 726 } 727 } 728 729 for (Instruction *I : DebugInsts) 730 I->eraseFromParent(); 731 } 732 } 733 734 /// Find the the constants that will need to be lifted into arguments 735 /// as they are not the same in each instance of the region. 736 /// 737 /// \param [in] C - The IRSimilarityCandidate containing the region we are 738 /// analyzing. 739 /// \param [in] NotSame - The set of global value numbers that do not have a 740 /// single Constant across all OutlinableRegions similar to \p C. 741 /// \param [out] Inputs - The list containing the global value numbers of the 742 /// arguments needed for the region of code. 743 static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame, 744 std::vector<unsigned> &Inputs) { 745 DenseSet<unsigned> Seen; 746 // Iterate over the instructions, and find what constants will need to be 747 // extracted into arguments. 748 for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end(); 749 IDIt != EndIDIt; IDIt++) { 750 for (Value *V : (*IDIt).OperVals) { 751 // Since these are stored before any outlining, they will be in the 752 // global value numbering. 753 unsigned GVN = C.getGVN(V).getValue(); 754 if (isa<Constant>(V)) 755 if (NotSame.contains(GVN) && !Seen.contains(GVN)) { 756 Inputs.push_back(GVN); 757 Seen.insert(GVN); 758 } 759 } 760 } 761 } 762 763 /// Find the GVN for the inputs that have been found by the CodeExtractor. 764 /// 765 /// \param [in] C - The IRSimilarityCandidate containing the region we are 766 /// analyzing. 767 /// \param [in] CurrentInputs - The set of inputs found by the 768 /// CodeExtractor. 769 /// \param [in] OutputMappings - The mapping of values that have been replaced 770 /// by a new output value. 771 /// \param [out] EndInputNumbers - The global value numbers for the extracted 772 /// arguments. 773 static void mapInputsToGVNs(IRSimilarityCandidate &C, 774 SetVector<Value *> &CurrentInputs, 775 const DenseMap<Value *, Value *> &OutputMappings, 776 std::vector<unsigned> &EndInputNumbers) { 777 // Get the Global Value Number for each input. We check if the Value has been 778 // replaced by a different value at output, and use the original value before 779 // replacement. 780 for (Value *Input : CurrentInputs) { 781 assert(Input && "Have a nullptr as an input"); 782 if (OutputMappings.find(Input) != OutputMappings.end()) 783 Input = OutputMappings.find(Input)->second; 784 assert(C.getGVN(Input).hasValue() && 785 "Could not find a numbering for the given input"); 786 EndInputNumbers.push_back(C.getGVN(Input).getValue()); 787 } 788 } 789 790 /// Find the original value for the \p ArgInput values if any one of them was 791 /// replaced during a previous extraction. 792 /// 793 /// \param [in] ArgInputs - The inputs to be extracted by the code extractor. 794 /// \param [in] OutputMappings - The mapping of values that have been replaced 795 /// by a new output value. 796 /// \param [out] RemappedArgInputs - The remapped values according to 797 /// \p OutputMappings that will be extracted. 798 static void 799 remapExtractedInputs(const ArrayRef<Value *> ArgInputs, 800 const DenseMap<Value *, Value *> &OutputMappings, 801 SetVector<Value *> &RemappedArgInputs) { 802 // Get the global value number for each input that will be extracted as an 803 // argument by the code extractor, remapping if needed for reloaded values. 804 for (Value *Input : ArgInputs) { 805 if (OutputMappings.find(Input) != OutputMappings.end()) 806 Input = OutputMappings.find(Input)->second; 807 RemappedArgInputs.insert(Input); 808 } 809 } 810 811 /// Find the input GVNs and the output values for a region of Instructions. 812 /// Using the code extractor, we collect the inputs to the extracted function. 813 /// 814 /// The \p Region can be identified as needing to be ignored in this function. 815 /// It should be checked whether it should be ignored after a call to this 816 /// function. 817 /// 818 /// \param [in,out] Region - The region of code to be analyzed. 819 /// \param [out] InputGVNs - The global value numbers for the extracted 820 /// arguments. 821 /// \param [in] NotSame - The global value numbers in the region that do not 822 /// have the same constant value in the regions structurally similar to 823 /// \p Region. 824 /// \param [in] OutputMappings - The mapping of values that have been replaced 825 /// by a new output value after extraction. 826 /// \param [out] ArgInputs - The values of the inputs to the extracted function. 827 /// \param [out] Outputs - The set of values extracted by the CodeExtractor 828 /// as outputs. 829 static void getCodeExtractorArguments( 830 OutlinableRegion &Region, std::vector<unsigned> &InputGVNs, 831 DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings, 832 SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) { 833 IRSimilarityCandidate &C = *Region.Candidate; 834 835 // OverallInputs are the inputs to the region found by the CodeExtractor, 836 // SinkCands and HoistCands are used by the CodeExtractor to find sunken 837 // allocas of values whose lifetimes are contained completely within the 838 // outlined region. PremappedInputs are the arguments found by the 839 // CodeExtractor, removing conditions such as sunken allocas, but that 840 // may need to be remapped due to the extracted output values replacing 841 // the original values. We use DummyOutputs for this first run of finding 842 // inputs and outputs since the outputs could change during findAllocas, 843 // the correct set of extracted outputs will be in the final Outputs ValueSet. 844 SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands, 845 DummyOutputs; 846 847 // Use the code extractor to get the inputs and outputs, without sunken 848 // allocas or removing llvm.assumes. 849 CodeExtractor *CE = Region.CE; 850 CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands); 851 assert(Region.StartBB && "Region must have a start BasicBlock!"); 852 Function *OrigF = Region.StartBB->getParent(); 853 CodeExtractorAnalysisCache CEAC(*OrigF); 854 BasicBlock *Dummy = nullptr; 855 856 // The region may be ineligible due to VarArgs in the parent function. In this 857 // case we ignore the region. 858 if (!CE->isEligible()) { 859 Region.IgnoreRegion = true; 860 return; 861 } 862 863 // Find if any values are going to be sunk into the function when extracted 864 CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy); 865 CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands); 866 867 // TODO: Support regions with sunken allocas: values whose lifetimes are 868 // contained completely within the outlined region. These are not guaranteed 869 // to be the same in every region, so we must elevate them all to arguments 870 // when they appear. If these values are not equal, it means there is some 871 // Input in OverallInputs that was removed for ArgInputs. 872 if (OverallInputs.size() != PremappedInputs.size()) { 873 Region.IgnoreRegion = true; 874 return; 875 } 876 877 findConstants(C, NotSame, InputGVNs); 878 879 mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs); 880 881 remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings, 882 ArgInputs); 883 884 // Sort the GVNs, since we now have constants included in the \ref InputGVNs 885 // we need to make sure they are in a deterministic order. 886 stable_sort(InputGVNs); 887 } 888 889 /// Look over the inputs and map each input argument to an argument in the 890 /// overall function for the OutlinableRegions. This creates a way to replace 891 /// the arguments of the extracted function with the arguments of the new 892 /// overall function. 893 /// 894 /// \param [in,out] Region - The region of code to be analyzed. 895 /// \param [in] InputGVNs - The global value numbering of the input values 896 /// collected. 897 /// \param [in] ArgInputs - The values of the arguments to the extracted 898 /// function. 899 static void 900 findExtractedInputToOverallInputMapping(OutlinableRegion &Region, 901 std::vector<unsigned> &InputGVNs, 902 SetVector<Value *> &ArgInputs) { 903 904 IRSimilarityCandidate &C = *Region.Candidate; 905 OutlinableGroup &Group = *Region.Parent; 906 907 // This counts the argument number in the overall function. 908 unsigned TypeIndex = 0; 909 910 // This counts the argument number in the extracted function. 911 unsigned OriginalIndex = 0; 912 913 // Find the mapping of the extracted arguments to the arguments for the 914 // overall function. Since there may be extra arguments in the overall 915 // function to account for the extracted constants, we have two different 916 // counters as we find extracted arguments, and as we come across overall 917 // arguments. 918 919 // Additionally, in our first pass, for the first extracted function, 920 // we find argument locations for the canonical value numbering. This 921 // numbering overrides any discovered location for the extracted code. 922 for (unsigned InputVal : InputGVNs) { 923 Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal); 924 assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?"); 925 unsigned CanonicalNumber = CanonicalNumberOpt.getValue(); 926 927 Optional<Value *> InputOpt = C.fromGVN(InputVal); 928 assert(InputOpt.hasValue() && "Global value number not found?"); 929 Value *Input = InputOpt.getValue(); 930 931 DenseMap<unsigned, unsigned>::iterator AggArgIt = 932 Group.CanonicalNumberToAggArg.find(CanonicalNumber); 933 934 if (!Group.InputTypesSet) { 935 Group.ArgumentTypes.push_back(Input->getType()); 936 // If the input value has a swifterr attribute, make sure to mark the 937 // argument in the overall function. 938 if (Input->isSwiftError()) { 939 assert( 940 !Group.SwiftErrorArgument.hasValue() && 941 "Argument already marked with swifterr for this OutlinableGroup!"); 942 Group.SwiftErrorArgument = TypeIndex; 943 } 944 } 945 946 // Check if we have a constant. If we do add it to the overall argument 947 // number to Constant map for the region, and continue to the next input. 948 if (Constant *CST = dyn_cast<Constant>(Input)) { 949 if (AggArgIt != Group.CanonicalNumberToAggArg.end()) 950 Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST)); 951 else { 952 Group.CanonicalNumberToAggArg.insert( 953 std::make_pair(CanonicalNumber, TypeIndex)); 954 Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST)); 955 } 956 TypeIndex++; 957 continue; 958 } 959 960 // It is not a constant, we create the mapping from extracted argument list 961 // to the overall argument list, using the canonical location, if it exists. 962 assert(ArgInputs.count(Input) && "Input cannot be found!"); 963 964 if (AggArgIt != Group.CanonicalNumberToAggArg.end()) { 965 if (OriginalIndex != AggArgIt->second) 966 Region.ChangedArgOrder = true; 967 Region.ExtractedArgToAgg.insert( 968 std::make_pair(OriginalIndex, AggArgIt->second)); 969 Region.AggArgToExtracted.insert( 970 std::make_pair(AggArgIt->second, OriginalIndex)); 971 } else { 972 Group.CanonicalNumberToAggArg.insert( 973 std::make_pair(CanonicalNumber, TypeIndex)); 974 Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex)); 975 Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex)); 976 } 977 OriginalIndex++; 978 TypeIndex++; 979 } 980 981 // If the function type definitions for the OutlinableGroup holding the region 982 // have not been set, set the length of the inputs here. We should have the 983 // same inputs for all of the different regions contained in the 984 // OutlinableGroup since they are all structurally similar to one another. 985 if (!Group.InputTypesSet) { 986 Group.NumAggregateInputs = TypeIndex; 987 Group.InputTypesSet = true; 988 } 989 990 Region.NumExtractedInputs = OriginalIndex; 991 } 992 993 /// Check if the \p V has any uses outside of the region other than \p PN. 994 /// 995 /// \param V [in] - The value to check. 996 /// \param PHILoc [in] - The location in the PHINode of \p V. 997 /// \param PN [in] - The PHINode using \p V. 998 /// \param Exits [in] - The potential blocks we exit to from the outlined 999 /// region. 1000 /// \param BlocksInRegion [in] - The basic blocks contained in the region. 1001 /// \returns true if \p V has any use soutside its region other than \p PN. 1002 static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN, 1003 SmallPtrSet<BasicBlock *, 1> &Exits, 1004 DenseSet<BasicBlock *> &BlocksInRegion) { 1005 // We check to see if the value is used by the PHINode from some other 1006 // predecessor not included in the region. If it is, we make sure 1007 // to keep it as an output. 1008 if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()), 1009 [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) { 1010 return (Idx != PHILoc && V == PN.getIncomingValue(Idx) && 1011 !BlocksInRegion.contains(PN.getIncomingBlock(Idx))); 1012 })) 1013 return true; 1014 1015 // Check if the value is used by any other instructions outside the region. 1016 return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) { 1017 Instruction *I = dyn_cast<Instruction>(U); 1018 if (!I) 1019 return false; 1020 1021 // If the use of the item is inside the region, we skip it. Uses 1022 // inside the region give us useful information about how the item could be 1023 // used as an output. 1024 BasicBlock *Parent = I->getParent(); 1025 if (BlocksInRegion.contains(Parent)) 1026 return false; 1027 1028 // If it's not a PHINode then we definitely know the use matters. This 1029 // output value will not completely combined with another item in a PHINode 1030 // as it is directly reference by another non-phi instruction 1031 if (!isa<PHINode>(I)) 1032 return true; 1033 1034 // If we have a PHINode outside one of the exit locations, then it 1035 // can be considered an outside use as well. If there is a PHINode 1036 // contained in the Exit where this values use matters, it will be 1037 // caught when we analyze that PHINode. 1038 if (!Exits.contains(Parent)) 1039 return true; 1040 1041 return false; 1042 }); 1043 } 1044 1045 /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be 1046 /// considered outputs. A PHINodes is an output when more than one incoming 1047 /// value has been marked by the CodeExtractor as an output. 1048 /// 1049 /// \param CurrentExitFromRegion [in] - The block to analyze. 1050 /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the 1051 /// region. 1052 /// \param RegionBlocks [in] - The basic blocks in the region. 1053 /// \param Outputs [in, out] - The existing outputs for the region, we may add 1054 /// PHINodes to this as we find that they replace output values. 1055 /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are 1056 /// totally replaced by a PHINode. 1057 /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used 1058 /// in PHINodes, but have other uses, and should still be considered outputs. 1059 static void analyzeExitPHIsForOutputUses( 1060 BasicBlock *CurrentExitFromRegion, 1061 SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion, 1062 DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs, 1063 DenseSet<Value *> &OutputsReplacedByPHINode, 1064 DenseSet<Value *> &OutputsWithNonPhiUses) { 1065 for (PHINode &PN : CurrentExitFromRegion->phis()) { 1066 // Find all incoming values from the outlining region. 1067 SmallVector<unsigned, 2> IncomingVals; 1068 for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I) 1069 if (RegionBlocks.contains(PN.getIncomingBlock(I))) 1070 IncomingVals.push_back(I); 1071 1072 // Do not process PHI if there are no predecessors from region. 1073 unsigned NumIncomingVals = IncomingVals.size(); 1074 if (NumIncomingVals == 0) 1075 continue; 1076 1077 // If there is one predecessor, we mark it as a value that needs to be kept 1078 // as an output. 1079 if (NumIncomingVals == 1) { 1080 Value *V = PN.getIncomingValue(*IncomingVals.begin()); 1081 OutputsWithNonPhiUses.insert(V); 1082 OutputsReplacedByPHINode.erase(V); 1083 continue; 1084 } 1085 1086 // This PHINode will be used as an output value, so we add it to our list. 1087 Outputs.insert(&PN); 1088 1089 // Not all of the incoming values should be ignored as other inputs and 1090 // outputs may have uses in outlined region. If they have other uses 1091 // outside of the single PHINode we should not skip over it. 1092 for (unsigned Idx : IncomingVals) { 1093 Value *V = PN.getIncomingValue(Idx); 1094 if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) { 1095 OutputsWithNonPhiUses.insert(V); 1096 OutputsReplacedByPHINode.erase(V); 1097 continue; 1098 } 1099 if (!OutputsWithNonPhiUses.contains(V)) 1100 OutputsReplacedByPHINode.insert(V); 1101 } 1102 } 1103 } 1104 1105 // Represents the type for the unsigned number denoting the output number for 1106 // phi node, along with the canonical number for the exit block. 1107 using ArgLocWithBBCanon = std::pair<unsigned, unsigned>; 1108 // The list of canonical numbers for the incoming values to a PHINode. 1109 using CanonList = SmallVector<unsigned, 2>; 1110 // The pair type representing the set of canonical values being combined in the 1111 // PHINode, along with the location data for the PHINode. 1112 using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>; 1113 1114 /// Encode \p PND as an integer for easy lookup based on the argument location, 1115 /// the parent BasicBlock canonical numbering, and the canonical numbering of 1116 /// the values stored in the PHINode. 1117 /// 1118 /// \param PND - The data to hash. 1119 /// \returns The hash code of \p PND. 1120 static hash_code encodePHINodeData(PHINodeData &PND) { 1121 return llvm::hash_combine( 1122 llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second), 1123 llvm::hash_combine_range(PND.second.begin(), PND.second.end())); 1124 } 1125 1126 /// Create a special GVN for PHINodes that will be used outside of 1127 /// the region. We create a hash code based on the Canonical number of the 1128 /// parent BasicBlock, the canonical numbering of the values stored in the 1129 /// PHINode and the aggregate argument location. This is used to find whether 1130 /// this PHINode type has been given a canonical numbering already. If not, we 1131 /// assign it a value and store it for later use. The value is returned to 1132 /// identify different output schemes for the set of regions. 1133 /// 1134 /// \param Region - The region that \p PN is an output for. 1135 /// \param PN - The PHINode we are analyzing. 1136 /// \param Blocks - The blocks for the region we are analyzing. 1137 /// \param AggArgIdx - The argument \p PN will be stored into. 1138 /// \returns An optional holding the assigned canonical number, or None if 1139 /// there is some attribute of the PHINode blocking it from being used. 1140 static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region, 1141 PHINode *PN, 1142 DenseSet<BasicBlock *> &Blocks, 1143 unsigned AggArgIdx) { 1144 OutlinableGroup &Group = *Region.Parent; 1145 IRSimilarityCandidate &Cand = *Region.Candidate; 1146 BasicBlock *PHIBB = PN->getParent(); 1147 CanonList PHIGVNs; 1148 Value *Incoming; 1149 BasicBlock *IncomingBlock; 1150 for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) { 1151 Incoming = PN->getIncomingValue(Idx); 1152 IncomingBlock = PN->getIncomingBlock(Idx); 1153 // If we cannot find a GVN, and the incoming block is included in the region 1154 // this means that the input to the PHINode is not included in the region we 1155 // are trying to analyze, meaning, that if it was outlined, we would be 1156 // adding an extra input. We ignore this case for now, and so ignore the 1157 // region. 1158 Optional<unsigned> OGVN = Cand.getGVN(Incoming); 1159 if (!OGVN.hasValue() && (Blocks.find(IncomingBlock) != Blocks.end())) { 1160 Region.IgnoreRegion = true; 1161 return None; 1162 } 1163 1164 // If the incoming block isn't in the region, we don't have to worry about 1165 // this incoming value. 1166 if (Blocks.find(IncomingBlock) == Blocks.end()) 1167 continue; 1168 1169 // Collect the canonical numbers of the values in the PHINode. 1170 unsigned GVN = OGVN.getValue(); 1171 OGVN = Cand.getCanonicalNum(GVN); 1172 assert(OGVN.hasValue() && "No GVN found for incoming value?"); 1173 PHIGVNs.push_back(*OGVN); 1174 } 1175 1176 // Now that we have the GVNs for the incoming values, we are going to combine 1177 // them with the GVN of the incoming bock, and the output location of the 1178 // PHINode to generate a hash value representing this instance of the PHINode. 1179 DenseMap<hash_code, unsigned>::iterator GVNToPHIIt; 1180 DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt; 1181 Optional<unsigned> BBGVN = Cand.getGVN(PHIBB); 1182 assert(BBGVN.hasValue() && "Could not find GVN for the incoming block!"); 1183 1184 BBGVN = Cand.getCanonicalNum(BBGVN.getValue()); 1185 assert(BBGVN.hasValue() && 1186 "Could not find canonical number for the incoming block!"); 1187 // Create a pair of the exit block canonical value, and the aggregate 1188 // argument location, connected to the canonical numbers stored in the 1189 // PHINode. 1190 PHINodeData TemporaryPair = 1191 std::make_pair(std::make_pair(BBGVN.getValue(), AggArgIdx), PHIGVNs); 1192 hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair); 1193 1194 // Look for and create a new entry in our connection between canonical 1195 // numbers for PHINodes, and the set of objects we just created. 1196 GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash); 1197 if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) { 1198 bool Inserted = false; 1199 std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert( 1200 std::make_pair(Group.PHINodeGVNTracker, TemporaryPair)); 1201 std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert( 1202 std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--)); 1203 } 1204 1205 return GVNToPHIIt->second; 1206 } 1207 1208 /// Create a mapping of the output arguments for the \p Region to the output 1209 /// arguments of the overall outlined function. 1210 /// 1211 /// \param [in,out] Region - The region of code to be analyzed. 1212 /// \param [in] Outputs - The values found by the code extractor. 1213 static void 1214 findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region, 1215 SetVector<Value *> &Outputs) { 1216 OutlinableGroup &Group = *Region.Parent; 1217 IRSimilarityCandidate &C = *Region.Candidate; 1218 1219 SmallVector<BasicBlock *> BE; 1220 DenseSet<BasicBlock *> BlocksInRegion; 1221 C.getBasicBlocks(BlocksInRegion, BE); 1222 1223 // Find the exits to the region. 1224 SmallPtrSet<BasicBlock *, 1> Exits; 1225 for (BasicBlock *Block : BE) 1226 for (BasicBlock *Succ : successors(Block)) 1227 if (!BlocksInRegion.contains(Succ)) 1228 Exits.insert(Succ); 1229 1230 // After determining which blocks exit to PHINodes, we add these PHINodes to 1231 // the set of outputs to be processed. We also check the incoming values of 1232 // the PHINodes for whether they should no longer be considered outputs. 1233 DenseSet<Value *> OutputsReplacedByPHINode; 1234 DenseSet<Value *> OutputsWithNonPhiUses; 1235 for (BasicBlock *ExitBB : Exits) 1236 analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs, 1237 OutputsReplacedByPHINode, 1238 OutputsWithNonPhiUses); 1239 1240 // This counts the argument number in the extracted function. 1241 unsigned OriginalIndex = Region.NumExtractedInputs; 1242 1243 // This counts the argument number in the overall function. 1244 unsigned TypeIndex = Group.NumAggregateInputs; 1245 bool TypeFound; 1246 DenseSet<unsigned> AggArgsUsed; 1247 1248 // Iterate over the output types and identify if there is an aggregate pointer 1249 // type whose base type matches the current output type. If there is, we mark 1250 // that we will use this output register for this value. If not we add another 1251 // type to the overall argument type list. We also store the GVNs used for 1252 // stores to identify which values will need to be moved into an special 1253 // block that holds the stores to the output registers. 1254 for (Value *Output : Outputs) { 1255 TypeFound = false; 1256 // We can do this since it is a result value, and will have a number 1257 // that is necessarily the same. BUT if in the future, the instructions 1258 // do not have to be in same order, but are functionally the same, we will 1259 // have to use a different scheme, as one-to-one correspondence is not 1260 // guaranteed. 1261 unsigned ArgumentSize = Group.ArgumentTypes.size(); 1262 1263 // If the output is combined in a PHINode, we make sure to skip over it. 1264 if (OutputsReplacedByPHINode.contains(Output)) 1265 continue; 1266 1267 unsigned AggArgIdx = 0; 1268 for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) { 1269 if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType())) 1270 continue; 1271 1272 if (AggArgsUsed.contains(Jdx)) 1273 continue; 1274 1275 TypeFound = true; 1276 AggArgsUsed.insert(Jdx); 1277 Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx)); 1278 Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex)); 1279 AggArgIdx = Jdx; 1280 break; 1281 } 1282 1283 // We were unable to find an unused type in the output type set that matches 1284 // the output, so we add a pointer type to the argument types of the overall 1285 // function to handle this output and create a mapping to it. 1286 if (!TypeFound) { 1287 Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType())); 1288 // Mark the new pointer type as the last value in the aggregate argument 1289 // list. 1290 unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1; 1291 AggArgsUsed.insert(ArgTypeIdx); 1292 Region.ExtractedArgToAgg.insert( 1293 std::make_pair(OriginalIndex, ArgTypeIdx)); 1294 Region.AggArgToExtracted.insert( 1295 std::make_pair(ArgTypeIdx, OriginalIndex)); 1296 AggArgIdx = ArgTypeIdx; 1297 } 1298 1299 // TODO: Adapt to the extra input from the PHINode. 1300 PHINode *PN = dyn_cast<PHINode>(Output); 1301 1302 Optional<unsigned> GVN; 1303 if (PN && !BlocksInRegion.contains(PN->getParent())) { 1304 // Values outside the region can be combined into PHINode when we 1305 // have multiple exits. We collect both of these into a list to identify 1306 // which values are being used in the PHINode. Each list identifies a 1307 // different PHINode, and a different output. We store the PHINode as it's 1308 // own canonical value. These canonical values are also dependent on the 1309 // output argument it is saved to. 1310 1311 // If two PHINodes have the same canonical values, but different aggregate 1312 // argument locations, then they will have distinct Canonical Values. 1313 GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx); 1314 if (!GVN.hasValue()) 1315 return; 1316 } else { 1317 // If we do not have a PHINode we use the global value numbering for the 1318 // output value, to find the canonical number to add to the set of stored 1319 // values. 1320 GVN = C.getGVN(Output); 1321 GVN = C.getCanonicalNum(*GVN); 1322 } 1323 1324 // Each region has a potentially unique set of outputs. We save which 1325 // values are output in a list of canonical values so we can differentiate 1326 // among the different store schemes. 1327 Region.GVNStores.push_back(*GVN); 1328 1329 OriginalIndex++; 1330 TypeIndex++; 1331 } 1332 1333 // We sort the stored values to make sure that we are not affected by analysis 1334 // order when determining what combination of items were stored. 1335 stable_sort(Region.GVNStores); 1336 } 1337 1338 void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region, 1339 DenseSet<unsigned> &NotSame) { 1340 std::vector<unsigned> Inputs; 1341 SetVector<Value *> ArgInputs, Outputs; 1342 1343 getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs, 1344 Outputs); 1345 1346 if (Region.IgnoreRegion) 1347 return; 1348 1349 // Map the inputs found by the CodeExtractor to the arguments found for 1350 // the overall function. 1351 findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs); 1352 1353 // Map the outputs found by the CodeExtractor to the arguments found for 1354 // the overall function. 1355 findExtractedOutputToOverallOutputMapping(Region, Outputs); 1356 } 1357 1358 /// Replace the extracted function in the Region with a call to the overall 1359 /// function constructed from the deduplicated similar regions, replacing and 1360 /// remapping the values passed to the extracted function as arguments to the 1361 /// new arguments of the overall function. 1362 /// 1363 /// \param [in] M - The module to outline from. 1364 /// \param [in] Region - The regions of extracted code to be replaced with a new 1365 /// function. 1366 /// \returns a call instruction with the replaced function. 1367 CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) { 1368 std::vector<Value *> NewCallArgs; 1369 DenseMap<unsigned, unsigned>::iterator ArgPair; 1370 1371 OutlinableGroup &Group = *Region.Parent; 1372 CallInst *Call = Region.Call; 1373 assert(Call && "Call to replace is nullptr?"); 1374 Function *AggFunc = Group.OutlinedFunction; 1375 assert(AggFunc && "Function to replace with is nullptr?"); 1376 1377 // If the arguments are the same size, there are not values that need to be 1378 // made into an argument, the argument ordering has not been change, or 1379 // different output registers to handle. We can simply replace the called 1380 // function in this case. 1381 if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) { 1382 LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 1383 << *AggFunc << " with same number of arguments\n"); 1384 Call->setCalledFunction(AggFunc); 1385 return Call; 1386 } 1387 1388 // We have a different number of arguments than the new function, so 1389 // we need to use our previously mappings off extracted argument to overall 1390 // function argument, and constants to overall function argument to create the 1391 // new argument list. 1392 for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) { 1393 1394 if (AggArgIdx == AggFunc->arg_size() - 1 && 1395 Group.OutputGVNCombinations.size() > 1) { 1396 // If we are on the last argument, and we need to differentiate between 1397 // output blocks, add an integer to the argument list to determine 1398 // what block to take 1399 LLVM_DEBUG(dbgs() << "Set switch block argument to " 1400 << Region.OutputBlockNum << "\n"); 1401 NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()), 1402 Region.OutputBlockNum)); 1403 continue; 1404 } 1405 1406 ArgPair = Region.AggArgToExtracted.find(AggArgIdx); 1407 if (ArgPair != Region.AggArgToExtracted.end()) { 1408 Value *ArgumentValue = Call->getArgOperand(ArgPair->second); 1409 // If we found the mapping from the extracted function to the overall 1410 // function, we simply add it to the argument list. We use the same 1411 // value, it just needs to honor the new order of arguments. 1412 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 1413 << *ArgumentValue << "\n"); 1414 NewCallArgs.push_back(ArgumentValue); 1415 continue; 1416 } 1417 1418 // If it is a constant, we simply add it to the argument list as a value. 1419 if (Region.AggArgToConstant.find(AggArgIdx) != 1420 Region.AggArgToConstant.end()) { 1421 Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second; 1422 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 1423 << *CST << "\n"); 1424 NewCallArgs.push_back(CST); 1425 continue; 1426 } 1427 1428 // Add a nullptr value if the argument is not found in the extracted 1429 // function. If we cannot find a value, it means it is not in use 1430 // for the region, so we should not pass anything to it. 1431 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n"); 1432 NewCallArgs.push_back(ConstantPointerNull::get( 1433 static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType()))); 1434 } 1435 1436 LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 1437 << *AggFunc << " with new set of arguments\n"); 1438 // Create the new call instruction and erase the old one. 1439 Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "", 1440 Call); 1441 1442 // It is possible that the call to the outlined function is either the first 1443 // instruction is in the new block, the last instruction, or both. If either 1444 // of these is the case, we need to make sure that we replace the instruction 1445 // in the IRInstructionData struct with the new call. 1446 CallInst *OldCall = Region.Call; 1447 if (Region.NewFront->Inst == OldCall) 1448 Region.NewFront->Inst = Call; 1449 if (Region.NewBack->Inst == OldCall) 1450 Region.NewBack->Inst = Call; 1451 1452 // Transfer any debug information. 1453 Call->setDebugLoc(Region.Call->getDebugLoc()); 1454 // Since our output may determine which branch we go to, we make sure to 1455 // propogate this new call value through the module. 1456 OldCall->replaceAllUsesWith(Call); 1457 1458 // Remove the old instruction. 1459 OldCall->eraseFromParent(); 1460 Region.Call = Call; 1461 1462 // Make sure that the argument in the new function has the SwiftError 1463 // argument. 1464 if (Group.SwiftErrorArgument.hasValue()) 1465 Call->addParamAttr(Group.SwiftErrorArgument.getValue(), 1466 Attribute::SwiftError); 1467 1468 return Call; 1469 } 1470 1471 /// Find or create a BasicBlock in the outlined function containing PhiBlocks 1472 /// for \p RetVal. 1473 /// 1474 /// \param Group - The OutlinableGroup containing the information about the 1475 /// overall outlined function. 1476 /// \param RetVal - The return value or exit option that we are currently 1477 /// evaluating. 1478 /// \returns The found or newly created BasicBlock to contain the needed 1479 /// PHINodes to be used as outputs. 1480 static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) { 1481 DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal, 1482 ReturnBlockForRetVal; 1483 PhiBlockForRetVal = Group.PHIBlocks.find(RetVal); 1484 ReturnBlockForRetVal = Group.EndBBs.find(RetVal); 1485 assert(ReturnBlockForRetVal != Group.EndBBs.end() && 1486 "Could not find output value!"); 1487 BasicBlock *ReturnBB = ReturnBlockForRetVal->second; 1488 1489 // Find if a PHIBlock exists for this return value already. If it is 1490 // the first time we are analyzing this, we will not, so we record it. 1491 PhiBlockForRetVal = Group.PHIBlocks.find(RetVal); 1492 if (PhiBlockForRetVal != Group.PHIBlocks.end()) 1493 return PhiBlockForRetVal->second; 1494 1495 // If we did not find a block, we create one, and insert it into the 1496 // overall function and record it. 1497 bool Inserted = false; 1498 BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block", 1499 ReturnBB->getParent()); 1500 std::tie(PhiBlockForRetVal, Inserted) = 1501 Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock)); 1502 1503 // We find the predecessors of the return block in the newly created outlined 1504 // function in order to point them to the new PHIBlock rather than the already 1505 // existing return block. 1506 SmallVector<BranchInst *, 2> BranchesToChange; 1507 for (BasicBlock *Pred : predecessors(ReturnBB)) 1508 BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator())); 1509 1510 // Now we mark the branch instructions found, and change the references of the 1511 // return block to the newly created PHIBlock. 1512 for (BranchInst *BI : BranchesToChange) 1513 for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) { 1514 if (BI->getSuccessor(Succ) != ReturnBB) 1515 continue; 1516 BI->setSuccessor(Succ, PHIBlock); 1517 } 1518 1519 BranchInst::Create(ReturnBB, PHIBlock); 1520 1521 return PhiBlockForRetVal->second; 1522 } 1523 1524 /// For the function call now representing the \p Region, find the passed value 1525 /// to that call that represents Argument \p A at the call location if the 1526 /// call has already been replaced with a call to the overall, aggregate 1527 /// function. 1528 /// 1529 /// \param A - The Argument to get the passed value for. 1530 /// \param Region - The extracted Region corresponding to the outlined function. 1531 /// \returns The Value representing \p A at the call site. 1532 static Value * 1533 getPassedArgumentInAlreadyOutlinedFunction(const Argument *A, 1534 const OutlinableRegion &Region) { 1535 // If we don't need to adjust the argument number at all (since the call 1536 // has already been replaced by a call to the overall outlined function) 1537 // we can just get the specified argument. 1538 return Region.Call->getArgOperand(A->getArgNo()); 1539 } 1540 1541 /// For the function call now representing the \p Region, find the passed value 1542 /// to that call that represents Argument \p A at the call location if the 1543 /// call has only been replaced by the call to the aggregate function. 1544 /// 1545 /// \param A - The Argument to get the passed value for. 1546 /// \param Region - The extracted Region corresponding to the outlined function. 1547 /// \returns The Value representing \p A at the call site. 1548 static Value * 1549 getPassedArgumentAndAdjustArgumentLocation(const Argument *A, 1550 const OutlinableRegion &Region) { 1551 unsigned ArgNum = A->getArgNo(); 1552 1553 // If it is a constant, we can look at our mapping from when we created 1554 // the outputs to figure out what the constant value is. 1555 if (Region.AggArgToConstant.count(ArgNum)) 1556 return Region.AggArgToConstant.find(ArgNum)->second; 1557 1558 // If it is not a constant, and we are not looking at the overall function, we 1559 // need to adjust which argument we are looking at. 1560 ArgNum = Region.AggArgToExtracted.find(ArgNum)->second; 1561 return Region.Call->getArgOperand(ArgNum); 1562 } 1563 1564 /// Find the canonical numbering for the incoming Values into the PHINode \p PN. 1565 /// 1566 /// \param PN [in] - The PHINode that we are finding the canonical numbers for. 1567 /// \param Region [in] - The OutlinableRegion containing \p PN. 1568 /// \param OutputMappings [in] - The mapping of output values from outlined 1569 /// region to their original values. 1570 /// \param CanonNums [out] - The canonical numbering for the incoming values to 1571 /// \p PN paired with their incoming block. 1572 /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call 1573 /// of \p Region rather than the overall function's call. 1574 static void findCanonNumsForPHI( 1575 PHINode *PN, OutlinableRegion &Region, 1576 const DenseMap<Value *, Value *> &OutputMappings, 1577 SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums, 1578 bool ReplacedWithOutlinedCall = true) { 1579 // Iterate over the incoming values. 1580 for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) { 1581 Value *IVal = PN->getIncomingValue(Idx); 1582 BasicBlock *IBlock = PN->getIncomingBlock(Idx); 1583 // If we have an argument as incoming value, we need to grab the passed 1584 // value from the call itself. 1585 if (Argument *A = dyn_cast<Argument>(IVal)) { 1586 if (ReplacedWithOutlinedCall) 1587 IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region); 1588 else 1589 IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region); 1590 } 1591 1592 // Get the original value if it has been replaced by an output value. 1593 IVal = findOutputMapping(OutputMappings, IVal); 1594 1595 // Find and add the canonical number for the incoming value. 1596 Optional<unsigned> GVN = Region.Candidate->getGVN(IVal); 1597 assert(GVN.hasValue() && "No GVN for incoming value"); 1598 Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN); 1599 assert(CanonNum.hasValue() && "No Canonical Number for GVN"); 1600 CanonNums.push_back(std::make_pair(*CanonNum, IBlock)); 1601 } 1602 } 1603 1604 /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock 1605 /// in order to condense the number of instructions added to the outlined 1606 /// function. 1607 /// 1608 /// \param PN [in] - The PHINode that we are finding the canonical numbers for. 1609 /// \param Region [in] - The OutlinableRegion containing \p PN. 1610 /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find 1611 /// \p PN in. 1612 /// \param OutputMappings [in] - The mapping of output values from outlined 1613 /// region to their original values. 1614 /// \param UsedPHIs [in, out] - The PHINodes in the block that have already been 1615 /// matched. 1616 /// \return the newly found or created PHINode in \p OverallPhiBlock. 1617 static PHINode* 1618 findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region, 1619 BasicBlock *OverallPhiBlock, 1620 const DenseMap<Value *, Value *> &OutputMappings, 1621 DenseSet<PHINode *> &UsedPHIs) { 1622 OutlinableGroup &Group = *Region.Parent; 1623 1624 1625 // A list of the canonical numbering assigned to each incoming value, paired 1626 // with the incoming block for the PHINode passed into this function. 1627 SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums; 1628 1629 // We have to use the extracted function since we have merged this region into 1630 // the overall function yet. We make sure to reassign the argument numbering 1631 // since it is possible that the argument ordering is different between the 1632 // functions. 1633 findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums, 1634 /* ReplacedWithOutlinedCall = */ false); 1635 1636 OutlinableRegion *FirstRegion = Group.Regions[0]; 1637 1638 // A list of the canonical numbering assigned to each incoming value, paired 1639 // with the incoming block for the PHINode that we are currently comparing 1640 // the passed PHINode to. 1641 SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums; 1642 1643 // Find the Canonical Numbering for each PHINode, if it matches, we replace 1644 // the uses of the PHINode we are searching for, with the found PHINode. 1645 for (PHINode &CurrPN : OverallPhiBlock->phis()) { 1646 // If this PHINode has already been matched to another PHINode to be merged, 1647 // we skip it. 1648 if (UsedPHIs.find(&CurrPN) != UsedPHIs.end()) 1649 continue; 1650 1651 CurrentCanonNums.clear(); 1652 findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums, 1653 /* ReplacedWithOutlinedCall = */ true); 1654 1655 // If the list of incoming values is not the same length, then they cannot 1656 // match since there is not an analogue for each incoming value. 1657 if (PNCanonNums.size() != CurrentCanonNums.size()) 1658 continue; 1659 1660 bool FoundMatch = true; 1661 1662 // We compare the canonical value for each incoming value in the passed 1663 // in PHINode to one already present in the outlined region. If the 1664 // incoming values do not match, then the PHINodes do not match. 1665 1666 // We also check to make sure that the incoming block matches as well by 1667 // finding the corresponding incoming block in the combined outlined region 1668 // for the current outlined region. 1669 for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) { 1670 std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx]; 1671 std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx]; 1672 if (ToCompareTo.first != ToAdd.first) { 1673 FoundMatch = false; 1674 break; 1675 } 1676 1677 BasicBlock *CorrespondingBlock = 1678 Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second); 1679 assert(CorrespondingBlock && "Found block is nullptr"); 1680 if (CorrespondingBlock != ToCompareTo.second) { 1681 FoundMatch = false; 1682 break; 1683 } 1684 } 1685 1686 // If all incoming values and branches matched, then we can merge 1687 // into the found PHINode. 1688 if (FoundMatch) { 1689 UsedPHIs.insert(&CurrPN); 1690 return &CurrPN; 1691 } 1692 } 1693 1694 // If we've made it here, it means we weren't able to replace the PHINode, so 1695 // we must insert it ourselves. 1696 PHINode *NewPN = cast<PHINode>(PN.clone()); 1697 NewPN->insertBefore(&*OverallPhiBlock->begin()); 1698 for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx; 1699 Idx++) { 1700 Value *IncomingVal = NewPN->getIncomingValue(Idx); 1701 BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx); 1702 1703 // Find corresponding basic block in the overall function for the incoming 1704 // block. 1705 BasicBlock *BlockToUse = 1706 Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock); 1707 NewPN->setIncomingBlock(Idx, BlockToUse); 1708 1709 // If we have an argument we make sure we replace using the argument from 1710 // the correct function. 1711 if (Argument *A = dyn_cast<Argument>(IncomingVal)) { 1712 Value *Val = Group.OutlinedFunction->getArg(A->getArgNo()); 1713 NewPN->setIncomingValue(Idx, Val); 1714 continue; 1715 } 1716 1717 // Find the corresponding value in the overall function. 1718 IncomingVal = findOutputMapping(OutputMappings, IncomingVal); 1719 Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal); 1720 assert(Val && "Value is nullptr?"); 1721 NewPN->setIncomingValue(Idx, Val); 1722 } 1723 return NewPN; 1724 } 1725 1726 // Within an extracted function, replace the argument uses of the extracted 1727 // region with the arguments of the function for an OutlinableGroup. 1728 // 1729 /// \param [in] Region - The region of extracted code to be changed. 1730 /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this 1731 /// region. 1732 /// \param [in] FirstFunction - A flag to indicate whether we are using this 1733 /// function to define the overall outlined function for all the regions, or 1734 /// if we are operating on one of the following regions. 1735 static void 1736 replaceArgumentUses(OutlinableRegion &Region, 1737 DenseMap<Value *, BasicBlock *> &OutputBBs, 1738 const DenseMap<Value *, Value *> &OutputMappings, 1739 bool FirstFunction = false) { 1740 OutlinableGroup &Group = *Region.Parent; 1741 assert(Region.ExtractedFunction && "Region has no extracted function?"); 1742 1743 Function *DominatingFunction = Region.ExtractedFunction; 1744 if (FirstFunction) 1745 DominatingFunction = Group.OutlinedFunction; 1746 DominatorTree DT(*DominatingFunction); 1747 DenseSet<PHINode *> UsedPHIs; 1748 1749 for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size(); 1750 ArgIdx++) { 1751 assert(Region.ExtractedArgToAgg.find(ArgIdx) != 1752 Region.ExtractedArgToAgg.end() && 1753 "No mapping from extracted to outlined?"); 1754 unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second; 1755 Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx); 1756 Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx); 1757 // The argument is an input, so we can simply replace it with the overall 1758 // argument value 1759 if (ArgIdx < Region.NumExtractedInputs) { 1760 LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function " 1761 << *Region.ExtractedFunction << " with " << *AggArg 1762 << " in function " << *Group.OutlinedFunction << "\n"); 1763 Arg->replaceAllUsesWith(AggArg); 1764 continue; 1765 } 1766 1767 // If we are replacing an output, we place the store value in its own 1768 // block inside the overall function before replacing the use of the output 1769 // in the function. 1770 assert(Arg->hasOneUse() && "Output argument can only have one use"); 1771 User *InstAsUser = Arg->user_back(); 1772 assert(InstAsUser && "User is nullptr!"); 1773 1774 Instruction *I = cast<Instruction>(InstAsUser); 1775 BasicBlock *BB = I->getParent(); 1776 SmallVector<BasicBlock *, 4> Descendants; 1777 DT.getDescendants(BB, Descendants); 1778 bool EdgeAdded = false; 1779 if (Descendants.size() == 0) { 1780 EdgeAdded = true; 1781 DT.insertEdge(&DominatingFunction->getEntryBlock(), BB); 1782 DT.getDescendants(BB, Descendants); 1783 } 1784 1785 // Iterate over the following blocks, looking for return instructions, 1786 // if we find one, find the corresponding output block for the return value 1787 // and move our store instruction there. 1788 for (BasicBlock *DescendBB : Descendants) { 1789 ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator()); 1790 if (!RI) 1791 continue; 1792 Value *RetVal = RI->getReturnValue(); 1793 auto VBBIt = OutputBBs.find(RetVal); 1794 assert(VBBIt != OutputBBs.end() && "Could not find output value!"); 1795 1796 // If this is storing a PHINode, we must make sure it is included in the 1797 // overall function. 1798 StoreInst *SI = cast<StoreInst>(I); 1799 1800 Value *ValueOperand = SI->getValueOperand(); 1801 1802 StoreInst *NewI = cast<StoreInst>(I->clone()); 1803 NewI->setDebugLoc(DebugLoc()); 1804 BasicBlock *OutputBB = VBBIt->second; 1805 OutputBB->getInstList().push_back(NewI); 1806 LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to " 1807 << *OutputBB << "\n"); 1808 1809 // If this is storing a PHINode, we must make sure it is included in the 1810 // overall function. 1811 if (!isa<PHINode>(ValueOperand) || 1812 Region.Candidate->getGVN(ValueOperand).hasValue()) { 1813 if (FirstFunction) 1814 continue; 1815 Value *CorrVal = 1816 Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand); 1817 assert(CorrVal && "Value is nullptr?"); 1818 NewI->setOperand(0, CorrVal); 1819 continue; 1820 } 1821 PHINode *PN = cast<PHINode>(SI->getValueOperand()); 1822 // If it has a value, it was not split by the code extractor, which 1823 // is what we are looking for. 1824 if (Region.Candidate->getGVN(PN).hasValue()) 1825 continue; 1826 1827 // We record the parent block for the PHINode in the Region so that 1828 // we can exclude it from checks later on. 1829 Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent())); 1830 1831 // If this is the first function, we do not need to worry about mergiing 1832 // this with any other block in the overall outlined function, so we can 1833 // just continue. 1834 if (FirstFunction) { 1835 BasicBlock *PHIBlock = PN->getParent(); 1836 Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock)); 1837 continue; 1838 } 1839 1840 // We look for the aggregate block that contains the PHINodes leading into 1841 // this exit path. If we can't find one, we create one. 1842 BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal); 1843 1844 // For our PHINode, we find the combined canonical numbering, and 1845 // attempt to find a matching PHINode in the overall PHIBlock. If we 1846 // cannot, we copy the PHINode and move it into this new block. 1847 PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock, 1848 OutputMappings, UsedPHIs); 1849 NewI->setOperand(0, NewPN); 1850 } 1851 1852 // If we added an edge for basic blocks without a predecessor, we remove it 1853 // here. 1854 if (EdgeAdded) 1855 DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB); 1856 I->eraseFromParent(); 1857 1858 LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function " 1859 << *Region.ExtractedFunction << " with " << *AggArg 1860 << " in function " << *Group.OutlinedFunction << "\n"); 1861 Arg->replaceAllUsesWith(AggArg); 1862 } 1863 } 1864 1865 /// Within an extracted function, replace the constants that need to be lifted 1866 /// into arguments with the actual argument. 1867 /// 1868 /// \param Region [in] - The region of extracted code to be changed. 1869 void replaceConstants(OutlinableRegion &Region) { 1870 OutlinableGroup &Group = *Region.Parent; 1871 // Iterate over the constants that need to be elevated into arguments 1872 for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) { 1873 unsigned AggArgIdx = Const.first; 1874 Function *OutlinedFunction = Group.OutlinedFunction; 1875 assert(OutlinedFunction && "Overall Function is not defined?"); 1876 Constant *CST = Const.second; 1877 Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx); 1878 // Identify the argument it will be elevated to, and replace instances of 1879 // that constant in the function. 1880 1881 // TODO: If in the future constants do not have one global value number, 1882 // i.e. a constant 1 could be mapped to several values, this check will 1883 // have to be more strict. It cannot be using only replaceUsesWithIf. 1884 1885 LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST 1886 << " in function " << *OutlinedFunction << " with " 1887 << *Arg << "\n"); 1888 CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) { 1889 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) 1890 return I->getFunction() == OutlinedFunction; 1891 return false; 1892 }); 1893 } 1894 } 1895 1896 /// It is possible that there is a basic block that already performs the same 1897 /// stores. This returns a duplicate block, if it exists 1898 /// 1899 /// \param OutputBBs [in] the blocks we are looking for a duplicate of. 1900 /// \param OutputStoreBBs [in] The existing output blocks. 1901 /// \returns an optional value with the number output block if there is a match. 1902 Optional<unsigned> findDuplicateOutputBlock( 1903 DenseMap<Value *, BasicBlock *> &OutputBBs, 1904 std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 1905 1906 bool Mismatch = false; 1907 unsigned MatchingNum = 0; 1908 // We compare the new set output blocks to the other sets of output blocks. 1909 // If they are the same number, and have identical instructions, they are 1910 // considered to be the same. 1911 for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) { 1912 Mismatch = false; 1913 for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) { 1914 DenseMap<Value *, BasicBlock *>::iterator OutputBBIt = 1915 OutputBBs.find(VToB.first); 1916 if (OutputBBIt == OutputBBs.end()) { 1917 Mismatch = true; 1918 break; 1919 } 1920 1921 BasicBlock *CompBB = VToB.second; 1922 BasicBlock *OutputBB = OutputBBIt->second; 1923 if (CompBB->size() - 1 != OutputBB->size()) { 1924 Mismatch = true; 1925 break; 1926 } 1927 1928 BasicBlock::iterator NIt = OutputBB->begin(); 1929 for (Instruction &I : *CompBB) { 1930 if (isa<BranchInst>(&I)) 1931 continue; 1932 1933 if (!I.isIdenticalTo(&(*NIt))) { 1934 Mismatch = true; 1935 break; 1936 } 1937 1938 NIt++; 1939 } 1940 } 1941 1942 if (!Mismatch) 1943 return MatchingNum; 1944 1945 MatchingNum++; 1946 } 1947 1948 return None; 1949 } 1950 1951 /// Remove empty output blocks from the outlined region. 1952 /// 1953 /// \param BlocksToPrune - Mapping of return values output blocks for the \p 1954 /// Region. 1955 /// \param Region - The OutlinableRegion we are analyzing. 1956 static bool 1957 analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune, 1958 OutlinableRegion &Region) { 1959 bool AllRemoved = true; 1960 Value *RetValueForBB; 1961 BasicBlock *NewBB; 1962 SmallVector<Value *, 4> ToRemove; 1963 // Iterate over the output blocks created in the outlined section. 1964 for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) { 1965 RetValueForBB = VtoBB.first; 1966 NewBB = VtoBB.second; 1967 1968 // If there are no instructions, we remove it from the module, and also 1969 // mark the value for removal from the return value to output block mapping. 1970 if (NewBB->size() == 0) { 1971 NewBB->eraseFromParent(); 1972 ToRemove.push_back(RetValueForBB); 1973 continue; 1974 } 1975 1976 // Mark that we could not remove all the blocks since they were not all 1977 // empty. 1978 AllRemoved = false; 1979 } 1980 1981 // Remove the return value from the mapping. 1982 for (Value *V : ToRemove) 1983 BlocksToPrune.erase(V); 1984 1985 // Mark the region as having the no output scheme. 1986 if (AllRemoved) 1987 Region.OutputBlockNum = -1; 1988 1989 return AllRemoved; 1990 } 1991 1992 /// For the outlined section, move needed the StoreInsts for the output 1993 /// registers into their own block. Then, determine if there is a duplicate 1994 /// output block already created. 1995 /// 1996 /// \param [in] OG - The OutlinableGroup of regions to be outlined. 1997 /// \param [in] Region - The OutlinableRegion that is being analyzed. 1998 /// \param [in,out] OutputBBs - the blocks that stores for this region will be 1999 /// placed in. 2000 /// \param [in] EndBBs - the final blocks of the extracted function. 2001 /// \param [in] OutputMappings - OutputMappings the mapping of values that have 2002 /// been replaced by a new output value. 2003 /// \param [in,out] OutputStoreBBs - The existing output blocks. 2004 static void alignOutputBlockWithAggFunc( 2005 OutlinableGroup &OG, OutlinableRegion &Region, 2006 DenseMap<Value *, BasicBlock *> &OutputBBs, 2007 DenseMap<Value *, BasicBlock *> &EndBBs, 2008 const DenseMap<Value *, Value *> &OutputMappings, 2009 std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 2010 // If none of the output blocks have any instructions, this means that we do 2011 // not have to determine if it matches any of the other output schemes, and we 2012 // don't have to do anything else. 2013 if (analyzeAndPruneOutputBlocks(OutputBBs, Region)) 2014 return; 2015 2016 // Determine is there is a duplicate set of blocks. 2017 Optional<unsigned> MatchingBB = 2018 findDuplicateOutputBlock(OutputBBs, OutputStoreBBs); 2019 2020 // If there is, we remove the new output blocks. If it does not, 2021 // we add it to our list of sets of output blocks. 2022 if (MatchingBB.hasValue()) { 2023 LLVM_DEBUG(dbgs() << "Set output block for region in function" 2024 << Region.ExtractedFunction << " to " 2025 << MatchingBB.getValue()); 2026 2027 Region.OutputBlockNum = MatchingBB.getValue(); 2028 for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) 2029 VtoBB.second->eraseFromParent(); 2030 return; 2031 } 2032 2033 Region.OutputBlockNum = OutputStoreBBs.size(); 2034 2035 Value *RetValueForBB; 2036 BasicBlock *NewBB; 2037 OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>()); 2038 for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) { 2039 RetValueForBB = VtoBB.first; 2040 NewBB = VtoBB.second; 2041 DenseMap<Value *, BasicBlock *>::iterator VBBIt = 2042 EndBBs.find(RetValueForBB); 2043 LLVM_DEBUG(dbgs() << "Create output block for region in" 2044 << Region.ExtractedFunction << " to " 2045 << *NewBB); 2046 BranchInst::Create(VBBIt->second, NewBB); 2047 OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB)); 2048 } 2049 } 2050 2051 /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys, 2052 /// before creating a basic block for each \p NewMap, and inserting into the new 2053 /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>". 2054 /// 2055 /// \param OldMap [in] - The mapping to base the new mapping off of. 2056 /// \param NewMap [out] - The output mapping using the keys of \p OldMap. 2057 /// \param ParentFunc [in] - The function to put the new basic block in. 2058 /// \param BaseName [in] - The start of the BasicBlock names to be appended to 2059 /// by an index value. 2060 static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap, 2061 DenseMap<Value *, BasicBlock *> &NewMap, 2062 Function *ParentFunc, Twine BaseName) { 2063 unsigned Idx = 0; 2064 std::vector<Value *> SortedKeys; 2065 2066 getSortedConstantKeys(SortedKeys, OldMap); 2067 2068 for (Value *RetVal : SortedKeys) { 2069 BasicBlock *NewBB = BasicBlock::Create( 2070 ParentFunc->getContext(), 2071 Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)), 2072 ParentFunc); 2073 NewMap.insert(std::make_pair(RetVal, NewBB)); 2074 } 2075 } 2076 2077 /// Create the switch statement for outlined function to differentiate between 2078 /// all the output blocks. 2079 /// 2080 /// For the outlined section, determine if an outlined block already exists that 2081 /// matches the needed stores for the extracted section. 2082 /// \param [in] M - The module we are outlining from. 2083 /// \param [in] OG - The group of regions to be outlined. 2084 /// \param [in] EndBBs - The final blocks of the extracted function. 2085 /// \param [in,out] OutputStoreBBs - The existing output blocks. 2086 void createSwitchStatement( 2087 Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs, 2088 std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 2089 // We only need the switch statement if there is more than one store 2090 // combination, or there is more than one set of output blocks. The first 2091 // will occur when we store different sets of values for two different 2092 // regions. The second will occur when we have two outputs that are combined 2093 // in a PHINode outside of the region in one outlined instance, and are used 2094 // seaparately in another. This will create the same set of OutputGVNs, but 2095 // will generate two different output schemes. 2096 if (OG.OutputGVNCombinations.size() > 1) { 2097 Function *AggFunc = OG.OutlinedFunction; 2098 // Create a final block for each different return block. 2099 DenseMap<Value *, BasicBlock *> ReturnBBs; 2100 createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block"); 2101 2102 for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) { 2103 std::pair<Value *, BasicBlock *> &OutputBlock = 2104 *OG.EndBBs.find(RetBlockPair.first); 2105 BasicBlock *ReturnBlock = RetBlockPair.second; 2106 BasicBlock *EndBB = OutputBlock.second; 2107 Instruction *Term = EndBB->getTerminator(); 2108 // Move the return value to the final block instead of the original exit 2109 // stub. 2110 Term->moveBefore(*ReturnBlock, ReturnBlock->end()); 2111 // Put the switch statement in the old end basic block for the function 2112 // with a fall through to the new return block. 2113 LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for " 2114 << OutputStoreBBs.size() << "\n"); 2115 SwitchInst *SwitchI = 2116 SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1), 2117 ReturnBlock, OutputStoreBBs.size(), EndBB); 2118 2119 unsigned Idx = 0; 2120 for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) { 2121 DenseMap<Value *, BasicBlock *>::iterator OSBBIt = 2122 OutputStoreBB.find(OutputBlock.first); 2123 2124 if (OSBBIt == OutputStoreBB.end()) 2125 continue; 2126 2127 BasicBlock *BB = OSBBIt->second; 2128 SwitchI->addCase( 2129 ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB); 2130 Term = BB->getTerminator(); 2131 Term->setSuccessor(0, ReturnBlock); 2132 Idx++; 2133 } 2134 } 2135 return; 2136 } 2137 2138 assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!"); 2139 2140 // If there needs to be stores, move them from the output blocks to their 2141 // corresponding ending block. We do not check that the OutputGVNCombinations 2142 // is equal to 1 here since that could just been the case where there are 0 2143 // outputs. Instead, we check whether there is more than one set of output 2144 // blocks since this is the only case where we would have to move the 2145 // stores, and erase the extraneous blocks. 2146 if (OutputStoreBBs.size() == 1) { 2147 LLVM_DEBUG(dbgs() << "Move store instructions to the end block in " 2148 << *OG.OutlinedFunction << "\n"); 2149 DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0]; 2150 for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) { 2151 DenseMap<Value *, BasicBlock *>::iterator EndBBIt = 2152 EndBBs.find(VBPair.first); 2153 assert(EndBBIt != EndBBs.end() && "Could not find end block"); 2154 BasicBlock *EndBB = EndBBIt->second; 2155 BasicBlock *OutputBB = VBPair.second; 2156 Instruction *Term = OutputBB->getTerminator(); 2157 Term->eraseFromParent(); 2158 Term = EndBB->getTerminator(); 2159 moveBBContents(*OutputBB, *EndBB); 2160 Term->moveBefore(*EndBB, EndBB->end()); 2161 OutputBB->eraseFromParent(); 2162 } 2163 } 2164 } 2165 2166 /// Fill the new function that will serve as the replacement function for all of 2167 /// the extracted regions of a certain structure from the first region in the 2168 /// list of regions. Replace this first region's extracted function with the 2169 /// new overall function. 2170 /// 2171 /// \param [in] M - The module we are outlining from. 2172 /// \param [in] CurrentGroup - The group of regions to be outlined. 2173 /// \param [in,out] OutputStoreBBs - The output blocks for each different 2174 /// set of stores needed for the different functions. 2175 /// \param [in,out] FuncsToRemove - Extracted functions to erase from module 2176 /// once outlining is complete. 2177 /// \param [in] OutputMappings - Extracted functions to erase from module 2178 /// once outlining is complete. 2179 static void fillOverallFunction( 2180 Module &M, OutlinableGroup &CurrentGroup, 2181 std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs, 2182 std::vector<Function *> &FuncsToRemove, 2183 const DenseMap<Value *, Value *> &OutputMappings) { 2184 OutlinableRegion *CurrentOS = CurrentGroup.Regions[0]; 2185 2186 // Move first extracted function's instructions into new function. 2187 LLVM_DEBUG(dbgs() << "Move instructions from " 2188 << *CurrentOS->ExtractedFunction << " to instruction " 2189 << *CurrentGroup.OutlinedFunction << "\n"); 2190 moveFunctionData(*CurrentOS->ExtractedFunction, 2191 *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs); 2192 2193 // Transfer the attributes from the function to the new function. 2194 for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs()) 2195 CurrentGroup.OutlinedFunction->addFnAttr(A); 2196 2197 // Create a new set of output blocks for the first extracted function. 2198 DenseMap<Value *, BasicBlock *> NewBBs; 2199 createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs, 2200 CurrentGroup.OutlinedFunction, "output_block_0"); 2201 CurrentOS->OutputBlockNum = 0; 2202 2203 replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true); 2204 replaceConstants(*CurrentOS); 2205 2206 // We first identify if any output blocks are empty, if they are we remove 2207 // them. We then create a branch instruction to the basic block to the return 2208 // block for the function for each non empty output block. 2209 if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) { 2210 OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>()); 2211 for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) { 2212 DenseMap<Value *, BasicBlock *>::iterator VBBIt = 2213 CurrentGroup.EndBBs.find(VToBB.first); 2214 BasicBlock *EndBB = VBBIt->second; 2215 BranchInst::Create(EndBB, VToBB.second); 2216 OutputStoreBBs.back().insert(VToBB); 2217 } 2218 } 2219 2220 // Replace the call to the extracted function with the outlined function. 2221 CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 2222 2223 // We only delete the extracted functions at the end since we may need to 2224 // reference instructions contained in them for mapping purposes. 2225 FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 2226 } 2227 2228 void IROutliner::deduplicateExtractedSections( 2229 Module &M, OutlinableGroup &CurrentGroup, 2230 std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) { 2231 createFunction(M, CurrentGroup, OutlinedFunctionNum); 2232 2233 std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs; 2234 2235 OutlinableRegion *CurrentOS; 2236 2237 fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove, 2238 OutputMappings); 2239 2240 std::vector<Value *> SortedKeys; 2241 for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) { 2242 CurrentOS = CurrentGroup.Regions[Idx]; 2243 AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction, 2244 *CurrentOS->ExtractedFunction); 2245 2246 // Create a set of BasicBlocks, one for each return block, to hold the 2247 // needed store instructions. 2248 DenseMap<Value *, BasicBlock *> NewBBs; 2249 createAndInsertBasicBlocks( 2250 CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction, 2251 "output_block_" + Twine(static_cast<unsigned>(Idx))); 2252 replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings); 2253 alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs, 2254 CurrentGroup.EndBBs, OutputMappings, 2255 OutputStoreBBs); 2256 2257 CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 2258 FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 2259 } 2260 2261 // Create a switch statement to handle the different output schemes. 2262 createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs); 2263 2264 OutlinedFunctionNum++; 2265 } 2266 2267 /// Checks that the next instruction in the InstructionDataList matches the 2268 /// next instruction in the module. If they do not, there could be the 2269 /// possibility that extra code has been inserted, and we must ignore it. 2270 /// 2271 /// \param ID - The IRInstructionData to check the next instruction of. 2272 /// \returns true if the InstructionDataList and actual instruction match. 2273 static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) { 2274 // We check if there is a discrepancy between the InstructionDataList 2275 // and the actual next instruction in the module. If there is, it means 2276 // that an extra instruction was added, likely by the CodeExtractor. 2277 2278 // Since we do not have any similarity data about this particular 2279 // instruction, we cannot confidently outline it, and must discard this 2280 // candidate. 2281 IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator()); 2282 Instruction *NextIDLInst = NextIDIt->Inst; 2283 Instruction *NextModuleInst = nullptr; 2284 if (!ID.Inst->isTerminator()) 2285 NextModuleInst = ID.Inst->getNextNonDebugInstruction(); 2286 else if (NextIDLInst != nullptr) 2287 NextModuleInst = 2288 &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin(); 2289 2290 if (NextIDLInst && NextIDLInst != NextModuleInst) 2291 return false; 2292 2293 return true; 2294 } 2295 2296 bool IROutliner::isCompatibleWithAlreadyOutlinedCode( 2297 const OutlinableRegion &Region) { 2298 IRSimilarityCandidate *IRSC = Region.Candidate; 2299 unsigned StartIdx = IRSC->getStartIdx(); 2300 unsigned EndIdx = IRSC->getEndIdx(); 2301 2302 // A check to make sure that we are not about to attempt to outline something 2303 // that has already been outlined. 2304 for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2305 if (Outlined.contains(Idx)) 2306 return false; 2307 2308 // We check if the recorded instruction matches the actual next instruction, 2309 // if it does not, we fix it in the InstructionDataList. 2310 if (!Region.Candidate->backInstruction()->isTerminator()) { 2311 Instruction *NewEndInst = 2312 Region.Candidate->backInstruction()->getNextNonDebugInstruction(); 2313 assert(NewEndInst && "Next instruction is a nullptr?"); 2314 if (Region.Candidate->end()->Inst != NewEndInst) { 2315 IRInstructionDataList *IDL = Region.Candidate->front()->IDL; 2316 IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate()) 2317 IRInstructionData(*NewEndInst, 2318 InstructionClassifier.visit(*NewEndInst), *IDL); 2319 2320 // Insert the first IRInstructionData of the new region after the 2321 // last IRInstructionData of the IRSimilarityCandidate. 2322 IDL->insert(Region.Candidate->end(), *NewEndIRID); 2323 } 2324 } 2325 2326 return none_of(*IRSC, [this](IRInstructionData &ID) { 2327 if (!nextIRInstructionDataMatchesNextInst(ID)) 2328 return true; 2329 2330 return !this->InstructionClassifier.visit(ID.Inst); 2331 }); 2332 } 2333 2334 void IROutliner::pruneIncompatibleRegions( 2335 std::vector<IRSimilarityCandidate> &CandidateVec, 2336 OutlinableGroup &CurrentGroup) { 2337 bool PreviouslyOutlined; 2338 2339 // Sort from beginning to end, so the IRSimilarityCandidates are in order. 2340 stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS, 2341 const IRSimilarityCandidate &RHS) { 2342 return LHS.getStartIdx() < RHS.getStartIdx(); 2343 }); 2344 2345 IRSimilarityCandidate &FirstCandidate = CandidateVec[0]; 2346 // Since outlining a call and a branch instruction will be the same as only 2347 // outlinining a call instruction, we ignore it as a space saving. 2348 if (FirstCandidate.getLength() == 2) { 2349 if (isa<CallInst>(FirstCandidate.front()->Inst) && 2350 isa<BranchInst>(FirstCandidate.back()->Inst)) 2351 return; 2352 } 2353 2354 unsigned CurrentEndIdx = 0; 2355 for (IRSimilarityCandidate &IRSC : CandidateVec) { 2356 PreviouslyOutlined = false; 2357 unsigned StartIdx = IRSC.getStartIdx(); 2358 unsigned EndIdx = IRSC.getEndIdx(); 2359 2360 for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2361 if (Outlined.contains(Idx)) { 2362 PreviouslyOutlined = true; 2363 break; 2364 } 2365 2366 if (PreviouslyOutlined) 2367 continue; 2368 2369 // Check over the instructions, and if the basic block has its address 2370 // taken for use somewhere else, we do not outline that block. 2371 bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){ 2372 return ID.Inst->getParent()->hasAddressTaken(); 2373 }); 2374 2375 if (BBHasAddressTaken) 2376 continue; 2377 2378 if (IRSC.getFunction()->hasOptNone()) 2379 continue; 2380 2381 if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() && 2382 !OutlineFromLinkODRs) 2383 continue; 2384 2385 // Greedily prune out any regions that will overlap with already chosen 2386 // regions. 2387 if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx) 2388 continue; 2389 2390 bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) { 2391 if (!nextIRInstructionDataMatchesNextInst(ID)) 2392 return true; 2393 2394 return !this->InstructionClassifier.visit(ID.Inst); 2395 }); 2396 2397 if (BadInst) 2398 continue; 2399 2400 OutlinableRegion *OS = new (RegionAllocator.Allocate()) 2401 OutlinableRegion(IRSC, CurrentGroup); 2402 CurrentGroup.Regions.push_back(OS); 2403 2404 CurrentEndIdx = EndIdx; 2405 } 2406 } 2407 2408 InstructionCost 2409 IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) { 2410 InstructionCost RegionBenefit = 0; 2411 for (OutlinableRegion *Region : CurrentGroup.Regions) { 2412 TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 2413 // We add the number of instructions in the region to the benefit as an 2414 // estimate as to how much will be removed. 2415 RegionBenefit += Region->getBenefit(TTI); 2416 LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit 2417 << " saved instructions to overfall benefit.\n"); 2418 } 2419 2420 return RegionBenefit; 2421 } 2422 2423 /// For the \p OutputCanon number passed in find the value represented by this 2424 /// canonical number. If it is from a PHINode, we pick the first incoming 2425 /// value and return that Value instead. 2426 /// 2427 /// \param Region - The OutlinableRegion to get the Value from. 2428 /// \param OutputCanon - The canonical number to find the Value from. 2429 /// \returns The Value represented by a canonical number \p OutputCanon in \p 2430 /// Region. 2431 static Value *findOutputValueInRegion(OutlinableRegion &Region, 2432 unsigned OutputCanon) { 2433 OutlinableGroup &CurrentGroup = *Region.Parent; 2434 // If the value is greater than the value in the tracker, we have a 2435 // PHINode and will instead use one of the incoming values to find the 2436 // type. 2437 if (OutputCanon > CurrentGroup.PHINodeGVNTracker) { 2438 auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon); 2439 assert(It != CurrentGroup.PHINodeGVNToGVNs.end() && 2440 "Could not find GVN set for PHINode number!"); 2441 assert(It->second.second.size() > 0 && "PHINode does not have any values!"); 2442 OutputCanon = *It->second.second.begin(); 2443 } 2444 Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon); 2445 assert(OGVN.hasValue() && "Could not find GVN for Canonical Number?"); 2446 Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN); 2447 assert(OV.hasValue() && "Could not find value for GVN?"); 2448 return *OV; 2449 } 2450 2451 InstructionCost 2452 IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) { 2453 InstructionCost OverallCost = 0; 2454 for (OutlinableRegion *Region : CurrentGroup.Regions) { 2455 TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 2456 2457 // Each output incurs a load after the call, so we add that to the cost. 2458 for (unsigned OutputCanon : Region->GVNStores) { 2459 Value *V = findOutputValueInRegion(*Region, OutputCanon); 2460 InstructionCost LoadCost = 2461 TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 2462 TargetTransformInfo::TCK_CodeSize); 2463 2464 LLVM_DEBUG(dbgs() << "Adding: " << LoadCost 2465 << " instructions to cost for output of type " 2466 << *V->getType() << "\n"); 2467 OverallCost += LoadCost; 2468 } 2469 } 2470 2471 return OverallCost; 2472 } 2473 2474 /// Find the extra instructions needed to handle any output values for the 2475 /// region. 2476 /// 2477 /// \param [in] M - The Module to outline from. 2478 /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze. 2479 /// \param [in] TTI - The TargetTransformInfo used to collect information for 2480 /// new instruction costs. 2481 /// \returns the additional cost to handle the outputs. 2482 static InstructionCost findCostForOutputBlocks(Module &M, 2483 OutlinableGroup &CurrentGroup, 2484 TargetTransformInfo &TTI) { 2485 InstructionCost OutputCost = 0; 2486 unsigned NumOutputBranches = 0; 2487 2488 OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0]; 2489 IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate; 2490 DenseSet<BasicBlock *> CandidateBlocks; 2491 Candidate.getBasicBlocks(CandidateBlocks); 2492 2493 // Count the number of different output branches that point to blocks outside 2494 // of the region. 2495 DenseSet<BasicBlock *> FoundBlocks; 2496 for (IRInstructionData &ID : Candidate) { 2497 if (!isa<BranchInst>(ID.Inst)) 2498 continue; 2499 2500 for (Value *V : ID.OperVals) { 2501 BasicBlock *BB = static_cast<BasicBlock *>(V); 2502 DenseSet<BasicBlock *>::iterator CBIt = CandidateBlocks.find(BB); 2503 if (CBIt != CandidateBlocks.end() || FoundBlocks.contains(BB)) 2504 continue; 2505 FoundBlocks.insert(BB); 2506 NumOutputBranches++; 2507 } 2508 } 2509 2510 CurrentGroup.BranchesToOutside = NumOutputBranches; 2511 2512 for (const ArrayRef<unsigned> &OutputUse : 2513 CurrentGroup.OutputGVNCombinations) { 2514 for (unsigned OutputCanon : OutputUse) { 2515 Value *V = findOutputValueInRegion(FirstRegion, OutputCanon); 2516 InstructionCost StoreCost = 2517 TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 2518 TargetTransformInfo::TCK_CodeSize); 2519 2520 // An instruction cost is added for each store set that needs to occur for 2521 // various output combinations inside the function, plus a branch to 2522 // return to the exit block. 2523 LLVM_DEBUG(dbgs() << "Adding: " << StoreCost 2524 << " instructions to cost for output of type " 2525 << *V->getType() << "\n"); 2526 OutputCost += StoreCost * NumOutputBranches; 2527 } 2528 2529 InstructionCost BranchCost = 2530 TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 2531 LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for" 2532 << " a branch instruction\n"); 2533 OutputCost += BranchCost * NumOutputBranches; 2534 } 2535 2536 // If there is more than one output scheme, we must have a comparison and 2537 // branch for each different item in the switch statement. 2538 if (CurrentGroup.OutputGVNCombinations.size() > 1) { 2539 InstructionCost ComparisonCost = TTI.getCmpSelInstrCost( 2540 Instruction::ICmp, Type::getInt32Ty(M.getContext()), 2541 Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE, 2542 TargetTransformInfo::TCK_CodeSize); 2543 InstructionCost BranchCost = 2544 TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 2545 2546 unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size(); 2547 InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks; 2548 2549 LLVM_DEBUG(dbgs() << "Adding: " << TotalCost 2550 << " instructions for each switch case for each different" 2551 << " output path in a function\n"); 2552 OutputCost += TotalCost * NumOutputBranches; 2553 } 2554 2555 return OutputCost; 2556 } 2557 2558 void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) { 2559 InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup); 2560 CurrentGroup.Benefit += RegionBenefit; 2561 LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n"); 2562 2563 InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup); 2564 CurrentGroup.Cost += OutputReloadCost; 2565 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2566 2567 InstructionCost AverageRegionBenefit = 2568 RegionBenefit / CurrentGroup.Regions.size(); 2569 unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size(); 2570 unsigned NumRegions = CurrentGroup.Regions.size(); 2571 TargetTransformInfo &TTI = 2572 getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction()); 2573 2574 // We add one region to the cost once, to account for the instructions added 2575 // inside of the newly created function. 2576 LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit 2577 << " instructions to cost for body of new function.\n"); 2578 CurrentGroup.Cost += AverageRegionBenefit; 2579 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2580 2581 // For each argument, we must add an instruction for loading the argument 2582 // out of the register and into a value inside of the newly outlined function. 2583 LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 2584 << " instructions to cost for each argument in the new" 2585 << " function.\n"); 2586 CurrentGroup.Cost += 2587 OverallArgumentNum * TargetTransformInfo::TCC_Basic; 2588 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2589 2590 // Each argument needs to either be loaded into a register or onto the stack. 2591 // Some arguments will only be loaded into the stack once the argument 2592 // registers are filled. 2593 LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 2594 << " instructions to cost for each argument in the new" 2595 << " function " << NumRegions << " times for the " 2596 << "needed argument handling at the call site.\n"); 2597 CurrentGroup.Cost += 2598 2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions; 2599 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2600 2601 CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI); 2602 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2603 } 2604 2605 void IROutliner::updateOutputMapping(OutlinableRegion &Region, 2606 ArrayRef<Value *> Outputs, 2607 LoadInst *LI) { 2608 // For and load instructions following the call 2609 Value *Operand = LI->getPointerOperand(); 2610 Optional<unsigned> OutputIdx = None; 2611 // Find if the operand it is an output register. 2612 for (unsigned ArgIdx = Region.NumExtractedInputs; 2613 ArgIdx < Region.Call->arg_size(); ArgIdx++) { 2614 if (Operand == Region.Call->getArgOperand(ArgIdx)) { 2615 OutputIdx = ArgIdx - Region.NumExtractedInputs; 2616 break; 2617 } 2618 } 2619 2620 // If we found an output register, place a mapping of the new value 2621 // to the original in the mapping. 2622 if (!OutputIdx.hasValue()) 2623 return; 2624 2625 if (OutputMappings.find(Outputs[OutputIdx.getValue()]) == 2626 OutputMappings.end()) { 2627 LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to " 2628 << *Outputs[OutputIdx.getValue()] << "\n"); 2629 OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()])); 2630 } else { 2631 Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second; 2632 LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to " 2633 << *Outputs[OutputIdx.getValue()] << "\n"); 2634 OutputMappings.insert(std::make_pair(LI, Orig)); 2635 } 2636 } 2637 2638 bool IROutliner::extractSection(OutlinableRegion &Region) { 2639 SetVector<Value *> ArgInputs, Outputs, SinkCands; 2640 assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!"); 2641 BasicBlock *InitialStart = Region.StartBB; 2642 Function *OrigF = Region.StartBB->getParent(); 2643 CodeExtractorAnalysisCache CEAC(*OrigF); 2644 Region.ExtractedFunction = 2645 Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs); 2646 2647 // If the extraction was successful, find the BasicBlock, and reassign the 2648 // OutlinableRegion blocks 2649 if (!Region.ExtractedFunction) { 2650 LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB 2651 << "\n"); 2652 Region.reattachCandidate(); 2653 return false; 2654 } 2655 2656 // Get the block containing the called branch, and reassign the blocks as 2657 // necessary. If the original block still exists, it is because we ended on 2658 // a branch instruction, and so we move the contents into the block before 2659 // and assign the previous block correctly. 2660 User *InstAsUser = Region.ExtractedFunction->user_back(); 2661 BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent(); 2662 Region.PrevBB = RewrittenBB->getSinglePredecessor(); 2663 assert(Region.PrevBB && "PrevBB is nullptr?"); 2664 if (Region.PrevBB == InitialStart) { 2665 BasicBlock *NewPrev = InitialStart->getSinglePredecessor(); 2666 Instruction *BI = NewPrev->getTerminator(); 2667 BI->eraseFromParent(); 2668 moveBBContents(*InitialStart, *NewPrev); 2669 Region.PrevBB = NewPrev; 2670 InitialStart->eraseFromParent(); 2671 } 2672 2673 Region.StartBB = RewrittenBB; 2674 Region.EndBB = RewrittenBB; 2675 2676 // The sequences of outlinable regions has now changed. We must fix the 2677 // IRInstructionDataList for consistency. Although they may not be illegal 2678 // instructions, they should not be compared with anything else as they 2679 // should not be outlined in this round. So marking these as illegal is 2680 // allowed. 2681 IRInstructionDataList *IDL = Region.Candidate->front()->IDL; 2682 Instruction *BeginRewritten = &*RewrittenBB->begin(); 2683 Instruction *EndRewritten = &*RewrittenBB->begin(); 2684 Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData( 2685 *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL); 2686 Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData( 2687 *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL); 2688 2689 // Insert the first IRInstructionData of the new region in front of the 2690 // first IRInstructionData of the IRSimilarityCandidate. 2691 IDL->insert(Region.Candidate->begin(), *Region.NewFront); 2692 // Insert the first IRInstructionData of the new region after the 2693 // last IRInstructionData of the IRSimilarityCandidate. 2694 IDL->insert(Region.Candidate->end(), *Region.NewBack); 2695 // Remove the IRInstructionData from the IRSimilarityCandidate. 2696 IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end())); 2697 2698 assert(RewrittenBB != nullptr && 2699 "Could not find a predecessor after extraction!"); 2700 2701 // Iterate over the new set of instructions to find the new call 2702 // instruction. 2703 for (Instruction &I : *RewrittenBB) 2704 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 2705 if (Region.ExtractedFunction == CI->getCalledFunction()) 2706 Region.Call = CI; 2707 } else if (LoadInst *LI = dyn_cast<LoadInst>(&I)) 2708 updateOutputMapping(Region, Outputs.getArrayRef(), LI); 2709 Region.reattachCandidate(); 2710 return true; 2711 } 2712 2713 unsigned IROutliner::doOutline(Module &M) { 2714 // Find the possible similarity sections. 2715 InstructionClassifier.EnableBranches = !DisableBranches; 2716 InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls; 2717 InstructionClassifier.EnableIntrinsics = !DisableIntrinsics; 2718 2719 IRSimilarityIdentifier &Identifier = getIRSI(M); 2720 SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity(); 2721 2722 // Sort them by size of extracted sections 2723 unsigned OutlinedFunctionNum = 0; 2724 // If we only have one SimilarityGroup in SimilarityCandidates, we do not have 2725 // to sort them by the potential number of instructions to be outlined 2726 if (SimilarityCandidates.size() > 1) 2727 llvm::stable_sort(SimilarityCandidates, 2728 [](const std::vector<IRSimilarityCandidate> &LHS, 2729 const std::vector<IRSimilarityCandidate> &RHS) { 2730 return LHS[0].getLength() * LHS.size() > 2731 RHS[0].getLength() * RHS.size(); 2732 }); 2733 // Creating OutlinableGroups for each SimilarityCandidate to be used in 2734 // each of the following for loops to avoid making an allocator. 2735 std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size()); 2736 2737 DenseSet<unsigned> NotSame; 2738 std::vector<OutlinableGroup *> NegativeCostGroups; 2739 std::vector<OutlinableRegion *> OutlinedRegions; 2740 // Iterate over the possible sets of similarity. 2741 unsigned PotentialGroupIdx = 0; 2742 for (SimilarityGroup &CandidateVec : SimilarityCandidates) { 2743 OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++]; 2744 2745 // Remove entries that were previously outlined 2746 pruneIncompatibleRegions(CandidateVec, CurrentGroup); 2747 2748 // We pruned the number of regions to 0 to 1, meaning that it's not worth 2749 // trying to outlined since there is no compatible similar instance of this 2750 // code. 2751 if (CurrentGroup.Regions.size() < 2) 2752 continue; 2753 2754 // Determine if there are any values that are the same constant throughout 2755 // each section in the set. 2756 NotSame.clear(); 2757 CurrentGroup.findSameConstants(NotSame); 2758 2759 if (CurrentGroup.IgnoreGroup) 2760 continue; 2761 2762 // Create a CodeExtractor for each outlinable region. Identify inputs and 2763 // outputs for each section using the code extractor and create the argument 2764 // types for the Aggregate Outlining Function. 2765 OutlinedRegions.clear(); 2766 for (OutlinableRegion *OS : CurrentGroup.Regions) { 2767 // Break the outlinable region out of its parent BasicBlock into its own 2768 // BasicBlocks (see function implementation). 2769 OS->splitCandidate(); 2770 2771 // There's a chance that when the region is split, extra instructions are 2772 // added to the region. This makes the region no longer viable 2773 // to be split, so we ignore it for outlining. 2774 if (!OS->CandidateSplit) 2775 continue; 2776 2777 SmallVector<BasicBlock *> BE; 2778 DenseSet<BasicBlock *> BlocksInRegion; 2779 OS->Candidate->getBasicBlocks(BlocksInRegion, BE); 2780 OS->CE = new (ExtractorAllocator.Allocate()) 2781 CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false, 2782 false, nullptr, "outlined"); 2783 findAddInputsOutputs(M, *OS, NotSame); 2784 if (!OS->IgnoreRegion) 2785 OutlinedRegions.push_back(OS); 2786 2787 // We recombine the blocks together now that we have gathered all the 2788 // needed information. 2789 OS->reattachCandidate(); 2790 } 2791 2792 CurrentGroup.Regions = std::move(OutlinedRegions); 2793 2794 if (CurrentGroup.Regions.empty()) 2795 continue; 2796 2797 CurrentGroup.collectGVNStoreSets(M); 2798 2799 if (CostModel) 2800 findCostBenefit(M, CurrentGroup); 2801 2802 // If we are adhering to the cost model, skip those groups where the cost 2803 // outweighs the benefits. 2804 if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) { 2805 OptimizationRemarkEmitter &ORE = 2806 getORE(*CurrentGroup.Regions[0]->Candidate->getFunction()); 2807 ORE.emit([&]() { 2808 IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 2809 OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize", 2810 C->frontInstruction()); 2811 R << "did not outline " 2812 << ore::NV(std::to_string(CurrentGroup.Regions.size())) 2813 << " regions due to estimated increase of " 2814 << ore::NV("InstructionIncrease", 2815 CurrentGroup.Cost - CurrentGroup.Benefit) 2816 << " instructions at locations "; 2817 interleave( 2818 CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 2819 [&R](OutlinableRegion *Region) { 2820 R << ore::NV( 2821 "DebugLoc", 2822 Region->Candidate->frontInstruction()->getDebugLoc()); 2823 }, 2824 [&R]() { R << " "; }); 2825 return R; 2826 }); 2827 continue; 2828 } 2829 2830 NegativeCostGroups.push_back(&CurrentGroup); 2831 } 2832 2833 ExtractorAllocator.DestroyAll(); 2834 2835 if (NegativeCostGroups.size() > 1) 2836 stable_sort(NegativeCostGroups, 2837 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) { 2838 return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost; 2839 }); 2840 2841 std::vector<Function *> FuncsToRemove; 2842 for (OutlinableGroup *CG : NegativeCostGroups) { 2843 OutlinableGroup &CurrentGroup = *CG; 2844 2845 OutlinedRegions.clear(); 2846 for (OutlinableRegion *Region : CurrentGroup.Regions) { 2847 // We check whether our region is compatible with what has already been 2848 // outlined, and whether we need to ignore this item. 2849 if (!isCompatibleWithAlreadyOutlinedCode(*Region)) 2850 continue; 2851 OutlinedRegions.push_back(Region); 2852 } 2853 2854 if (OutlinedRegions.size() < 2) 2855 continue; 2856 2857 // Reestimate the cost and benefit of the OutlinableGroup. Continue only if 2858 // we are still outlining enough regions to make up for the added cost. 2859 CurrentGroup.Regions = std::move(OutlinedRegions); 2860 if (CostModel) { 2861 CurrentGroup.Benefit = 0; 2862 CurrentGroup.Cost = 0; 2863 findCostBenefit(M, CurrentGroup); 2864 if (CurrentGroup.Cost >= CurrentGroup.Benefit) 2865 continue; 2866 } 2867 OutlinedRegions.clear(); 2868 for (OutlinableRegion *Region : CurrentGroup.Regions) { 2869 Region->splitCandidate(); 2870 if (!Region->CandidateSplit) 2871 continue; 2872 OutlinedRegions.push_back(Region); 2873 } 2874 2875 CurrentGroup.Regions = std::move(OutlinedRegions); 2876 if (CurrentGroup.Regions.size() < 2) { 2877 for (OutlinableRegion *R : CurrentGroup.Regions) 2878 R->reattachCandidate(); 2879 continue; 2880 } 2881 2882 LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost 2883 << " and benefit " << CurrentGroup.Benefit << "\n"); 2884 2885 // Create functions out of all the sections, and mark them as outlined. 2886 OutlinedRegions.clear(); 2887 for (OutlinableRegion *OS : CurrentGroup.Regions) { 2888 SmallVector<BasicBlock *> BE; 2889 DenseSet<BasicBlock *> BlocksInRegion; 2890 OS->Candidate->getBasicBlocks(BlocksInRegion, BE); 2891 OS->CE = new (ExtractorAllocator.Allocate()) 2892 CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false, 2893 false, nullptr, "outlined"); 2894 bool FunctionOutlined = extractSection(*OS); 2895 if (FunctionOutlined) { 2896 unsigned StartIdx = OS->Candidate->getStartIdx(); 2897 unsigned EndIdx = OS->Candidate->getEndIdx(); 2898 for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2899 Outlined.insert(Idx); 2900 2901 OutlinedRegions.push_back(OS); 2902 } 2903 } 2904 2905 LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size() 2906 << " with benefit " << CurrentGroup.Benefit 2907 << " and cost " << CurrentGroup.Cost << "\n"); 2908 2909 CurrentGroup.Regions = std::move(OutlinedRegions); 2910 2911 if (CurrentGroup.Regions.empty()) 2912 continue; 2913 2914 OptimizationRemarkEmitter &ORE = 2915 getORE(*CurrentGroup.Regions[0]->Call->getFunction()); 2916 ORE.emit([&]() { 2917 IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 2918 OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst); 2919 R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size())) 2920 << " regions with decrease of " 2921 << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost) 2922 << " instructions at locations "; 2923 interleave( 2924 CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 2925 [&R](OutlinableRegion *Region) { 2926 R << ore::NV("DebugLoc", 2927 Region->Candidate->frontInstruction()->getDebugLoc()); 2928 }, 2929 [&R]() { R << " "; }); 2930 return R; 2931 }); 2932 2933 deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove, 2934 OutlinedFunctionNum); 2935 } 2936 2937 for (Function *F : FuncsToRemove) 2938 F->eraseFromParent(); 2939 2940 return OutlinedFunctionNum; 2941 } 2942 2943 bool IROutliner::run(Module &M) { 2944 CostModel = !NoCostModel; 2945 OutlineFromLinkODRs = EnableLinkOnceODRIROutlining; 2946 2947 return doOutline(M) > 0; 2948 } 2949 2950 // Pass Manager Boilerplate 2951 namespace { 2952 class IROutlinerLegacyPass : public ModulePass { 2953 public: 2954 static char ID; 2955 IROutlinerLegacyPass() : ModulePass(ID) { 2956 initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry()); 2957 } 2958 2959 void getAnalysisUsage(AnalysisUsage &AU) const override { 2960 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2961 AU.addRequired<TargetTransformInfoWrapperPass>(); 2962 AU.addRequired<IRSimilarityIdentifierWrapperPass>(); 2963 } 2964 2965 bool runOnModule(Module &M) override; 2966 }; 2967 } // namespace 2968 2969 bool IROutlinerLegacyPass::runOnModule(Module &M) { 2970 if (skipModule(M)) 2971 return false; 2972 2973 std::unique_ptr<OptimizationRemarkEmitter> ORE; 2974 auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & { 2975 ORE.reset(new OptimizationRemarkEmitter(&F)); 2976 return *ORE; 2977 }; 2978 2979 auto GTTI = [this](Function &F) -> TargetTransformInfo & { 2980 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2981 }; 2982 2983 auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & { 2984 return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI(); 2985 }; 2986 2987 return IROutliner(GTTI, GIRSI, GORE).run(M); 2988 } 2989 2990 PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) { 2991 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2992 2993 std::function<TargetTransformInfo &(Function &)> GTTI = 2994 [&FAM](Function &F) -> TargetTransformInfo & { 2995 return FAM.getResult<TargetIRAnalysis>(F); 2996 }; 2997 2998 std::function<IRSimilarityIdentifier &(Module &)> GIRSI = 2999 [&AM](Module &M) -> IRSimilarityIdentifier & { 3000 return AM.getResult<IRSimilarityAnalysis>(M); 3001 }; 3002 3003 std::unique_ptr<OptimizationRemarkEmitter> ORE; 3004 std::function<OptimizationRemarkEmitter &(Function &)> GORE = 3005 [&ORE](Function &F) -> OptimizationRemarkEmitter & { 3006 ORE.reset(new OptimizationRemarkEmitter(&F)); 3007 return *ORE; 3008 }; 3009 3010 if (IROutliner(GTTI, GIRSI, GORE).run(M)) 3011 return PreservedAnalyses::none(); 3012 return PreservedAnalyses::all(); 3013 } 3014 3015 char IROutlinerLegacyPass::ID = 0; 3016 INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 3017 false) 3018 INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass) 3019 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 3020 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 3021 INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 3022 false) 3023 3024 ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); } 3025