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 ChangeStatus Attributor::run() { 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 size_t NumFinalAAs = AllAbstractAttributes.size(); 992 993 // Reset abstract arguments not settled in a sound fixpoint by now. This 994 // happens when we stopped the fixpoint iteration early. Note that only the 995 // ones marked as "changed" *and* the ones transitively depending on them 996 // need to be reverted to a pessimistic state. Others might not be in a 997 // fixpoint state but we can use the optimistic results for them anyway. 998 SmallPtrSet<AbstractAttribute *, 32> Visited; 999 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 1000 AbstractAttribute *ChangedAA = ChangedAAs[u]; 1001 if (!Visited.insert(ChangedAA).second) 1002 continue; 1003 1004 AbstractState &State = ChangedAA->getState(); 1005 if (!State.isAtFixpoint()) { 1006 State.indicatePessimisticFixpoint(); 1007 1008 NumAttributesTimedOut++; 1009 } 1010 1011 while (!ChangedAA->Deps.empty()) { 1012 ChangedAAs.push_back(ChangedAA->Deps.back().getPointer()); 1013 ChangedAA->Deps.pop_back(); 1014 } 1015 } 1016 1017 LLVM_DEBUG({ 1018 if (!Visited.empty()) 1019 dbgs() << "\n[Attributor] Finalized " << Visited.size() 1020 << " abstract attributes.\n"; 1021 }); 1022 1023 unsigned NumManifested = 0; 1024 unsigned NumAtFixpoint = 0; 1025 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 1026 for (AbstractAttribute *AA : AllAbstractAttributes) { 1027 AbstractState &State = AA->getState(); 1028 1029 // If there is not already a fixpoint reached, we can now take the 1030 // optimistic state. This is correct because we enforced a pessimistic one 1031 // on abstract attributes that were transitively dependent on a changed one 1032 // already above. 1033 if (!State.isAtFixpoint()) 1034 State.indicateOptimisticFixpoint(); 1035 1036 // If the state is invalid, we do not try to manifest it. 1037 if (!State.isValidState()) 1038 continue; 1039 1040 // Skip dead code. 1041 if (isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true)) 1042 continue; 1043 // Manifest the state and record if we changed the IR. 1044 ChangeStatus LocalChange = AA->manifest(*this); 1045 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 1046 AA->trackStatistics(); 1047 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA 1048 << "\n"); 1049 1050 ManifestChange = ManifestChange | LocalChange; 1051 1052 NumAtFixpoint++; 1053 NumManifested += (LocalChange == ChangeStatus::CHANGED); 1054 } 1055 1056 (void)NumManifested; 1057 (void)NumAtFixpoint; 1058 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 1059 << " arguments while " << NumAtFixpoint 1060 << " were in a valid fixpoint state\n"); 1061 1062 NumAttributesManifested += NumManifested; 1063 NumAttributesValidFixpoint += NumAtFixpoint; 1064 1065 (void)NumFinalAAs; 1066 if (NumFinalAAs != AllAbstractAttributes.size()) { 1067 for (unsigned u = NumFinalAAs; u < AllAbstractAttributes.size(); ++u) 1068 errs() << "Unexpected abstract attribute: " << *AllAbstractAttributes[u] 1069 << " :: " 1070 << AllAbstractAttributes[u]->getIRPosition().getAssociatedValue() 1071 << "\n"; 1072 llvm_unreachable("Expected the final number of abstract attributes to " 1073 "remain unchanged!"); 1074 } 1075 1076 // Delete stuff at the end to avoid invalid references and a nice order. 1077 { 1078 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least " 1079 << ToBeDeletedFunctions.size() << " functions and " 1080 << ToBeDeletedBlocks.size() << " blocks and " 1081 << ToBeDeletedInsts.size() << " instructions and " 1082 << ToBeChangedUses.size() << " uses\n"); 1083 1084 SmallVector<WeakTrackingVH, 32> DeadInsts; 1085 SmallVector<Instruction *, 32> TerminatorsToFold; 1086 1087 for (auto &It : ToBeChangedUses) { 1088 Use *U = It.first; 1089 Value *NewV = It.second; 1090 Value *OldV = U->get(); 1091 1092 // Do not replace uses in returns if the value is a must-tail call we will 1093 // not delete. 1094 if (isa<ReturnInst>(U->getUser())) 1095 if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts())) 1096 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI)) 1097 continue; 1098 1099 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser() 1100 << " instead of " << *OldV << "\n"); 1101 U->set(NewV); 1102 // Do not modify call instructions outside the SCC. 1103 if (auto *CB = dyn_cast<CallBase>(OldV)) 1104 if (!Functions.count(CB->getCaller())) 1105 continue; 1106 if (Instruction *I = dyn_cast<Instruction>(OldV)) { 1107 CGModifiedFunctions.insert(I->getFunction()); 1108 if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) && 1109 isInstructionTriviallyDead(I)) 1110 DeadInsts.push_back(I); 1111 } 1112 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) { 1113 Instruction *UserI = cast<Instruction>(U->getUser()); 1114 if (isa<UndefValue>(NewV)) { 1115 ToBeChangedToUnreachableInsts.insert(UserI); 1116 } else { 1117 TerminatorsToFold.push_back(UserI); 1118 } 1119 } 1120 } 1121 for (auto &V : InvokeWithDeadSuccessor) 1122 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) { 1123 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind); 1124 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn); 1125 bool Invoke2CallAllowed = 1126 !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction()); 1127 assert((UnwindBBIsDead || NormalBBIsDead) && 1128 "Invoke does not have dead successors!"); 1129 BasicBlock *BB = II->getParent(); 1130 BasicBlock *NormalDestBB = II->getNormalDest(); 1131 if (UnwindBBIsDead) { 1132 Instruction *NormalNextIP = &NormalDestBB->front(); 1133 if (Invoke2CallAllowed) { 1134 changeToCall(II); 1135 NormalNextIP = BB->getTerminator(); 1136 } 1137 if (NormalBBIsDead) 1138 ToBeChangedToUnreachableInsts.insert(NormalNextIP); 1139 } else { 1140 assert(NormalBBIsDead && "Broken invariant!"); 1141 if (!NormalDestBB->getUniquePredecessor()) 1142 NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 1143 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front()); 1144 } 1145 } 1146 for (Instruction *I : TerminatorsToFold) { 1147 CGModifiedFunctions.insert(I->getFunction()); 1148 ConstantFoldTerminator(I->getParent()); 1149 } 1150 for (auto &V : ToBeChangedToUnreachableInsts) 1151 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1152 CGModifiedFunctions.insert(I->getFunction()); 1153 changeToUnreachable(I, /* UseLLVMTrap */ false); 1154 } 1155 1156 for (auto &V : ToBeDeletedInsts) { 1157 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1158 I->dropDroppableUses(); 1159 CGModifiedFunctions.insert(I->getFunction()); 1160 if (!I->getType()->isVoidTy()) 1161 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1162 if (!isa<PHINode>(I) && isInstructionTriviallyDead(I)) 1163 DeadInsts.push_back(I); 1164 else 1165 I->eraseFromParent(); 1166 } 1167 } 1168 1169 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 1170 1171 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 1172 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 1173 ToBeDeletedBBs.reserve(NumDeadBlocks); 1174 for (BasicBlock *BB : ToBeDeletedBlocks) { 1175 CGModifiedFunctions.insert(BB->getParent()); 1176 ToBeDeletedBBs.push_back(BB); 1177 } 1178 // Actually we do not delete the blocks but squash them into a single 1179 // unreachable but untangling branches that jump here is something we need 1180 // to do in a more generic way. 1181 DetatchDeadBlocks(ToBeDeletedBBs, nullptr); 1182 } 1183 1184 // Identify dead internal functions and delete them. This happens outside 1185 // the other fixpoint analysis as we might treat potentially dead functions 1186 // as live to lower the number of iterations. If they happen to be dead, the 1187 // below fixpoint loop will identify and eliminate them. 1188 SmallVector<Function *, 8> InternalFns; 1189 for (Function *F : Functions) 1190 if (F->hasLocalLinkage()) 1191 InternalFns.push_back(F); 1192 1193 bool FoundDeadFn = true; 1194 while (FoundDeadFn) { 1195 FoundDeadFn = false; 1196 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 1197 Function *F = InternalFns[u]; 1198 if (!F) 1199 continue; 1200 1201 bool AllCallSitesKnown; 1202 if (!checkForAllCallSites( 1203 [this](AbstractCallSite ACS) { 1204 return ToBeDeletedFunctions.count( 1205 ACS.getInstruction()->getFunction()); 1206 }, 1207 *F, true, nullptr, AllCallSitesKnown)) 1208 continue; 1209 1210 ToBeDeletedFunctions.insert(F); 1211 InternalFns[u] = nullptr; 1212 FoundDeadFn = true; 1213 } 1214 } 1215 } 1216 1217 // Rewrite the functions as requested during manifest. 1218 ManifestChange = 1219 ManifestChange | rewriteFunctionSignatures(CGModifiedFunctions); 1220 1221 for (Function *Fn : CGModifiedFunctions) 1222 CGUpdater.reanalyzeFunction(*Fn); 1223 1224 for (Function *Fn : ToBeDeletedFunctions) 1225 CGUpdater.removeFunction(*Fn); 1226 1227 NumFnDeleted += ToBeDeletedFunctions.size(); 1228 1229 if (VerifyMaxFixpointIterations && 1230 IterationCounter != MaxFixpointIterations) { 1231 errs() << "\n[Attributor] Fixpoint iteration done after: " 1232 << IterationCounter << "/" << MaxFixpointIterations 1233 << " iterations\n"; 1234 llvm_unreachable("The fixpoint was not reached with exactly the number of " 1235 "specified iterations!"); 1236 } 1237 1238 #ifdef EXPENSIVE_CHECKS 1239 for (Function *F : Functions) { 1240 if (ToBeDeletedFunctions.count(F)) 1241 continue; 1242 assert(!verifyFunction(*F, &errs()) && "Module verification failed!"); 1243 } 1244 #endif 1245 1246 return ManifestChange; 1247 } 1248 1249 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) { 1250 // Use a new dependence vector for this update. 1251 DependenceVector DV; 1252 DependenceStack.push_back(&DV); 1253 1254 auto &AAState = AA.getState(); 1255 ChangeStatus CS = ChangeStatus::UNCHANGED; 1256 if (!isAssumedDead(AA, nullptr, /* CheckBBLivenessOnly */ true)) 1257 CS = AA.update(*this); 1258 1259 if (DV.empty()) { 1260 // If the attribute did not query any non-fix information, the state 1261 // will not change and we can indicate that right away. 1262 AAState.indicateOptimisticFixpoint(); 1263 } 1264 1265 if (!AAState.isAtFixpoint()) 1266 rememberDependences(); 1267 1268 // Verify the stack was used properly, that is we pop the dependence vector we 1269 // put there earlier. 1270 DependenceVector *PoppedDV = DependenceStack.pop_back_val(); 1271 (void)PoppedDV; 1272 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!"); 1273 1274 return CS; 1275 } 1276 1277 /// Create a shallow wrapper for \p F such that \p F has internal linkage 1278 /// afterwards. It also sets the original \p F 's name to anonymous 1279 /// 1280 /// A wrapper is a function with the same type (and attributes) as \p F 1281 /// that will only call \p F and return the result, if any. 1282 /// 1283 /// Assuming the declaration of looks like: 1284 /// rty F(aty0 arg0, ..., atyN argN); 1285 /// 1286 /// The wrapper will then look as follows: 1287 /// rty wrapper(aty0 arg0, ..., atyN argN) { 1288 /// return F(arg0, ..., argN); 1289 /// } 1290 /// 1291 static void createShallowWrapper(Function &F) { 1292 assert(AllowShallowWrappers && 1293 "Cannot create a wrapper if it is not allowed!"); 1294 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!"); 1295 1296 Module &M = *F.getParent(); 1297 LLVMContext &Ctx = M.getContext(); 1298 FunctionType *FnTy = F.getFunctionType(); 1299 1300 Function *Wrapper = 1301 Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName()); 1302 F.setName(""); // set the inside function anonymous 1303 M.getFunctionList().insert(F.getIterator(), Wrapper); 1304 1305 F.setLinkage(GlobalValue::InternalLinkage); 1306 1307 F.replaceAllUsesWith(Wrapper); 1308 assert(F.use_empty() && "Uses remained after wrapper was created!"); 1309 1310 // Move the COMDAT section to the wrapper. 1311 // TODO: Check if we need to keep it for F as well. 1312 Wrapper->setComdat(F.getComdat()); 1313 F.setComdat(nullptr); 1314 1315 // Copy all metadata and attributes but keep them on F as well. 1316 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1317 F.getAllMetadata(MDs); 1318 for (auto MDIt : MDs) 1319 Wrapper->addMetadata(MDIt.first, *MDIt.second); 1320 Wrapper->setAttributes(F.getAttributes()); 1321 1322 // Create the call in the wrapper. 1323 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper); 1324 1325 SmallVector<Value *, 8> Args; 1326 auto FArgIt = F.arg_begin(); 1327 for (Argument &Arg : Wrapper->args()) { 1328 Args.push_back(&Arg); 1329 Arg.setName((FArgIt++)->getName()); 1330 } 1331 1332 CallInst *CI = CallInst::Create(&F, Args, "", EntryBB); 1333 CI->setTailCall(true); 1334 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline); 1335 ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB); 1336 1337 NumFnShallowWrapperCreated++; 1338 } 1339 1340 bool Attributor::isValidFunctionSignatureRewrite( 1341 Argument &Arg, ArrayRef<Type *> ReplacementTypes) { 1342 1343 auto CallSiteCanBeChanged = [](AbstractCallSite ACS) { 1344 // Forbid the call site to cast the function return type. If we need to 1345 // rewrite these functions we need to re-create a cast for the new call site 1346 // (if the old had uses). 1347 if (!ACS.getCalledFunction() || 1348 ACS.getInstruction()->getType() != 1349 ACS.getCalledFunction()->getReturnType()) 1350 return false; 1351 // Forbid must-tail calls for now. 1352 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall(); 1353 }; 1354 1355 Function *Fn = Arg.getParent(); 1356 // Avoid var-arg functions for now. 1357 if (Fn->isVarArg()) { 1358 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n"); 1359 return false; 1360 } 1361 1362 // Avoid functions with complicated argument passing semantics. 1363 AttributeList FnAttributeList = Fn->getAttributes(); 1364 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) || 1365 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) || 1366 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca)) { 1367 LLVM_DEBUG( 1368 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n"); 1369 return false; 1370 } 1371 1372 // Avoid callbacks for now. 1373 bool AllCallSitesKnown; 1374 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr, 1375 AllCallSitesKnown)) { 1376 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n"); 1377 return false; 1378 } 1379 1380 auto InstPred = [](Instruction &I) { 1381 if (auto *CI = dyn_cast<CallInst>(&I)) 1382 return !CI->isMustTailCall(); 1383 return true; 1384 }; 1385 1386 // Forbid must-tail calls for now. 1387 // TODO: 1388 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn); 1389 if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr, 1390 nullptr, {Instruction::Call})) { 1391 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n"); 1392 return false; 1393 } 1394 1395 return true; 1396 } 1397 1398 bool Attributor::registerFunctionSignatureRewrite( 1399 Argument &Arg, ArrayRef<Type *> ReplacementTypes, 1400 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, 1401 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) { 1402 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1403 << Arg.getParent()->getName() << " with " 1404 << ReplacementTypes.size() << " replacements\n"); 1405 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) && 1406 "Cannot register an invalid rewrite"); 1407 1408 Function *Fn = Arg.getParent(); 1409 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1410 ArgumentReplacementMap[Fn]; 1411 if (ARIs.empty()) 1412 ARIs.resize(Fn->arg_size()); 1413 1414 // If we have a replacement already with less than or equal new arguments, 1415 // ignore this request. 1416 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()]; 1417 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) { 1418 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n"); 1419 return false; 1420 } 1421 1422 // If we have a replacement already but we like the new one better, delete 1423 // the old. 1424 ARI.reset(); 1425 1426 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1427 << Arg.getParent()->getName() << " with " 1428 << ReplacementTypes.size() << " replacements\n"); 1429 1430 // Remember the replacement. 1431 ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes, 1432 std::move(CalleeRepairCB), 1433 std::move(ACSRepairCB))); 1434 1435 return true; 1436 } 1437 1438 ChangeStatus Attributor::rewriteFunctionSignatures( 1439 SmallPtrSetImpl<Function *> &ModifiedFns) { 1440 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1441 1442 for (auto &It : ArgumentReplacementMap) { 1443 Function *OldFn = It.getFirst(); 1444 1445 // Deleted functions do not require rewrites. 1446 if (ToBeDeletedFunctions.count(OldFn)) 1447 continue; 1448 1449 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1450 It.getSecond(); 1451 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!"); 1452 1453 SmallVector<Type *, 16> NewArgumentTypes; 1454 SmallVector<AttributeSet, 16> NewArgumentAttributes; 1455 1456 // Collect replacement argument types and copy over existing attributes. 1457 AttributeList OldFnAttributeList = OldFn->getAttributes(); 1458 for (Argument &Arg : OldFn->args()) { 1459 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1460 ARIs[Arg.getArgNo()]) { 1461 NewArgumentTypes.append(ARI->ReplacementTypes.begin(), 1462 ARI->ReplacementTypes.end()); 1463 NewArgumentAttributes.append(ARI->getNumReplacementArgs(), 1464 AttributeSet()); 1465 } else { 1466 NewArgumentTypes.push_back(Arg.getType()); 1467 NewArgumentAttributes.push_back( 1468 OldFnAttributeList.getParamAttributes(Arg.getArgNo())); 1469 } 1470 } 1471 1472 FunctionType *OldFnTy = OldFn->getFunctionType(); 1473 Type *RetTy = OldFnTy->getReturnType(); 1474 1475 // Construct the new function type using the new arguments types. 1476 FunctionType *NewFnTy = 1477 FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg()); 1478 1479 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName() 1480 << "' from " << *OldFn->getFunctionType() << " to " 1481 << *NewFnTy << "\n"); 1482 1483 // Create the new function body and insert it into the module. 1484 Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(), 1485 OldFn->getAddressSpace(), ""); 1486 OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn); 1487 NewFn->takeName(OldFn); 1488 NewFn->copyAttributesFrom(OldFn); 1489 1490 // Patch the pointer to LLVM function in debug info descriptor. 1491 NewFn->setSubprogram(OldFn->getSubprogram()); 1492 OldFn->setSubprogram(nullptr); 1493 1494 // Recompute the parameter attributes list based on the new arguments for 1495 // the function. 1496 LLVMContext &Ctx = OldFn->getContext(); 1497 NewFn->setAttributes(AttributeList::get( 1498 Ctx, OldFnAttributeList.getFnAttributes(), 1499 OldFnAttributeList.getRetAttributes(), NewArgumentAttributes)); 1500 1501 // Since we have now created the new function, splice the body of the old 1502 // function right into the new function, leaving the old rotting hulk of the 1503 // function empty. 1504 NewFn->getBasicBlockList().splice(NewFn->begin(), 1505 OldFn->getBasicBlockList()); 1506 1507 // Fixup block addresses to reference new function. 1508 SmallVector<BlockAddress *, 8u> BlockAddresses; 1509 for (User *U : OldFn->users()) 1510 if (auto *BA = dyn_cast<BlockAddress>(U)) 1511 BlockAddresses.push_back(BA); 1512 for (auto *BA : BlockAddresses) 1513 BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock())); 1514 1515 // Set of all "call-like" instructions that invoke the old function mapped 1516 // to their new replacements. 1517 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs; 1518 1519 // Callback to create a new "call-like" instruction for a given one. 1520 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) { 1521 CallBase *OldCB = cast<CallBase>(ACS.getInstruction()); 1522 const AttributeList &OldCallAttributeList = OldCB->getAttributes(); 1523 1524 // Collect the new argument operands for the replacement call site. 1525 SmallVector<Value *, 16> NewArgOperands; 1526 SmallVector<AttributeSet, 16> NewArgOperandAttributes; 1527 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) { 1528 unsigned NewFirstArgNum = NewArgOperands.size(); 1529 (void)NewFirstArgNum; // only used inside assert. 1530 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1531 ARIs[OldArgNum]) { 1532 if (ARI->ACSRepairCB) 1533 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands); 1534 assert(ARI->getNumReplacementArgs() + NewFirstArgNum == 1535 NewArgOperands.size() && 1536 "ACS repair callback did not provide as many operand as new " 1537 "types were registered!"); 1538 // TODO: Exose the attribute set to the ACS repair callback 1539 NewArgOperandAttributes.append(ARI->ReplacementTypes.size(), 1540 AttributeSet()); 1541 } else { 1542 NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum)); 1543 NewArgOperandAttributes.push_back( 1544 OldCallAttributeList.getParamAttributes(OldArgNum)); 1545 } 1546 } 1547 1548 assert(NewArgOperands.size() == NewArgOperandAttributes.size() && 1549 "Mismatch # argument operands vs. # argument operand attributes!"); 1550 assert(NewArgOperands.size() == NewFn->arg_size() && 1551 "Mismatch # argument operands vs. # function arguments!"); 1552 1553 SmallVector<OperandBundleDef, 4> OperandBundleDefs; 1554 OldCB->getOperandBundlesAsDefs(OperandBundleDefs); 1555 1556 // Create a new call or invoke instruction to replace the old one. 1557 CallBase *NewCB; 1558 if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) { 1559 NewCB = 1560 InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(), 1561 NewArgOperands, OperandBundleDefs, "", OldCB); 1562 } else { 1563 auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs, 1564 "", OldCB); 1565 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind()); 1566 NewCB = NewCI; 1567 } 1568 1569 // Copy over various properties and the new attributes. 1570 uint64_t W; 1571 if (OldCB->extractProfTotalWeight(W)) 1572 NewCB->setProfWeight(W); 1573 NewCB->setCallingConv(OldCB->getCallingConv()); 1574 NewCB->setDebugLoc(OldCB->getDebugLoc()); 1575 NewCB->takeName(OldCB); 1576 NewCB->setAttributes(AttributeList::get( 1577 Ctx, OldCallAttributeList.getFnAttributes(), 1578 OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes)); 1579 1580 CallSitePairs.push_back({OldCB, NewCB}); 1581 return true; 1582 }; 1583 1584 // Use the CallSiteReplacementCreator to create replacement call sites. 1585 bool AllCallSitesKnown; 1586 bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn, 1587 true, nullptr, AllCallSitesKnown); 1588 (void)Success; 1589 assert(Success && "Assumed call site replacement to succeed!"); 1590 1591 // Rewire the arguments. 1592 auto OldFnArgIt = OldFn->arg_begin(); 1593 auto NewFnArgIt = NewFn->arg_begin(); 1594 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); 1595 ++OldArgNum, ++OldFnArgIt) { 1596 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1597 ARIs[OldArgNum]) { 1598 if (ARI->CalleeRepairCB) 1599 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt); 1600 NewFnArgIt += ARI->ReplacementTypes.size(); 1601 } else { 1602 NewFnArgIt->takeName(&*OldFnArgIt); 1603 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt); 1604 ++NewFnArgIt; 1605 } 1606 } 1607 1608 // Eliminate the instructions *after* we visited all of them. 1609 for (auto &CallSitePair : CallSitePairs) { 1610 CallBase &OldCB = *CallSitePair.first; 1611 CallBase &NewCB = *CallSitePair.second; 1612 assert(OldCB.getType() == NewCB.getType() && 1613 "Cannot handle call sites with different types!"); 1614 ModifiedFns.insert(OldCB.getFunction()); 1615 CGUpdater.replaceCallSite(OldCB, NewCB); 1616 OldCB.replaceAllUsesWith(&NewCB); 1617 OldCB.eraseFromParent(); 1618 } 1619 1620 // Replace the function in the call graph (if any). 1621 CGUpdater.replaceFunctionWith(*OldFn, *NewFn); 1622 1623 // If the old function was modified and needed to be reanalyzed, the new one 1624 // does now. 1625 if (ModifiedFns.erase(OldFn)) 1626 ModifiedFns.insert(NewFn); 1627 1628 Changed = ChangeStatus::CHANGED; 1629 } 1630 1631 return Changed; 1632 } 1633 1634 void InformationCache::initializeInformationCache(const Function &CF, 1635 FunctionInfo &FI) { 1636 // As we do not modify the function here we can remove the const 1637 // withouth breaking implicit assumptions. At the end of the day, we could 1638 // initialize the cache eagerly which would look the same to the users. 1639 Function &F = const_cast<Function &>(CF); 1640 1641 // Walk all instructions to find interesting instructions that might be 1642 // queried by abstract attributes during their initialization or update. 1643 // This has to happen before we create attributes. 1644 1645 for (Instruction &I : instructions(&F)) { 1646 bool IsInterestingOpcode = false; 1647 1648 // To allow easy access to all instructions in a function with a given 1649 // opcode we store them in the InfoCache. As not all opcodes are interesting 1650 // to concrete attributes we only cache the ones that are as identified in 1651 // the following switch. 1652 // Note: There are no concrete attributes now so this is initially empty. 1653 switch (I.getOpcode()) { 1654 default: 1655 assert(!isa<CallBase>(&I) && 1656 "New call base instruction type needs to be known in the " 1657 "Attributor."); 1658 break; 1659 case Instruction::Call: 1660 // Calls are interesting on their own, additionally: 1661 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them. 1662 // For `must-tail` calls we remember the caller and callee. 1663 if (IntrinsicInst *Assume = dyn_cast<IntrinsicInst>(&I)) { 1664 if (Assume->getIntrinsicID() == Intrinsic::assume) 1665 fillMapFromAssume(*Assume, KnowledgeMap); 1666 } else if (cast<CallInst>(I).isMustTailCall()) { 1667 FI.ContainsMustTailCall = true; 1668 if (const Function *Callee = cast<CallInst>(I).getCalledFunction()) 1669 getFunctionInfo(*Callee).CalledViaMustTail = true; 1670 } 1671 LLVM_FALLTHROUGH; 1672 case Instruction::CallBr: 1673 case Instruction::Invoke: 1674 case Instruction::CleanupRet: 1675 case Instruction::CatchSwitch: 1676 case Instruction::AtomicRMW: 1677 case Instruction::AtomicCmpXchg: 1678 case Instruction::Br: 1679 case Instruction::Resume: 1680 case Instruction::Ret: 1681 case Instruction::Load: 1682 // The alignment of a pointer is interesting for loads. 1683 case Instruction::Store: 1684 // The alignment of a pointer is interesting for stores. 1685 IsInterestingOpcode = true; 1686 } 1687 if (IsInterestingOpcode) { 1688 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()]; 1689 if (!Insts) 1690 Insts = new (Allocator) InstructionVectorTy(); 1691 Insts->push_back(&I); 1692 } 1693 if (I.mayReadOrWriteMemory()) 1694 FI.RWInsts.push_back(&I); 1695 } 1696 1697 if (F.hasFnAttribute(Attribute::AlwaysInline) && 1698 isInlineViable(F).isSuccess()) 1699 InlineableFunctions.insert(&F); 1700 } 1701 1702 InformationCache::FunctionInfo::~FunctionInfo() { 1703 // The instruction vectors are allocated using a BumpPtrAllocator, we need to 1704 // manually destroy them. 1705 for (auto &It : OpcodeInstMap) 1706 It.getSecond()->~InstructionVectorTy(); 1707 } 1708 1709 void Attributor::recordDependence(const AbstractAttribute &FromAA, 1710 const AbstractAttribute &ToAA, 1711 DepClassTy DepClass) { 1712 // If we are outside of an update, thus before the actual fixpoint iteration 1713 // started (= when we create AAs), we do not track dependences because we will 1714 // put all AAs into the initial worklist anyway. 1715 if (DependenceStack.empty()) 1716 return; 1717 if (FromAA.getState().isAtFixpoint()) 1718 return; 1719 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass}); 1720 } 1721 1722 void Attributor::rememberDependences() { 1723 assert(!DependenceStack.empty() && "No dependences to remember!"); 1724 1725 for (DepInfo &DI : *DependenceStack.back()) { 1726 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps; 1727 DepAAs.push_back(AbstractAttribute::DepTy( 1728 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass))); 1729 } 1730 } 1731 1732 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 1733 if (!VisitedFunctions.insert(&F).second) 1734 return; 1735 if (F.isDeclaration()) 1736 return; 1737 1738 // In non-module runs we need to look at the call sites of a function to 1739 // determine if it is part of a must-tail call edge. This will influence what 1740 // attributes we can derive. 1741 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F); 1742 if (!isModulePass() && !FI.CalledViaMustTail) { 1743 for (const Use &U : F.uses()) 1744 if (const auto *CB = dyn_cast<CallBase>(U.getUser())) 1745 if (CB->isCallee(&U) && CB->isMustTailCall()) 1746 FI.CalledViaMustTail = true; 1747 } 1748 1749 IRPosition FPos = IRPosition::function(F); 1750 1751 // Check for dead BasicBlocks in every function. 1752 // We need dead instruction detection because we do not want to deal with 1753 // broken IR in which SSA rules do not apply. 1754 getOrCreateAAFor<AAIsDead>(FPos); 1755 1756 // Every function might be "will-return". 1757 getOrCreateAAFor<AAWillReturn>(FPos); 1758 1759 // Every function might contain instructions that cause "undefined behavior". 1760 getOrCreateAAFor<AAUndefinedBehavior>(FPos); 1761 1762 // Every function can be nounwind. 1763 getOrCreateAAFor<AANoUnwind>(FPos); 1764 1765 // Every function might be marked "nosync" 1766 getOrCreateAAFor<AANoSync>(FPos); 1767 1768 // Every function might be "no-free". 1769 getOrCreateAAFor<AANoFree>(FPos); 1770 1771 // Every function might be "no-return". 1772 getOrCreateAAFor<AANoReturn>(FPos); 1773 1774 // Every function might be "no-recurse". 1775 getOrCreateAAFor<AANoRecurse>(FPos); 1776 1777 // Every function might be "readnone/readonly/writeonly/...". 1778 getOrCreateAAFor<AAMemoryBehavior>(FPos); 1779 1780 // Every function can be "readnone/argmemonly/inaccessiblememonly/...". 1781 getOrCreateAAFor<AAMemoryLocation>(FPos); 1782 1783 // Every function might be applicable for Heap-To-Stack conversion. 1784 if (EnableHeapToStack) 1785 getOrCreateAAFor<AAHeapToStack>(FPos); 1786 1787 // Return attributes are only appropriate if the return type is non void. 1788 Type *ReturnType = F.getReturnType(); 1789 if (!ReturnType->isVoidTy()) { 1790 // Argument attribute "returned" --- Create only one per function even 1791 // though it is an argument attribute. 1792 getOrCreateAAFor<AAReturnedValues>(FPos); 1793 1794 IRPosition RetPos = IRPosition::returned(F); 1795 1796 // Every returned value might be dead. 1797 getOrCreateAAFor<AAIsDead>(RetPos); 1798 1799 // Every function might be simplified. 1800 getOrCreateAAFor<AAValueSimplify>(RetPos); 1801 1802 if (ReturnType->isPointerTy()) { 1803 1804 // Every function with pointer return type might be marked align. 1805 getOrCreateAAFor<AAAlign>(RetPos); 1806 1807 // Every function with pointer return type might be marked nonnull. 1808 getOrCreateAAFor<AANonNull>(RetPos); 1809 1810 // Every function with pointer return type might be marked noalias. 1811 getOrCreateAAFor<AANoAlias>(RetPos); 1812 1813 // Every function with pointer return type might be marked 1814 // dereferenceable. 1815 getOrCreateAAFor<AADereferenceable>(RetPos); 1816 } 1817 } 1818 1819 for (Argument &Arg : F.args()) { 1820 IRPosition ArgPos = IRPosition::argument(Arg); 1821 1822 // Every argument might be simplified. 1823 getOrCreateAAFor<AAValueSimplify>(ArgPos); 1824 1825 // Every argument might be dead. 1826 getOrCreateAAFor<AAIsDead>(ArgPos); 1827 1828 if (Arg.getType()->isPointerTy()) { 1829 // Every argument with pointer type might be marked nonnull. 1830 getOrCreateAAFor<AANonNull>(ArgPos); 1831 1832 // Every argument with pointer type might be marked noalias. 1833 getOrCreateAAFor<AANoAlias>(ArgPos); 1834 1835 // Every argument with pointer type might be marked dereferenceable. 1836 getOrCreateAAFor<AADereferenceable>(ArgPos); 1837 1838 // Every argument with pointer type might be marked align. 1839 getOrCreateAAFor<AAAlign>(ArgPos); 1840 1841 // Every argument with pointer type might be marked nocapture. 1842 getOrCreateAAFor<AANoCapture>(ArgPos); 1843 1844 // Every argument with pointer type might be marked 1845 // "readnone/readonly/writeonly/..." 1846 getOrCreateAAFor<AAMemoryBehavior>(ArgPos); 1847 1848 // Every argument with pointer type might be marked nofree. 1849 getOrCreateAAFor<AANoFree>(ArgPos); 1850 1851 // Every argument with pointer type might be privatizable (or promotable) 1852 getOrCreateAAFor<AAPrivatizablePtr>(ArgPos); 1853 } 1854 } 1855 1856 auto CallSitePred = [&](Instruction &I) -> bool { 1857 auto &CB = cast<CallBase>(I); 1858 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 1859 1860 // Call sites might be dead if they do not have side effects and no live 1861 // users. The return value might be dead if there are no live users. 1862 getOrCreateAAFor<AAIsDead>(CBRetPos); 1863 1864 Function *Callee = CB.getCalledFunction(); 1865 // TODO: Even if the callee is not known now we might be able to simplify 1866 // the call/callee. 1867 if (!Callee) 1868 return true; 1869 1870 // Skip declarations except if annotations on their call sites were 1871 // explicitly requested. 1872 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() && 1873 !Callee->hasMetadata(LLVMContext::MD_callback)) 1874 return true; 1875 1876 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) { 1877 1878 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 1879 1880 // Call site return integer values might be limited by a constant range. 1881 if (Callee->getReturnType()->isIntegerTy()) 1882 getOrCreateAAFor<AAValueConstantRange>(CBRetPos); 1883 } 1884 1885 for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) { 1886 1887 IRPosition CBArgPos = IRPosition::callsite_argument(CB, I); 1888 1889 // Every call site argument might be dead. 1890 getOrCreateAAFor<AAIsDead>(CBArgPos); 1891 1892 // Call site argument might be simplified. 1893 getOrCreateAAFor<AAValueSimplify>(CBArgPos); 1894 1895 if (!CB.getArgOperand(I)->getType()->isPointerTy()) 1896 continue; 1897 1898 // Call site argument attribute "non-null". 1899 getOrCreateAAFor<AANonNull>(CBArgPos); 1900 1901 // Call site argument attribute "nocapture". 1902 getOrCreateAAFor<AANoCapture>(CBArgPos); 1903 1904 // Call site argument attribute "no-alias". 1905 getOrCreateAAFor<AANoAlias>(CBArgPos); 1906 1907 // Call site argument attribute "dereferenceable". 1908 getOrCreateAAFor<AADereferenceable>(CBArgPos); 1909 1910 // Call site argument attribute "align". 1911 getOrCreateAAFor<AAAlign>(CBArgPos); 1912 1913 // Call site argument attribute 1914 // "readnone/readonly/writeonly/..." 1915 getOrCreateAAFor<AAMemoryBehavior>(CBArgPos); 1916 1917 // Call site argument attribute "nofree". 1918 getOrCreateAAFor<AANoFree>(CBArgPos); 1919 } 1920 return true; 1921 }; 1922 1923 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); 1924 bool Success; 1925 Success = checkForAllInstructionsImpl( 1926 nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr, 1927 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 1928 (unsigned)Instruction::Call}); 1929 (void)Success; 1930 assert(Success && "Expected the check call to be successful!"); 1931 1932 auto LoadStorePred = [&](Instruction &I) -> bool { 1933 if (isa<LoadInst>(I)) 1934 getOrCreateAAFor<AAAlign>( 1935 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 1936 else 1937 getOrCreateAAFor<AAAlign>( 1938 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 1939 return true; 1940 }; 1941 Success = checkForAllInstructionsImpl( 1942 nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr, 1943 {(unsigned)Instruction::Load, (unsigned)Instruction::Store}); 1944 (void)Success; 1945 assert(Success && "Expected the check call to be successful!"); 1946 } 1947 1948 /// Helpers to ease debugging through output streams and print calls. 1949 /// 1950 ///{ 1951 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 1952 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 1953 } 1954 1955 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 1956 switch (AP) { 1957 case IRPosition::IRP_INVALID: 1958 return OS << "inv"; 1959 case IRPosition::IRP_FLOAT: 1960 return OS << "flt"; 1961 case IRPosition::IRP_RETURNED: 1962 return OS << "fn_ret"; 1963 case IRPosition::IRP_CALL_SITE_RETURNED: 1964 return OS << "cs_ret"; 1965 case IRPosition::IRP_FUNCTION: 1966 return OS << "fn"; 1967 case IRPosition::IRP_CALL_SITE: 1968 return OS << "cs"; 1969 case IRPosition::IRP_ARGUMENT: 1970 return OS << "arg"; 1971 case IRPosition::IRP_CALL_SITE_ARGUMENT: 1972 return OS << "cs_arg"; 1973 } 1974 llvm_unreachable("Unknown attribute position!"); 1975 } 1976 1977 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 1978 const Value &AV = Pos.getAssociatedValue(); 1979 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 1980 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 1981 } 1982 1983 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) { 1984 OS << "range-state(" << S.getBitWidth() << ")<"; 1985 S.getKnown().print(OS); 1986 OS << " / "; 1987 S.getAssumed().print(OS); 1988 OS << ">"; 1989 1990 return OS << static_cast<const AbstractState &>(S); 1991 } 1992 1993 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 1994 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 1995 } 1996 1997 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 1998 AA.print(OS); 1999 return OS; 2000 } 2001 2002 void AbstractAttribute::print(raw_ostream &OS) const { 2003 OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState() 2004 << "]"; 2005 } 2006 ///} 2007 2008 /// ---------------------------------------------------------------------------- 2009 /// Pass (Manager) Boilerplate 2010 /// ---------------------------------------------------------------------------- 2011 2012 static bool runAttributorOnFunctions(InformationCache &InfoCache, 2013 SetVector<Function *> &Functions, 2014 AnalysisGetter &AG, 2015 CallGraphUpdater &CGUpdater) { 2016 if (Functions.empty()) 2017 return false; 2018 2019 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << Functions.size() 2020 << " functions.\n"); 2021 2022 // Create an Attributor and initially empty information cache that is filled 2023 // while we identify default attribute opportunities. 2024 Attributor A(Functions, InfoCache, CGUpdater); 2025 2026 // Create shallow wrappers for all functions that are not IPO amendable 2027 if (AllowShallowWrappers) 2028 for (Function *F : Functions) 2029 if (!A.isFunctionIPOAmendable(*F)) 2030 createShallowWrapper(*F); 2031 2032 for (Function *F : Functions) { 2033 if (F->hasExactDefinition()) 2034 NumFnWithExactDefinition++; 2035 else 2036 NumFnWithoutExactDefinition++; 2037 2038 // We look at internal functions only on-demand but if any use is not a 2039 // direct call or outside the current set of analyzed functions, we have to 2040 // do it eagerly. 2041 if (F->hasLocalLinkage()) { 2042 if (llvm::all_of(F->uses(), [&Functions](const Use &U) { 2043 const auto *CB = dyn_cast<CallBase>(U.getUser()); 2044 return CB && CB->isCallee(&U) && 2045 Functions.count(const_cast<Function *>(CB->getCaller())); 2046 })) 2047 continue; 2048 } 2049 2050 // Populate the Attributor with abstract attribute opportunities in the 2051 // function and the information cache with IR information. 2052 A.identifyDefaultAbstractAttributes(*F); 2053 } 2054 2055 ChangeStatus Changed = A.run(); 2056 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size() 2057 << " functions, result: " << Changed << ".\n"); 2058 return Changed == ChangeStatus::CHANGED; 2059 } 2060 2061 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 2062 FunctionAnalysisManager &FAM = 2063 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2064 AnalysisGetter AG(FAM); 2065 2066 SetVector<Function *> Functions; 2067 for (Function &F : M) 2068 Functions.insert(&F); 2069 2070 CallGraphUpdater CGUpdater; 2071 BumpPtrAllocator Allocator; 2072 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2073 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2074 // FIXME: Think about passes we will preserve and add them here. 2075 return PreservedAnalyses::none(); 2076 } 2077 return PreservedAnalyses::all(); 2078 } 2079 2080 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C, 2081 CGSCCAnalysisManager &AM, 2082 LazyCallGraph &CG, 2083 CGSCCUpdateResult &UR) { 2084 FunctionAnalysisManager &FAM = 2085 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 2086 AnalysisGetter AG(FAM); 2087 2088 SetVector<Function *> Functions; 2089 for (LazyCallGraph::Node &N : C) 2090 Functions.insert(&N.getFunction()); 2091 2092 if (Functions.empty()) 2093 return PreservedAnalyses::all(); 2094 2095 Module &M = *Functions.back()->getParent(); 2096 CallGraphUpdater CGUpdater; 2097 CGUpdater.initialize(CG, C, AM, UR); 2098 BumpPtrAllocator Allocator; 2099 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2100 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2101 // FIXME: Think about passes we will preserve and add them here. 2102 return PreservedAnalyses::none(); 2103 } 2104 return PreservedAnalyses::all(); 2105 } 2106 2107 namespace { 2108 2109 struct AttributorLegacyPass : public ModulePass { 2110 static char ID; 2111 2112 AttributorLegacyPass() : ModulePass(ID) { 2113 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 2114 } 2115 2116 bool runOnModule(Module &M) override { 2117 if (skipModule(M)) 2118 return false; 2119 2120 AnalysisGetter AG; 2121 SetVector<Function *> Functions; 2122 for (Function &F : M) 2123 Functions.insert(&F); 2124 2125 CallGraphUpdater CGUpdater; 2126 BumpPtrAllocator Allocator; 2127 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2128 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2129 } 2130 2131 void getAnalysisUsage(AnalysisUsage &AU) const override { 2132 // FIXME: Think about passes we will preserve and add them here. 2133 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2134 } 2135 }; 2136 2137 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass { 2138 CallGraphUpdater CGUpdater; 2139 static char ID; 2140 2141 AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) { 2142 initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 2143 } 2144 2145 bool runOnSCC(CallGraphSCC &SCC) override { 2146 if (skipSCC(SCC)) 2147 return false; 2148 2149 SetVector<Function *> Functions; 2150 for (CallGraphNode *CGN : SCC) 2151 if (Function *Fn = CGN->getFunction()) 2152 if (!Fn->isDeclaration()) 2153 Functions.insert(Fn); 2154 2155 if (Functions.empty()) 2156 return false; 2157 2158 AnalysisGetter AG; 2159 CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph()); 2160 CGUpdater.initialize(CG, SCC); 2161 Module &M = *Functions.back()->getParent(); 2162 BumpPtrAllocator Allocator; 2163 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2164 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2165 } 2166 2167 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 2168 2169 void getAnalysisUsage(AnalysisUsage &AU) const override { 2170 // FIXME: Think about passes we will preserve and add them here. 2171 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2172 CallGraphSCCPass::getAnalysisUsage(AU); 2173 } 2174 }; 2175 2176 } // end anonymous namespace 2177 2178 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 2179 Pass *llvm::createAttributorCGSCCLegacyPass() { 2180 return new AttributorCGSCCLegacyPass(); 2181 } 2182 2183 char AttributorLegacyPass::ID = 0; 2184 char AttributorCGSCCLegacyPass::ID = 0; 2185 2186 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 2187 "Deduce and propagate attributes", false, false) 2188 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2189 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 2190 "Deduce and propagate attributes", false, false) 2191 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc", 2192 "Deduce and propagate attributes (CGSCC pass)", false, 2193 false) 2194 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2195 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2196 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc", 2197 "Deduce and propagate attributes (CGSCC pass)", false, 2198 false) 2199