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