1 //===- Attributor.cpp - Module-wide attribute deduction -------------------===// 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 // This file implements an interprocedural pass that deduces and/or propagates 10 // attributes. This is done in an abstract interpretation style fixpoint 11 // iteration. See the Attributor.h file comment and the class descriptions in 12 // that file for more information. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/IPO/Attributor.h" 17 18 #include "llvm/ADT/GraphTraits.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/TinyPtrVector.h" 22 #include "llvm/Analysis/InlineCost.h" 23 #include "llvm/Analysis/LazyValueInfo.h" 24 #include "llvm/Analysis/MemorySSAUpdater.h" 25 #include "llvm/Analysis/MustExecute.h" 26 #include "llvm/Analysis/ValueTracking.h" 27 #include "llvm/IR/GlobalValue.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/NoFolder.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/InitializePasses.h" 32 #include "llvm/Support/Casting.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/FileSystem.h" 36 #include "llvm/Support/GraphWriter.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 39 #include "llvm/Transforms/Utils/Cloning.h" 40 #include "llvm/Transforms/Utils/Local.h" 41 42 #include <cassert> 43 #include <string> 44 45 using namespace llvm; 46 47 #define DEBUG_TYPE "attributor" 48 49 STATISTIC(NumFnDeleted, "Number of function deleted"); 50 STATISTIC(NumFnWithExactDefinition, 51 "Number of functions with exact definitions"); 52 STATISTIC(NumFnWithoutExactDefinition, 53 "Number of functions without exact definitions"); 54 STATISTIC(NumFnShallowWrapperCreated, "Number of shallow wrappers created"); 55 STATISTIC(NumAttributesTimedOut, 56 "Number of abstract attributes timed out before fixpoint"); 57 STATISTIC(NumAttributesValidFixpoint, 58 "Number of abstract attributes in a valid fixpoint state"); 59 STATISTIC(NumAttributesManifested, 60 "Number of abstract attributes manifested in IR"); 61 STATISTIC(NumAttributesFixedDueToRequiredDependences, 62 "Number of abstract attributes fixed due to required dependences"); 63 64 // TODO: Determine a good default value. 65 // 66 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 67 // (when run with the first 5 abstract attributes). The results also indicate 68 // that we never reach 32 iterations but always find a fixpoint sooner. 69 // 70 // This will become more evolved once we perform two interleaved fixpoint 71 // iterations: bottom-up and top-down. 72 static cl::opt<unsigned> 73 MaxFixpointIterations("attributor-max-iterations", cl::Hidden, 74 cl::desc("Maximal number of fixpoint iterations."), 75 cl::init(32)); 76 static cl::opt<bool> VerifyMaxFixpointIterations( 77 "attributor-max-iterations-verify", cl::Hidden, 78 cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), 79 cl::init(false)); 80 81 static cl::opt<bool> AnnotateDeclarationCallSites( 82 "attributor-annotate-decl-cs", cl::Hidden, 83 cl::desc("Annotate call sites of function declarations."), cl::init(false)); 84 85 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion", 86 cl::init(true), cl::Hidden); 87 88 static cl::opt<bool> 89 AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden, 90 cl::desc("Allow the Attributor to create shallow " 91 "wrappers for non-exact definitions."), 92 cl::init(false)); 93 94 static cl::opt<bool> 95 AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden, 96 cl::desc("Allow the Attributor to use IP information " 97 "derived from non-exact functions via cloning"), 98 cl::init(false)); 99 100 // These options can only used for debug builds. 101 #ifndef NDEBUG 102 static cl::list<std::string> 103 SeedAllowList("attributor-seed-allow-list", cl::Hidden, 104 cl::desc("Comma seperated list of attribute names that are " 105 "allowed to be seeded."), 106 cl::ZeroOrMore, cl::CommaSeparated); 107 108 static cl::list<std::string> FunctionSeedAllowList( 109 "attributor-function-seed-allow-list", cl::Hidden, 110 cl::desc("Comma seperated list of function names that are " 111 "allowed to be seeded."), 112 cl::ZeroOrMore, cl::CommaSeparated); 113 #endif 114 115 static cl::opt<bool> 116 DumpDepGraph("attributor-dump-dep-graph", cl::Hidden, 117 cl::desc("Dump the dependency graph to dot files."), 118 cl::init(false)); 119 120 static cl::opt<std::string> DepGraphDotFileNamePrefix( 121 "attributor-depgraph-dot-filename-prefix", cl::Hidden, 122 cl::desc("The prefix used for the CallGraph dot file names.")); 123 124 static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden, 125 cl::desc("View the dependency graph."), 126 cl::init(false)); 127 128 static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden, 129 cl::desc("Print attribute dependencies"), 130 cl::init(false)); 131 132 /// Logic operators for the change status enum class. 133 /// 134 ///{ 135 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { 136 return l == ChangeStatus::CHANGED ? l : r; 137 } 138 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { 139 return l == ChangeStatus::UNCHANGED ? l : r; 140 } 141 ///} 142 143 /// Return true if \p New is equal or worse than \p Old. 144 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 145 if (!Old.isIntAttribute()) 146 return true; 147 148 return Old.getValueAsInt() >= New.getValueAsInt(); 149 } 150 151 /// Return true if the information provided by \p Attr was added to the 152 /// attribute list \p Attrs. This is only the case if it was not already present 153 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 154 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 155 AttributeList &Attrs, int AttrIdx) { 156 157 if (Attr.isEnumAttribute()) { 158 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 159 if (Attrs.hasAttribute(AttrIdx, Kind)) 160 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 161 return false; 162 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 163 return true; 164 } 165 if (Attr.isStringAttribute()) { 166 StringRef Kind = Attr.getKindAsString(); 167 if (Attrs.hasAttribute(AttrIdx, Kind)) 168 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 169 return false; 170 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 171 return true; 172 } 173 if (Attr.isIntAttribute()) { 174 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 175 if (Attrs.hasAttribute(AttrIdx, Kind)) 176 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 177 return false; 178 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 179 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 180 return true; 181 } 182 183 llvm_unreachable("Expected enum or string attribute!"); 184 } 185 186 Argument *IRPosition::getAssociatedArgument() const { 187 if (getPositionKind() == IRP_ARGUMENT) 188 return cast<Argument>(&getAnchorValue()); 189 190 // Not an Argument and no argument number means this is not a call site 191 // argument, thus we cannot find a callback argument to return. 192 int ArgNo = getArgNo(); 193 if (ArgNo < 0) 194 return nullptr; 195 196 // Use abstract call sites to make the connection between the call site 197 // values and the ones in callbacks. If a callback was found that makes use 198 // of the underlying call site operand, we want the corresponding callback 199 // callee argument and not the direct callee argument. 200 Optional<Argument *> CBCandidateArg; 201 SmallVector<const Use *, 4> CallbackUses; 202 const auto &CB = cast<CallBase>(getAnchorValue()); 203 AbstractCallSite::getCallbackUses(CB, CallbackUses); 204 for (const Use *U : CallbackUses) { 205 AbstractCallSite ACS(U); 206 assert(ACS && ACS.isCallbackCall()); 207 if (!ACS.getCalledFunction()) 208 continue; 209 210 for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) { 211 212 // Test if the underlying call site operand is argument number u of the 213 // callback callee. 214 if (ACS.getCallArgOperandNo(u) != ArgNo) 215 continue; 216 217 assert(ACS.getCalledFunction()->arg_size() > u && 218 "ACS mapped into var-args arguments!"); 219 if (CBCandidateArg.hasValue()) { 220 CBCandidateArg = nullptr; 221 break; 222 } 223 CBCandidateArg = ACS.getCalledFunction()->getArg(u); 224 } 225 } 226 227 // If we found a unique callback candidate argument, return it. 228 if (CBCandidateArg.hasValue() && CBCandidateArg.getValue()) 229 return CBCandidateArg.getValue(); 230 231 // If no callbacks were found, or none used the underlying call site operand 232 // exclusively, use the direct callee argument if available. 233 const Function *Callee = CB.getCalledFunction(); 234 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 235 return Callee->getArg(ArgNo); 236 237 return nullptr; 238 } 239 240 ChangeStatus AbstractAttribute::update(Attributor &A) { 241 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 242 if (getState().isAtFixpoint()) 243 return HasChanged; 244 245 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 246 247 HasChanged = updateImpl(A); 248 249 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 250 << "\n"); 251 252 return HasChanged; 253 } 254 255 ChangeStatus 256 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP, 257 const ArrayRef<Attribute> &DeducedAttrs) { 258 Function *ScopeFn = IRP.getAnchorScope(); 259 IRPosition::Kind PK = IRP.getPositionKind(); 260 261 // In the following some generic code that will manifest attributes in 262 // DeducedAttrs if they improve the current IR. Due to the different 263 // annotation positions we use the underlying AttributeList interface. 264 265 AttributeList Attrs; 266 switch (PK) { 267 case IRPosition::IRP_INVALID: 268 case IRPosition::IRP_FLOAT: 269 return ChangeStatus::UNCHANGED; 270 case IRPosition::IRP_ARGUMENT: 271 case IRPosition::IRP_FUNCTION: 272 case IRPosition::IRP_RETURNED: 273 Attrs = ScopeFn->getAttributes(); 274 break; 275 case IRPosition::IRP_CALL_SITE: 276 case IRPosition::IRP_CALL_SITE_RETURNED: 277 case IRPosition::IRP_CALL_SITE_ARGUMENT: 278 Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes(); 279 break; 280 } 281 282 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 283 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 284 for (const Attribute &Attr : DeducedAttrs) { 285 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 286 continue; 287 288 HasChanged = ChangeStatus::CHANGED; 289 } 290 291 if (HasChanged == ChangeStatus::UNCHANGED) 292 return HasChanged; 293 294 switch (PK) { 295 case IRPosition::IRP_ARGUMENT: 296 case IRPosition::IRP_FUNCTION: 297 case IRPosition::IRP_RETURNED: 298 ScopeFn->setAttributes(Attrs); 299 break; 300 case IRPosition::IRP_CALL_SITE: 301 case IRPosition::IRP_CALL_SITE_RETURNED: 302 case IRPosition::IRP_CALL_SITE_ARGUMENT: 303 cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs); 304 break; 305 case IRPosition::IRP_INVALID: 306 case IRPosition::IRP_FLOAT: 307 break; 308 } 309 310 return HasChanged; 311 } 312 313 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey()); 314 const IRPosition 315 IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey()); 316 317 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 318 IRPositions.emplace_back(IRP); 319 320 const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue()); 321 switch (IRP.getPositionKind()) { 322 case IRPosition::IRP_INVALID: 323 case IRPosition::IRP_FLOAT: 324 case IRPosition::IRP_FUNCTION: 325 return; 326 case IRPosition::IRP_ARGUMENT: 327 case IRPosition::IRP_RETURNED: 328 IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope())); 329 return; 330 case IRPosition::IRP_CALL_SITE: 331 assert(CB && "Expected call site!"); 332 // TODO: We need to look at the operand bundles similar to the redirection 333 // in CallBase. 334 if (!CB->hasOperandBundles()) 335 if (const Function *Callee = CB->getCalledFunction()) 336 IRPositions.emplace_back(IRPosition::function(*Callee)); 337 return; 338 case IRPosition::IRP_CALL_SITE_RETURNED: 339 assert(CB && "Expected call site!"); 340 // TODO: We need to look at the operand bundles similar to the redirection 341 // in CallBase. 342 if (!CB->hasOperandBundles()) { 343 if (const Function *Callee = CB->getCalledFunction()) { 344 IRPositions.emplace_back(IRPosition::returned(*Callee)); 345 IRPositions.emplace_back(IRPosition::function(*Callee)); 346 for (const Argument &Arg : Callee->args()) 347 if (Arg.hasReturnedAttr()) { 348 IRPositions.emplace_back( 349 IRPosition::callsite_argument(*CB, Arg.getArgNo())); 350 IRPositions.emplace_back( 351 IRPosition::value(*CB->getArgOperand(Arg.getArgNo()))); 352 IRPositions.emplace_back(IRPosition::argument(Arg)); 353 } 354 } 355 } 356 IRPositions.emplace_back(IRPosition::callsite_function(*CB)); 357 return; 358 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 359 int ArgNo = IRP.getArgNo(); 360 assert(CB && ArgNo >= 0 && "Expected call site!"); 361 // TODO: We need to look at the operand bundles similar to the redirection 362 // in CallBase. 363 if (!CB->hasOperandBundles()) { 364 const Function *Callee = CB->getCalledFunction(); 365 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 366 IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo))); 367 if (Callee) 368 IRPositions.emplace_back(IRPosition::function(*Callee)); 369 } 370 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 371 return; 372 } 373 } 374 } 375 376 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs, 377 bool IgnoreSubsumingPositions, Attributor *A) const { 378 SmallVector<Attribute, 4> Attrs; 379 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 380 for (Attribute::AttrKind AK : AKs) 381 if (EquivIRP.getAttrsFromIRAttr(AK, Attrs)) 382 return true; 383 // The first position returned by the SubsumingPositionIterator is 384 // always the position itself. If we ignore subsuming positions we 385 // are done after the first iteration. 386 if (IgnoreSubsumingPositions) 387 break; 388 } 389 if (A) 390 for (Attribute::AttrKind AK : AKs) 391 if (getAttrsFromAssumes(AK, Attrs, *A)) 392 return true; 393 return false; 394 } 395 396 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 397 SmallVectorImpl<Attribute> &Attrs, 398 bool IgnoreSubsumingPositions, Attributor *A) const { 399 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 400 for (Attribute::AttrKind AK : AKs) 401 EquivIRP.getAttrsFromIRAttr(AK, Attrs); 402 // The first position returned by the SubsumingPositionIterator is 403 // always the position itself. If we ignore subsuming positions we 404 // are done after the first iteration. 405 if (IgnoreSubsumingPositions) 406 break; 407 } 408 if (A) 409 for (Attribute::AttrKind AK : AKs) 410 getAttrsFromAssumes(AK, Attrs, *A); 411 } 412 413 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK, 414 SmallVectorImpl<Attribute> &Attrs) const { 415 if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT) 416 return false; 417 418 AttributeList AttrList; 419 if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue())) 420 AttrList = CB->getAttributes(); 421 else 422 AttrList = getAssociatedFunction()->getAttributes(); 423 424 bool HasAttr = AttrList.hasAttribute(getAttrIdx(), AK); 425 if (HasAttr) 426 Attrs.push_back(AttrList.getAttribute(getAttrIdx(), AK)); 427 return HasAttr; 428 } 429 430 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK, 431 SmallVectorImpl<Attribute> &Attrs, 432 Attributor &A) const { 433 assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!"); 434 Value &AssociatedValue = getAssociatedValue(); 435 436 const Assume2KnowledgeMap &A2K = 437 A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK}); 438 439 // Check if we found any potential assume use, if not we don't need to create 440 // explorer iterators. 441 if (A2K.empty()) 442 return false; 443 444 LLVMContext &Ctx = AssociatedValue.getContext(); 445 unsigned AttrsSize = Attrs.size(); 446 MustBeExecutedContextExplorer &Explorer = 447 A.getInfoCache().getMustBeExecutedContextExplorer(); 448 auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI()); 449 for (auto &It : A2K) 450 if (Explorer.findInContextOf(It.first, EIt, EEnd)) 451 Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max)); 452 return AttrsSize != Attrs.size(); 453 } 454 455 void IRPosition::verify() { 456 #ifdef EXPENSIVE_CHECKS 457 switch (getPositionKind()) { 458 case IRP_INVALID: 459 assert(!Enc.getOpaqueValue() && 460 "Expected a nullptr for an invalid position!"); 461 return; 462 case IRP_FLOAT: 463 assert((!isa<CallBase>(&getAssociatedValue()) && 464 !isa<Argument>(&getAssociatedValue())) && 465 "Expected specialized kind for call base and argument values!"); 466 return; 467 case IRP_RETURNED: 468 assert(isa<Function>(getAsValuePtr()) && 469 "Expected function for a 'returned' position!"); 470 assert(getAsValuePtr() == &getAssociatedValue() && 471 "Associated value mismatch!"); 472 return; 473 case IRP_CALL_SITE_RETURNED: 474 assert((isa<CallBase>(getAsValuePtr())) && 475 "Expected call base for 'call site returned' position!"); 476 assert(getAsValuePtr() == &getAssociatedValue() && 477 "Associated value mismatch!"); 478 return; 479 case IRP_CALL_SITE: 480 assert((isa<CallBase>(getAsValuePtr())) && 481 "Expected call base for 'call site function' position!"); 482 assert(getAsValuePtr() == &getAssociatedValue() && 483 "Associated value mismatch!"); 484 return; 485 case IRP_FUNCTION: 486 assert(isa<Function>(getAsValuePtr()) && 487 "Expected function for a 'function' position!"); 488 assert(getAsValuePtr() == &getAssociatedValue() && 489 "Associated value mismatch!"); 490 return; 491 case IRP_ARGUMENT: 492 assert(isa<Argument>(getAsValuePtr()) && 493 "Expected argument for a 'argument' position!"); 494 assert(getAsValuePtr() == &getAssociatedValue() && 495 "Associated value mismatch!"); 496 return; 497 case IRP_CALL_SITE_ARGUMENT: { 498 Use *U = getAsUsePtr(); 499 assert(U && "Expected use for a 'call site argument' position!"); 500 assert(isa<CallBase>(U->getUser()) && 501 "Expected call base user for a 'call site argument' position!"); 502 assert(cast<CallBase>(U->getUser())->isArgOperand(U) && 503 "Expected call base argument operand for a 'call site argument' " 504 "position"); 505 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) == 506 unsigned(getArgNo()) && 507 "Argument number mismatch!"); 508 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!"); 509 return; 510 } 511 } 512 #endif 513 } 514 515 Optional<Constant *> 516 Attributor::getAssumedConstant(const Value &V, const AbstractAttribute &AA, 517 bool &UsedAssumedInformation) { 518 const auto &ValueSimplifyAA = getAAFor<AAValueSimplify>( 519 AA, IRPosition::value(V), /* TrackDependence */ false); 520 Optional<Value *> SimplifiedV = 521 ValueSimplifyAA.getAssumedSimplifiedValue(*this); 522 bool IsKnown = ValueSimplifyAA.isKnown(); 523 UsedAssumedInformation |= !IsKnown; 524 if (!SimplifiedV.hasValue()) { 525 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 526 return llvm::None; 527 } 528 if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) { 529 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 530 return llvm::None; 531 } 532 Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue()); 533 if (CI && CI->getType() != V.getType()) { 534 // TODO: Check for a save conversion. 535 return nullptr; 536 } 537 if (CI) 538 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 539 return CI; 540 } 541 542 Attributor::~Attributor() { 543 // The abstract attributes are allocated via the BumpPtrAllocator Allocator, 544 // thus we cannot delete them. We can, and want to, destruct them though. 545 for (auto &DepAA : DG.SyntheticRoot.Deps) { 546 AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer()); 547 AA->~AbstractAttribute(); 548 } 549 } 550 551 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 552 const AAIsDead *FnLivenessAA, 553 bool CheckBBLivenessOnly, DepClassTy DepClass) { 554 const IRPosition &IRP = AA.getIRPosition(); 555 if (!Functions.count(IRP.getAnchorScope())) 556 return false; 557 return isAssumedDead(IRP, &AA, FnLivenessAA, CheckBBLivenessOnly, DepClass); 558 } 559 560 bool Attributor::isAssumedDead(const Use &U, 561 const AbstractAttribute *QueryingAA, 562 const AAIsDead *FnLivenessAA, 563 bool CheckBBLivenessOnly, DepClassTy DepClass) { 564 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 565 if (!UserI) 566 return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA, 567 CheckBBLivenessOnly, DepClass); 568 569 if (auto *CB = dyn_cast<CallBase>(UserI)) { 570 // For call site argument uses we can check if the argument is 571 // unused/dead. 572 if (CB->isArgOperand(&U)) { 573 const IRPosition &CSArgPos = 574 IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 575 return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA, 576 CheckBBLivenessOnly, DepClass); 577 } 578 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) { 579 const IRPosition &RetPos = IRPosition::returned(*RI->getFunction()); 580 return isAssumedDead(RetPos, QueryingAA, FnLivenessAA, CheckBBLivenessOnly, 581 DepClass); 582 } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) { 583 BasicBlock *IncomingBB = PHI->getIncomingBlock(U); 584 return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA, 585 CheckBBLivenessOnly, DepClass); 586 } 587 588 return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA, 589 CheckBBLivenessOnly, DepClass); 590 } 591 592 bool Attributor::isAssumedDead(const Instruction &I, 593 const AbstractAttribute *QueryingAA, 594 const AAIsDead *FnLivenessAA, 595 bool CheckBBLivenessOnly, DepClassTy DepClass) { 596 if (!FnLivenessAA) 597 FnLivenessAA = lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction()), 598 QueryingAA, 599 /* TrackDependence */ false); 600 601 // If we have a context instruction and a liveness AA we use it. 602 if (FnLivenessAA && 603 FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() && 604 FnLivenessAA->isAssumedDead(&I)) { 605 if (QueryingAA) 606 recordDependence(*FnLivenessAA, *QueryingAA, DepClass); 607 return true; 608 } 609 610 if (CheckBBLivenessOnly) 611 return false; 612 613 const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>( 614 IRPosition::value(I), QueryingAA, /* TrackDependence */ false); 615 // Don't check liveness for AAIsDead. 616 if (QueryingAA == &IsDeadAA) 617 return false; 618 619 if (IsDeadAA.isAssumedDead()) { 620 if (QueryingAA) 621 recordDependence(IsDeadAA, *QueryingAA, DepClass); 622 return true; 623 } 624 625 return false; 626 } 627 628 bool Attributor::isAssumedDead(const IRPosition &IRP, 629 const AbstractAttribute *QueryingAA, 630 const AAIsDead *FnLivenessAA, 631 bool CheckBBLivenessOnly, DepClassTy DepClass) { 632 Instruction *CtxI = IRP.getCtxI(); 633 if (CtxI && 634 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, 635 /* CheckBBLivenessOnly */ true, 636 CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL)) 637 return true; 638 639 if (CheckBBLivenessOnly) 640 return false; 641 642 // If we haven't succeeded we query the specific liveness info for the IRP. 643 const AAIsDead *IsDeadAA; 644 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE) 645 IsDeadAA = &getOrCreateAAFor<AAIsDead>( 646 IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())), 647 QueryingAA, /* TrackDependence */ false); 648 else 649 IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, 650 /* TrackDependence */ false); 651 // Don't check liveness for AAIsDead. 652 if (QueryingAA == IsDeadAA) 653 return false; 654 655 if (IsDeadAA->isAssumedDead()) { 656 if (QueryingAA) 657 recordDependence(*IsDeadAA, *QueryingAA, DepClass); 658 return true; 659 } 660 661 return false; 662 } 663 664 bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred, 665 const AbstractAttribute &QueryingAA, 666 const Value &V, DepClassTy LivenessDepClass) { 667 668 // Check the trivial case first as it catches void values. 669 if (V.use_empty()) 670 return true; 671 672 // If the value is replaced by another one, for now a constant, we do not have 673 // uses. Note that this requires users of `checkForAllUses` to not recurse but 674 // instead use the `follow` callback argument to look at transitive users, 675 // however, that should be clear from the presence of the argument. 676 bool UsedAssumedInformation = false; 677 Optional<Constant *> C = 678 getAssumedConstant(V, QueryingAA, UsedAssumedInformation); 679 if (C.hasValue() && C.getValue()) { 680 LLVM_DEBUG(dbgs() << "[Attributor] Value is simplified, uses skipped: " << V 681 << " -> " << *C.getValue() << "\n"); 682 return true; 683 } 684 685 const IRPosition &IRP = QueryingAA.getIRPosition(); 686 SmallVector<const Use *, 16> Worklist; 687 SmallPtrSet<const Use *, 16> Visited; 688 689 for (const Use &U : V.uses()) 690 Worklist.push_back(&U); 691 692 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size() 693 << " initial uses to check\n"); 694 695 const Function *ScopeFn = IRP.getAnchorScope(); 696 const auto *LivenessAA = 697 ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn), 698 /* TrackDependence */ false) 699 : nullptr; 700 701 while (!Worklist.empty()) { 702 const Use *U = Worklist.pop_back_val(); 703 if (!Visited.insert(U).second) 704 continue; 705 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in " 706 << *U->getUser() << "\n"); 707 if (isAssumedDead(*U, &QueryingAA, LivenessAA, 708 /* CheckBBLivenessOnly */ false, LivenessDepClass)) { 709 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 710 continue; 711 } 712 if (U->getUser()->isDroppable()) { 713 LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n"); 714 continue; 715 } 716 717 bool Follow = false; 718 if (!Pred(*U, Follow)) 719 return false; 720 if (!Follow) 721 continue; 722 for (const Use &UU : U->getUser()->uses()) 723 Worklist.push_back(&UU); 724 } 725 726 return true; 727 } 728 729 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 730 const AbstractAttribute &QueryingAA, 731 bool RequireAllCallSites, 732 bool &AllCallSitesKnown) { 733 // We can try to determine information from 734 // the call sites. However, this is only possible all call sites are known, 735 // hence the function has internal linkage. 736 const IRPosition &IRP = QueryingAA.getIRPosition(); 737 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 738 if (!AssociatedFunction) { 739 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP 740 << "\n"); 741 AllCallSitesKnown = false; 742 return false; 743 } 744 745 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites, 746 &QueryingAA, AllCallSitesKnown); 747 } 748 749 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 750 const Function &Fn, 751 bool RequireAllCallSites, 752 const AbstractAttribute *QueryingAA, 753 bool &AllCallSitesKnown) { 754 if (RequireAllCallSites && !Fn.hasLocalLinkage()) { 755 LLVM_DEBUG( 756 dbgs() 757 << "[Attributor] Function " << Fn.getName() 758 << " has no internal linkage, hence not all call sites are known\n"); 759 AllCallSitesKnown = false; 760 return false; 761 } 762 763 // If we do not require all call sites we might not see all. 764 AllCallSitesKnown = RequireAllCallSites; 765 766 SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses())); 767 for (unsigned u = 0; u < Uses.size(); ++u) { 768 const Use &U = *Uses[u]; 769 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in " 770 << *U.getUser() << "\n"); 771 if (isAssumedDead(U, QueryingAA, nullptr, /* CheckBBLivenessOnly */ true)) { 772 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 773 continue; 774 } 775 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) { 776 if (CE->isCast() && CE->getType()->isPointerTy() && 777 CE->getType()->getPointerElementType()->isFunctionTy()) { 778 for (const Use &CEU : CE->uses()) 779 Uses.push_back(&CEU); 780 continue; 781 } 782 } 783 784 AbstractCallSite ACS(&U); 785 if (!ACS) { 786 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName() 787 << " has non call site use " << *U.get() << " in " 788 << *U.getUser() << "\n"); 789 // BlockAddress users are allowed. 790 if (isa<BlockAddress>(U.getUser())) 791 continue; 792 return false; 793 } 794 795 const Use *EffectiveUse = 796 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U; 797 if (!ACS.isCallee(EffectiveUse)) { 798 if (!RequireAllCallSites) 799 continue; 800 LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser() 801 << " is an invalid use of " << Fn.getName() << "\n"); 802 return false; 803 } 804 805 // Make sure the arguments that can be matched between the call site and the 806 // callee argee on their type. It is unlikely they do not and it doesn't 807 // make sense for all attributes to know/care about this. 808 assert(&Fn == ACS.getCalledFunction() && "Expected known callee"); 809 unsigned MinArgsParams = 810 std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size()); 811 for (unsigned u = 0; u < MinArgsParams; ++u) { 812 Value *CSArgOp = ACS.getCallArgOperand(u); 813 if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) { 814 LLVM_DEBUG( 815 dbgs() << "[Attributor] Call site / callee argument type mismatch [" 816 << u << "@" << Fn.getName() << ": " 817 << *Fn.getArg(u)->getType() << " vs. " 818 << *ACS.getCallArgOperand(u)->getType() << "\n"); 819 return false; 820 } 821 } 822 823 if (Pred(ACS)) 824 continue; 825 826 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 827 << *ACS.getInstruction() << "\n"); 828 return false; 829 } 830 831 return true; 832 } 833 834 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 835 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred, 836 const AbstractAttribute &QueryingAA) { 837 838 const IRPosition &IRP = QueryingAA.getIRPosition(); 839 // Since we need to provide return instructions we have to have an exact 840 // definition. 841 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 842 if (!AssociatedFunction) 843 return false; 844 845 // If this is a call site query we use the call site specific return values 846 // and liveness information. 847 // TODO: use the function scope once we have call site AAReturnedValues. 848 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 849 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 850 if (!AARetVal.getState().isValidState()) 851 return false; 852 853 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 854 } 855 856 bool Attributor::checkForAllReturnedValues( 857 function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) { 858 859 const IRPosition &IRP = QueryingAA.getIRPosition(); 860 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 861 if (!AssociatedFunction) 862 return false; 863 864 // TODO: use the function scope once we have call site AAReturnedValues. 865 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 866 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 867 if (!AARetVal.getState().isValidState()) 868 return false; 869 870 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 871 [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) { 872 return Pred(RV); 873 }); 874 } 875 876 static bool checkForAllInstructionsImpl( 877 Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap, 878 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA, 879 const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes, 880 bool CheckBBLivenessOnly = false) { 881 for (unsigned Opcode : Opcodes) { 882 // Check if we have instructions with this opcode at all first. 883 auto *Insts = OpcodeInstMap.lookup(Opcode); 884 if (!Insts) 885 continue; 886 887 for (Instruction *I : *Insts) { 888 // Skip dead instructions. 889 if (A && A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA, 890 CheckBBLivenessOnly)) 891 continue; 892 893 if (!Pred(*I)) 894 return false; 895 } 896 } 897 return true; 898 } 899 900 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred, 901 const AbstractAttribute &QueryingAA, 902 const ArrayRef<unsigned> &Opcodes, 903 bool CheckBBLivenessOnly) { 904 905 const IRPosition &IRP = QueryingAA.getIRPosition(); 906 // Since we need to provide instructions we have to have an exact definition. 907 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 908 if (!AssociatedFunction) 909 return false; 910 911 // TODO: use the function scope once we have call site AAReturnedValues. 912 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 913 const auto *LivenessAA = 914 CheckBBLivenessOnly ? nullptr 915 : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, 916 /* TrackDependence */ false)); 917 918 auto &OpcodeInstMap = 919 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 920 if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA, 921 LivenessAA, Opcodes, CheckBBLivenessOnly)) 922 return false; 923 924 return true; 925 } 926 927 bool Attributor::checkForAllReadWriteInstructions( 928 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA) { 929 930 const Function *AssociatedFunction = 931 QueryingAA.getIRPosition().getAssociatedFunction(); 932 if (!AssociatedFunction) 933 return false; 934 935 // TODO: use the function scope once we have call site AAReturnedValues. 936 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 937 const auto &LivenessAA = 938 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 939 940 for (Instruction *I : 941 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 942 // Skip dead instructions. 943 if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA)) 944 continue; 945 946 if (!Pred(*I)) 947 return false; 948 } 949 950 return true; 951 } 952 953 void Attributor::runTillFixpoint() { 954 TimeTraceScope TimeScope("Attributor::runTillFixpoint"); 955 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 956 << DG.SyntheticRoot.Deps.size() 957 << " abstract attributes.\n"); 958 959 // Now that all abstract attributes are collected and initialized we start 960 // the abstract analysis. 961 962 unsigned IterationCounter = 1; 963 964 SmallVector<AbstractAttribute *, 32> ChangedAAs; 965 SetVector<AbstractAttribute *> Worklist, InvalidAAs; 966 Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end()); 967 968 do { 969 // Remember the size to determine new attributes. 970 size_t NumAAs = DG.SyntheticRoot.Deps.size(); 971 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 972 << ", Worklist size: " << Worklist.size() << "\n"); 973 974 // For invalid AAs we can fix dependent AAs that have a required dependence, 975 // thereby folding long dependence chains in a single step without the need 976 // to run updates. 977 for (unsigned u = 0; u < InvalidAAs.size(); ++u) { 978 AbstractAttribute *InvalidAA = InvalidAAs[u]; 979 980 // Check the dependences to fast track invalidation. 981 LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has " 982 << InvalidAA->Deps.size() 983 << " required & optional dependences\n"); 984 while (!InvalidAA->Deps.empty()) { 985 const auto &Dep = InvalidAA->Deps.back(); 986 InvalidAA->Deps.pop_back(); 987 AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer()); 988 if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) { 989 Worklist.insert(DepAA); 990 continue; 991 } 992 DepAA->getState().indicatePessimisticFixpoint(); 993 assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!"); 994 if (!DepAA->getState().isValidState()) 995 InvalidAAs.insert(DepAA); 996 else 997 ChangedAAs.push_back(DepAA); 998 } 999 } 1000 1001 // Add all abstract attributes that are potentially dependent on one that 1002 // changed to the work list. 1003 for (AbstractAttribute *ChangedAA : ChangedAAs) 1004 while (!ChangedAA->Deps.empty()) { 1005 Worklist.insert( 1006 cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer())); 1007 ChangedAA->Deps.pop_back(); 1008 } 1009 1010 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter 1011 << ", Worklist+Dependent size: " << Worklist.size() 1012 << "\n"); 1013 1014 // Reset the changed and invalid set. 1015 ChangedAAs.clear(); 1016 InvalidAAs.clear(); 1017 1018 // Update all abstract attribute in the work list and record the ones that 1019 // changed. 1020 for (AbstractAttribute *AA : Worklist) { 1021 const auto &AAState = AA->getState(); 1022 if (!AAState.isAtFixpoint()) 1023 if (updateAA(*AA) == ChangeStatus::CHANGED) 1024 ChangedAAs.push_back(AA); 1025 1026 // Use the InvalidAAs vector to propagate invalid states fast transitively 1027 // without requiring updates. 1028 if (!AAState.isValidState()) 1029 InvalidAAs.insert(AA); 1030 } 1031 1032 // Add attributes to the changed set if they have been created in the last 1033 // iteration. 1034 ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs, 1035 DG.SyntheticRoot.end()); 1036 1037 // Reset the work list and repopulate with the changed abstract attributes. 1038 // Note that dependent ones are added above. 1039 Worklist.clear(); 1040 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 1041 1042 } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations || 1043 VerifyMaxFixpointIterations)); 1044 1045 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 1046 << IterationCounter << "/" << MaxFixpointIterations 1047 << " iterations\n"); 1048 1049 // Reset abstract arguments not settled in a sound fixpoint by now. This 1050 // happens when we stopped the fixpoint iteration early. Note that only the 1051 // ones marked as "changed" *and* the ones transitively depending on them 1052 // need to be reverted to a pessimistic state. Others might not be in a 1053 // fixpoint state but we can use the optimistic results for them anyway. 1054 SmallPtrSet<AbstractAttribute *, 32> Visited; 1055 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 1056 AbstractAttribute *ChangedAA = ChangedAAs[u]; 1057 if (!Visited.insert(ChangedAA).second) 1058 continue; 1059 1060 AbstractState &State = ChangedAA->getState(); 1061 if (!State.isAtFixpoint()) { 1062 State.indicatePessimisticFixpoint(); 1063 1064 NumAttributesTimedOut++; 1065 } 1066 1067 while (!ChangedAA->Deps.empty()) { 1068 ChangedAAs.push_back( 1069 cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer())); 1070 ChangedAA->Deps.pop_back(); 1071 } 1072 } 1073 1074 LLVM_DEBUG({ 1075 if (!Visited.empty()) 1076 dbgs() << "\n[Attributor] Finalized " << Visited.size() 1077 << " abstract attributes.\n"; 1078 }); 1079 1080 if (VerifyMaxFixpointIterations && 1081 IterationCounter != MaxFixpointIterations) { 1082 errs() << "\n[Attributor] Fixpoint iteration done after: " 1083 << IterationCounter << "/" << MaxFixpointIterations 1084 << " iterations\n"; 1085 llvm_unreachable("The fixpoint was not reached with exactly the number of " 1086 "specified iterations!"); 1087 } 1088 } 1089 1090 ChangeStatus Attributor::manifestAttributes() { 1091 TimeTraceScope TimeScope("Attributor::manifestAttributes"); 1092 size_t NumFinalAAs = DG.SyntheticRoot.Deps.size(); 1093 1094 unsigned NumManifested = 0; 1095 unsigned NumAtFixpoint = 0; 1096 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 1097 for (auto &DepAA : DG.SyntheticRoot.Deps) { 1098 AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer()); 1099 AbstractState &State = AA->getState(); 1100 1101 // If there is not already a fixpoint reached, we can now take the 1102 // optimistic state. This is correct because we enforced a pessimistic one 1103 // on abstract attributes that were transitively dependent on a changed one 1104 // already above. 1105 if (!State.isAtFixpoint()) 1106 State.indicateOptimisticFixpoint(); 1107 1108 // If the state is invalid, we do not try to manifest it. 1109 if (!State.isValidState()) 1110 continue; 1111 1112 // Skip dead code. 1113 if (isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true)) 1114 continue; 1115 // Manifest the state and record if we changed the IR. 1116 ChangeStatus LocalChange = AA->manifest(*this); 1117 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 1118 AA->trackStatistics(); 1119 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA 1120 << "\n"); 1121 1122 ManifestChange = ManifestChange | LocalChange; 1123 1124 NumAtFixpoint++; 1125 NumManifested += (LocalChange == ChangeStatus::CHANGED); 1126 } 1127 1128 (void)NumManifested; 1129 (void)NumAtFixpoint; 1130 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 1131 << " arguments while " << NumAtFixpoint 1132 << " were in a valid fixpoint state\n"); 1133 1134 NumAttributesManifested += NumManifested; 1135 NumAttributesValidFixpoint += NumAtFixpoint; 1136 1137 (void)NumFinalAAs; 1138 if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) { 1139 for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u) 1140 errs() << "Unexpected abstract attribute: " 1141 << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer()) 1142 << " :: " 1143 << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer()) 1144 ->getIRPosition() 1145 .getAssociatedValue() 1146 << "\n"; 1147 llvm_unreachable("Expected the final number of abstract attributes to " 1148 "remain unchanged!"); 1149 } 1150 return ManifestChange; 1151 } 1152 1153 ChangeStatus Attributor::cleanupIR() { 1154 TimeTraceScope TimeScope("Attributor::cleanupIR"); 1155 // Delete stuff at the end to avoid invalid references and a nice order. 1156 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least " 1157 << ToBeDeletedFunctions.size() << " functions and " 1158 << ToBeDeletedBlocks.size() << " blocks and " 1159 << ToBeDeletedInsts.size() << " instructions and " 1160 << ToBeChangedUses.size() << " uses\n"); 1161 1162 SmallVector<WeakTrackingVH, 32> DeadInsts; 1163 SmallVector<Instruction *, 32> TerminatorsToFold; 1164 1165 for (auto &It : ToBeChangedUses) { 1166 Use *U = It.first; 1167 Value *NewV = It.second; 1168 Value *OldV = U->get(); 1169 1170 // Do not replace uses in returns if the value is a must-tail call we will 1171 // not delete. 1172 if (isa<ReturnInst>(U->getUser())) 1173 if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts())) 1174 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI)) 1175 continue; 1176 1177 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser() 1178 << " instead of " << *OldV << "\n"); 1179 U->set(NewV); 1180 // Do not modify call instructions outside the SCC. 1181 if (auto *CB = dyn_cast<CallBase>(OldV)) 1182 if (!Functions.count(CB->getCaller())) 1183 continue; 1184 if (Instruction *I = dyn_cast<Instruction>(OldV)) { 1185 CGModifiedFunctions.insert(I->getFunction()); 1186 if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) && 1187 isInstructionTriviallyDead(I)) 1188 DeadInsts.push_back(I); 1189 } 1190 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) { 1191 Instruction *UserI = cast<Instruction>(U->getUser()); 1192 if (isa<UndefValue>(NewV)) { 1193 ToBeChangedToUnreachableInsts.insert(UserI); 1194 } else { 1195 TerminatorsToFold.push_back(UserI); 1196 } 1197 } 1198 } 1199 for (auto &V : InvokeWithDeadSuccessor) 1200 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) { 1201 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind); 1202 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn); 1203 bool Invoke2CallAllowed = 1204 !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction()); 1205 assert((UnwindBBIsDead || NormalBBIsDead) && 1206 "Invoke does not have dead successors!"); 1207 BasicBlock *BB = II->getParent(); 1208 BasicBlock *NormalDestBB = II->getNormalDest(); 1209 if (UnwindBBIsDead) { 1210 Instruction *NormalNextIP = &NormalDestBB->front(); 1211 if (Invoke2CallAllowed) { 1212 changeToCall(II); 1213 NormalNextIP = BB->getTerminator(); 1214 } 1215 if (NormalBBIsDead) 1216 ToBeChangedToUnreachableInsts.insert(NormalNextIP); 1217 } else { 1218 assert(NormalBBIsDead && "Broken invariant!"); 1219 if (!NormalDestBB->getUniquePredecessor()) 1220 NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 1221 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front()); 1222 } 1223 } 1224 for (Instruction *I : TerminatorsToFold) { 1225 CGModifiedFunctions.insert(I->getFunction()); 1226 ConstantFoldTerminator(I->getParent()); 1227 } 1228 for (auto &V : ToBeChangedToUnreachableInsts) 1229 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1230 CGModifiedFunctions.insert(I->getFunction()); 1231 changeToUnreachable(I, /* UseLLVMTrap */ false); 1232 } 1233 1234 for (auto &V : ToBeDeletedInsts) { 1235 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1236 I->dropDroppableUses(); 1237 CGModifiedFunctions.insert(I->getFunction()); 1238 if (!I->getType()->isVoidTy()) 1239 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1240 if (!isa<PHINode>(I) && isInstructionTriviallyDead(I)) 1241 DeadInsts.push_back(I); 1242 else 1243 I->eraseFromParent(); 1244 } 1245 } 1246 1247 LLVM_DEBUG(dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() 1248 << "\n"); 1249 1250 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 1251 1252 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 1253 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 1254 ToBeDeletedBBs.reserve(NumDeadBlocks); 1255 for (BasicBlock *BB : ToBeDeletedBlocks) { 1256 CGModifiedFunctions.insert(BB->getParent()); 1257 ToBeDeletedBBs.push_back(BB); 1258 } 1259 // Actually we do not delete the blocks but squash them into a single 1260 // unreachable but untangling branches that jump here is something we need 1261 // to do in a more generic way. 1262 DetatchDeadBlocks(ToBeDeletedBBs, nullptr); 1263 } 1264 1265 // Identify dead internal functions and delete them. This happens outside 1266 // the other fixpoint analysis as we might treat potentially dead functions 1267 // as live to lower the number of iterations. If they happen to be dead, the 1268 // below fixpoint loop will identify and eliminate them. 1269 SmallVector<Function *, 8> InternalFns; 1270 for (Function *F : Functions) 1271 if (F->hasLocalLinkage()) 1272 InternalFns.push_back(F); 1273 1274 bool FoundDeadFn = true; 1275 while (FoundDeadFn) { 1276 FoundDeadFn = false; 1277 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 1278 Function *F = InternalFns[u]; 1279 if (!F) 1280 continue; 1281 1282 bool AllCallSitesKnown; 1283 if (!checkForAllCallSites( 1284 [this](AbstractCallSite ACS) { 1285 return ToBeDeletedFunctions.count( 1286 ACS.getInstruction()->getFunction()); 1287 }, 1288 *F, true, nullptr, AllCallSitesKnown)) 1289 continue; 1290 1291 ToBeDeletedFunctions.insert(F); 1292 InternalFns[u] = nullptr; 1293 FoundDeadFn = true; 1294 } 1295 } 1296 1297 // Rewrite the functions as requested during manifest. 1298 ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions); 1299 1300 for (Function *Fn : CGModifiedFunctions) 1301 CGUpdater.reanalyzeFunction(*Fn); 1302 1303 for (Function *Fn : ToBeDeletedFunctions) { 1304 if (!Functions.count(Fn)) 1305 continue; 1306 CGUpdater.removeFunction(*Fn); 1307 } 1308 1309 if (!ToBeDeletedFunctions.empty()) 1310 ManifestChange = ChangeStatus::CHANGED; 1311 1312 NumFnDeleted += ToBeDeletedFunctions.size(); 1313 1314 LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << NumFnDeleted 1315 << " functions after manifest.\n"); 1316 1317 #ifdef EXPENSIVE_CHECKS 1318 for (Function *F : Functions) { 1319 if (ToBeDeletedFunctions.count(F)) 1320 continue; 1321 assert(!verifyFunction(*F, &errs()) && "Module verification failed!"); 1322 } 1323 #endif 1324 1325 return ManifestChange; 1326 } 1327 1328 ChangeStatus Attributor::run() { 1329 TimeTraceScope TimeScope("Attributor::run"); 1330 1331 Phase = AttributorPhase::UPDATE; 1332 runTillFixpoint(); 1333 1334 // dump graphs on demand 1335 if (DumpDepGraph) 1336 DG.dumpGraph(); 1337 1338 if (ViewDepGraph) 1339 DG.viewGraph(); 1340 1341 if (PrintDependencies) 1342 DG.print(); 1343 1344 Phase = AttributorPhase::MANIFEST; 1345 ChangeStatus ManifestChange = manifestAttributes(); 1346 1347 Phase = AttributorPhase::CLEANUP; 1348 ChangeStatus CleanupChange = cleanupIR(); 1349 1350 return ManifestChange | CleanupChange; 1351 } 1352 1353 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) { 1354 TimeTraceScope TimeScope(AA.getName() + "::updateAA"); 1355 assert(Phase == AttributorPhase::UPDATE && 1356 "We can update AA only in the update stage!"); 1357 1358 // Use a new dependence vector for this update. 1359 DependenceVector DV; 1360 DependenceStack.push_back(&DV); 1361 1362 auto &AAState = AA.getState(); 1363 ChangeStatus CS = ChangeStatus::UNCHANGED; 1364 if (!isAssumedDead(AA, nullptr, /* CheckBBLivenessOnly */ true)) 1365 CS = AA.update(*this); 1366 1367 if (DV.empty()) { 1368 // If the attribute did not query any non-fix information, the state 1369 // will not change and we can indicate that right away. 1370 AAState.indicateOptimisticFixpoint(); 1371 } 1372 1373 if (!AAState.isAtFixpoint()) 1374 rememberDependences(); 1375 1376 // Verify the stack was used properly, that is we pop the dependence vector we 1377 // put there earlier. 1378 DependenceVector *PoppedDV = DependenceStack.pop_back_val(); 1379 (void)PoppedDV; 1380 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!"); 1381 1382 return CS; 1383 } 1384 1385 /// Create a shallow wrapper for \p F such that \p F has internal linkage 1386 /// afterwards. It also sets the original \p F 's name to anonymous 1387 /// 1388 /// A wrapper is a function with the same type (and attributes) as \p F 1389 /// that will only call \p F and return the result, if any. 1390 /// 1391 /// Assuming the declaration of looks like: 1392 /// rty F(aty0 arg0, ..., atyN argN); 1393 /// 1394 /// The wrapper will then look as follows: 1395 /// rty wrapper(aty0 arg0, ..., atyN argN) { 1396 /// return F(arg0, ..., argN); 1397 /// } 1398 /// 1399 static void createShallowWrapper(Function &F) { 1400 assert(AllowShallowWrappers && 1401 "Cannot create a wrapper if it is not allowed!"); 1402 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!"); 1403 1404 Module &M = *F.getParent(); 1405 LLVMContext &Ctx = M.getContext(); 1406 FunctionType *FnTy = F.getFunctionType(); 1407 1408 Function *Wrapper = 1409 Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName()); 1410 F.setName(""); // set the inside function anonymous 1411 M.getFunctionList().insert(F.getIterator(), Wrapper); 1412 1413 F.setLinkage(GlobalValue::InternalLinkage); 1414 1415 F.replaceAllUsesWith(Wrapper); 1416 assert(F.use_empty() && "Uses remained after wrapper was created!"); 1417 1418 // Move the COMDAT section to the wrapper. 1419 // TODO: Check if we need to keep it for F as well. 1420 Wrapper->setComdat(F.getComdat()); 1421 F.setComdat(nullptr); 1422 1423 // Copy all metadata and attributes but keep them on F as well. 1424 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1425 F.getAllMetadata(MDs); 1426 for (auto MDIt : MDs) 1427 Wrapper->addMetadata(MDIt.first, *MDIt.second); 1428 Wrapper->setAttributes(F.getAttributes()); 1429 1430 // Create the call in the wrapper. 1431 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper); 1432 1433 SmallVector<Value *, 8> Args; 1434 auto FArgIt = F.arg_begin(); 1435 for (Argument &Arg : Wrapper->args()) { 1436 Args.push_back(&Arg); 1437 Arg.setName((FArgIt++)->getName()); 1438 } 1439 1440 CallInst *CI = CallInst::Create(&F, Args, "", EntryBB); 1441 CI->setTailCall(true); 1442 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline); 1443 ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB); 1444 1445 NumFnShallowWrapperCreated++; 1446 } 1447 1448 /// Make another copy of the function \p F such that the copied version has 1449 /// internal linkage afterwards and can be analysed. Then we replace all uses 1450 /// of the original function to the copied one 1451 /// 1452 /// Only non-exactly defined functions that have `linkonce_odr` or `weak_odr` 1453 /// linkage can be internalized because these linkages guarantee that other 1454 /// definitions with the same name have the same semantics as this one 1455 /// 1456 static Function *internalizeFunction(Function &F) { 1457 assert(AllowDeepWrapper && "Cannot create a copy if not allowed."); 1458 assert(!F.isDeclaration() && !F.hasExactDefinition() && 1459 !GlobalValue::isInterposableLinkage(F.getLinkage()) && 1460 "Trying to internalize function which cannot be internalized."); 1461 1462 Module &M = *F.getParent(); 1463 FunctionType *FnTy = F.getFunctionType(); 1464 1465 // create a copy of the current function 1466 Function *Copied = 1467 Function::Create(FnTy, GlobalValue::PrivateLinkage, F.getAddressSpace(), 1468 F.getName() + ".internalized"); 1469 ValueToValueMapTy VMap; 1470 auto *NewFArgIt = Copied->arg_begin(); 1471 for (auto &Arg : F.args()) { 1472 auto ArgName = Arg.getName(); 1473 NewFArgIt->setName(ArgName); 1474 VMap[&Arg] = &(*NewFArgIt++); 1475 } 1476 SmallVector<ReturnInst *, 8> Returns; 1477 1478 // Copy the body of the original function to the new one 1479 CloneFunctionInto(Copied, &F, VMap, /* ModuleLevelChanges */ false, Returns); 1480 1481 // Copy metadata 1482 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1483 F.getAllMetadata(MDs); 1484 for (auto MDIt : MDs) 1485 Copied->addMetadata(MDIt.first, *MDIt.second); 1486 1487 M.getFunctionList().insert(F.getIterator(), Copied); 1488 F.replaceAllUsesWith(Copied); 1489 Copied->setDSOLocal(true); 1490 1491 return Copied; 1492 } 1493 1494 bool Attributor::isValidFunctionSignatureRewrite( 1495 Argument &Arg, ArrayRef<Type *> ReplacementTypes) { 1496 1497 auto CallSiteCanBeChanged = [](AbstractCallSite ACS) { 1498 // Forbid the call site to cast the function return type. If we need to 1499 // rewrite these functions we need to re-create a cast for the new call site 1500 // (if the old had uses). 1501 if (!ACS.getCalledFunction() || 1502 ACS.getInstruction()->getType() != 1503 ACS.getCalledFunction()->getReturnType()) 1504 return false; 1505 // Forbid must-tail calls for now. 1506 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall(); 1507 }; 1508 1509 Function *Fn = Arg.getParent(); 1510 // Avoid var-arg functions for now. 1511 if (Fn->isVarArg()) { 1512 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n"); 1513 return false; 1514 } 1515 1516 // Avoid functions with complicated argument passing semantics. 1517 AttributeList FnAttributeList = Fn->getAttributes(); 1518 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) || 1519 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) || 1520 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) || 1521 FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) { 1522 LLVM_DEBUG( 1523 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n"); 1524 return false; 1525 } 1526 1527 // Avoid callbacks for now. 1528 bool AllCallSitesKnown; 1529 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr, 1530 AllCallSitesKnown)) { 1531 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n"); 1532 return false; 1533 } 1534 1535 auto InstPred = [](Instruction &I) { 1536 if (auto *CI = dyn_cast<CallInst>(&I)) 1537 return !CI->isMustTailCall(); 1538 return true; 1539 }; 1540 1541 // Forbid must-tail calls for now. 1542 // TODO: 1543 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn); 1544 if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr, 1545 nullptr, {Instruction::Call})) { 1546 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n"); 1547 return false; 1548 } 1549 1550 return true; 1551 } 1552 1553 bool Attributor::registerFunctionSignatureRewrite( 1554 Argument &Arg, ArrayRef<Type *> ReplacementTypes, 1555 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, 1556 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) { 1557 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1558 << Arg.getParent()->getName() << " with " 1559 << ReplacementTypes.size() << " replacements\n"); 1560 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) && 1561 "Cannot register an invalid rewrite"); 1562 1563 Function *Fn = Arg.getParent(); 1564 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1565 ArgumentReplacementMap[Fn]; 1566 if (ARIs.empty()) 1567 ARIs.resize(Fn->arg_size()); 1568 1569 // If we have a replacement already with less than or equal new arguments, 1570 // ignore this request. 1571 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()]; 1572 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) { 1573 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n"); 1574 return false; 1575 } 1576 1577 // If we have a replacement already but we like the new one better, delete 1578 // the old. 1579 ARI.reset(); 1580 1581 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1582 << Arg.getParent()->getName() << " with " 1583 << ReplacementTypes.size() << " replacements\n"); 1584 1585 // Remember the replacement. 1586 ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes, 1587 std::move(CalleeRepairCB), 1588 std::move(ACSRepairCB))); 1589 1590 return true; 1591 } 1592 1593 bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) { 1594 bool Result = true; 1595 #ifndef NDEBUG 1596 if (SeedAllowList.size() != 0) 1597 Result = 1598 std::count(SeedAllowList.begin(), SeedAllowList.end(), AA.getName()); 1599 Function *Fn = AA.getAnchorScope(); 1600 if (FunctionSeedAllowList.size() != 0 && Fn) 1601 Result &= std::count(FunctionSeedAllowList.begin(), 1602 FunctionSeedAllowList.end(), Fn->getName()); 1603 #endif 1604 return Result; 1605 } 1606 1607 ChangeStatus Attributor::rewriteFunctionSignatures( 1608 SmallPtrSetImpl<Function *> &ModifiedFns) { 1609 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1610 1611 for (auto &It : ArgumentReplacementMap) { 1612 Function *OldFn = It.getFirst(); 1613 1614 // Deleted functions do not require rewrites. 1615 if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn)) 1616 continue; 1617 1618 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1619 It.getSecond(); 1620 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!"); 1621 1622 SmallVector<Type *, 16> NewArgumentTypes; 1623 SmallVector<AttributeSet, 16> NewArgumentAttributes; 1624 1625 // Collect replacement argument types and copy over existing attributes. 1626 AttributeList OldFnAttributeList = OldFn->getAttributes(); 1627 for (Argument &Arg : OldFn->args()) { 1628 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1629 ARIs[Arg.getArgNo()]) { 1630 NewArgumentTypes.append(ARI->ReplacementTypes.begin(), 1631 ARI->ReplacementTypes.end()); 1632 NewArgumentAttributes.append(ARI->getNumReplacementArgs(), 1633 AttributeSet()); 1634 } else { 1635 NewArgumentTypes.push_back(Arg.getType()); 1636 NewArgumentAttributes.push_back( 1637 OldFnAttributeList.getParamAttributes(Arg.getArgNo())); 1638 } 1639 } 1640 1641 FunctionType *OldFnTy = OldFn->getFunctionType(); 1642 Type *RetTy = OldFnTy->getReturnType(); 1643 1644 // Construct the new function type using the new arguments types. 1645 FunctionType *NewFnTy = 1646 FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg()); 1647 1648 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName() 1649 << "' from " << *OldFn->getFunctionType() << " to " 1650 << *NewFnTy << "\n"); 1651 1652 // Create the new function body and insert it into the module. 1653 Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(), 1654 OldFn->getAddressSpace(), ""); 1655 OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn); 1656 NewFn->takeName(OldFn); 1657 NewFn->copyAttributesFrom(OldFn); 1658 1659 // Patch the pointer to LLVM function in debug info descriptor. 1660 NewFn->setSubprogram(OldFn->getSubprogram()); 1661 OldFn->setSubprogram(nullptr); 1662 1663 // Recompute the parameter attributes list based on the new arguments for 1664 // the function. 1665 LLVMContext &Ctx = OldFn->getContext(); 1666 NewFn->setAttributes(AttributeList::get( 1667 Ctx, OldFnAttributeList.getFnAttributes(), 1668 OldFnAttributeList.getRetAttributes(), NewArgumentAttributes)); 1669 1670 // Since we have now created the new function, splice the body of the old 1671 // function right into the new function, leaving the old rotting hulk of the 1672 // function empty. 1673 NewFn->getBasicBlockList().splice(NewFn->begin(), 1674 OldFn->getBasicBlockList()); 1675 1676 // Fixup block addresses to reference new function. 1677 SmallVector<BlockAddress *, 8u> BlockAddresses; 1678 for (User *U : OldFn->users()) 1679 if (auto *BA = dyn_cast<BlockAddress>(U)) 1680 BlockAddresses.push_back(BA); 1681 for (auto *BA : BlockAddresses) 1682 BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock())); 1683 1684 // Set of all "call-like" instructions that invoke the old function mapped 1685 // to their new replacements. 1686 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs; 1687 1688 // Callback to create a new "call-like" instruction for a given one. 1689 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) { 1690 CallBase *OldCB = cast<CallBase>(ACS.getInstruction()); 1691 const AttributeList &OldCallAttributeList = OldCB->getAttributes(); 1692 1693 // Collect the new argument operands for the replacement call site. 1694 SmallVector<Value *, 16> NewArgOperands; 1695 SmallVector<AttributeSet, 16> NewArgOperandAttributes; 1696 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) { 1697 unsigned NewFirstArgNum = NewArgOperands.size(); 1698 (void)NewFirstArgNum; // only used inside assert. 1699 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1700 ARIs[OldArgNum]) { 1701 if (ARI->ACSRepairCB) 1702 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands); 1703 assert(ARI->getNumReplacementArgs() + NewFirstArgNum == 1704 NewArgOperands.size() && 1705 "ACS repair callback did not provide as many operand as new " 1706 "types were registered!"); 1707 // TODO: Exose the attribute set to the ACS repair callback 1708 NewArgOperandAttributes.append(ARI->ReplacementTypes.size(), 1709 AttributeSet()); 1710 } else { 1711 NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum)); 1712 NewArgOperandAttributes.push_back( 1713 OldCallAttributeList.getParamAttributes(OldArgNum)); 1714 } 1715 } 1716 1717 assert(NewArgOperands.size() == NewArgOperandAttributes.size() && 1718 "Mismatch # argument operands vs. # argument operand attributes!"); 1719 assert(NewArgOperands.size() == NewFn->arg_size() && 1720 "Mismatch # argument operands vs. # function arguments!"); 1721 1722 SmallVector<OperandBundleDef, 4> OperandBundleDefs; 1723 OldCB->getOperandBundlesAsDefs(OperandBundleDefs); 1724 1725 // Create a new call or invoke instruction to replace the old one. 1726 CallBase *NewCB; 1727 if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) { 1728 NewCB = 1729 InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(), 1730 NewArgOperands, OperandBundleDefs, "", OldCB); 1731 } else { 1732 auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs, 1733 "", OldCB); 1734 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind()); 1735 NewCB = NewCI; 1736 } 1737 1738 // Copy over various properties and the new attributes. 1739 NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg}); 1740 NewCB->setCallingConv(OldCB->getCallingConv()); 1741 NewCB->takeName(OldCB); 1742 NewCB->setAttributes(AttributeList::get( 1743 Ctx, OldCallAttributeList.getFnAttributes(), 1744 OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes)); 1745 1746 CallSitePairs.push_back({OldCB, NewCB}); 1747 return true; 1748 }; 1749 1750 // Use the CallSiteReplacementCreator to create replacement call sites. 1751 bool AllCallSitesKnown; 1752 bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn, 1753 true, nullptr, AllCallSitesKnown); 1754 (void)Success; 1755 assert(Success && "Assumed call site replacement to succeed!"); 1756 1757 // Rewire the arguments. 1758 auto OldFnArgIt = OldFn->arg_begin(); 1759 auto NewFnArgIt = NewFn->arg_begin(); 1760 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); 1761 ++OldArgNum, ++OldFnArgIt) { 1762 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1763 ARIs[OldArgNum]) { 1764 if (ARI->CalleeRepairCB) 1765 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt); 1766 NewFnArgIt += ARI->ReplacementTypes.size(); 1767 } else { 1768 NewFnArgIt->takeName(&*OldFnArgIt); 1769 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt); 1770 ++NewFnArgIt; 1771 } 1772 } 1773 1774 // Eliminate the instructions *after* we visited all of them. 1775 for (auto &CallSitePair : CallSitePairs) { 1776 CallBase &OldCB = *CallSitePair.first; 1777 CallBase &NewCB = *CallSitePair.second; 1778 assert(OldCB.getType() == NewCB.getType() && 1779 "Cannot handle call sites with different types!"); 1780 ModifiedFns.insert(OldCB.getFunction()); 1781 CGUpdater.replaceCallSite(OldCB, NewCB); 1782 OldCB.replaceAllUsesWith(&NewCB); 1783 OldCB.eraseFromParent(); 1784 } 1785 1786 // Replace the function in the call graph (if any). 1787 CGUpdater.replaceFunctionWith(*OldFn, *NewFn); 1788 1789 // If the old function was modified and needed to be reanalyzed, the new one 1790 // does now. 1791 if (ModifiedFns.erase(OldFn)) 1792 ModifiedFns.insert(NewFn); 1793 1794 Changed = ChangeStatus::CHANGED; 1795 } 1796 1797 return Changed; 1798 } 1799 1800 void InformationCache::initializeInformationCache(const Function &CF, 1801 FunctionInfo &FI) { 1802 // As we do not modify the function here we can remove the const 1803 // withouth breaking implicit assumptions. At the end of the day, we could 1804 // initialize the cache eagerly which would look the same to the users. 1805 Function &F = const_cast<Function &>(CF); 1806 1807 // Walk all instructions to find interesting instructions that might be 1808 // queried by abstract attributes during their initialization or update. 1809 // This has to happen before we create attributes. 1810 1811 for (Instruction &I : instructions(&F)) { 1812 bool IsInterestingOpcode = false; 1813 1814 // To allow easy access to all instructions in a function with a given 1815 // opcode we store them in the InfoCache. As not all opcodes are interesting 1816 // to concrete attributes we only cache the ones that are as identified in 1817 // the following switch. 1818 // Note: There are no concrete attributes now so this is initially empty. 1819 switch (I.getOpcode()) { 1820 default: 1821 assert(!isa<CallBase>(&I) && 1822 "New call base instruction type needs to be known in the " 1823 "Attributor."); 1824 break; 1825 case Instruction::Call: 1826 // Calls are interesting on their own, additionally: 1827 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them. 1828 // For `must-tail` calls we remember the caller and callee. 1829 if (IntrinsicInst *Assume = dyn_cast<IntrinsicInst>(&I)) { 1830 if (Assume->getIntrinsicID() == Intrinsic::assume) 1831 fillMapFromAssume(*Assume, KnowledgeMap); 1832 } else if (cast<CallInst>(I).isMustTailCall()) { 1833 FI.ContainsMustTailCall = true; 1834 if (const Function *Callee = cast<CallInst>(I).getCalledFunction()) 1835 getFunctionInfo(*Callee).CalledViaMustTail = true; 1836 } 1837 LLVM_FALLTHROUGH; 1838 case Instruction::CallBr: 1839 case Instruction::Invoke: 1840 case Instruction::CleanupRet: 1841 case Instruction::CatchSwitch: 1842 case Instruction::AtomicRMW: 1843 case Instruction::AtomicCmpXchg: 1844 case Instruction::Br: 1845 case Instruction::Resume: 1846 case Instruction::Ret: 1847 case Instruction::Load: 1848 // The alignment of a pointer is interesting for loads. 1849 case Instruction::Store: 1850 // The alignment of a pointer is interesting for stores. 1851 IsInterestingOpcode = true; 1852 } 1853 if (IsInterestingOpcode) { 1854 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()]; 1855 if (!Insts) 1856 Insts = new (Allocator) InstructionVectorTy(); 1857 Insts->push_back(&I); 1858 } 1859 if (I.mayReadOrWriteMemory()) 1860 FI.RWInsts.push_back(&I); 1861 } 1862 1863 if (F.hasFnAttribute(Attribute::AlwaysInline) && 1864 isInlineViable(F).isSuccess()) 1865 InlineableFunctions.insert(&F); 1866 } 1867 1868 InformationCache::FunctionInfo::~FunctionInfo() { 1869 // The instruction vectors are allocated using a BumpPtrAllocator, we need to 1870 // manually destroy them. 1871 for (auto &It : OpcodeInstMap) 1872 It.getSecond()->~InstructionVectorTy(); 1873 } 1874 1875 void Attributor::recordDependence(const AbstractAttribute &FromAA, 1876 const AbstractAttribute &ToAA, 1877 DepClassTy DepClass) { 1878 // If we are outside of an update, thus before the actual fixpoint iteration 1879 // started (= when we create AAs), we do not track dependences because we will 1880 // put all AAs into the initial worklist anyway. 1881 if (DependenceStack.empty()) 1882 return; 1883 if (FromAA.getState().isAtFixpoint()) 1884 return; 1885 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass}); 1886 } 1887 1888 void Attributor::rememberDependences() { 1889 assert(!DependenceStack.empty() && "No dependences to remember!"); 1890 1891 for (DepInfo &DI : *DependenceStack.back()) { 1892 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps; 1893 DepAAs.push_back(AbstractAttribute::DepTy( 1894 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass))); 1895 } 1896 } 1897 1898 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 1899 if (!VisitedFunctions.insert(&F).second) 1900 return; 1901 if (F.isDeclaration()) 1902 return; 1903 1904 // In non-module runs we need to look at the call sites of a function to 1905 // determine if it is part of a must-tail call edge. This will influence what 1906 // attributes we can derive. 1907 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F); 1908 if (!isModulePass() && !FI.CalledViaMustTail) { 1909 for (const Use &U : F.uses()) 1910 if (const auto *CB = dyn_cast<CallBase>(U.getUser())) 1911 if (CB->isCallee(&U) && CB->isMustTailCall()) 1912 FI.CalledViaMustTail = true; 1913 } 1914 1915 IRPosition FPos = IRPosition::function(F); 1916 1917 // Check for dead BasicBlocks in every function. 1918 // We need dead instruction detection because we do not want to deal with 1919 // broken IR in which SSA rules do not apply. 1920 getOrCreateAAFor<AAIsDead>(FPos); 1921 1922 // Every function might be "will-return". 1923 getOrCreateAAFor<AAWillReturn>(FPos); 1924 1925 // Every function might contain instructions that cause "undefined behavior". 1926 getOrCreateAAFor<AAUndefinedBehavior>(FPos); 1927 1928 // Every function can be nounwind. 1929 getOrCreateAAFor<AANoUnwind>(FPos); 1930 1931 // Every function might be marked "nosync" 1932 getOrCreateAAFor<AANoSync>(FPos); 1933 1934 // Every function might be "no-free". 1935 getOrCreateAAFor<AANoFree>(FPos); 1936 1937 // Every function might be "no-return". 1938 getOrCreateAAFor<AANoReturn>(FPos); 1939 1940 // Every function might be "no-recurse". 1941 getOrCreateAAFor<AANoRecurse>(FPos); 1942 1943 // Every function might be "readnone/readonly/writeonly/...". 1944 getOrCreateAAFor<AAMemoryBehavior>(FPos); 1945 1946 // Every function can be "readnone/argmemonly/inaccessiblememonly/...". 1947 getOrCreateAAFor<AAMemoryLocation>(FPos); 1948 1949 // Every function might be applicable for Heap-To-Stack conversion. 1950 if (EnableHeapToStack) 1951 getOrCreateAAFor<AAHeapToStack>(FPos); 1952 1953 // Return attributes are only appropriate if the return type is non void. 1954 Type *ReturnType = F.getReturnType(); 1955 if (!ReturnType->isVoidTy()) { 1956 // Argument attribute "returned" --- Create only one per function even 1957 // though it is an argument attribute. 1958 getOrCreateAAFor<AAReturnedValues>(FPos); 1959 1960 IRPosition RetPos = IRPosition::returned(F); 1961 1962 // Every returned value might be dead. 1963 getOrCreateAAFor<AAIsDead>(RetPos); 1964 1965 // Every function might be simplified. 1966 getOrCreateAAFor<AAValueSimplify>(RetPos); 1967 1968 // Every returned value might be marked noundef. 1969 getOrCreateAAFor<AANoUndef>(RetPos); 1970 1971 if (ReturnType->isPointerTy()) { 1972 1973 // Every function with pointer return type might be marked align. 1974 getOrCreateAAFor<AAAlign>(RetPos); 1975 1976 // Every function with pointer return type might be marked nonnull. 1977 getOrCreateAAFor<AANonNull>(RetPos); 1978 1979 // Every function with pointer return type might be marked noalias. 1980 getOrCreateAAFor<AANoAlias>(RetPos); 1981 1982 // Every function with pointer return type might be marked 1983 // dereferenceable. 1984 getOrCreateAAFor<AADereferenceable>(RetPos); 1985 } 1986 } 1987 1988 for (Argument &Arg : F.args()) { 1989 IRPosition ArgPos = IRPosition::argument(Arg); 1990 1991 // Every argument might be simplified. 1992 getOrCreateAAFor<AAValueSimplify>(ArgPos); 1993 1994 // Every argument might be dead. 1995 getOrCreateAAFor<AAIsDead>(ArgPos); 1996 1997 // Every argument might be marked noundef. 1998 getOrCreateAAFor<AANoUndef>(ArgPos); 1999 2000 if (Arg.getType()->isPointerTy()) { 2001 // Every argument with pointer type might be marked nonnull. 2002 getOrCreateAAFor<AANonNull>(ArgPos); 2003 2004 // Every argument with pointer type might be marked noalias. 2005 getOrCreateAAFor<AANoAlias>(ArgPos); 2006 2007 // Every argument with pointer type might be marked dereferenceable. 2008 getOrCreateAAFor<AADereferenceable>(ArgPos); 2009 2010 // Every argument with pointer type might be marked align. 2011 getOrCreateAAFor<AAAlign>(ArgPos); 2012 2013 // Every argument with pointer type might be marked nocapture. 2014 getOrCreateAAFor<AANoCapture>(ArgPos); 2015 2016 // Every argument with pointer type might be marked 2017 // "readnone/readonly/writeonly/..." 2018 getOrCreateAAFor<AAMemoryBehavior>(ArgPos); 2019 2020 // Every argument with pointer type might be marked nofree. 2021 getOrCreateAAFor<AANoFree>(ArgPos); 2022 2023 // Every argument with pointer type might be privatizable (or promotable) 2024 getOrCreateAAFor<AAPrivatizablePtr>(ArgPos); 2025 } 2026 } 2027 2028 auto CallSitePred = [&](Instruction &I) -> bool { 2029 auto &CB = cast<CallBase>(I); 2030 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 2031 2032 // Call sites might be dead if they do not have side effects and no live 2033 // users. The return value might be dead if there are no live users. 2034 getOrCreateAAFor<AAIsDead>(CBRetPos); 2035 2036 Function *Callee = CB.getCalledFunction(); 2037 // TODO: Even if the callee is not known now we might be able to simplify 2038 // the call/callee. 2039 if (!Callee) 2040 return true; 2041 2042 // Skip declarations except if annotations on their call sites were 2043 // explicitly requested. 2044 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() && 2045 !Callee->hasMetadata(LLVMContext::MD_callback)) 2046 return true; 2047 2048 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) { 2049 2050 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 2051 2052 // Call site return integer values might be limited by a constant range. 2053 if (Callee->getReturnType()->isIntegerTy()) 2054 getOrCreateAAFor<AAValueConstantRange>(CBRetPos); 2055 } 2056 2057 for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) { 2058 2059 IRPosition CBArgPos = IRPosition::callsite_argument(CB, I); 2060 2061 // Every call site argument might be dead. 2062 getOrCreateAAFor<AAIsDead>(CBArgPos); 2063 2064 // Call site argument might be simplified. 2065 getOrCreateAAFor<AAValueSimplify>(CBArgPos); 2066 2067 // Every call site argument might be marked "noundef". 2068 getOrCreateAAFor<AANoUndef>(CBArgPos); 2069 2070 if (!CB.getArgOperand(I)->getType()->isPointerTy()) 2071 continue; 2072 2073 // Call site argument attribute "non-null". 2074 getOrCreateAAFor<AANonNull>(CBArgPos); 2075 2076 // Call site argument attribute "nocapture". 2077 getOrCreateAAFor<AANoCapture>(CBArgPos); 2078 2079 // Call site argument attribute "no-alias". 2080 getOrCreateAAFor<AANoAlias>(CBArgPos); 2081 2082 // Call site argument attribute "dereferenceable". 2083 getOrCreateAAFor<AADereferenceable>(CBArgPos); 2084 2085 // Call site argument attribute "align". 2086 getOrCreateAAFor<AAAlign>(CBArgPos); 2087 2088 // Call site argument attribute 2089 // "readnone/readonly/writeonly/..." 2090 getOrCreateAAFor<AAMemoryBehavior>(CBArgPos); 2091 2092 // Call site argument attribute "nofree". 2093 getOrCreateAAFor<AANoFree>(CBArgPos); 2094 } 2095 return true; 2096 }; 2097 2098 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); 2099 bool Success; 2100 Success = checkForAllInstructionsImpl( 2101 nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr, 2102 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 2103 (unsigned)Instruction::Call}); 2104 (void)Success; 2105 assert(Success && "Expected the check call to be successful!"); 2106 2107 auto LoadStorePred = [&](Instruction &I) -> bool { 2108 if (isa<LoadInst>(I)) 2109 getOrCreateAAFor<AAAlign>( 2110 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 2111 else 2112 getOrCreateAAFor<AAAlign>( 2113 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 2114 return true; 2115 }; 2116 Success = checkForAllInstructionsImpl( 2117 nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr, 2118 {(unsigned)Instruction::Load, (unsigned)Instruction::Store}); 2119 (void)Success; 2120 assert(Success && "Expected the check call to be successful!"); 2121 } 2122 2123 /// Helpers to ease debugging through output streams and print calls. 2124 /// 2125 ///{ 2126 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 2127 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 2128 } 2129 2130 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 2131 switch (AP) { 2132 case IRPosition::IRP_INVALID: 2133 return OS << "inv"; 2134 case IRPosition::IRP_FLOAT: 2135 return OS << "flt"; 2136 case IRPosition::IRP_RETURNED: 2137 return OS << "fn_ret"; 2138 case IRPosition::IRP_CALL_SITE_RETURNED: 2139 return OS << "cs_ret"; 2140 case IRPosition::IRP_FUNCTION: 2141 return OS << "fn"; 2142 case IRPosition::IRP_CALL_SITE: 2143 return OS << "cs"; 2144 case IRPosition::IRP_ARGUMENT: 2145 return OS << "arg"; 2146 case IRPosition::IRP_CALL_SITE_ARGUMENT: 2147 return OS << "cs_arg"; 2148 } 2149 llvm_unreachable("Unknown attribute position!"); 2150 } 2151 2152 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 2153 const Value &AV = Pos.getAssociatedValue(); 2154 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 2155 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 2156 } 2157 2158 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) { 2159 OS << "range-state(" << S.getBitWidth() << ")<"; 2160 S.getKnown().print(OS); 2161 OS << " / "; 2162 S.getAssumed().print(OS); 2163 OS << ">"; 2164 2165 return OS << static_cast<const AbstractState &>(S); 2166 } 2167 2168 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 2169 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 2170 } 2171 2172 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 2173 AA.print(OS); 2174 return OS; 2175 } 2176 2177 raw_ostream &llvm::operator<<(raw_ostream &OS, 2178 const PotentialConstantIntValuesState &S) { 2179 OS << "set-state(< {"; 2180 if (!S.isValidState()) 2181 OS << "full-set"; 2182 else { 2183 for (auto &it : S.getAssumedSet()) 2184 OS << it << ", "; 2185 if (S.undefIsContained()) 2186 OS << "undef "; 2187 } 2188 OS << "} >)"; 2189 2190 return OS; 2191 } 2192 2193 void AbstractAttribute::print(raw_ostream &OS) const { 2194 OS << "["; 2195 OS << getName(); 2196 OS << "] for CtxI "; 2197 2198 if (auto *I = getCtxI()) { 2199 OS << "'"; 2200 I->print(OS); 2201 OS << "'"; 2202 } else 2203 OS << "<<null inst>>"; 2204 2205 OS << " at position " << getIRPosition() << " with state " << getAsStr() 2206 << '\n'; 2207 } 2208 2209 void AbstractAttribute::printWithDeps(raw_ostream &OS) const { 2210 print(OS); 2211 2212 for (const auto &DepAA : Deps) { 2213 auto *AA = DepAA.getPointer(); 2214 OS << " updates "; 2215 AA->print(OS); 2216 } 2217 2218 OS << '\n'; 2219 } 2220 ///} 2221 2222 /// ---------------------------------------------------------------------------- 2223 /// Pass (Manager) Boilerplate 2224 /// ---------------------------------------------------------------------------- 2225 2226 static bool runAttributorOnFunctions(InformationCache &InfoCache, 2227 SetVector<Function *> &Functions, 2228 AnalysisGetter &AG, 2229 CallGraphUpdater &CGUpdater) { 2230 if (Functions.empty()) 2231 return false; 2232 2233 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << Functions.size() 2234 << " functions.\n"); 2235 2236 // Create an Attributor and initially empty information cache that is filled 2237 // while we identify default attribute opportunities. 2238 Attributor A(Functions, InfoCache, CGUpdater); 2239 2240 // Create shallow wrappers for all functions that are not IPO amendable 2241 if (AllowShallowWrappers) 2242 for (Function *F : Functions) 2243 if (!A.isFunctionIPOAmendable(*F)) 2244 createShallowWrapper(*F); 2245 2246 // Internalize non-exact functions 2247 // TODO: for now we eagerly internalize functions without calculating the 2248 // cost, we need a cost interface to determine whether internalizing 2249 // a function is "benefitial" 2250 if (AllowDeepWrapper) { 2251 unsigned FunSize = Functions.size(); 2252 for (unsigned u = 0; u < FunSize; u++) { 2253 Function *F = Functions[u]; 2254 if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() && 2255 !GlobalValue::isInterposableLinkage(F->getLinkage())) { 2256 Function *NewF = internalizeFunction(*F); 2257 Functions.insert(NewF); 2258 2259 // Update call graph 2260 CGUpdater.replaceFunctionWith(*F, *NewF); 2261 for (const Use &U : NewF->uses()) 2262 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) { 2263 auto *CallerF = CB->getCaller(); 2264 CGUpdater.reanalyzeFunction(*CallerF); 2265 } 2266 } 2267 } 2268 } 2269 2270 for (Function *F : Functions) { 2271 if (F->hasExactDefinition()) 2272 NumFnWithExactDefinition++; 2273 else 2274 NumFnWithoutExactDefinition++; 2275 2276 // We look at internal functions only on-demand but if any use is not a 2277 // direct call or outside the current set of analyzed functions, we have 2278 // to do it eagerly. 2279 if (F->hasLocalLinkage()) { 2280 if (llvm::all_of(F->uses(), [&Functions](const Use &U) { 2281 const auto *CB = dyn_cast<CallBase>(U.getUser()); 2282 return CB && CB->isCallee(&U) && 2283 Functions.count(const_cast<Function *>(CB->getCaller())); 2284 })) 2285 continue; 2286 } 2287 2288 // Populate the Attributor with abstract attribute opportunities in the 2289 // function and the information cache with IR information. 2290 A.identifyDefaultAbstractAttributes(*F); 2291 } 2292 2293 ChangeStatus Changed = A.run(); 2294 2295 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size() 2296 << " functions, result: " << Changed << ".\n"); 2297 return Changed == ChangeStatus::CHANGED; 2298 } 2299 2300 void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); } 2301 2302 void AADepGraph::dumpGraph() { 2303 static std::atomic<int> CallTimes; 2304 std::string Prefix; 2305 2306 if (!DepGraphDotFileNamePrefix.empty()) 2307 Prefix = DepGraphDotFileNamePrefix; 2308 else 2309 Prefix = "dep_graph"; 2310 std::string Filename = 2311 Prefix + "_" + std::to_string(CallTimes.load()) + ".dot"; 2312 2313 outs() << "Dependency graph dump to " << Filename << ".\n"; 2314 2315 std::error_code EC; 2316 2317 raw_fd_ostream File(Filename, EC, sys::fs::OF_Text); 2318 if (!EC) 2319 llvm::WriteGraph(File, this); 2320 2321 CallTimes++; 2322 } 2323 2324 void AADepGraph::print() { 2325 for (auto DepAA : SyntheticRoot.Deps) 2326 cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs()); 2327 } 2328 2329 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 2330 FunctionAnalysisManager &FAM = 2331 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2332 AnalysisGetter AG(FAM); 2333 2334 SetVector<Function *> Functions; 2335 for (Function &F : M) 2336 Functions.insert(&F); 2337 2338 CallGraphUpdater CGUpdater; 2339 BumpPtrAllocator Allocator; 2340 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2341 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2342 // FIXME: Think about passes we will preserve and add them here. 2343 return PreservedAnalyses::none(); 2344 } 2345 return PreservedAnalyses::all(); 2346 } 2347 2348 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C, 2349 CGSCCAnalysisManager &AM, 2350 LazyCallGraph &CG, 2351 CGSCCUpdateResult &UR) { 2352 FunctionAnalysisManager &FAM = 2353 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 2354 AnalysisGetter AG(FAM); 2355 2356 SetVector<Function *> Functions; 2357 for (LazyCallGraph::Node &N : C) 2358 Functions.insert(&N.getFunction()); 2359 2360 if (Functions.empty()) 2361 return PreservedAnalyses::all(); 2362 2363 Module &M = *Functions.back()->getParent(); 2364 CallGraphUpdater CGUpdater; 2365 CGUpdater.initialize(CG, C, AM, UR); 2366 BumpPtrAllocator Allocator; 2367 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2368 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2369 // FIXME: Think about passes we will preserve and add them here. 2370 PreservedAnalyses PA; 2371 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 2372 return PA; 2373 } 2374 return PreservedAnalyses::all(); 2375 } 2376 2377 namespace llvm { 2378 2379 template <> struct GraphTraits<AADepGraphNode *> { 2380 using NodeRef = AADepGraphNode *; 2381 using DepTy = PointerIntPair<AADepGraphNode *, 1>; 2382 using EdgeRef = PointerIntPair<AADepGraphNode *, 1>; 2383 2384 static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; } 2385 static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); } 2386 2387 using ChildIteratorType = 2388 mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>; 2389 using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator; 2390 2391 static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); } 2392 2393 static ChildIteratorType child_end(NodeRef N) { return N->child_end(); } 2394 }; 2395 2396 template <> 2397 struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> { 2398 static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); } 2399 2400 using nodes_iterator = 2401 mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>; 2402 2403 static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); } 2404 2405 static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); } 2406 }; 2407 2408 template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits { 2409 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 2410 2411 static std::string getNodeLabel(const AADepGraphNode *Node, 2412 const AADepGraph *DG) { 2413 std::string AAString = ""; 2414 raw_string_ostream O(AAString); 2415 Node->print(O); 2416 return AAString; 2417 } 2418 }; 2419 2420 } // end namespace llvm 2421 2422 namespace { 2423 2424 struct AttributorLegacyPass : public ModulePass { 2425 static char ID; 2426 2427 AttributorLegacyPass() : ModulePass(ID) { 2428 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 2429 } 2430 2431 bool runOnModule(Module &M) override { 2432 if (skipModule(M)) 2433 return false; 2434 2435 AnalysisGetter AG; 2436 SetVector<Function *> Functions; 2437 for (Function &F : M) 2438 Functions.insert(&F); 2439 2440 CallGraphUpdater CGUpdater; 2441 BumpPtrAllocator Allocator; 2442 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2443 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2444 } 2445 2446 void getAnalysisUsage(AnalysisUsage &AU) const override { 2447 // FIXME: Think about passes we will preserve and add them here. 2448 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2449 } 2450 }; 2451 2452 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass { 2453 CallGraphUpdater CGUpdater; 2454 static char ID; 2455 2456 AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) { 2457 initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 2458 } 2459 2460 bool runOnSCC(CallGraphSCC &SCC) override { 2461 if (skipSCC(SCC)) 2462 return false; 2463 2464 SetVector<Function *> Functions; 2465 for (CallGraphNode *CGN : SCC) 2466 if (Function *Fn = CGN->getFunction()) 2467 if (!Fn->isDeclaration()) 2468 Functions.insert(Fn); 2469 2470 if (Functions.empty()) 2471 return false; 2472 2473 AnalysisGetter AG; 2474 CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph()); 2475 CGUpdater.initialize(CG, SCC); 2476 Module &M = *Functions.back()->getParent(); 2477 BumpPtrAllocator Allocator; 2478 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2479 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2480 } 2481 2482 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 2483 2484 void getAnalysisUsage(AnalysisUsage &AU) const override { 2485 // FIXME: Think about passes we will preserve and add them here. 2486 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2487 CallGraphSCCPass::getAnalysisUsage(AU); 2488 } 2489 }; 2490 2491 } // end anonymous namespace 2492 2493 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 2494 Pass *llvm::createAttributorCGSCCLegacyPass() { 2495 return new AttributorCGSCCLegacyPass(); 2496 } 2497 2498 char AttributorLegacyPass::ID = 0; 2499 char AttributorCGSCCLegacyPass::ID = 0; 2500 2501 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 2502 "Deduce and propagate attributes", false, false) 2503 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2504 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 2505 "Deduce and propagate attributes", false, false) 2506 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc", 2507 "Deduce and propagate attributes (CGSCC pass)", false, 2508 false) 2509 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2510 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2511 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc", 2512 "Deduce and propagate attributes (CGSCC pass)", false, 2513 false) 2514