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