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