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