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