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