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