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/DebugInfoMetadata.h" 20 #include "llvm/IR/DIBuilder.h" 21 #include "llvm/IR/Mangler.h" 22 #include "llvm/IR/PassManager.h" 23 #include "llvm/InitializePasses.h" 24 #include "llvm/Pass.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Transforms/IPO.h" 27 #include <map> 28 #include <set> 29 #include <vector> 30 31 #define DEBUG_TYPE "iroutliner" 32 33 using namespace llvm; 34 using namespace IRSimilarity; 35 36 // Set to true if the user wants the ir outliner to run on linkonceodr linkage 37 // functions. This is false by default because the linker can dedupe linkonceodr 38 // functions. Since the outliner is confined to a single module (modulo LTO), 39 // this is off by default. It should, however, be the default behavior in 40 // LTO. 41 static cl::opt<bool> EnableLinkOnceODRIROutlining( 42 "enable-linkonceodr-ir-outlining", cl::Hidden, 43 cl::desc("Enable the IR outliner on linkonceodr functions"), 44 cl::init(false)); 45 46 // This is a debug option to test small pieces of code to ensure that outlining 47 // works correctly. 48 static cl::opt<bool> NoCostModel( 49 "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden, 50 cl::desc("Debug option to outline greedily, without restriction that " 51 "calculated benefit outweighs cost")); 52 53 /// The OutlinableGroup holds all the overarching information for outlining 54 /// a set of regions that are structurally similar to one another, such as the 55 /// types of the overall function, the output blocks, the sets of stores needed 56 /// and a list of the different regions. This information is used in the 57 /// deduplication of extracted regions with the same structure. 58 struct OutlinableGroup { 59 /// The sections that could be outlined 60 std::vector<OutlinableRegion *> Regions; 61 62 /// The argument types for the function created as the overall function to 63 /// replace the extracted function for each region. 64 std::vector<Type *> ArgumentTypes; 65 /// The FunctionType for the overall function. 66 FunctionType *OutlinedFunctionType = nullptr; 67 /// The Function for the collective overall function. 68 Function *OutlinedFunction = nullptr; 69 70 /// Flag for whether we should not consider this group of OutlinableRegions 71 /// for extraction. 72 bool IgnoreGroup = false; 73 74 /// The return block for the overall function. 75 BasicBlock *EndBB = nullptr; 76 77 /// A set containing the different GVN store sets needed. Each array contains 78 /// a sorted list of the different values that need to be stored into output 79 /// registers. 80 DenseSet<ArrayRef<unsigned>> OutputGVNCombinations; 81 82 /// Flag for whether the \ref ArgumentTypes have been defined after the 83 /// extraction of the first region. 84 bool InputTypesSet = false; 85 86 /// The number of input values in \ref ArgumentTypes. Anything after this 87 /// index in ArgumentTypes is an output argument. 88 unsigned NumAggregateInputs = 0; 89 90 /// The number of instructions that will be outlined by extracting \ref 91 /// Regions. 92 InstructionCost Benefit = 0; 93 /// The number of added instructions needed for the outlining of the \ref 94 /// Regions. 95 InstructionCost Cost = 0; 96 97 /// The argument that needs to be marked with the swifterr attribute. If not 98 /// needed, there is no value. 99 Optional<unsigned> SwiftErrorArgument; 100 101 /// For the \ref Regions, we look at every Value. If it is a constant, 102 /// we check whether it is the same in Region. 103 /// 104 /// \param [in,out] NotSame contains the global value numbers where the 105 /// constant is not always the same, and must be passed in as an argument. 106 void findSameConstants(DenseSet<unsigned> &NotSame); 107 108 /// For the regions, look at each set of GVN stores needed and account for 109 /// each combination. Add an argument to the argument types if there is 110 /// more than one combination. 111 /// 112 /// \param [in] M - The module we are outlining from. 113 void collectGVNStoreSets(Module &M); 114 }; 115 116 /// Move the contents of \p SourceBB to before the last instruction of \p 117 /// TargetBB. 118 /// \param SourceBB - the BasicBlock to pull Instructions from. 119 /// \param TargetBB - the BasicBlock to put Instruction into. 120 static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) { 121 BasicBlock::iterator BBCurr, BBEnd, BBNext; 122 for (BBCurr = SourceBB.begin(), BBEnd = SourceBB.end(); BBCurr != BBEnd; 123 BBCurr = BBNext) { 124 BBNext = std::next(BBCurr); 125 BBCurr->moveBefore(TargetBB, TargetBB.end()); 126 } 127 } 128 129 void OutlinableRegion::splitCandidate() { 130 assert(!CandidateSplit && "Candidate already split!"); 131 132 Instruction *StartInst = (*Candidate->begin()).Inst; 133 Instruction *EndInst = (*Candidate->end()).Inst; 134 assert(StartInst && EndInst && "Expected a start and end instruction?"); 135 StartBB = StartInst->getParent(); 136 PrevBB = StartBB; 137 138 // The basic block gets split like so: 139 // block: block: 140 // inst1 inst1 141 // inst2 inst2 142 // region1 br block_to_outline 143 // region2 block_to_outline: 144 // region3 -> region1 145 // region4 region2 146 // inst3 region3 147 // inst4 region4 148 // br block_after_outline 149 // block_after_outline: 150 // inst3 151 // inst4 152 153 std::string OriginalName = PrevBB->getName().str(); 154 155 StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline"); 156 157 // This is the case for the inner block since we do not have to include 158 // multiple blocks. 159 EndBB = StartBB; 160 FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline"); 161 162 CandidateSplit = true; 163 } 164 165 void OutlinableRegion::reattachCandidate() { 166 assert(CandidateSplit && "Candidate is not split!"); 167 168 // The basic block gets reattached like so: 169 // block: block: 170 // inst1 inst1 171 // inst2 inst2 172 // br block_to_outline region1 173 // block_to_outline: -> region2 174 // region1 region3 175 // region2 region4 176 // region3 inst3 177 // region4 inst4 178 // br block_after_outline 179 // block_after_outline: 180 // inst3 181 // inst4 182 assert(StartBB != nullptr && "StartBB for Candidate is not defined!"); 183 assert(FollowBB != nullptr && "StartBB for Candidate is not defined!"); 184 185 // StartBB should only have one predecessor since we put an unconditional 186 // branch at the end of PrevBB when we split the BasicBlock. 187 PrevBB = StartBB->getSinglePredecessor(); 188 assert(PrevBB != nullptr && 189 "No Predecessor for the region start basic block!"); 190 191 assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!"); 192 assert(EndBB->getTerminator() && "Terminator removed from EndBB!"); 193 PrevBB->getTerminator()->eraseFromParent(); 194 EndBB->getTerminator()->eraseFromParent(); 195 196 moveBBContents(*StartBB, *PrevBB); 197 198 BasicBlock *PlacementBB = PrevBB; 199 if (StartBB != EndBB) 200 PlacementBB = EndBB; 201 moveBBContents(*FollowBB, *PlacementBB); 202 203 PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB); 204 PrevBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB); 205 StartBB->eraseFromParent(); 206 FollowBB->eraseFromParent(); 207 208 // Make sure to save changes back to the StartBB. 209 StartBB = PrevBB; 210 EndBB = nullptr; 211 PrevBB = nullptr; 212 FollowBB = nullptr; 213 214 CandidateSplit = false; 215 } 216 217 /// Find whether \p V matches the Constants previously found for the \p GVN. 218 /// 219 /// \param V - The value to check for consistency. 220 /// \param GVN - The global value number assigned to \p V. 221 /// \param GVNToConstant - The mapping of global value number to Constants. 222 /// \returns true if the Value matches the Constant mapped to by V and false if 223 /// it \p V is a Constant but does not match. 224 /// \returns None if \p V is not a Constant. 225 static Optional<bool> 226 constantMatches(Value *V, unsigned GVN, 227 DenseMap<unsigned, Constant *> &GVNToConstant) { 228 // See if we have a constants 229 Constant *CST = dyn_cast<Constant>(V); 230 if (!CST) 231 return None; 232 233 // Holds a mapping from a global value number to a Constant. 234 DenseMap<unsigned, Constant *>::iterator GVNToConstantIt; 235 bool Inserted; 236 237 238 // If we have a constant, try to make a new entry in the GVNToConstant. 239 std::tie(GVNToConstantIt, Inserted) = 240 GVNToConstant.insert(std::make_pair(GVN, CST)); 241 // If it was found and is not equal, it is not the same. We do not 242 // handle this case yet, and exit early. 243 if (Inserted || (GVNToConstantIt->second == CST)) 244 return true; 245 246 return false; 247 } 248 249 InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) { 250 InstructionCost Benefit = 0; 251 252 // Estimate the benefit of outlining a specific sections of the program. We 253 // delegate mostly this task to the TargetTransformInfo so that if the target 254 // has specific changes, we can have a more accurate estimate. 255 256 // However, getInstructionCost delegates the code size calculation for 257 // arithmetic instructions to getArithmeticInstrCost in 258 // include/Analysis/TargetTransformImpl.h, where it always estimates that the 259 // code size for a division and remainder instruction to be equal to 4, and 260 // everything else to 1. This is not an accurate representation of the 261 // division instruction for targets that have a native division instruction. 262 // To be overly conservative, we only add 1 to the number of instructions for 263 // each division instruction. 264 for (Instruction &I : *StartBB) { 265 switch (I.getOpcode()) { 266 case Instruction::FDiv: 267 case Instruction::FRem: 268 case Instruction::SDiv: 269 case Instruction::SRem: 270 case Instruction::UDiv: 271 case Instruction::URem: 272 Benefit += 1; 273 break; 274 default: 275 Benefit += TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize); 276 break; 277 } 278 } 279 280 return Benefit; 281 } 282 283 /// Find whether \p Region matches the global value numbering to Constant 284 /// mapping found so far. 285 /// 286 /// \param Region - The OutlinableRegion we are checking for constants 287 /// \param GVNToConstant - The mapping of global value number to Constants. 288 /// \param NotSame - The set of global value numbers that do not have the same 289 /// constant in each region. 290 /// \returns true if all Constants are the same in every use of a Constant in \p 291 /// Region and false if not 292 static bool 293 collectRegionsConstants(OutlinableRegion &Region, 294 DenseMap<unsigned, Constant *> &GVNToConstant, 295 DenseSet<unsigned> &NotSame) { 296 bool ConstantsTheSame = true; 297 298 IRSimilarityCandidate &C = *Region.Candidate; 299 for (IRInstructionData &ID : C) { 300 301 // Iterate over the operands in an instruction. If the global value number, 302 // assigned by the IRSimilarityCandidate, has been seen before, we check if 303 // the the number has been found to be not the same value in each instance. 304 for (Value *V : ID.OperVals) { 305 Optional<unsigned> GVNOpt = C.getGVN(V); 306 assert(GVNOpt.hasValue() && "Expected a GVN for operand?"); 307 unsigned GVN = GVNOpt.getValue(); 308 309 // Check if this global value has been found to not be the same already. 310 if (NotSame.contains(GVN)) { 311 if (isa<Constant>(V)) 312 ConstantsTheSame = false; 313 continue; 314 } 315 316 // If it has been the same so far, we check the value for if the 317 // associated Constant value match the previous instances of the same 318 // global value number. If the global value does not map to a Constant, 319 // it is considered to not be the same value. 320 Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant); 321 if (ConstantMatches.hasValue()) { 322 if (ConstantMatches.getValue()) 323 continue; 324 else 325 ConstantsTheSame = false; 326 } 327 328 // While this value is a register, it might not have been previously, 329 // make sure we don't already have a constant mapped to this global value 330 // number. 331 if (GVNToConstant.find(GVN) != GVNToConstant.end()) 332 ConstantsTheSame = false; 333 334 NotSame.insert(GVN); 335 } 336 } 337 338 return ConstantsTheSame; 339 } 340 341 void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) { 342 DenseMap<unsigned, Constant *> GVNToConstant; 343 344 for (OutlinableRegion *Region : Regions) 345 collectRegionsConstants(*Region, GVNToConstant, NotSame); 346 } 347 348 void OutlinableGroup::collectGVNStoreSets(Module &M) { 349 for (OutlinableRegion *OS : Regions) 350 OutputGVNCombinations.insert(OS->GVNStores); 351 352 // We are adding an extracted argument to decide between which output path 353 // to use in the basic block. It is used in a switch statement and only 354 // needs to be an integer. 355 if (OutputGVNCombinations.size() > 1) 356 ArgumentTypes.push_back(Type::getInt32Ty(M.getContext())); 357 } 358 359 /// Get the subprogram if it exists for one of the outlined regions. 360 /// 361 /// \param [in] Group - The set of regions to find a subprogram for. 362 /// \returns the subprogram if it exists, or nullptr. 363 static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) { 364 for (OutlinableRegion *OS : Group.Regions) 365 if (Function *F = OS->Call->getFunction()) 366 if (DISubprogram *SP = F->getSubprogram()) 367 return SP; 368 369 return nullptr; 370 } 371 372 Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group, 373 unsigned FunctionNameSuffix) { 374 assert(!Group.OutlinedFunction && "Function is already defined!"); 375 376 Group.OutlinedFunctionType = FunctionType::get( 377 Type::getVoidTy(M.getContext()), Group.ArgumentTypes, false); 378 379 // These functions will only be called from within the same module, so 380 // we can set an internal linkage. 381 Group.OutlinedFunction = Function::Create( 382 Group.OutlinedFunctionType, GlobalValue::InternalLinkage, 383 "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M); 384 385 // Transfer the swifterr attribute to the correct function parameter. 386 if (Group.SwiftErrorArgument.hasValue()) 387 Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(), 388 Attribute::SwiftError); 389 390 Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize); 391 Group.OutlinedFunction->addFnAttr(Attribute::MinSize); 392 393 // If there's a DISubprogram associated with this outlined function, then 394 // emit debug info for the outlined function. 395 if (DISubprogram *SP = getSubprogramOrNull(Group)) { 396 Function *F = Group.OutlinedFunction; 397 // We have a DISubprogram. Get its DICompileUnit. 398 DICompileUnit *CU = SP->getUnit(); 399 DIBuilder DB(M, true, CU); 400 DIFile *Unit = SP->getFile(); 401 Mangler Mg; 402 // Get the mangled name of the function for the linkage name. 403 std::string Dummy; 404 llvm::raw_string_ostream MangledNameStream(Dummy); 405 Mg.getNameWithPrefix(MangledNameStream, F, false); 406 407 DISubprogram *OutlinedSP = DB.createFunction( 408 Unit /* Context */, F->getName(), MangledNameStream.str(), 409 Unit /* File */, 410 0 /* Line 0 is reserved for compiler-generated code. */, 411 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */ 412 0, /* Line 0 is reserved for compiler-generated code. */ 413 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 414 /* Outlined code is optimized code by definition. */ 415 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); 416 417 // Don't add any new variables to the subprogram. 418 DB.finalizeSubprogram(OutlinedSP); 419 420 // Attach subprogram to the function. 421 F->setSubprogram(OutlinedSP); 422 // We're done with the DIBuilder. 423 DB.finalize(); 424 } 425 426 return Group.OutlinedFunction; 427 } 428 429 /// Move each BasicBlock in \p Old to \p New. 430 /// 431 /// \param [in] Old - The function to move the basic blocks from. 432 /// \param [in] New - The function to move the basic blocks to. 433 /// \returns the first return block for the function in New. 434 static BasicBlock *moveFunctionData(Function &Old, Function &New) { 435 Function::iterator CurrBB, NextBB, FinalBB; 436 BasicBlock *NewEnd = nullptr; 437 for (CurrBB = Old.begin(), FinalBB = Old.end(); CurrBB != FinalBB; 438 CurrBB = NextBB) { 439 NextBB = std::next(CurrBB); 440 CurrBB->removeFromParent(); 441 CurrBB->insertInto(&New); 442 Instruction *I = CurrBB->getTerminator(); 443 if (isa<ReturnInst>(I)) 444 NewEnd = &(*CurrBB); 445 446 std::vector<Instruction *> DebugInsts; 447 448 for (Instruction &Val : *CurrBB) { 449 // We must handle the scoping of called functions differently than 450 // other outlined instructions. 451 if (!isa<CallInst>(&Val)) { 452 // Remove the debug information for outlined functions. 453 Val.setDebugLoc(DebugLoc()); 454 continue; 455 } 456 457 // From this point we are only handling call instructions. 458 CallInst *CI = cast<CallInst>(&Val); 459 460 // We add any debug statements here, to be removed after. Since the 461 // instructions originate from many different locations in the program, 462 // it will cause incorrect reporting from a debugger if we keep the 463 // same debug instructions. 464 if (isa<DbgInfoIntrinsic>(CI)) { 465 DebugInsts.push_back(&Val); 466 continue; 467 } 468 469 // Edit the scope of called functions inside of outlined functions. 470 if (DISubprogram *SP = New.getSubprogram()) { 471 DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP); 472 Val.setDebugLoc(DI); 473 } 474 } 475 476 for (Instruction *I : DebugInsts) 477 I->eraseFromParent(); 478 } 479 480 assert(NewEnd && "No return instruction for new function?"); 481 return NewEnd; 482 } 483 484 /// Find the the constants that will need to be lifted into arguments 485 /// as they are not the same in each instance of the region. 486 /// 487 /// \param [in] C - The IRSimilarityCandidate containing the region we are 488 /// analyzing. 489 /// \param [in] NotSame - The set of global value numbers that do not have a 490 /// single Constant across all OutlinableRegions similar to \p C. 491 /// \param [out] Inputs - The list containing the global value numbers of the 492 /// arguments needed for the region of code. 493 static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame, 494 std::vector<unsigned> &Inputs) { 495 DenseSet<unsigned> Seen; 496 // Iterate over the instructions, and find what constants will need to be 497 // extracted into arguments. 498 for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end(); 499 IDIt != EndIDIt; IDIt++) { 500 for (Value *V : (*IDIt).OperVals) { 501 // Since these are stored before any outlining, they will be in the 502 // global value numbering. 503 unsigned GVN = C.getGVN(V).getValue(); 504 if (isa<Constant>(V)) 505 if (NotSame.contains(GVN) && !Seen.contains(GVN)) { 506 Inputs.push_back(GVN); 507 Seen.insert(GVN); 508 } 509 } 510 } 511 } 512 513 /// Find the GVN for the inputs that have been found by the CodeExtractor. 514 /// 515 /// \param [in] C - The IRSimilarityCandidate containing the region we are 516 /// analyzing. 517 /// \param [in] CurrentInputs - The set of inputs found by the 518 /// CodeExtractor. 519 /// \param [in] OutputMappings - The mapping of values that have been replaced 520 /// by a new output value. 521 /// \param [out] EndInputNumbers - The global value numbers for the extracted 522 /// arguments. 523 static void mapInputsToGVNs(IRSimilarityCandidate &C, 524 SetVector<Value *> &CurrentInputs, 525 const DenseMap<Value *, Value *> &OutputMappings, 526 std::vector<unsigned> &EndInputNumbers) { 527 // Get the Global Value Number for each input. We check if the Value has been 528 // replaced by a different value at output, and use the original value before 529 // replacement. 530 for (Value *Input : CurrentInputs) { 531 assert(Input && "Have a nullptr as an input"); 532 if (OutputMappings.find(Input) != OutputMappings.end()) 533 Input = OutputMappings.find(Input)->second; 534 assert(C.getGVN(Input).hasValue() && 535 "Could not find a numbering for the given input"); 536 EndInputNumbers.push_back(C.getGVN(Input).getValue()); 537 } 538 } 539 540 /// Find the original value for the \p ArgInput values if any one of them was 541 /// replaced during a previous extraction. 542 /// 543 /// \param [in] ArgInputs - The inputs to be extracted by the code extractor. 544 /// \param [in] OutputMappings - The mapping of values that have been replaced 545 /// by a new output value. 546 /// \param [out] RemappedArgInputs - The remapped values according to 547 /// \p OutputMappings that will be extracted. 548 static void 549 remapExtractedInputs(const ArrayRef<Value *> ArgInputs, 550 const DenseMap<Value *, Value *> &OutputMappings, 551 SetVector<Value *> &RemappedArgInputs) { 552 // Get the global value number for each input that will be extracted as an 553 // argument by the code extractor, remapping if needed for reloaded values. 554 for (Value *Input : ArgInputs) { 555 if (OutputMappings.find(Input) != OutputMappings.end()) 556 Input = OutputMappings.find(Input)->second; 557 RemappedArgInputs.insert(Input); 558 } 559 } 560 561 /// Find the input GVNs and the output values for a region of Instructions. 562 /// Using the code extractor, we collect the inputs to the extracted function. 563 /// 564 /// The \p Region can be identified as needing to be ignored in this function. 565 /// It should be checked whether it should be ignored after a call to this 566 /// function. 567 /// 568 /// \param [in,out] Region - The region of code to be analyzed. 569 /// \param [out] InputGVNs - The global value numbers for the extracted 570 /// arguments. 571 /// \param [in] NotSame - The global value numbers in the region that do not 572 /// have the same constant value in the regions structurally similar to 573 /// \p Region. 574 /// \param [in] OutputMappings - The mapping of values that have been replaced 575 /// by a new output value after extraction. 576 /// \param [out] ArgInputs - The values of the inputs to the extracted function. 577 /// \param [out] Outputs - The set of values extracted by the CodeExtractor 578 /// as outputs. 579 static void getCodeExtractorArguments( 580 OutlinableRegion &Region, std::vector<unsigned> &InputGVNs, 581 DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings, 582 SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) { 583 IRSimilarityCandidate &C = *Region.Candidate; 584 585 // OverallInputs are the inputs to the region found by the CodeExtractor, 586 // SinkCands and HoistCands are used by the CodeExtractor to find sunken 587 // allocas of values whose lifetimes are contained completely within the 588 // outlined region. PremappedInputs are the arguments found by the 589 // CodeExtractor, removing conditions such as sunken allocas, but that 590 // may need to be remapped due to the extracted output values replacing 591 // the original values. We use DummyOutputs for this first run of finding 592 // inputs and outputs since the outputs could change during findAllocas, 593 // the correct set of extracted outputs will be in the final Outputs ValueSet. 594 SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands, 595 DummyOutputs; 596 597 // Use the code extractor to get the inputs and outputs, without sunken 598 // allocas or removing llvm.assumes. 599 CodeExtractor *CE = Region.CE; 600 CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands); 601 assert(Region.StartBB && "Region must have a start BasicBlock!"); 602 Function *OrigF = Region.StartBB->getParent(); 603 CodeExtractorAnalysisCache CEAC(*OrigF); 604 BasicBlock *Dummy = nullptr; 605 606 // The region may be ineligible due to VarArgs in the parent function. In this 607 // case we ignore the region. 608 if (!CE->isEligible()) { 609 Region.IgnoreRegion = true; 610 return; 611 } 612 613 // Find if any values are going to be sunk into the function when extracted 614 CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy); 615 CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands); 616 617 // TODO: Support regions with sunken allocas: values whose lifetimes are 618 // contained completely within the outlined region. These are not guaranteed 619 // to be the same in every region, so we must elevate them all to arguments 620 // when they appear. If these values are not equal, it means there is some 621 // Input in OverallInputs that was removed for ArgInputs. 622 if (OverallInputs.size() != PremappedInputs.size()) { 623 Region.IgnoreRegion = true; 624 return; 625 } 626 627 findConstants(C, NotSame, InputGVNs); 628 629 mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs); 630 631 remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings, 632 ArgInputs); 633 634 // Sort the GVNs, since we now have constants included in the \ref InputGVNs 635 // we need to make sure they are in a deterministic order. 636 stable_sort(InputGVNs); 637 } 638 639 /// Look over the inputs and map each input argument to an argument in the 640 /// overall function for the OutlinableRegions. This creates a way to replace 641 /// the arguments of the extracted function with the arguments of the new 642 /// overall function. 643 /// 644 /// \param [in,out] Region - The region of code to be analyzed. 645 /// \param [in] InputGVNs - The global value numbering of the input values 646 /// collected. 647 /// \param [in] ArgInputs - The values of the arguments to the extracted 648 /// function. 649 static void 650 findExtractedInputToOverallInputMapping(OutlinableRegion &Region, 651 std::vector<unsigned> &InputGVNs, 652 SetVector<Value *> &ArgInputs) { 653 654 IRSimilarityCandidate &C = *Region.Candidate; 655 OutlinableGroup &Group = *Region.Parent; 656 657 // This counts the argument number in the overall function. 658 unsigned TypeIndex = 0; 659 660 // This counts the argument number in the extracted function. 661 unsigned OriginalIndex = 0; 662 663 // Find the mapping of the extracted arguments to the arguments for the 664 // overall function. Since there may be extra arguments in the overall 665 // function to account for the extracted constants, we have two different 666 // counters as we find extracted arguments, and as we come across overall 667 // arguments. 668 for (unsigned InputVal : InputGVNs) { 669 Optional<Value *> InputOpt = C.fromGVN(InputVal); 670 assert(InputOpt.hasValue() && "Global value number not found?"); 671 Value *Input = InputOpt.getValue(); 672 673 if (!Group.InputTypesSet) { 674 Group.ArgumentTypes.push_back(Input->getType()); 675 // If the input value has a swifterr attribute, make sure to mark the 676 // argument in the overall function. 677 if (Input->isSwiftError()) { 678 assert( 679 !Group.SwiftErrorArgument.hasValue() && 680 "Argument already marked with swifterr for this OutlinableGroup!"); 681 Group.SwiftErrorArgument = TypeIndex; 682 } 683 } 684 685 // Check if we have a constant. If we do add it to the overall argument 686 // number to Constant map for the region, and continue to the next input. 687 if (Constant *CST = dyn_cast<Constant>(Input)) { 688 Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST)); 689 TypeIndex++; 690 continue; 691 } 692 693 // It is not a constant, we create the mapping from extracted argument list 694 // to the overall argument list. 695 assert(ArgInputs.count(Input) && "Input cannot be found!"); 696 697 Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex)); 698 Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex)); 699 OriginalIndex++; 700 TypeIndex++; 701 } 702 703 // If the function type definitions for the OutlinableGroup holding the region 704 // have not been set, set the length of the inputs here. We should have the 705 // same inputs for all of the different regions contained in the 706 // OutlinableGroup since they are all structurally similar to one another. 707 if (!Group.InputTypesSet) { 708 Group.NumAggregateInputs = TypeIndex; 709 Group.InputTypesSet = true; 710 } 711 712 Region.NumExtractedInputs = OriginalIndex; 713 } 714 715 /// Create a mapping of the output arguments for the \p Region to the output 716 /// arguments of the overall outlined function. 717 /// 718 /// \param [in,out] Region - The region of code to be analyzed. 719 /// \param [in] Outputs - The values found by the code extractor. 720 static void 721 findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region, 722 ArrayRef<Value *> Outputs) { 723 OutlinableGroup &Group = *Region.Parent; 724 IRSimilarityCandidate &C = *Region.Candidate; 725 726 // This counts the argument number in the extracted function. 727 unsigned OriginalIndex = Region.NumExtractedInputs; 728 729 // This counts the argument number in the overall function. 730 unsigned TypeIndex = Group.NumAggregateInputs; 731 bool TypeFound; 732 DenseSet<unsigned> AggArgsUsed; 733 734 // Iterate over the output types and identify if there is an aggregate pointer 735 // type whose base type matches the current output type. If there is, we mark 736 // that we will use this output register for this value. If not we add another 737 // type to the overall argument type list. We also store the GVNs used for 738 // stores to identify which values will need to be moved into an special 739 // block that holds the stores to the output registers. 740 for (Value *Output : Outputs) { 741 TypeFound = false; 742 // We can do this since it is a result value, and will have a number 743 // that is necessarily the same. BUT if in the future, the instructions 744 // do not have to be in same order, but are functionally the same, we will 745 // have to use a different scheme, as one-to-one correspondence is not 746 // guaranteed. 747 unsigned GlobalValue = C.getGVN(Output).getValue(); 748 unsigned ArgumentSize = Group.ArgumentTypes.size(); 749 750 for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) { 751 if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType())) 752 continue; 753 754 if (AggArgsUsed.contains(Jdx)) 755 continue; 756 757 TypeFound = true; 758 AggArgsUsed.insert(Jdx); 759 Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx)); 760 Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex)); 761 Region.GVNStores.push_back(GlobalValue); 762 break; 763 } 764 765 // We were unable to find an unused type in the output type set that matches 766 // the output, so we add a pointer type to the argument types of the overall 767 // function to handle this output and create a mapping to it. 768 if (!TypeFound) { 769 Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType())); 770 AggArgsUsed.insert(Group.ArgumentTypes.size() - 1); 771 Region.ExtractedArgToAgg.insert( 772 std::make_pair(OriginalIndex, Group.ArgumentTypes.size() - 1)); 773 Region.AggArgToExtracted.insert( 774 std::make_pair(Group.ArgumentTypes.size() - 1, OriginalIndex)); 775 Region.GVNStores.push_back(GlobalValue); 776 } 777 778 stable_sort(Region.GVNStores); 779 OriginalIndex++; 780 TypeIndex++; 781 } 782 } 783 784 void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region, 785 DenseSet<unsigned> &NotSame) { 786 std::vector<unsigned> Inputs; 787 SetVector<Value *> ArgInputs, Outputs; 788 789 getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs, 790 Outputs); 791 792 if (Region.IgnoreRegion) 793 return; 794 795 // Map the inputs found by the CodeExtractor to the arguments found for 796 // the overall function. 797 findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs); 798 799 // Map the outputs found by the CodeExtractor to the arguments found for 800 // the overall function. 801 findExtractedOutputToOverallOutputMapping(Region, Outputs.getArrayRef()); 802 } 803 804 /// Replace the extracted function in the Region with a call to the overall 805 /// function constructed from the deduplicated similar regions, replacing and 806 /// remapping the values passed to the extracted function as arguments to the 807 /// new arguments of the overall function. 808 /// 809 /// \param [in] M - The module to outline from. 810 /// \param [in] Region - The regions of extracted code to be replaced with a new 811 /// function. 812 /// \returns a call instruction with the replaced function. 813 CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) { 814 std::vector<Value *> NewCallArgs; 815 DenseMap<unsigned, unsigned>::iterator ArgPair; 816 817 OutlinableGroup &Group = *Region.Parent; 818 CallInst *Call = Region.Call; 819 assert(Call && "Call to replace is nullptr?"); 820 Function *AggFunc = Group.OutlinedFunction; 821 assert(AggFunc && "Function to replace with is nullptr?"); 822 823 // If the arguments are the same size, there are not values that need to be 824 // made argument, or different output registers to handle. We can simply 825 // replace the called function in this case. 826 if (AggFunc->arg_size() == Call->arg_size()) { 827 LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 828 << *AggFunc << " with same number of arguments\n"); 829 Call->setCalledFunction(AggFunc); 830 return Call; 831 } 832 833 // We have a different number of arguments than the new function, so 834 // we need to use our previously mappings off extracted argument to overall 835 // function argument, and constants to overall function argument to create the 836 // new argument list. 837 for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) { 838 839 if (AggArgIdx == AggFunc->arg_size() - 1 && 840 Group.OutputGVNCombinations.size() > 1) { 841 // If we are on the last argument, and we need to differentiate between 842 // output blocks, add an integer to the argument list to determine 843 // what block to take 844 LLVM_DEBUG(dbgs() << "Set switch block argument to " 845 << Region.OutputBlockNum << "\n"); 846 NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()), 847 Region.OutputBlockNum)); 848 continue; 849 } 850 851 ArgPair = Region.AggArgToExtracted.find(AggArgIdx); 852 if (ArgPair != Region.AggArgToExtracted.end()) { 853 Value *ArgumentValue = Call->getArgOperand(ArgPair->second); 854 // If we found the mapping from the extracted function to the overall 855 // function, we simply add it to the argument list. We use the same 856 // value, it just needs to honor the new order of arguments. 857 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 858 << *ArgumentValue << "\n"); 859 NewCallArgs.push_back(ArgumentValue); 860 continue; 861 } 862 863 // If it is a constant, we simply add it to the argument list as a value. 864 if (Region.AggArgToConstant.find(AggArgIdx) != 865 Region.AggArgToConstant.end()) { 866 Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second; 867 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 868 << *CST << "\n"); 869 NewCallArgs.push_back(CST); 870 continue; 871 } 872 873 // Add a nullptr value if the argument is not found in the extracted 874 // function. If we cannot find a value, it means it is not in use 875 // for the region, so we should not pass anything to it. 876 LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n"); 877 NewCallArgs.push_back(ConstantPointerNull::get( 878 static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType()))); 879 } 880 881 LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 882 << *AggFunc << " with new set of arguments\n"); 883 // Create the new call instruction and erase the old one. 884 Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "", 885 Call); 886 887 // It is possible that the call to the outlined function is either the first 888 // instruction is in the new block, the last instruction, or both. If either 889 // of these is the case, we need to make sure that we replace the instruction 890 // in the IRInstructionData struct with the new call. 891 CallInst *OldCall = Region.Call; 892 if (Region.NewFront->Inst == OldCall) 893 Region.NewFront->Inst = Call; 894 if (Region.NewBack->Inst == OldCall) 895 Region.NewBack->Inst = Call; 896 897 // Transfer any debug information. 898 Call->setDebugLoc(Region.Call->getDebugLoc()); 899 900 // Remove the old instruction. 901 OldCall->eraseFromParent(); 902 Region.Call = Call; 903 904 // Make sure that the argument in the new function has the SwiftError 905 // argument. 906 if (Group.SwiftErrorArgument.hasValue()) 907 Call->addParamAttr(Group.SwiftErrorArgument.getValue(), 908 Attribute::SwiftError); 909 910 return Call; 911 } 912 913 // Within an extracted function, replace the argument uses of the extracted 914 // region with the arguments of the function for an OutlinableGroup. 915 // 916 /// \param [in] Region - The region of extracted code to be changed. 917 /// \param [in,out] OutputBB - The BasicBlock for the output stores for this 918 /// region. 919 static void replaceArgumentUses(OutlinableRegion &Region, 920 BasicBlock *OutputBB) { 921 OutlinableGroup &Group = *Region.Parent; 922 assert(Region.ExtractedFunction && "Region has no extracted function?"); 923 924 for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size(); 925 ArgIdx++) { 926 assert(Region.ExtractedArgToAgg.find(ArgIdx) != 927 Region.ExtractedArgToAgg.end() && 928 "No mapping from extracted to outlined?"); 929 unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second; 930 Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx); 931 Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx); 932 // The argument is an input, so we can simply replace it with the overall 933 // argument value 934 if (ArgIdx < Region.NumExtractedInputs) { 935 LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function " 936 << *Region.ExtractedFunction << " with " << *AggArg 937 << " in function " << *Group.OutlinedFunction << "\n"); 938 Arg->replaceAllUsesWith(AggArg); 939 continue; 940 } 941 942 // If we are replacing an output, we place the store value in its own 943 // block inside the overall function before replacing the use of the output 944 // in the function. 945 assert(Arg->hasOneUse() && "Output argument can only have one use"); 946 User *InstAsUser = Arg->user_back(); 947 assert(InstAsUser && "User is nullptr!"); 948 949 Instruction *I = cast<Instruction>(InstAsUser); 950 I->setDebugLoc(DebugLoc()); 951 LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to " 952 << *OutputBB << "\n"); 953 954 I->moveBefore(*OutputBB, OutputBB->end()); 955 956 LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function " 957 << *Region.ExtractedFunction << " with " << *AggArg 958 << " in function " << *Group.OutlinedFunction << "\n"); 959 Arg->replaceAllUsesWith(AggArg); 960 } 961 } 962 963 /// Within an extracted function, replace the constants that need to be lifted 964 /// into arguments with the actual argument. 965 /// 966 /// \param Region [in] - The region of extracted code to be changed. 967 void replaceConstants(OutlinableRegion &Region) { 968 OutlinableGroup &Group = *Region.Parent; 969 // Iterate over the constants that need to be elevated into arguments 970 for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) { 971 unsigned AggArgIdx = Const.first; 972 Function *OutlinedFunction = Group.OutlinedFunction; 973 assert(OutlinedFunction && "Overall Function is not defined?"); 974 Constant *CST = Const.second; 975 Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx); 976 // Identify the argument it will be elevated to, and replace instances of 977 // that constant in the function. 978 979 // TODO: If in the future constants do not have one global value number, 980 // i.e. a constant 1 could be mapped to several values, this check will 981 // have to be more strict. It cannot be using only replaceUsesWithIf. 982 983 LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST 984 << " in function " << *OutlinedFunction << " with " 985 << *Arg << "\n"); 986 CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) { 987 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) 988 return I->getFunction() == OutlinedFunction; 989 return false; 990 }); 991 } 992 } 993 994 /// For the given function, find all the nondebug or lifetime instructions, 995 /// and return them as a vector. Exclude any blocks in \p ExludeBlocks. 996 /// 997 /// \param [in] F - The function we collect the instructions from. 998 /// \param [in] ExcludeBlocks - BasicBlocks to ignore. 999 /// \returns the list of instructions extracted. 1000 static std::vector<Instruction *> 1001 collectRelevantInstructions(Function &F, 1002 DenseSet<BasicBlock *> &ExcludeBlocks) { 1003 std::vector<Instruction *> RelevantInstructions; 1004 1005 for (BasicBlock &BB : F) { 1006 if (ExcludeBlocks.contains(&BB)) 1007 continue; 1008 1009 for (Instruction &Inst : BB) { 1010 if (Inst.isLifetimeStartOrEnd()) 1011 continue; 1012 if (isa<DbgInfoIntrinsic>(Inst)) 1013 continue; 1014 1015 RelevantInstructions.push_back(&Inst); 1016 } 1017 } 1018 1019 return RelevantInstructions; 1020 } 1021 1022 /// It is possible that there is a basic block that already performs the same 1023 /// stores. This returns a duplicate block, if it exists 1024 /// 1025 /// \param OutputBB [in] the block we are looking for a duplicate of. 1026 /// \param OutputStoreBBs [in] The existing output blocks. 1027 /// \returns an optional value with the number output block if there is a match. 1028 Optional<unsigned> 1029 findDuplicateOutputBlock(BasicBlock *OutputBB, 1030 ArrayRef<BasicBlock *> OutputStoreBBs) { 1031 1032 bool WrongInst = false; 1033 bool WrongSize = false; 1034 unsigned MatchingNum = 0; 1035 for (BasicBlock *CompBB : OutputStoreBBs) { 1036 WrongInst = false; 1037 if (CompBB->size() - 1 != OutputBB->size()) { 1038 WrongSize = true; 1039 MatchingNum++; 1040 continue; 1041 } 1042 1043 WrongSize = false; 1044 BasicBlock::iterator NIt = OutputBB->begin(); 1045 for (Instruction &I : *CompBB) { 1046 if (isa<BranchInst>(&I)) 1047 continue; 1048 1049 if (!I.isIdenticalTo(&(*NIt))) { 1050 WrongInst = true; 1051 break; 1052 } 1053 1054 NIt++; 1055 } 1056 if (!WrongInst && !WrongSize) 1057 return MatchingNum; 1058 1059 MatchingNum++; 1060 } 1061 1062 return None; 1063 } 1064 1065 /// For the outlined section, move needed the StoreInsts for the output 1066 /// registers into their own block. Then, determine if there is a duplicate 1067 /// output block already created. 1068 /// 1069 /// \param [in] OG - The OutlinableGroup of regions to be outlined. 1070 /// \param [in] Region - The OutlinableRegion that is being analyzed. 1071 /// \param [in,out] OutputBB - the block that stores for this region will be 1072 /// placed in. 1073 /// \param [in] EndBB - the final block of the extracted function. 1074 /// \param [in] OutputMappings - OutputMappings the mapping of values that have 1075 /// been replaced by a new output value. 1076 /// \param [in,out] OutputStoreBBs - The existing output blocks. 1077 static void 1078 alignOutputBlockWithAggFunc(OutlinableGroup &OG, OutlinableRegion &Region, 1079 BasicBlock *OutputBB, BasicBlock *EndBB, 1080 const DenseMap<Value *, Value *> &OutputMappings, 1081 std::vector<BasicBlock *> &OutputStoreBBs) { 1082 DenseSet<unsigned> ValuesToFind(Region.GVNStores.begin(), 1083 Region.GVNStores.end()); 1084 1085 // We iterate over the instructions in the extracted function, and find the 1086 // global value number of the instructions. If we find a value that should 1087 // be contained in a store, we replace the uses of the value with the value 1088 // from the overall function, so that the store is storing the correct 1089 // value from the overall function. 1090 DenseSet<BasicBlock *> ExcludeBBs(OutputStoreBBs.begin(), 1091 OutputStoreBBs.end()); 1092 ExcludeBBs.insert(OutputBB); 1093 std::vector<Instruction *> ExtractedFunctionInsts = 1094 collectRelevantInstructions(*(Region.ExtractedFunction), ExcludeBBs); 1095 std::vector<Instruction *> OverallFunctionInsts = 1096 collectRelevantInstructions(*OG.OutlinedFunction, ExcludeBBs); 1097 1098 assert(ExtractedFunctionInsts.size() == OverallFunctionInsts.size() && 1099 "Number of relevant instructions not equal!"); 1100 1101 unsigned NumInstructions = ExtractedFunctionInsts.size(); 1102 for (unsigned Idx = 0; Idx < NumInstructions; Idx++) { 1103 Value *V = ExtractedFunctionInsts[Idx]; 1104 1105 if (OutputMappings.find(V) != OutputMappings.end()) 1106 V = OutputMappings.find(V)->second; 1107 Optional<unsigned> GVN = Region.Candidate->getGVN(V); 1108 1109 // If we have found one of the stored values for output, replace the value 1110 // with the corresponding one from the overall function. 1111 if (GVN.hasValue() && ValuesToFind.erase(GVN.getValue())) { 1112 V->replaceAllUsesWith(OverallFunctionInsts[Idx]); 1113 if (ValuesToFind.size() == 0) 1114 break; 1115 } 1116 1117 if (ValuesToFind.size() == 0) 1118 break; 1119 } 1120 1121 assert(ValuesToFind.size() == 0 && "Not all store values were handled!"); 1122 1123 // If the size of the block is 0, then there are no stores, and we do not 1124 // need to save this block. 1125 if (OutputBB->size() == 0) { 1126 Region.OutputBlockNum = -1; 1127 OutputBB->eraseFromParent(); 1128 return; 1129 } 1130 1131 // Determine is there is a duplicate block. 1132 Optional<unsigned> MatchingBB = 1133 findDuplicateOutputBlock(OutputBB, OutputStoreBBs); 1134 1135 // If there is, we remove the new output block. If it does not, 1136 // we add it to our list of output blocks. 1137 if (MatchingBB.hasValue()) { 1138 LLVM_DEBUG(dbgs() << "Set output block for region in function" 1139 << Region.ExtractedFunction << " to " 1140 << MatchingBB.getValue()); 1141 1142 Region.OutputBlockNum = MatchingBB.getValue(); 1143 OutputBB->eraseFromParent(); 1144 return; 1145 } 1146 1147 Region.OutputBlockNum = OutputStoreBBs.size(); 1148 1149 LLVM_DEBUG(dbgs() << "Create output block for region in" 1150 << Region.ExtractedFunction << " to " 1151 << *OutputBB); 1152 OutputStoreBBs.push_back(OutputBB); 1153 BranchInst::Create(EndBB, OutputBB); 1154 } 1155 1156 /// Create the switch statement for outlined function to differentiate between 1157 /// all the output blocks. 1158 /// 1159 /// For the outlined section, determine if an outlined block already exists that 1160 /// matches the needed stores for the extracted section. 1161 /// \param [in] M - The module we are outlining from. 1162 /// \param [in] OG - The group of regions to be outlined. 1163 /// \param [in] EndBB - The final block of the extracted function. 1164 /// \param [in,out] OutputStoreBBs - The existing output blocks. 1165 void createSwitchStatement(Module &M, OutlinableGroup &OG, BasicBlock *EndBB, 1166 ArrayRef<BasicBlock *> OutputStoreBBs) { 1167 // We only need the switch statement if there is more than one store 1168 // combination. 1169 if (OG.OutputGVNCombinations.size() > 1) { 1170 Function *AggFunc = OG.OutlinedFunction; 1171 // Create a final block 1172 BasicBlock *ReturnBlock = 1173 BasicBlock::Create(M.getContext(), "final_block", AggFunc); 1174 Instruction *Term = EndBB->getTerminator(); 1175 Term->moveBefore(*ReturnBlock, ReturnBlock->end()); 1176 // Put the switch statement in the old end basic block for the function with 1177 // a fall through to the new return block 1178 LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for " 1179 << OutputStoreBBs.size() << "\n"); 1180 SwitchInst *SwitchI = 1181 SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1), 1182 ReturnBlock, OutputStoreBBs.size(), EndBB); 1183 1184 unsigned Idx = 0; 1185 for (BasicBlock *BB : OutputStoreBBs) { 1186 SwitchI->addCase(ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), 1187 BB); 1188 Term = BB->getTerminator(); 1189 Term->setSuccessor(0, ReturnBlock); 1190 Idx++; 1191 } 1192 return; 1193 } 1194 1195 // If there needs to be stores, move them from the output block to the end 1196 // block to save on branching instructions. 1197 if (OutputStoreBBs.size() == 1) { 1198 LLVM_DEBUG(dbgs() << "Move store instructions to the end block in " 1199 << *OG.OutlinedFunction << "\n"); 1200 BasicBlock *OutputBlock = OutputStoreBBs[0]; 1201 Instruction *Term = OutputBlock->getTerminator(); 1202 Term->eraseFromParent(); 1203 Term = EndBB->getTerminator(); 1204 moveBBContents(*OutputBlock, *EndBB); 1205 Term->moveBefore(*EndBB, EndBB->end()); 1206 OutputBlock->eraseFromParent(); 1207 } 1208 } 1209 1210 /// Fill the new function that will serve as the replacement function for all of 1211 /// the extracted regions of a certain structure from the first region in the 1212 /// list of regions. Replace this first region's extracted function with the 1213 /// new overall function. 1214 /// 1215 /// \param [in] M - The module we are outlining from. 1216 /// \param [in] CurrentGroup - The group of regions to be outlined. 1217 /// \param [in,out] OutputStoreBBs - The output blocks for each different 1218 /// set of stores needed for the different functions. 1219 /// \param [in,out] FuncsToRemove - Extracted functions to erase from module 1220 /// once outlining is complete. 1221 static void fillOverallFunction(Module &M, OutlinableGroup &CurrentGroup, 1222 std::vector<BasicBlock *> &OutputStoreBBs, 1223 std::vector<Function *> &FuncsToRemove) { 1224 OutlinableRegion *CurrentOS = CurrentGroup.Regions[0]; 1225 1226 // Move first extracted function's instructions into new function. 1227 LLVM_DEBUG(dbgs() << "Move instructions from " 1228 << *CurrentOS->ExtractedFunction << " to instruction " 1229 << *CurrentGroup.OutlinedFunction << "\n"); 1230 1231 CurrentGroup.EndBB = moveFunctionData(*CurrentOS->ExtractedFunction, 1232 *CurrentGroup.OutlinedFunction); 1233 1234 // Transfer the attributes from the function to the new function. 1235 for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs()) 1236 CurrentGroup.OutlinedFunction->addFnAttr(A); 1237 1238 // Create an output block for the first extracted function. 1239 BasicBlock *NewBB = BasicBlock::Create( 1240 M.getContext(), Twine("output_block_") + Twine(static_cast<unsigned>(0)), 1241 CurrentGroup.OutlinedFunction); 1242 CurrentOS->OutputBlockNum = 0; 1243 1244 replaceArgumentUses(*CurrentOS, NewBB); 1245 replaceConstants(*CurrentOS); 1246 1247 // If the new basic block has no new stores, we can erase it from the module. 1248 // It it does, we create a branch instruction to the last basic block from the 1249 // new one. 1250 if (NewBB->size() == 0) { 1251 CurrentOS->OutputBlockNum = -1; 1252 NewBB->eraseFromParent(); 1253 } else { 1254 BranchInst::Create(CurrentGroup.EndBB, NewBB); 1255 OutputStoreBBs.push_back(NewBB); 1256 } 1257 1258 // Replace the call to the extracted function with the outlined function. 1259 CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 1260 1261 // We only delete the extracted functions at the end since we may need to 1262 // reference instructions contained in them for mapping purposes. 1263 FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 1264 } 1265 1266 void IROutliner::deduplicateExtractedSections( 1267 Module &M, OutlinableGroup &CurrentGroup, 1268 std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) { 1269 createFunction(M, CurrentGroup, OutlinedFunctionNum); 1270 1271 std::vector<BasicBlock *> OutputStoreBBs; 1272 1273 OutlinableRegion *CurrentOS; 1274 1275 fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove); 1276 1277 for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) { 1278 CurrentOS = CurrentGroup.Regions[Idx]; 1279 AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction, 1280 *CurrentOS->ExtractedFunction); 1281 1282 // Create a new BasicBlock to hold the needed store instructions. 1283 BasicBlock *NewBB = BasicBlock::Create( 1284 M.getContext(), "output_block_" + std::to_string(Idx), 1285 CurrentGroup.OutlinedFunction); 1286 replaceArgumentUses(*CurrentOS, NewBB); 1287 1288 alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBB, 1289 CurrentGroup.EndBB, OutputMappings, 1290 OutputStoreBBs); 1291 1292 CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 1293 FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 1294 } 1295 1296 // Create a switch statement to handle the different output schemes. 1297 createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBB, OutputStoreBBs); 1298 1299 OutlinedFunctionNum++; 1300 } 1301 1302 void IROutliner::pruneIncompatibleRegions( 1303 std::vector<IRSimilarityCandidate> &CandidateVec, 1304 OutlinableGroup &CurrentGroup) { 1305 bool PreviouslyOutlined; 1306 1307 // Sort from beginning to end, so the IRSimilarityCandidates are in order. 1308 stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS, 1309 const IRSimilarityCandidate &RHS) { 1310 return LHS.getStartIdx() < RHS.getStartIdx(); 1311 }); 1312 1313 unsigned CurrentEndIdx = 0; 1314 for (IRSimilarityCandidate &IRSC : CandidateVec) { 1315 PreviouslyOutlined = false; 1316 unsigned StartIdx = IRSC.getStartIdx(); 1317 unsigned EndIdx = IRSC.getEndIdx(); 1318 1319 for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 1320 if (Outlined.contains(Idx)) { 1321 PreviouslyOutlined = true; 1322 break; 1323 } 1324 1325 if (PreviouslyOutlined) 1326 continue; 1327 1328 // TODO: If in the future we can outline across BasicBlocks, we will need to 1329 // check all BasicBlocks contained in the region. 1330 if (IRSC.getStartBB()->hasAddressTaken()) 1331 continue; 1332 1333 if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() && 1334 !OutlineFromLinkODRs) 1335 continue; 1336 1337 // Greedily prune out any regions that will overlap with already chosen 1338 // regions. 1339 if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx) 1340 continue; 1341 1342 bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) { 1343 // We check if there is a discrepancy between the InstructionDataList 1344 // and the actual next instruction in the module. If there is, it means 1345 // that an extra instruction was added, likely by the CodeExtractor. 1346 1347 // Since we do not have any similarity data about this particular 1348 // instruction, we cannot confidently outline it, and must discard this 1349 // candidate. 1350 if (std::next(ID.getIterator())->Inst != 1351 ID.Inst->getNextNonDebugInstruction()) 1352 return true; 1353 return !this->InstructionClassifier.visit(ID.Inst); 1354 }); 1355 1356 if (BadInst) 1357 continue; 1358 1359 OutlinableRegion *OS = new (RegionAllocator.Allocate()) 1360 OutlinableRegion(IRSC, CurrentGroup); 1361 CurrentGroup.Regions.push_back(OS); 1362 1363 CurrentEndIdx = EndIdx; 1364 } 1365 } 1366 1367 InstructionCost 1368 IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) { 1369 InstructionCost RegionBenefit = 0; 1370 for (OutlinableRegion *Region : CurrentGroup.Regions) { 1371 TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 1372 // We add the number of instructions in the region to the benefit as an 1373 // estimate as to how much will be removed. 1374 RegionBenefit += Region->getBenefit(TTI); 1375 LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit 1376 << " saved instructions to overfall benefit.\n"); 1377 } 1378 1379 return RegionBenefit; 1380 } 1381 1382 InstructionCost 1383 IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) { 1384 InstructionCost OverallCost = 0; 1385 for (OutlinableRegion *Region : CurrentGroup.Regions) { 1386 TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 1387 1388 // Each output incurs a load after the call, so we add that to the cost. 1389 for (unsigned OutputGVN : Region->GVNStores) { 1390 Optional<Value *> OV = Region->Candidate->fromGVN(OutputGVN); 1391 assert(OV.hasValue() && "Could not find value for GVN?"); 1392 Value *V = OV.getValue(); 1393 InstructionCost LoadCost = 1394 TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 1395 TargetTransformInfo::TCK_CodeSize); 1396 1397 LLVM_DEBUG(dbgs() << "Adding: " << LoadCost 1398 << " instructions to cost for output of type " 1399 << *V->getType() << "\n"); 1400 OverallCost += LoadCost; 1401 } 1402 } 1403 1404 return OverallCost; 1405 } 1406 1407 /// Find the extra instructions needed to handle any output values for the 1408 /// region. 1409 /// 1410 /// \param [in] M - The Module to outline from. 1411 /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze. 1412 /// \param [in] TTI - The TargetTransformInfo used to collect information for 1413 /// new instruction costs. 1414 /// \returns the additional cost to handle the outputs. 1415 static InstructionCost findCostForOutputBlocks(Module &M, 1416 OutlinableGroup &CurrentGroup, 1417 TargetTransformInfo &TTI) { 1418 InstructionCost OutputCost = 0; 1419 1420 for (const ArrayRef<unsigned> &OutputUse : 1421 CurrentGroup.OutputGVNCombinations) { 1422 IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate; 1423 for (unsigned GVN : OutputUse) { 1424 Optional<Value *> OV = Candidate.fromGVN(GVN); 1425 assert(OV.hasValue() && "Could not find value for GVN?"); 1426 Value *V = OV.getValue(); 1427 InstructionCost StoreCost = 1428 TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 1429 TargetTransformInfo::TCK_CodeSize); 1430 1431 // An instruction cost is added for each store set that needs to occur for 1432 // various output combinations inside the function, plus a branch to 1433 // return to the exit block. 1434 LLVM_DEBUG(dbgs() << "Adding: " << StoreCost 1435 << " instructions to cost for output of type " 1436 << *V->getType() << "\n"); 1437 OutputCost += StoreCost; 1438 } 1439 1440 InstructionCost BranchCost = 1441 TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 1442 LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for" 1443 << " a branch instruction\n"); 1444 OutputCost += BranchCost; 1445 } 1446 1447 // If there is more than one output scheme, we must have a comparison and 1448 // branch for each different item in the switch statement. 1449 if (CurrentGroup.OutputGVNCombinations.size() > 1) { 1450 InstructionCost ComparisonCost = TTI.getCmpSelInstrCost( 1451 Instruction::ICmp, Type::getInt32Ty(M.getContext()), 1452 Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE, 1453 TargetTransformInfo::TCK_CodeSize); 1454 InstructionCost BranchCost = 1455 TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 1456 1457 unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size(); 1458 InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks; 1459 1460 LLVM_DEBUG(dbgs() << "Adding: " << TotalCost 1461 << " instructions for each switch case for each different" 1462 << " output path in a function\n"); 1463 OutputCost += TotalCost; 1464 } 1465 1466 return OutputCost; 1467 } 1468 1469 void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) { 1470 InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup); 1471 CurrentGroup.Benefit += RegionBenefit; 1472 LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n"); 1473 1474 InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup); 1475 CurrentGroup.Cost += OutputReloadCost; 1476 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 1477 1478 InstructionCost AverageRegionBenefit = 1479 RegionBenefit / CurrentGroup.Regions.size(); 1480 unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size(); 1481 unsigned NumRegions = CurrentGroup.Regions.size(); 1482 TargetTransformInfo &TTI = 1483 getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction()); 1484 1485 // We add one region to the cost once, to account for the instructions added 1486 // inside of the newly created function. 1487 LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit 1488 << " instructions to cost for body of new function.\n"); 1489 CurrentGroup.Cost += AverageRegionBenefit; 1490 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 1491 1492 // For each argument, we must add an instruction for loading the argument 1493 // out of the register and into a value inside of the newly outlined function. 1494 LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 1495 << " instructions to cost for each argument in the new" 1496 << " function.\n"); 1497 CurrentGroup.Cost += 1498 OverallArgumentNum * TargetTransformInfo::TCC_Basic; 1499 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 1500 1501 // Each argument needs to either be loaded into a register or onto the stack. 1502 // Some arguments will only be loaded into the stack once the argument 1503 // registers are filled. 1504 LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 1505 << " instructions to cost for each argument in the new" 1506 << " function " << NumRegions << " times for the " 1507 << "needed argument handling at the call site.\n"); 1508 CurrentGroup.Cost += 1509 2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions; 1510 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 1511 1512 CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI); 1513 LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 1514 } 1515 1516 void IROutliner::updateOutputMapping(OutlinableRegion &Region, 1517 ArrayRef<Value *> Outputs, 1518 LoadInst *LI) { 1519 // For and load instructions following the call 1520 Value *Operand = LI->getPointerOperand(); 1521 Optional<unsigned> OutputIdx = None; 1522 // Find if the operand it is an output register. 1523 for (unsigned ArgIdx = Region.NumExtractedInputs; 1524 ArgIdx < Region.Call->arg_size(); ArgIdx++) { 1525 if (Operand == Region.Call->getArgOperand(ArgIdx)) { 1526 OutputIdx = ArgIdx - Region.NumExtractedInputs; 1527 break; 1528 } 1529 } 1530 1531 // If we found an output register, place a mapping of the new value 1532 // to the original in the mapping. 1533 if (!OutputIdx.hasValue()) 1534 return; 1535 1536 if (OutputMappings.find(Outputs[OutputIdx.getValue()]) == 1537 OutputMappings.end()) { 1538 LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to " 1539 << *Outputs[OutputIdx.getValue()] << "\n"); 1540 OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()])); 1541 } else { 1542 Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second; 1543 LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to " 1544 << *Outputs[OutputIdx.getValue()] << "\n"); 1545 OutputMappings.insert(std::make_pair(LI, Orig)); 1546 } 1547 } 1548 1549 bool IROutliner::extractSection(OutlinableRegion &Region) { 1550 SetVector<Value *> ArgInputs, Outputs, SinkCands; 1551 Region.CE->findInputsOutputs(ArgInputs, Outputs, SinkCands); 1552 1553 assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!"); 1554 assert(Region.FollowBB && "FollowBB for the OutlinableRegion is nullptr!"); 1555 Function *OrigF = Region.StartBB->getParent(); 1556 CodeExtractorAnalysisCache CEAC(*OrigF); 1557 Region.ExtractedFunction = Region.CE->extractCodeRegion(CEAC); 1558 1559 // If the extraction was successful, find the BasicBlock, and reassign the 1560 // OutlinableRegion blocks 1561 if (!Region.ExtractedFunction) { 1562 LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB 1563 << "\n"); 1564 Region.reattachCandidate(); 1565 return false; 1566 } 1567 1568 BasicBlock *RewrittenBB = Region.FollowBB->getSinglePredecessor(); 1569 Region.StartBB = RewrittenBB; 1570 Region.EndBB = RewrittenBB; 1571 1572 // The sequences of outlinable regions has now changed. We must fix the 1573 // IRInstructionDataList for consistency. Although they may not be illegal 1574 // instructions, they should not be compared with anything else as they 1575 // should not be outlined in this round. So marking these as illegal is 1576 // allowed. 1577 IRInstructionDataList *IDL = Region.Candidate->front()->IDL; 1578 Instruction *BeginRewritten = &*RewrittenBB->begin(); 1579 Instruction *EndRewritten = &*RewrittenBB->begin(); 1580 Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData( 1581 *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL); 1582 Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData( 1583 *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL); 1584 1585 // Insert the first IRInstructionData of the new region in front of the 1586 // first IRInstructionData of the IRSimilarityCandidate. 1587 IDL->insert(Region.Candidate->begin(), *Region.NewFront); 1588 // Insert the first IRInstructionData of the new region after the 1589 // last IRInstructionData of the IRSimilarityCandidate. 1590 IDL->insert(Region.Candidate->end(), *Region.NewBack); 1591 // Remove the IRInstructionData from the IRSimilarityCandidate. 1592 IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end())); 1593 1594 assert(RewrittenBB != nullptr && 1595 "Could not find a predecessor after extraction!"); 1596 1597 // Iterate over the new set of instructions to find the new call 1598 // instruction. 1599 for (Instruction &I : *RewrittenBB) 1600 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1601 if (Region.ExtractedFunction == CI->getCalledFunction()) 1602 Region.Call = CI; 1603 } else if (LoadInst *LI = dyn_cast<LoadInst>(&I)) 1604 updateOutputMapping(Region, Outputs.getArrayRef(), LI); 1605 Region.reattachCandidate(); 1606 return true; 1607 } 1608 1609 unsigned IROutliner::doOutline(Module &M) { 1610 // Find the possible similarity sections. 1611 IRSimilarityIdentifier &Identifier = getIRSI(M); 1612 SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity(); 1613 1614 // Sort them by size of extracted sections 1615 unsigned OutlinedFunctionNum = 0; 1616 // If we only have one SimilarityGroup in SimilarityCandidates, we do not have 1617 // to sort them by the potential number of instructions to be outlined 1618 if (SimilarityCandidates.size() > 1) 1619 llvm::stable_sort(SimilarityCandidates, 1620 [](const std::vector<IRSimilarityCandidate> &LHS, 1621 const std::vector<IRSimilarityCandidate> &RHS) { 1622 return LHS[0].getLength() * LHS.size() > 1623 RHS[0].getLength() * RHS.size(); 1624 }); 1625 1626 DenseSet<unsigned> NotSame; 1627 std::vector<Function *> FuncsToRemove; 1628 // Iterate over the possible sets of similarity. 1629 for (SimilarityGroup &CandidateVec : SimilarityCandidates) { 1630 OutlinableGroup CurrentGroup; 1631 1632 // Remove entries that were previously outlined 1633 pruneIncompatibleRegions(CandidateVec, CurrentGroup); 1634 1635 // We pruned the number of regions to 0 to 1, meaning that it's not worth 1636 // trying to outlined since there is no compatible similar instance of this 1637 // code. 1638 if (CurrentGroup.Regions.size() < 2) 1639 continue; 1640 1641 // Determine if there are any values that are the same constant throughout 1642 // each section in the set. 1643 NotSame.clear(); 1644 CurrentGroup.findSameConstants(NotSame); 1645 1646 if (CurrentGroup.IgnoreGroup) 1647 continue; 1648 1649 // Create a CodeExtractor for each outlinable region. Identify inputs and 1650 // outputs for each section using the code extractor and create the argument 1651 // types for the Aggregate Outlining Function. 1652 std::vector<OutlinableRegion *> OutlinedRegions; 1653 for (OutlinableRegion *OS : CurrentGroup.Regions) { 1654 // Break the outlinable region out of its parent BasicBlock into its own 1655 // BasicBlocks (see function implementation). 1656 OS->splitCandidate(); 1657 std::vector<BasicBlock *> BE = {OS->StartBB}; 1658 OS->CE = new (ExtractorAllocator.Allocate()) 1659 CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false, 1660 false, "outlined"); 1661 findAddInputsOutputs(M, *OS, NotSame); 1662 if (!OS->IgnoreRegion) 1663 OutlinedRegions.push_back(OS); 1664 else 1665 OS->reattachCandidate(); 1666 } 1667 1668 CurrentGroup.Regions = std::move(OutlinedRegions); 1669 1670 if (CurrentGroup.Regions.empty()) 1671 continue; 1672 1673 CurrentGroup.collectGVNStoreSets(M); 1674 1675 if (CostModel) 1676 findCostBenefit(M, CurrentGroup); 1677 1678 // If we are adhering to the cost model, reattach all the candidates 1679 if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) { 1680 for (OutlinableRegion *OS : CurrentGroup.Regions) 1681 OS->reattachCandidate(); 1682 OptimizationRemarkEmitter &ORE = getORE( 1683 *CurrentGroup.Regions[0]->Candidate->getFunction()); 1684 ORE.emit([&]() { 1685 IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 1686 OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize", 1687 C->frontInstruction()); 1688 R << "did not outline " 1689 << ore::NV(std::to_string(CurrentGroup.Regions.size())) 1690 << " regions due to estimated increase of " 1691 << ore::NV("InstructionIncrease", 1692 CurrentGroup.Cost - CurrentGroup.Benefit) 1693 << " instructions at locations "; 1694 interleave( 1695 CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 1696 [&R](OutlinableRegion *Region) { 1697 R << ore::NV( 1698 "DebugLoc", 1699 Region->Candidate->frontInstruction()->getDebugLoc()); 1700 }, 1701 [&R]() { R << " "; }); 1702 return R; 1703 }); 1704 continue; 1705 } 1706 1707 LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost 1708 << " and benefit " << CurrentGroup.Benefit << "\n"); 1709 1710 // Create functions out of all the sections, and mark them as outlined. 1711 OutlinedRegions.clear(); 1712 for (OutlinableRegion *OS : CurrentGroup.Regions) { 1713 bool FunctionOutlined = extractSection(*OS); 1714 if (FunctionOutlined) { 1715 unsigned StartIdx = OS->Candidate->getStartIdx(); 1716 unsigned EndIdx = OS->Candidate->getEndIdx(); 1717 for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 1718 Outlined.insert(Idx); 1719 1720 OutlinedRegions.push_back(OS); 1721 } 1722 } 1723 1724 LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size() 1725 << " with benefit " << CurrentGroup.Benefit 1726 << " and cost " << CurrentGroup.Cost << "\n"); 1727 1728 CurrentGroup.Regions = std::move(OutlinedRegions); 1729 1730 if (CurrentGroup.Regions.empty()) 1731 continue; 1732 1733 OptimizationRemarkEmitter &ORE = 1734 getORE(*CurrentGroup.Regions[0]->Call->getFunction()); 1735 ORE.emit([&]() { 1736 IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 1737 OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst); 1738 R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size())) 1739 << " regions with decrease of " 1740 << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost) 1741 << " instructions at locations "; 1742 interleave( 1743 CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 1744 [&R](OutlinableRegion *Region) { 1745 R << ore::NV("DebugLoc", 1746 Region->Candidate->frontInstruction()->getDebugLoc()); 1747 }, 1748 [&R]() { R << " "; }); 1749 return R; 1750 }); 1751 1752 deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove, 1753 OutlinedFunctionNum); 1754 } 1755 1756 for (Function *F : FuncsToRemove) 1757 F->eraseFromParent(); 1758 1759 return OutlinedFunctionNum; 1760 } 1761 1762 bool IROutliner::run(Module &M) { 1763 CostModel = !NoCostModel; 1764 OutlineFromLinkODRs = EnableLinkOnceODRIROutlining; 1765 1766 return doOutline(M) > 0; 1767 } 1768 1769 // Pass Manager Boilerplate 1770 class IROutlinerLegacyPass : public ModulePass { 1771 public: 1772 static char ID; 1773 IROutlinerLegacyPass() : ModulePass(ID) { 1774 initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry()); 1775 } 1776 1777 void getAnalysisUsage(AnalysisUsage &AU) const override { 1778 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1779 AU.addRequired<TargetTransformInfoWrapperPass>(); 1780 AU.addRequired<IRSimilarityIdentifierWrapperPass>(); 1781 } 1782 1783 bool runOnModule(Module &M) override; 1784 }; 1785 1786 bool IROutlinerLegacyPass::runOnModule(Module &M) { 1787 if (skipModule(M)) 1788 return false; 1789 1790 std::unique_ptr<OptimizationRemarkEmitter> ORE; 1791 auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & { 1792 ORE.reset(new OptimizationRemarkEmitter(&F)); 1793 return *ORE.get(); 1794 }; 1795 1796 auto GTTI = [this](Function &F) -> TargetTransformInfo & { 1797 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1798 }; 1799 1800 auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & { 1801 return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI(); 1802 }; 1803 1804 return IROutliner(GTTI, GIRSI, GORE).run(M); 1805 } 1806 1807 PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) { 1808 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1809 1810 std::function<TargetTransformInfo &(Function &)> GTTI = 1811 [&FAM](Function &F) -> TargetTransformInfo & { 1812 return FAM.getResult<TargetIRAnalysis>(F); 1813 }; 1814 1815 std::function<IRSimilarityIdentifier &(Module &)> GIRSI = 1816 [&AM](Module &M) -> IRSimilarityIdentifier & { 1817 return AM.getResult<IRSimilarityAnalysis>(M); 1818 }; 1819 1820 std::unique_ptr<OptimizationRemarkEmitter> ORE; 1821 std::function<OptimizationRemarkEmitter &(Function &)> GORE = 1822 [&ORE](Function &F) -> OptimizationRemarkEmitter & { 1823 ORE.reset(new OptimizationRemarkEmitter(&F)); 1824 return *ORE.get(); 1825 }; 1826 1827 if (IROutliner(GTTI, GIRSI, GORE).run(M)) 1828 return PreservedAnalyses::none(); 1829 return PreservedAnalyses::all(); 1830 } 1831 1832 char IROutlinerLegacyPass::ID = 0; 1833 INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 1834 false) 1835 INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass) 1836 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1837 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1838 INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 1839 false) 1840 1841 ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); } 1842