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 inter procedural pass that deduces and/or propagating 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/DepthFirstIterator.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/CaptureTracking.h" 24 #include "llvm/Analysis/EHPersonalities.h" 25 #include "llvm/Analysis/GlobalsModRef.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryBuiltins.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/IR/Argument.h" 30 #include "llvm/IR/Attributes.h" 31 #include "llvm/IR/CFG.h" 32 #include "llvm/IR/InstIterator.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 40 #include <cassert> 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "attributor" 45 46 STATISTIC(NumFnWithExactDefinition, 47 "Number of function with exact definitions"); 48 STATISTIC(NumFnWithoutExactDefinition, 49 "Number of function without exact definitions"); 50 STATISTIC(NumAttributesTimedOut, 51 "Number of abstract attributes timed out before fixpoint"); 52 STATISTIC(NumAttributesValidFixpoint, 53 "Number of abstract attributes in a valid fixpoint state"); 54 STATISTIC(NumAttributesManifested, 55 "Number of abstract attributes manifested in IR"); 56 57 // Some helper macros to deal with statistics tracking. 58 // 59 // Usage: 60 // For simple IR attribute tracking overload trackStatistics in the abstract 61 // attribute and choose the right STATS_DECLTRACK_********* macro, 62 // e.g.,: 63 // void trackStatistics() const override { 64 // STATS_DECLTRACK_ARG_ATTR(returned) 65 // } 66 // If there is a single "increment" side one can use the macro 67 // STATS_DECLTRACK with a custom message. If there are multiple increment 68 // sides, STATS_DECL and STATS_TRACK can also be used separatly. 69 // 70 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 71 ("Number of " #TYPE " marked '" #NAME "'") 72 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 73 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG); 74 #define STATS_DECL(NAME, TYPE, MSG) \ 75 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG); 76 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 77 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 78 { \ 79 STATS_DECL(NAME, TYPE, MSG) \ 80 STATS_TRACK(NAME, TYPE) \ 81 } 82 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 83 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 84 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 85 STATS_DECLTRACK(NAME, CSArguments, \ 86 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 87 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 88 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 89 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 90 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 91 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 92 STATS_DECLTRACK(NAME, FunctionReturn, \ 93 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 94 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 95 STATS_DECLTRACK(NAME, CSReturn, \ 96 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 97 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 98 STATS_DECLTRACK(NAME, Floating, \ 99 ("Number of floating values known to be '" #NAME "'")) 100 101 // TODO: Determine a good default value. 102 // 103 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 104 // (when run with the first 5 abstract attributes). The results also indicate 105 // that we never reach 32 iterations but always find a fixpoint sooner. 106 // 107 // This will become more evolved once we perform two interleaved fixpoint 108 // iterations: bottom-up and top-down. 109 static cl::opt<unsigned> 110 MaxFixpointIterations("attributor-max-iterations", cl::Hidden, 111 cl::desc("Maximal number of fixpoint iterations."), 112 cl::init(32)); 113 static cl::opt<bool> VerifyMaxFixpointIterations( 114 "attributor-max-iterations-verify", cl::Hidden, 115 cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), 116 cl::init(false)); 117 118 static cl::opt<bool> DisableAttributor( 119 "attributor-disable", cl::Hidden, 120 cl::desc("Disable the attributor inter-procedural deduction pass."), 121 cl::init(true)); 122 123 static cl::opt<bool> ManifestInternal( 124 "attributor-manifest-internal", cl::Hidden, 125 cl::desc("Manifest Attributor internal string attributes."), 126 cl::init(false)); 127 128 static cl::opt<unsigned> DepRecInterval( 129 "attributor-dependence-recompute-interval", cl::Hidden, 130 cl::desc("Number of iterations until dependences are recomputed."), 131 cl::init(4)); 132 133 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion", 134 cl::init(true), cl::Hidden); 135 136 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128), 137 cl::Hidden); 138 139 /// Logic operators for the change status enum class. 140 /// 141 ///{ 142 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { 143 return l == ChangeStatus::CHANGED ? l : r; 144 } 145 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { 146 return l == ChangeStatus::UNCHANGED ? l : r; 147 } 148 ///} 149 150 /// Recursively visit all values that might become \p IRP at some point. This 151 /// will be done by looking through cast instructions, selects, phis, and calls 152 /// with the "returned" attribute. Once we cannot look through the value any 153 /// further, the callback \p VisitValueCB is invoked and passed the current 154 /// value, the \p State, and a flag to indicate if we stripped anything. To 155 /// limit how much effort is invested, we will never visit more values than 156 /// specified by \p MaxValues. 157 template <typename AAType, typename StateTy> 158 static bool genericValueTraversal( 159 Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State, 160 const function_ref<bool(Value &, StateTy &, bool)> &VisitValueCB, 161 int MaxValues = 8) { 162 163 const AAIsDead *LivenessAA = nullptr; 164 if (IRP.getAnchorScope()) 165 LivenessAA = &A.getAAFor<AAIsDead>( 166 QueryingAA, IRPosition::function(*IRP.getAnchorScope()), 167 /* TrackDependence */ false); 168 bool AnyDead = false; 169 170 // TODO: Use Positions here to allow context sensitivity in VisitValueCB 171 SmallPtrSet<Value *, 16> Visited; 172 SmallVector<Value *, 16> Worklist; 173 Worklist.push_back(&IRP.getAssociatedValue()); 174 175 int Iteration = 0; 176 do { 177 Value *V = Worklist.pop_back_val(); 178 179 // Check if we should process the current value. To prevent endless 180 // recursion keep a record of the values we followed! 181 if (!Visited.insert(V).second) 182 continue; 183 184 // Make sure we limit the compile time for complex expressions. 185 if (Iteration++ >= MaxValues) 186 return false; 187 188 // Explicitly look through calls with a "returned" attribute if we do 189 // not have a pointer as stripPointerCasts only works on them. 190 Value *NewV = nullptr; 191 if (V->getType()->isPointerTy()) { 192 NewV = V->stripPointerCasts(); 193 } else { 194 CallSite CS(V); 195 if (CS && CS.getCalledFunction()) { 196 for (Argument &Arg : CS.getCalledFunction()->args()) 197 if (Arg.hasReturnedAttr()) { 198 NewV = CS.getArgOperand(Arg.getArgNo()); 199 break; 200 } 201 } 202 } 203 if (NewV && NewV != V) { 204 Worklist.push_back(NewV); 205 continue; 206 } 207 208 // Look through select instructions, visit both potential values. 209 if (auto *SI = dyn_cast<SelectInst>(V)) { 210 Worklist.push_back(SI->getTrueValue()); 211 Worklist.push_back(SI->getFalseValue()); 212 continue; 213 } 214 215 // Look through phi nodes, visit all live operands. 216 if (auto *PHI = dyn_cast<PHINode>(V)) { 217 assert(LivenessAA && 218 "Expected liveness in the presence of instructions!"); 219 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) { 220 const BasicBlock *IncomingBB = PHI->getIncomingBlock(u); 221 if (LivenessAA->isAssumedDead(IncomingBB->getTerminator())) { 222 AnyDead = true; 223 continue; 224 } 225 Worklist.push_back(PHI->getIncomingValue(u)); 226 } 227 continue; 228 } 229 230 // Once a leaf is reached we inform the user through the callback. 231 if (!VisitValueCB(*V, State, Iteration > 1)) 232 return false; 233 } while (!Worklist.empty()); 234 235 // If we actually used liveness information so we have to record a dependence. 236 if (AnyDead) 237 A.recordDependence(*LivenessAA, QueryingAA); 238 239 // All values have been visited. 240 return true; 241 } 242 243 /// Return true if \p New is equal or worse than \p Old. 244 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 245 if (!Old.isIntAttribute()) 246 return true; 247 248 return Old.getValueAsInt() >= New.getValueAsInt(); 249 } 250 251 /// Return true if the information provided by \p Attr was added to the 252 /// attribute list \p Attrs. This is only the case if it was not already present 253 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 254 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 255 AttributeList &Attrs, int AttrIdx) { 256 257 if (Attr.isEnumAttribute()) { 258 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 259 if (Attrs.hasAttribute(AttrIdx, Kind)) 260 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 261 return false; 262 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 263 return true; 264 } 265 if (Attr.isStringAttribute()) { 266 StringRef Kind = Attr.getKindAsString(); 267 if (Attrs.hasAttribute(AttrIdx, Kind)) 268 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 269 return false; 270 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 271 return true; 272 } 273 if (Attr.isIntAttribute()) { 274 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 275 if (Attrs.hasAttribute(AttrIdx, Kind)) 276 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 277 return false; 278 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 279 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 280 return true; 281 } 282 283 llvm_unreachable("Expected enum or string attribute!"); 284 } 285 static const Value *getPointerOperand(const Instruction *I) { 286 if (auto *LI = dyn_cast<LoadInst>(I)) 287 if (!LI->isVolatile()) 288 return LI->getPointerOperand(); 289 290 if (auto *SI = dyn_cast<StoreInst>(I)) 291 if (!SI->isVolatile()) 292 return SI->getPointerOperand(); 293 294 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) 295 if (!CXI->isVolatile()) 296 return CXI->getPointerOperand(); 297 298 if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) 299 if (!RMWI->isVolatile()) 300 return RMWI->getPointerOperand(); 301 302 return nullptr; 303 } 304 static const Value *getBasePointerOfAccessPointerOperand(const Instruction *I, 305 int64_t &BytesOffset, 306 const DataLayout &DL) { 307 const Value *Ptr = getPointerOperand(I); 308 if (!Ptr) 309 return nullptr; 310 311 return GetPointerBaseWithConstantOffset(Ptr, BytesOffset, DL, 312 /*AllowNonInbounds*/ false); 313 } 314 315 ChangeStatus AbstractAttribute::update(Attributor &A) { 316 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 317 if (getState().isAtFixpoint()) 318 return HasChanged; 319 320 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 321 322 HasChanged = updateImpl(A); 323 324 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 325 << "\n"); 326 327 return HasChanged; 328 } 329 330 ChangeStatus 331 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP, 332 const ArrayRef<Attribute> &DeducedAttrs) { 333 Function *ScopeFn = IRP.getAssociatedFunction(); 334 IRPosition::Kind PK = IRP.getPositionKind(); 335 336 // In the following some generic code that will manifest attributes in 337 // DeducedAttrs if they improve the current IR. Due to the different 338 // annotation positions we use the underlying AttributeList interface. 339 340 AttributeList Attrs; 341 switch (PK) { 342 case IRPosition::IRP_INVALID: 343 case IRPosition::IRP_FLOAT: 344 return ChangeStatus::UNCHANGED; 345 case IRPosition::IRP_ARGUMENT: 346 case IRPosition::IRP_FUNCTION: 347 case IRPosition::IRP_RETURNED: 348 Attrs = ScopeFn->getAttributes(); 349 break; 350 case IRPosition::IRP_CALL_SITE: 351 case IRPosition::IRP_CALL_SITE_RETURNED: 352 case IRPosition::IRP_CALL_SITE_ARGUMENT: 353 Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes(); 354 break; 355 } 356 357 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 358 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 359 for (const Attribute &Attr : DeducedAttrs) { 360 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 361 continue; 362 363 HasChanged = ChangeStatus::CHANGED; 364 } 365 366 if (HasChanged == ChangeStatus::UNCHANGED) 367 return HasChanged; 368 369 switch (PK) { 370 case IRPosition::IRP_ARGUMENT: 371 case IRPosition::IRP_FUNCTION: 372 case IRPosition::IRP_RETURNED: 373 ScopeFn->setAttributes(Attrs); 374 break; 375 case IRPosition::IRP_CALL_SITE: 376 case IRPosition::IRP_CALL_SITE_RETURNED: 377 case IRPosition::IRP_CALL_SITE_ARGUMENT: 378 CallSite(&IRP.getAnchorValue()).setAttributes(Attrs); 379 break; 380 case IRPosition::IRP_INVALID: 381 case IRPosition::IRP_FLOAT: 382 break; 383 } 384 385 return HasChanged; 386 } 387 388 const IRPosition IRPosition::EmptyKey(255); 389 const IRPosition IRPosition::TombstoneKey(256); 390 391 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 392 IRPositions.emplace_back(IRP); 393 394 ImmutableCallSite ICS(&IRP.getAnchorValue()); 395 switch (IRP.getPositionKind()) { 396 case IRPosition::IRP_INVALID: 397 case IRPosition::IRP_FLOAT: 398 case IRPosition::IRP_FUNCTION: 399 return; 400 case IRPosition::IRP_ARGUMENT: 401 case IRPosition::IRP_RETURNED: 402 IRPositions.emplace_back( 403 IRPosition::function(*IRP.getAssociatedFunction())); 404 return; 405 case IRPosition::IRP_CALL_SITE: 406 assert(ICS && "Expected call site!"); 407 // TODO: We need to look at the operand bundles similar to the redirection 408 // in CallBase. 409 if (!ICS.hasOperandBundles()) 410 if (const Function *Callee = ICS.getCalledFunction()) 411 IRPositions.emplace_back(IRPosition::function(*Callee)); 412 return; 413 case IRPosition::IRP_CALL_SITE_RETURNED: 414 assert(ICS && "Expected call site!"); 415 // TODO: We need to look at the operand bundles similar to the redirection 416 // in CallBase. 417 if (!ICS.hasOperandBundles()) { 418 if (const Function *Callee = ICS.getCalledFunction()) { 419 IRPositions.emplace_back(IRPosition::returned(*Callee)); 420 IRPositions.emplace_back(IRPosition::function(*Callee)); 421 } 422 } 423 IRPositions.emplace_back( 424 IRPosition::callsite_function(cast<CallBase>(*ICS.getInstruction()))); 425 return; 426 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 427 int ArgNo = IRP.getArgNo(); 428 assert(ICS && ArgNo >= 0 && "Expected call site!"); 429 // TODO: We need to look at the operand bundles similar to the redirection 430 // in CallBase. 431 if (!ICS.hasOperandBundles()) { 432 const Function *Callee = ICS.getCalledFunction(); 433 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 434 IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo))); 435 if (Callee) 436 IRPositions.emplace_back(IRPosition::function(*Callee)); 437 } 438 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 439 return; 440 } 441 } 442 } 443 444 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs, 445 bool IgnoreSubsumingPositions) const { 446 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 447 for (Attribute::AttrKind AK : AKs) 448 if (EquivIRP.getAttr(AK).getKindAsEnum() == AK) 449 return true; 450 // The first position returned by the SubsumingPositionIterator is 451 // always the position itself. If we ignore subsuming positions we 452 // are done after the first iteration. 453 if (IgnoreSubsumingPositions) 454 break; 455 } 456 return false; 457 } 458 459 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 460 SmallVectorImpl<Attribute> &Attrs) const { 461 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) 462 for (Attribute::AttrKind AK : AKs) { 463 const Attribute &Attr = EquivIRP.getAttr(AK); 464 if (Attr.getKindAsEnum() == AK) 465 Attrs.push_back(Attr); 466 } 467 } 468 469 void IRPosition::verify() { 470 switch (KindOrArgNo) { 471 default: 472 assert(KindOrArgNo >= 0 && "Expected argument or call site argument!"); 473 assert((isa<CallBase>(AnchorVal) || isa<Argument>(AnchorVal)) && 474 "Expected call base or argument for positive attribute index!"); 475 if (isa<Argument>(AnchorVal)) { 476 assert(cast<Argument>(AnchorVal)->getArgNo() == unsigned(getArgNo()) && 477 "Argument number mismatch!"); 478 assert(cast<Argument>(AnchorVal) == &getAssociatedValue() && 479 "Associated value mismatch!"); 480 } else { 481 assert(cast<CallBase>(*AnchorVal).arg_size() > unsigned(getArgNo()) && 482 "Call site argument number mismatch!"); 483 assert(cast<CallBase>(*AnchorVal).getArgOperand(getArgNo()) == 484 &getAssociatedValue() && 485 "Associated value mismatch!"); 486 } 487 break; 488 case IRP_INVALID: 489 assert(!AnchorVal && "Expected no value for an invalid position!"); 490 break; 491 case IRP_FLOAT: 492 assert((!isa<CallBase>(&getAssociatedValue()) && 493 !isa<Argument>(&getAssociatedValue())) && 494 "Expected specialized kind for call base and argument values!"); 495 break; 496 case IRP_RETURNED: 497 assert(isa<Function>(AnchorVal) && 498 "Expected function for a 'returned' position!"); 499 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 500 break; 501 case IRP_CALL_SITE_RETURNED: 502 assert((isa<CallBase>(AnchorVal)) && 503 "Expected call base for 'call site returned' position!"); 504 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 505 break; 506 case IRP_CALL_SITE: 507 assert((isa<CallBase>(AnchorVal)) && 508 "Expected call base for 'call site function' position!"); 509 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 510 break; 511 case IRP_FUNCTION: 512 assert(isa<Function>(AnchorVal) && 513 "Expected function for a 'function' position!"); 514 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 515 break; 516 } 517 } 518 519 namespace { 520 /// Helper function to clamp a state \p S of type \p StateType with the 521 /// information in \p R and indicate/return if \p S did change (as-in update is 522 /// required to be run again). 523 template <typename StateType> 524 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) { 525 auto Assumed = S.getAssumed(); 526 S ^= R; 527 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 528 : ChangeStatus::CHANGED; 529 } 530 531 /// Clamp the information known for all returned values of a function 532 /// (identified by \p QueryingAA) into \p S. 533 template <typename AAType, typename StateType = typename AAType::StateType> 534 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA, 535 StateType &S) { 536 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for " 537 << static_cast<const AbstractAttribute &>(QueryingAA) 538 << " into " << S << "\n"); 539 540 assert((QueryingAA.getIRPosition().getPositionKind() == 541 IRPosition::IRP_RETURNED || 542 QueryingAA.getIRPosition().getPositionKind() == 543 IRPosition::IRP_CALL_SITE_RETURNED) && 544 "Can only clamp returned value states for a function returned or call " 545 "site returned position!"); 546 547 // Use an optional state as there might not be any return values and we want 548 // to join (IntegerState::operator&) the state of all there are. 549 Optional<StateType> T; 550 551 // Callback for each possibly returned value. 552 auto CheckReturnValue = [&](Value &RV) -> bool { 553 const IRPosition &RVPos = IRPosition::value(RV); 554 const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos); 555 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr() 556 << " @ " << RVPos << "\n"); 557 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 558 if (T.hasValue()) 559 *T &= AAS; 560 else 561 T = AAS; 562 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T 563 << "\n"); 564 return T->isValidState(); 565 }; 566 567 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA)) 568 S.indicatePessimisticFixpoint(); 569 else if (T.hasValue()) 570 S ^= *T; 571 } 572 573 /// Helper class to compose two generic deduction 574 template <typename AAType, typename Base, typename StateType, 575 template <typename...> class F, template <typename...> class G> 576 struct AAComposeTwoGenericDeduction 577 : public F<AAType, G<AAType, Base, StateType>, StateType> { 578 AAComposeTwoGenericDeduction(const IRPosition &IRP) 579 : F<AAType, G<AAType, Base, StateType>, StateType>(IRP) {} 580 581 /// See AbstractAttribute::updateImpl(...). 582 ChangeStatus updateImpl(Attributor &A) override { 583 ChangeStatus ChangedF = F<AAType, G<AAType, Base, StateType>, StateType>::updateImpl(A); 584 ChangeStatus ChangedG = G<AAType, Base, StateType>::updateImpl(A); 585 return ChangedF | ChangedG; 586 } 587 }; 588 589 /// Helper class for generic deduction: return value -> returned position. 590 template <typename AAType, typename Base, 591 typename StateType = typename AAType::StateType> 592 struct AAReturnedFromReturnedValues : public Base { 593 AAReturnedFromReturnedValues(const IRPosition &IRP) : Base(IRP) {} 594 595 /// See AbstractAttribute::updateImpl(...). 596 ChangeStatus updateImpl(Attributor &A) override { 597 StateType S; 598 clampReturnedValueStates<AAType, StateType>(A, *this, S); 599 // TODO: If we know we visited all returned values, thus no are assumed 600 // dead, we can take the known information from the state T. 601 return clampStateAndIndicateChange<StateType>(this->getState(), S); 602 } 603 }; 604 605 /// Clamp the information known at all call sites for a given argument 606 /// (identified by \p QueryingAA) into \p S. 607 template <typename AAType, typename StateType = typename AAType::StateType> 608 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA, 609 StateType &S) { 610 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for " 611 << static_cast<const AbstractAttribute &>(QueryingAA) 612 << " into " << S << "\n"); 613 614 assert(QueryingAA.getIRPosition().getPositionKind() == 615 IRPosition::IRP_ARGUMENT && 616 "Can only clamp call site argument states for an argument position!"); 617 618 // Use an optional state as there might not be any return values and we want 619 // to join (IntegerState::operator&) the state of all there are. 620 Optional<StateType> T; 621 622 // The argument number which is also the call site argument number. 623 unsigned ArgNo = QueryingAA.getIRPosition().getArgNo(); 624 625 auto CallSiteCheck = [&](AbstractCallSite ACS) { 626 const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo); 627 // Check if a coresponding argument was found or if it is on not associated 628 // (which can happen for callback calls). 629 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 630 return false; 631 632 const AAType &AA = A.getAAFor<AAType>(QueryingAA, ACSArgPos); 633 LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction() 634 << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n"); 635 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 636 if (T.hasValue()) 637 *T &= AAS; 638 else 639 T = AAS; 640 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T 641 << "\n"); 642 return T->isValidState(); 643 }; 644 645 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true)) 646 S.indicatePessimisticFixpoint(); 647 else if (T.hasValue()) 648 S ^= *T; 649 } 650 651 /// Helper class for generic deduction: call site argument -> argument position. 652 template <typename AAType, typename Base, 653 typename StateType = typename AAType::StateType> 654 struct AAArgumentFromCallSiteArguments : public Base { 655 AAArgumentFromCallSiteArguments(const IRPosition &IRP) : Base(IRP) {} 656 657 /// See AbstractAttribute::updateImpl(...). 658 ChangeStatus updateImpl(Attributor &A) override { 659 StateType S; 660 clampCallSiteArgumentStates<AAType, StateType>(A, *this, S); 661 // TODO: If we know we visited all incoming values, thus no are assumed 662 // dead, we can take the known information from the state T. 663 return clampStateAndIndicateChange<StateType>(this->getState(), S); 664 } 665 }; 666 667 /// Helper class for generic replication: function returned -> cs returned. 668 template <typename AAType, typename Base, 669 typename StateType = typename AAType::StateType> 670 struct AACallSiteReturnedFromReturned : public Base { 671 AACallSiteReturnedFromReturned(const IRPosition &IRP) : Base(IRP) {} 672 673 /// See AbstractAttribute::updateImpl(...). 674 ChangeStatus updateImpl(Attributor &A) override { 675 assert(this->getIRPosition().getPositionKind() == 676 IRPosition::IRP_CALL_SITE_RETURNED && 677 "Can only wrap function returned positions for call site returned " 678 "positions!"); 679 auto &S = this->getState(); 680 681 const Function *AssociatedFunction = 682 this->getIRPosition().getAssociatedFunction(); 683 if (!AssociatedFunction) 684 return S.indicatePessimisticFixpoint(); 685 686 IRPosition FnPos = IRPosition::returned(*AssociatedFunction); 687 const AAType &AA = A.getAAFor<AAType>(*this, FnPos); 688 return clampStateAndIndicateChange( 689 S, static_cast<const typename AAType::StateType &>(AA.getState())); 690 } 691 }; 692 693 /// Helper class for generic deduction using must-be-executed-context 694 /// Base class is required to have `followUse` method. 695 696 /// bool followUse(Attributor &A, const Use *U, const Instruction *I) 697 /// U - Underlying use. 698 /// I - The user of the \p U. 699 /// `followUse` returns true if the value should be tracked transitively. 700 701 template <typename AAType, typename Base, 702 typename StateType = typename AAType::StateType> 703 struct AAFromMustBeExecutedContext : public Base { 704 AAFromMustBeExecutedContext(const IRPosition &IRP) : Base(IRP) {} 705 706 void initialize(Attributor &A) override { 707 Base::initialize(A); 708 const IRPosition &IRP = this->getIRPosition(); 709 Instruction *CtxI = IRP.getCtxI(); 710 711 if (!CtxI) 712 return; 713 714 for (const Use &U : IRP.getAssociatedValue().uses()) 715 Uses.insert(&U); 716 } 717 718 /// See AbstractAttribute::updateImpl(...). 719 ChangeStatus updateImpl(Attributor &A) override { 720 auto BeforeState = this->getState(); 721 auto &S = this->getState(); 722 Instruction *CtxI = this->getIRPosition().getCtxI(); 723 if (!CtxI) 724 return ChangeStatus::UNCHANGED; 725 726 MustBeExecutedContextExplorer &Explorer = 727 A.getInfoCache().getMustBeExecutedContextExplorer(); 728 729 SetVector<const Use *> NextUses; 730 731 auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI); 732 for (const Use *U : Uses) { 733 if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) { 734 bool Found = Explorer.findInContextOf(UserI, EIt, EEnd); 735 if (Found && Base::followUse(A, U, UserI)) 736 for (const Use &Us : UserI->uses()) 737 NextUses.insert(&Us); 738 } 739 } 740 for (const Use *U : NextUses) 741 Uses.insert(U); 742 743 return BeforeState == S ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED; 744 } 745 746 private: 747 /// Container for (transitive) uses of the associated value. 748 SetVector<const Use *> Uses; 749 }; 750 751 template <typename AAType, typename Base, 752 typename StateType = typename AAType::StateType> 753 using AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext = 754 AAComposeTwoGenericDeduction<AAType, Base, StateType, 755 AAFromMustBeExecutedContext, 756 AAArgumentFromCallSiteArguments>; 757 758 template <typename AAType, typename Base, 759 typename StateType = typename AAType::StateType> 760 using AACallSiteReturnedFromReturnedAndMustBeExecutedContext = 761 AAComposeTwoGenericDeduction<AAType, Base, StateType, 762 AAFromMustBeExecutedContext, 763 AACallSiteReturnedFromReturned>; 764 765 /// -----------------------NoUnwind Function Attribute-------------------------- 766 767 struct AANoUnwindImpl : AANoUnwind { 768 AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {} 769 770 const std::string getAsStr() const override { 771 return getAssumed() ? "nounwind" : "may-unwind"; 772 } 773 774 /// See AbstractAttribute::updateImpl(...). 775 ChangeStatus updateImpl(Attributor &A) override { 776 auto Opcodes = { 777 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 778 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, 779 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; 780 781 auto CheckForNoUnwind = [&](Instruction &I) { 782 if (!I.mayThrow()) 783 return true; 784 785 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 786 const auto &NoUnwindAA = 787 A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(ICS)); 788 return NoUnwindAA.isAssumedNoUnwind(); 789 } 790 return false; 791 }; 792 793 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes)) 794 return indicatePessimisticFixpoint(); 795 796 return ChangeStatus::UNCHANGED; 797 } 798 }; 799 800 struct AANoUnwindFunction final : public AANoUnwindImpl { 801 AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {} 802 803 /// See AbstractAttribute::trackStatistics() 804 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) } 805 }; 806 807 /// NoUnwind attribute deduction for a call sites. 808 struct AANoUnwindCallSite final : AANoUnwindImpl { 809 AANoUnwindCallSite(const IRPosition &IRP) : AANoUnwindImpl(IRP) {} 810 811 /// See AbstractAttribute::initialize(...). 812 void initialize(Attributor &A) override { 813 AANoUnwindImpl::initialize(A); 814 Function *F = getAssociatedFunction(); 815 if (!F) 816 indicatePessimisticFixpoint(); 817 } 818 819 /// See AbstractAttribute::updateImpl(...). 820 ChangeStatus updateImpl(Attributor &A) override { 821 // TODO: Once we have call site specific value information we can provide 822 // call site specific liveness information and then it makes 823 // sense to specialize attributes for call sites arguments instead of 824 // redirecting requests to the callee argument. 825 Function *F = getAssociatedFunction(); 826 const IRPosition &FnPos = IRPosition::function(*F); 827 auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos); 828 return clampStateAndIndicateChange( 829 getState(), 830 static_cast<const AANoUnwind::StateType &>(FnAA.getState())); 831 } 832 833 /// See AbstractAttribute::trackStatistics() 834 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); } 835 }; 836 837 /// --------------------- Function Return Values ------------------------------- 838 839 /// "Attribute" that collects all potential returned values and the return 840 /// instructions that they arise from. 841 /// 842 /// If there is a unique returned value R, the manifest method will: 843 /// - mark R with the "returned" attribute, if R is an argument. 844 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState { 845 846 /// Mapping of values potentially returned by the associated function to the 847 /// return instructions that might return them. 848 MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues; 849 850 /// Mapping to remember the number of returned values for a call site such 851 /// that we can avoid updates if nothing changed. 852 DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA; 853 854 /// Set of unresolved calls returned by the associated function. 855 SmallSetVector<CallBase *, 4> UnresolvedCalls; 856 857 /// State flags 858 /// 859 ///{ 860 bool IsFixed = false; 861 bool IsValidState = true; 862 ///} 863 864 public: 865 AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {} 866 867 /// See AbstractAttribute::initialize(...). 868 void initialize(Attributor &A) override { 869 // Reset the state. 870 IsFixed = false; 871 IsValidState = true; 872 ReturnedValues.clear(); 873 874 Function *F = getAssociatedFunction(); 875 if (!F) { 876 indicatePessimisticFixpoint(); 877 return; 878 } 879 880 // The map from instruction opcodes to those instructions in the function. 881 auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F); 882 883 // Look through all arguments, if one is marked as returned we are done. 884 for (Argument &Arg : F->args()) { 885 if (Arg.hasReturnedAttr()) { 886 auto &ReturnInstSet = ReturnedValues[&Arg]; 887 for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) 888 ReturnInstSet.insert(cast<ReturnInst>(RI)); 889 890 indicateOptimisticFixpoint(); 891 return; 892 } 893 } 894 895 if (!F->hasExactDefinition()) 896 indicatePessimisticFixpoint(); 897 } 898 899 /// See AbstractAttribute::manifest(...). 900 ChangeStatus manifest(Attributor &A) override; 901 902 /// See AbstractAttribute::getState(...). 903 AbstractState &getState() override { return *this; } 904 905 /// See AbstractAttribute::getState(...). 906 const AbstractState &getState() const override { return *this; } 907 908 /// See AbstractAttribute::updateImpl(Attributor &A). 909 ChangeStatus updateImpl(Attributor &A) override; 910 911 llvm::iterator_range<iterator> returned_values() override { 912 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 913 } 914 915 llvm::iterator_range<const_iterator> returned_values() const override { 916 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 917 } 918 919 const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override { 920 return UnresolvedCalls; 921 } 922 923 /// Return the number of potential return values, -1 if unknown. 924 size_t getNumReturnValues() const override { 925 return isValidState() ? ReturnedValues.size() : -1; 926 } 927 928 /// Return an assumed unique return value if a single candidate is found. If 929 /// there cannot be one, return a nullptr. If it is not clear yet, return the 930 /// Optional::NoneType. 931 Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const; 932 933 /// See AbstractState::checkForAllReturnedValues(...). 934 bool checkForAllReturnedValuesAndReturnInsts( 935 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 936 &Pred) const override; 937 938 /// Pretty print the attribute similar to the IR representation. 939 const std::string getAsStr() const override; 940 941 /// See AbstractState::isAtFixpoint(). 942 bool isAtFixpoint() const override { return IsFixed; } 943 944 /// See AbstractState::isValidState(). 945 bool isValidState() const override { return IsValidState; } 946 947 /// See AbstractState::indicateOptimisticFixpoint(...). 948 ChangeStatus indicateOptimisticFixpoint() override { 949 IsFixed = true; 950 return ChangeStatus::UNCHANGED; 951 } 952 953 ChangeStatus indicatePessimisticFixpoint() override { 954 IsFixed = true; 955 IsValidState = false; 956 return ChangeStatus::CHANGED; 957 } 958 }; 959 960 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { 961 ChangeStatus Changed = ChangeStatus::UNCHANGED; 962 963 // Bookkeeping. 964 assert(isValidState()); 965 STATS_DECLTRACK(KnownReturnValues, FunctionReturn, 966 "Number of function with known return values"); 967 968 // Check if we have an assumed unique return value that we could manifest. 969 Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); 970 971 if (!UniqueRV.hasValue() || !UniqueRV.getValue()) 972 return Changed; 973 974 // Bookkeeping. 975 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, 976 "Number of function with unique return"); 977 978 // Callback to replace the uses of CB with the constant C. 979 auto ReplaceCallSiteUsersWith = [](CallBase &CB, Constant &C) { 980 if (CB.getNumUses() == 0 || CB.isMustTailCall()) 981 return ChangeStatus::UNCHANGED; 982 CB.replaceAllUsesWith(&C); 983 return ChangeStatus::CHANGED; 984 }; 985 986 // If the assumed unique return value is an argument, annotate it. 987 if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { 988 // TODO: This should be handled differently! 989 this->AnchorVal = UniqueRVArg; 990 this->KindOrArgNo = UniqueRVArg->getArgNo(); 991 Changed = IRAttribute::manifest(A); 992 } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) { 993 // We can replace the returned value with the unique returned constant. 994 Value &AnchorValue = getAnchorValue(); 995 if (Function *F = dyn_cast<Function>(&AnchorValue)) { 996 for (const Use &U : F->uses()) 997 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) 998 if (CB->isCallee(&U)) { 999 Constant *RVCCast = 1000 ConstantExpr::getTruncOrBitCast(RVC, CB->getType()); 1001 Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed; 1002 } 1003 } else { 1004 assert(isa<CallBase>(AnchorValue) && 1005 "Expcected a function or call base anchor!"); 1006 Constant *RVCCast = 1007 ConstantExpr::getTruncOrBitCast(RVC, AnchorValue.getType()); 1008 Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast); 1009 } 1010 if (Changed == ChangeStatus::CHANGED) 1011 STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn, 1012 "Number of function returns replaced by constant return"); 1013 } 1014 1015 return Changed; 1016 } 1017 1018 const std::string AAReturnedValuesImpl::getAsStr() const { 1019 return (isAtFixpoint() ? "returns(#" : "may-return(#") + 1020 (isValidState() ? std::to_string(getNumReturnValues()) : "?") + 1021 ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]"; 1022 } 1023 1024 Optional<Value *> 1025 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const { 1026 // If checkForAllReturnedValues provides a unique value, ignoring potential 1027 // undef values that can also be present, it is assumed to be the actual 1028 // return value and forwarded to the caller of this method. If there are 1029 // multiple, a nullptr is returned indicating there cannot be a unique 1030 // returned value. 1031 Optional<Value *> UniqueRV; 1032 1033 auto Pred = [&](Value &RV) -> bool { 1034 // If we found a second returned value and neither the current nor the saved 1035 // one is an undef, there is no unique returned value. Undefs are special 1036 // since we can pretend they have any value. 1037 if (UniqueRV.hasValue() && UniqueRV != &RV && 1038 !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) { 1039 UniqueRV = nullptr; 1040 return false; 1041 } 1042 1043 // Do not overwrite a value with an undef. 1044 if (!UniqueRV.hasValue() || !isa<UndefValue>(RV)) 1045 UniqueRV = &RV; 1046 1047 return true; 1048 }; 1049 1050 if (!A.checkForAllReturnedValues(Pred, *this)) 1051 UniqueRV = nullptr; 1052 1053 return UniqueRV; 1054 } 1055 1056 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts( 1057 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 1058 &Pred) const { 1059 if (!isValidState()) 1060 return false; 1061 1062 // Check all returned values but ignore call sites as long as we have not 1063 // encountered an overdefined one during an update. 1064 for (auto &It : ReturnedValues) { 1065 Value *RV = It.first; 1066 1067 CallBase *CB = dyn_cast<CallBase>(RV); 1068 if (CB && !UnresolvedCalls.count(CB)) 1069 continue; 1070 1071 if (!Pred(*RV, It.second)) 1072 return false; 1073 } 1074 1075 return true; 1076 } 1077 1078 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { 1079 size_t NumUnresolvedCalls = UnresolvedCalls.size(); 1080 bool Changed = false; 1081 1082 // State used in the value traversals starting in returned values. 1083 struct RVState { 1084 // The map in which we collect return values -> return instrs. 1085 decltype(ReturnedValues) &RetValsMap; 1086 // The flag to indicate a change. 1087 bool &Changed; 1088 // The return instrs we come from. 1089 SmallSetVector<ReturnInst *, 4> RetInsts; 1090 }; 1091 1092 // Callback for a leaf value returned by the associated function. 1093 auto VisitValueCB = [](Value &Val, RVState &RVS, bool) -> bool { 1094 auto Size = RVS.RetValsMap[&Val].size(); 1095 RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end()); 1096 bool Inserted = RVS.RetValsMap[&Val].size() != Size; 1097 RVS.Changed |= Inserted; 1098 LLVM_DEBUG({ 1099 if (Inserted) 1100 dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val 1101 << " => " << RVS.RetInsts.size() << "\n"; 1102 }); 1103 return true; 1104 }; 1105 1106 // Helper method to invoke the generic value traversal. 1107 auto VisitReturnedValue = [&](Value &RV, RVState &RVS) { 1108 IRPosition RetValPos = IRPosition::value(RV); 1109 return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *this, 1110 RVS, VisitValueCB); 1111 }; 1112 1113 // Callback for all "return intructions" live in the associated function. 1114 auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) { 1115 ReturnInst &Ret = cast<ReturnInst>(I); 1116 RVState RVS({ReturnedValues, Changed, {}}); 1117 RVS.RetInsts.insert(&Ret); 1118 return VisitReturnedValue(*Ret.getReturnValue(), RVS); 1119 }; 1120 1121 // Start by discovering returned values from all live returned instructions in 1122 // the associated function. 1123 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret})) 1124 return indicatePessimisticFixpoint(); 1125 1126 // Once returned values "directly" present in the code are handled we try to 1127 // resolve returned calls. 1128 decltype(ReturnedValues) NewRVsMap; 1129 for (auto &It : ReturnedValues) { 1130 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first 1131 << " by #" << It.second.size() << " RIs\n"); 1132 CallBase *CB = dyn_cast<CallBase>(It.first); 1133 if (!CB || UnresolvedCalls.count(CB)) 1134 continue; 1135 1136 if (!CB->getCalledFunction()) { 1137 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1138 << "\n"); 1139 UnresolvedCalls.insert(CB); 1140 continue; 1141 } 1142 1143 // TODO: use the function scope once we have call site AAReturnedValues. 1144 const auto &RetValAA = A.getAAFor<AAReturnedValues>( 1145 *this, IRPosition::function(*CB->getCalledFunction())); 1146 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: " 1147 << static_cast<const AbstractAttribute &>(RetValAA) 1148 << "\n"); 1149 1150 // Skip dead ends, thus if we do not know anything about the returned 1151 // call we mark it as unresolved and it will stay that way. 1152 if (!RetValAA.getState().isValidState()) { 1153 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1154 << "\n"); 1155 UnresolvedCalls.insert(CB); 1156 continue; 1157 } 1158 1159 // Do not try to learn partial information. If the callee has unresolved 1160 // return values we will treat the call as unresolved/opaque. 1161 auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls(); 1162 if (!RetValAAUnresolvedCalls.empty()) { 1163 UnresolvedCalls.insert(CB); 1164 continue; 1165 } 1166 1167 // Now check if we can track transitively returned values. If possible, thus 1168 // if all return value can be represented in the current scope, do so. 1169 bool Unresolved = false; 1170 for (auto &RetValAAIt : RetValAA.returned_values()) { 1171 Value *RetVal = RetValAAIt.first; 1172 if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) || 1173 isa<Constant>(RetVal)) 1174 continue; 1175 // Anything that did not fit in the above categories cannot be resolved, 1176 // mark the call as unresolved. 1177 LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value " 1178 "cannot be translated: " 1179 << *RetVal << "\n"); 1180 UnresolvedCalls.insert(CB); 1181 Unresolved = true; 1182 break; 1183 } 1184 1185 if (Unresolved) 1186 continue; 1187 1188 // Now track transitively returned values. 1189 unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB]; 1190 if (NumRetAA == RetValAA.getNumReturnValues()) { 1191 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not " 1192 "changed since it was seen last\n"); 1193 continue; 1194 } 1195 NumRetAA = RetValAA.getNumReturnValues(); 1196 1197 for (auto &RetValAAIt : RetValAA.returned_values()) { 1198 Value *RetVal = RetValAAIt.first; 1199 if (Argument *Arg = dyn_cast<Argument>(RetVal)) { 1200 // Arguments are mapped to call site operands and we begin the traversal 1201 // again. 1202 bool Unused = false; 1203 RVState RVS({NewRVsMap, Unused, RetValAAIt.second}); 1204 VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS); 1205 continue; 1206 } else if (isa<CallBase>(RetVal)) { 1207 // Call sites are resolved by the callee attribute over time, no need to 1208 // do anything for us. 1209 continue; 1210 } else if (isa<Constant>(RetVal)) { 1211 // Constants are valid everywhere, we can simply take them. 1212 NewRVsMap[RetVal].insert(It.second.begin(), It.second.end()); 1213 continue; 1214 } 1215 } 1216 } 1217 1218 // To avoid modifications to the ReturnedValues map while we iterate over it 1219 // we kept record of potential new entries in a copy map, NewRVsMap. 1220 for (auto &It : NewRVsMap) { 1221 assert(!It.second.empty() && "Entry does not add anything."); 1222 auto &ReturnInsts = ReturnedValues[It.first]; 1223 for (ReturnInst *RI : It.second) 1224 if (ReturnInsts.insert(RI)) { 1225 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value " 1226 << *It.first << " => " << *RI << "\n"); 1227 Changed = true; 1228 } 1229 } 1230 1231 Changed |= (NumUnresolvedCalls != UnresolvedCalls.size()); 1232 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 1233 } 1234 1235 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl { 1236 AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {} 1237 1238 /// See AbstractAttribute::trackStatistics() 1239 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) } 1240 }; 1241 1242 /// Returned values information for a call sites. 1243 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl { 1244 AAReturnedValuesCallSite(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {} 1245 1246 /// See AbstractAttribute::initialize(...). 1247 void initialize(Attributor &A) override { 1248 // TODO: Once we have call site specific value information we can provide 1249 // call site specific liveness information and then it makes 1250 // sense to specialize attributes for call sites instead of 1251 // redirecting requests to the callee. 1252 llvm_unreachable("Abstract attributes for returned values are not " 1253 "supported for call sites yet!"); 1254 } 1255 1256 /// See AbstractAttribute::updateImpl(...). 1257 ChangeStatus updateImpl(Attributor &A) override { 1258 return indicatePessimisticFixpoint(); 1259 } 1260 1261 /// See AbstractAttribute::trackStatistics() 1262 void trackStatistics() const override {} 1263 }; 1264 1265 /// ------------------------ NoSync Function Attribute ------------------------- 1266 1267 struct AANoSyncImpl : AANoSync { 1268 AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {} 1269 1270 const std::string getAsStr() const override { 1271 return getAssumed() ? "nosync" : "may-sync"; 1272 } 1273 1274 /// See AbstractAttribute::updateImpl(...). 1275 ChangeStatus updateImpl(Attributor &A) override; 1276 1277 /// Helper function used to determine whether an instruction is non-relaxed 1278 /// atomic. In other words, if an atomic instruction does not have unordered 1279 /// or monotonic ordering 1280 static bool isNonRelaxedAtomic(Instruction *I); 1281 1282 /// Helper function used to determine whether an instruction is volatile. 1283 static bool isVolatile(Instruction *I); 1284 1285 /// Helper function uset to check if intrinsic is volatile (memcpy, memmove, 1286 /// memset). 1287 static bool isNoSyncIntrinsic(Instruction *I); 1288 }; 1289 1290 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) { 1291 if (!I->isAtomic()) 1292 return false; 1293 1294 AtomicOrdering Ordering; 1295 switch (I->getOpcode()) { 1296 case Instruction::AtomicRMW: 1297 Ordering = cast<AtomicRMWInst>(I)->getOrdering(); 1298 break; 1299 case Instruction::Store: 1300 Ordering = cast<StoreInst>(I)->getOrdering(); 1301 break; 1302 case Instruction::Load: 1303 Ordering = cast<LoadInst>(I)->getOrdering(); 1304 break; 1305 case Instruction::Fence: { 1306 auto *FI = cast<FenceInst>(I); 1307 if (FI->getSyncScopeID() == SyncScope::SingleThread) 1308 return false; 1309 Ordering = FI->getOrdering(); 1310 break; 1311 } 1312 case Instruction::AtomicCmpXchg: { 1313 AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering(); 1314 AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering(); 1315 // Only if both are relaxed, than it can be treated as relaxed. 1316 // Otherwise it is non-relaxed. 1317 if (Success != AtomicOrdering::Unordered && 1318 Success != AtomicOrdering::Monotonic) 1319 return true; 1320 if (Failure != AtomicOrdering::Unordered && 1321 Failure != AtomicOrdering::Monotonic) 1322 return true; 1323 return false; 1324 } 1325 default: 1326 llvm_unreachable( 1327 "New atomic operations need to be known in the attributor."); 1328 } 1329 1330 // Relaxed. 1331 if (Ordering == AtomicOrdering::Unordered || 1332 Ordering == AtomicOrdering::Monotonic) 1333 return false; 1334 return true; 1335 } 1336 1337 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics. 1338 /// FIXME: We should ipmrove the handling of intrinsics. 1339 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) { 1340 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1341 switch (II->getIntrinsicID()) { 1342 /// Element wise atomic memory intrinsics are can only be unordered, 1343 /// therefore nosync. 1344 case Intrinsic::memset_element_unordered_atomic: 1345 case Intrinsic::memmove_element_unordered_atomic: 1346 case Intrinsic::memcpy_element_unordered_atomic: 1347 return true; 1348 case Intrinsic::memset: 1349 case Intrinsic::memmove: 1350 case Intrinsic::memcpy: 1351 if (!cast<MemIntrinsic>(II)->isVolatile()) 1352 return true; 1353 return false; 1354 default: 1355 return false; 1356 } 1357 } 1358 return false; 1359 } 1360 1361 bool AANoSyncImpl::isVolatile(Instruction *I) { 1362 assert(!ImmutableCallSite(I) && !isa<CallBase>(I) && 1363 "Calls should not be checked here"); 1364 1365 switch (I->getOpcode()) { 1366 case Instruction::AtomicRMW: 1367 return cast<AtomicRMWInst>(I)->isVolatile(); 1368 case Instruction::Store: 1369 return cast<StoreInst>(I)->isVolatile(); 1370 case Instruction::Load: 1371 return cast<LoadInst>(I)->isVolatile(); 1372 case Instruction::AtomicCmpXchg: 1373 return cast<AtomicCmpXchgInst>(I)->isVolatile(); 1374 default: 1375 return false; 1376 } 1377 } 1378 1379 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) { 1380 1381 auto CheckRWInstForNoSync = [&](Instruction &I) { 1382 /// We are looking for volatile instructions or Non-Relaxed atomics. 1383 /// FIXME: We should ipmrove the handling of intrinsics. 1384 1385 if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I)) 1386 return true; 1387 1388 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 1389 if (ICS.hasFnAttr(Attribute::NoSync)) 1390 return true; 1391 1392 const auto &NoSyncAA = 1393 A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(ICS)); 1394 if (NoSyncAA.isAssumedNoSync()) 1395 return true; 1396 return false; 1397 } 1398 1399 if (!isVolatile(&I) && !isNonRelaxedAtomic(&I)) 1400 return true; 1401 1402 return false; 1403 }; 1404 1405 auto CheckForNoSync = [&](Instruction &I) { 1406 // At this point we handled all read/write effects and they are all 1407 // nosync, so they can be skipped. 1408 if (I.mayReadOrWriteMemory()) 1409 return true; 1410 1411 // non-convergent and readnone imply nosync. 1412 return !ImmutableCallSite(&I).isConvergent(); 1413 }; 1414 1415 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) || 1416 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this)) 1417 return indicatePessimisticFixpoint(); 1418 1419 return ChangeStatus::UNCHANGED; 1420 } 1421 1422 struct AANoSyncFunction final : public AANoSyncImpl { 1423 AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {} 1424 1425 /// See AbstractAttribute::trackStatistics() 1426 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) } 1427 }; 1428 1429 /// NoSync attribute deduction for a call sites. 1430 struct AANoSyncCallSite final : AANoSyncImpl { 1431 AANoSyncCallSite(const IRPosition &IRP) : AANoSyncImpl(IRP) {} 1432 1433 /// See AbstractAttribute::initialize(...). 1434 void initialize(Attributor &A) override { 1435 AANoSyncImpl::initialize(A); 1436 Function *F = getAssociatedFunction(); 1437 if (!F) 1438 indicatePessimisticFixpoint(); 1439 } 1440 1441 /// See AbstractAttribute::updateImpl(...). 1442 ChangeStatus updateImpl(Attributor &A) override { 1443 // TODO: Once we have call site specific value information we can provide 1444 // call site specific liveness information and then it makes 1445 // sense to specialize attributes for call sites arguments instead of 1446 // redirecting requests to the callee argument. 1447 Function *F = getAssociatedFunction(); 1448 const IRPosition &FnPos = IRPosition::function(*F); 1449 auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos); 1450 return clampStateAndIndicateChange( 1451 getState(), static_cast<const AANoSync::StateType &>(FnAA.getState())); 1452 } 1453 1454 /// See AbstractAttribute::trackStatistics() 1455 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); } 1456 }; 1457 1458 /// ------------------------ No-Free Attributes ---------------------------- 1459 1460 struct AANoFreeImpl : public AANoFree { 1461 AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {} 1462 1463 /// See AbstractAttribute::updateImpl(...). 1464 ChangeStatus updateImpl(Attributor &A) override { 1465 auto CheckForNoFree = [&](Instruction &I) { 1466 ImmutableCallSite ICS(&I); 1467 if (ICS.hasFnAttr(Attribute::NoFree)) 1468 return true; 1469 1470 const auto &NoFreeAA = 1471 A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(ICS)); 1472 return NoFreeAA.isAssumedNoFree(); 1473 }; 1474 1475 if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this)) 1476 return indicatePessimisticFixpoint(); 1477 return ChangeStatus::UNCHANGED; 1478 } 1479 1480 /// See AbstractAttribute::getAsStr(). 1481 const std::string getAsStr() const override { 1482 return getAssumed() ? "nofree" : "may-free"; 1483 } 1484 }; 1485 1486 struct AANoFreeFunction final : public AANoFreeImpl { 1487 AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {} 1488 1489 /// See AbstractAttribute::trackStatistics() 1490 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) } 1491 }; 1492 1493 /// NoFree attribute deduction for a call sites. 1494 struct AANoFreeCallSite final : AANoFreeImpl { 1495 AANoFreeCallSite(const IRPosition &IRP) : AANoFreeImpl(IRP) {} 1496 1497 /// See AbstractAttribute::initialize(...). 1498 void initialize(Attributor &A) override { 1499 AANoFreeImpl::initialize(A); 1500 Function *F = getAssociatedFunction(); 1501 if (!F) 1502 indicatePessimisticFixpoint(); 1503 } 1504 1505 /// See AbstractAttribute::updateImpl(...). 1506 ChangeStatus updateImpl(Attributor &A) override { 1507 // TODO: Once we have call site specific value information we can provide 1508 // call site specific liveness information and then it makes 1509 // sense to specialize attributes for call sites arguments instead of 1510 // redirecting requests to the callee argument. 1511 Function *F = getAssociatedFunction(); 1512 const IRPosition &FnPos = IRPosition::function(*F); 1513 auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos); 1514 return clampStateAndIndicateChange( 1515 getState(), static_cast<const AANoFree::StateType &>(FnAA.getState())); 1516 } 1517 1518 /// See AbstractAttribute::trackStatistics() 1519 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); } 1520 }; 1521 1522 /// ------------------------ NonNull Argument Attribute ------------------------ 1523 static int64_t getKnownNonNullAndDerefBytesForUse( 1524 Attributor &A, AbstractAttribute &QueryingAA, Value &AssociatedValue, 1525 const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) { 1526 TrackUse = false; 1527 1528 const Value *UseV = U->get(); 1529 if (!UseV->getType()->isPointerTy()) 1530 return 0; 1531 1532 Type *PtrTy = UseV->getType(); 1533 const Function *F = I->getFunction(); 1534 bool NullPointerIsDefined = 1535 F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true; 1536 const DataLayout &DL = A.getInfoCache().getDL(); 1537 if (ImmutableCallSite ICS = ImmutableCallSite(I)) { 1538 if (ICS.isBundleOperand(U)) 1539 return 0; 1540 1541 if (ICS.isCallee(U)) { 1542 IsNonNull |= !NullPointerIsDefined; 1543 return 0; 1544 } 1545 1546 unsigned ArgNo = ICS.getArgumentNo(U); 1547 IRPosition IRP = IRPosition::callsite_argument(ICS, ArgNo); 1548 auto &DerefAA = A.getAAFor<AADereferenceable>(QueryingAA, IRP); 1549 IsNonNull |= DerefAA.isKnownNonNull(); 1550 return DerefAA.getKnownDereferenceableBytes(); 1551 } 1552 1553 int64_t Offset; 1554 if (const Value *Base = getBasePointerOfAccessPointerOperand(I, Offset, DL)) { 1555 if (Base == &AssociatedValue && getPointerOperand(I) == UseV) { 1556 int64_t DerefBytes = 1557 Offset + (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()); 1558 1559 IsNonNull |= !NullPointerIsDefined; 1560 return DerefBytes; 1561 } 1562 } 1563 if (const Value *Base = 1564 GetPointerBaseWithConstantOffset(UseV, Offset, DL, 1565 /*AllowNonInbounds*/ false)) { 1566 auto &DerefAA = 1567 A.getAAFor<AADereferenceable>(QueryingAA, IRPosition::value(*Base)); 1568 IsNonNull |= (!NullPointerIsDefined && DerefAA.isKnownNonNull()); 1569 IsNonNull |= (!NullPointerIsDefined && (Offset != 0)); 1570 int64_t DerefBytes = DerefAA.getKnownDereferenceableBytes(); 1571 return std::max(int64_t(0), DerefBytes - Offset); 1572 } 1573 1574 return 0; 1575 } 1576 1577 struct AANonNullImpl : AANonNull { 1578 AANonNullImpl(const IRPosition &IRP) 1579 : AANonNull(IRP), 1580 NullIsDefined(NullPointerIsDefined( 1581 getAnchorScope(), 1582 getAssociatedValue().getType()->getPointerAddressSpace())) {} 1583 1584 /// See AbstractAttribute::initialize(...). 1585 void initialize(Attributor &A) override { 1586 if (!NullIsDefined && 1587 hasAttr({Attribute::NonNull, Attribute::Dereferenceable})) 1588 indicateOptimisticFixpoint(); 1589 else 1590 AANonNull::initialize(A); 1591 } 1592 1593 /// See AAFromMustBeExecutedContext 1594 bool followUse(Attributor &A, const Use *U, const Instruction *I) { 1595 bool IsNonNull = false; 1596 bool TrackUse = false; 1597 getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I, 1598 IsNonNull, TrackUse); 1599 setKnown(IsNonNull); 1600 return TrackUse; 1601 } 1602 1603 /// See AbstractAttribute::getAsStr(). 1604 const std::string getAsStr() const override { 1605 return getAssumed() ? "nonnull" : "may-null"; 1606 } 1607 1608 /// Flag to determine if the underlying value can be null and still allow 1609 /// valid accesses. 1610 const bool NullIsDefined; 1611 }; 1612 1613 /// NonNull attribute for a floating value. 1614 struct AANonNullFloating 1615 : AAFromMustBeExecutedContext<AANonNull, AANonNullImpl> { 1616 using Base = AAFromMustBeExecutedContext<AANonNull, AANonNullImpl>; 1617 AANonNullFloating(const IRPosition &IRP) : Base(IRP) {} 1618 1619 /// See AbstractAttribute::initialize(...). 1620 void initialize(Attributor &A) override { 1621 Base::initialize(A); 1622 1623 if (isAtFixpoint()) 1624 return; 1625 1626 const IRPosition &IRP = getIRPosition(); 1627 const Value &V = IRP.getAssociatedValue(); 1628 const DataLayout &DL = A.getDataLayout(); 1629 1630 // TODO: This context sensitive query should be removed once we can do 1631 // context sensitive queries in the genericValueTraversal below. 1632 if (isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, IRP.getCtxI(), 1633 /* TODO: DT */ nullptr)) 1634 indicateOptimisticFixpoint(); 1635 } 1636 1637 /// See AbstractAttribute::updateImpl(...). 1638 ChangeStatus updateImpl(Attributor &A) override { 1639 ChangeStatus Change = Base::updateImpl(A); 1640 if (isKnownNonNull()) 1641 return Change; 1642 1643 if (!NullIsDefined) { 1644 const auto &DerefAA = A.getAAFor<AADereferenceable>(*this, getIRPosition()); 1645 if (DerefAA.getAssumedDereferenceableBytes()) 1646 return Change; 1647 } 1648 1649 const DataLayout &DL = A.getDataLayout(); 1650 1651 auto VisitValueCB = [&](Value &V, AANonNull::StateType &T, 1652 bool Stripped) -> bool { 1653 const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V)); 1654 if (!Stripped && this == &AA) { 1655 if (!isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, 1656 /* CtxI */ getCtxI(), 1657 /* TODO: DT */ nullptr)) 1658 T.indicatePessimisticFixpoint(); 1659 } else { 1660 // Use abstract attribute information. 1661 const AANonNull::StateType &NS = 1662 static_cast<const AANonNull::StateType &>(AA.getState()); 1663 T ^= NS; 1664 } 1665 return T.isValidState(); 1666 }; 1667 1668 StateType T; 1669 if (!genericValueTraversal<AANonNull, StateType>(A, getIRPosition(), *this, 1670 T, VisitValueCB)) 1671 return indicatePessimisticFixpoint(); 1672 1673 return clampStateAndIndicateChange(getState(), T); 1674 } 1675 1676 /// See AbstractAttribute::trackStatistics() 1677 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1678 }; 1679 1680 /// NonNull attribute for function return value. 1681 struct AANonNullReturned final 1682 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> { 1683 AANonNullReturned(const IRPosition &IRP) 1684 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {} 1685 1686 /// See AbstractAttribute::trackStatistics() 1687 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1688 }; 1689 1690 /// NonNull attribute for function argument. 1691 struct AANonNullArgument final 1692 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull, 1693 AANonNullImpl> { 1694 AANonNullArgument(const IRPosition &IRP) 1695 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull, 1696 AANonNullImpl>( 1697 IRP) {} 1698 1699 /// See AbstractAttribute::trackStatistics() 1700 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) } 1701 }; 1702 1703 struct AANonNullCallSiteArgument final : AANonNullFloating { 1704 AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullFloating(IRP) {} 1705 1706 /// See AbstractAttribute::trackStatistics() 1707 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) } 1708 }; 1709 1710 /// NonNull attribute for a call site return position. 1711 struct AANonNullCallSiteReturned final 1712 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull, 1713 AANonNullImpl> { 1714 AANonNullCallSiteReturned(const IRPosition &IRP) 1715 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull, 1716 AANonNullImpl>( 1717 IRP) {} 1718 1719 /// See AbstractAttribute::trackStatistics() 1720 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) } 1721 }; 1722 1723 /// ------------------------ No-Recurse Attributes ---------------------------- 1724 1725 struct AANoRecurseImpl : public AANoRecurse { 1726 AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {} 1727 1728 /// See AbstractAttribute::getAsStr() 1729 const std::string getAsStr() const override { 1730 return getAssumed() ? "norecurse" : "may-recurse"; 1731 } 1732 }; 1733 1734 struct AANoRecurseFunction final : AANoRecurseImpl { 1735 AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {} 1736 1737 /// See AbstractAttribute::initialize(...). 1738 void initialize(Attributor &A) override { 1739 AANoRecurseImpl::initialize(A); 1740 if (const Function *F = getAnchorScope()) 1741 if (A.getInfoCache().getSccSize(*F) == 1) 1742 return; 1743 indicatePessimisticFixpoint(); 1744 } 1745 1746 /// See AbstractAttribute::updateImpl(...). 1747 ChangeStatus updateImpl(Attributor &A) override { 1748 1749 auto CheckForNoRecurse = [&](Instruction &I) { 1750 ImmutableCallSite ICS(&I); 1751 if (ICS.hasFnAttr(Attribute::NoRecurse)) 1752 return true; 1753 1754 const auto &NoRecurseAA = 1755 A.getAAFor<AANoRecurse>(*this, IRPosition::callsite_function(ICS)); 1756 if (!NoRecurseAA.isAssumedNoRecurse()) 1757 return false; 1758 1759 // Recursion to the same function 1760 if (ICS.getCalledFunction() == getAnchorScope()) 1761 return false; 1762 1763 return true; 1764 }; 1765 1766 if (!A.checkForAllCallLikeInstructions(CheckForNoRecurse, *this)) 1767 return indicatePessimisticFixpoint(); 1768 return ChangeStatus::UNCHANGED; 1769 } 1770 1771 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) } 1772 }; 1773 1774 /// NoRecurse attribute deduction for a call sites. 1775 struct AANoRecurseCallSite final : AANoRecurseImpl { 1776 AANoRecurseCallSite(const IRPosition &IRP) : AANoRecurseImpl(IRP) {} 1777 1778 /// See AbstractAttribute::initialize(...). 1779 void initialize(Attributor &A) override { 1780 AANoRecurseImpl::initialize(A); 1781 Function *F = getAssociatedFunction(); 1782 if (!F) 1783 indicatePessimisticFixpoint(); 1784 } 1785 1786 /// See AbstractAttribute::updateImpl(...). 1787 ChangeStatus updateImpl(Attributor &A) override { 1788 // TODO: Once we have call site specific value information we can provide 1789 // call site specific liveness information and then it makes 1790 // sense to specialize attributes for call sites arguments instead of 1791 // redirecting requests to the callee argument. 1792 Function *F = getAssociatedFunction(); 1793 const IRPosition &FnPos = IRPosition::function(*F); 1794 auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos); 1795 return clampStateAndIndicateChange( 1796 getState(), 1797 static_cast<const AANoRecurse::StateType &>(FnAA.getState())); 1798 } 1799 1800 /// See AbstractAttribute::trackStatistics() 1801 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); } 1802 }; 1803 1804 /// ------------------------ Will-Return Attributes ---------------------------- 1805 1806 // Helper function that checks whether a function has any cycle. 1807 // TODO: Replace with more efficent code 1808 static bool containsCycle(Function &F) { 1809 SmallPtrSet<BasicBlock *, 32> Visited; 1810 1811 // Traverse BB by dfs and check whether successor is already visited. 1812 for (BasicBlock *BB : depth_first(&F)) { 1813 Visited.insert(BB); 1814 for (auto *SuccBB : successors(BB)) { 1815 if (Visited.count(SuccBB)) 1816 return true; 1817 } 1818 } 1819 return false; 1820 } 1821 1822 // Helper function that checks the function have a loop which might become an 1823 // endless loop 1824 // FIXME: Any cycle is regarded as endless loop for now. 1825 // We have to allow some patterns. 1826 static bool containsPossiblyEndlessLoop(Function *F) { 1827 return !F || !F->hasExactDefinition() || containsCycle(*F); 1828 } 1829 1830 struct AAWillReturnImpl : public AAWillReturn { 1831 AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {} 1832 1833 /// See AbstractAttribute::initialize(...). 1834 void initialize(Attributor &A) override { 1835 AAWillReturn::initialize(A); 1836 1837 Function *F = getAssociatedFunction(); 1838 if (containsPossiblyEndlessLoop(F)) 1839 indicatePessimisticFixpoint(); 1840 } 1841 1842 /// See AbstractAttribute::updateImpl(...). 1843 ChangeStatus updateImpl(Attributor &A) override { 1844 auto CheckForWillReturn = [&](Instruction &I) { 1845 IRPosition IPos = IRPosition::callsite_function(ImmutableCallSite(&I)); 1846 const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos); 1847 if (WillReturnAA.isKnownWillReturn()) 1848 return true; 1849 if (!WillReturnAA.isAssumedWillReturn()) 1850 return false; 1851 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos); 1852 return NoRecurseAA.isAssumedNoRecurse(); 1853 }; 1854 1855 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this)) 1856 return indicatePessimisticFixpoint(); 1857 1858 return ChangeStatus::UNCHANGED; 1859 } 1860 1861 /// See AbstractAttribute::getAsStr() 1862 const std::string getAsStr() const override { 1863 return getAssumed() ? "willreturn" : "may-noreturn"; 1864 } 1865 }; 1866 1867 struct AAWillReturnFunction final : AAWillReturnImpl { 1868 AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {} 1869 1870 /// See AbstractAttribute::trackStatistics() 1871 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) } 1872 }; 1873 1874 /// WillReturn attribute deduction for a call sites. 1875 struct AAWillReturnCallSite final : AAWillReturnImpl { 1876 AAWillReturnCallSite(const IRPosition &IRP) : AAWillReturnImpl(IRP) {} 1877 1878 /// See AbstractAttribute::initialize(...). 1879 void initialize(Attributor &A) override { 1880 AAWillReturnImpl::initialize(A); 1881 Function *F = getAssociatedFunction(); 1882 if (!F) 1883 indicatePessimisticFixpoint(); 1884 } 1885 1886 /// See AbstractAttribute::updateImpl(...). 1887 ChangeStatus updateImpl(Attributor &A) override { 1888 // TODO: Once we have call site specific value information we can provide 1889 // call site specific liveness information and then it makes 1890 // sense to specialize attributes for call sites arguments instead of 1891 // redirecting requests to the callee argument. 1892 Function *F = getAssociatedFunction(); 1893 const IRPosition &FnPos = IRPosition::function(*F); 1894 auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos); 1895 return clampStateAndIndicateChange( 1896 getState(), 1897 static_cast<const AAWillReturn::StateType &>(FnAA.getState())); 1898 } 1899 1900 /// See AbstractAttribute::trackStatistics() 1901 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); } 1902 }; 1903 1904 /// ------------------------ NoAlias Argument Attribute ------------------------ 1905 1906 struct AANoAliasImpl : AANoAlias { 1907 AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {} 1908 1909 const std::string getAsStr() const override { 1910 return getAssumed() ? "noalias" : "may-alias"; 1911 } 1912 }; 1913 1914 /// NoAlias attribute for a floating value. 1915 struct AANoAliasFloating final : AANoAliasImpl { 1916 AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1917 1918 /// See AbstractAttribute::initialize(...). 1919 void initialize(Attributor &A) override { 1920 AANoAliasImpl::initialize(A); 1921 Value &Val = getAssociatedValue(); 1922 if (isa<AllocaInst>(Val)) 1923 indicateOptimisticFixpoint(); 1924 if (isa<ConstantPointerNull>(Val) && 1925 Val.getType()->getPointerAddressSpace() == 0) 1926 indicateOptimisticFixpoint(); 1927 } 1928 1929 /// See AbstractAttribute::updateImpl(...). 1930 ChangeStatus updateImpl(Attributor &A) override { 1931 // TODO: Implement this. 1932 return indicatePessimisticFixpoint(); 1933 } 1934 1935 /// See AbstractAttribute::trackStatistics() 1936 void trackStatistics() const override { 1937 STATS_DECLTRACK_FLOATING_ATTR(noalias) 1938 } 1939 }; 1940 1941 /// NoAlias attribute for an argument. 1942 struct AANoAliasArgument final 1943 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> { 1944 AANoAliasArgument(const IRPosition &IRP) 1945 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>(IRP) {} 1946 1947 /// See AbstractAttribute::trackStatistics() 1948 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 1949 }; 1950 1951 struct AANoAliasCallSiteArgument final : AANoAliasImpl { 1952 AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1953 1954 /// See AbstractAttribute::initialize(...). 1955 void initialize(Attributor &A) override { 1956 // See callsite argument attribute and callee argument attribute. 1957 ImmutableCallSite ICS(&getAnchorValue()); 1958 if (ICS.paramHasAttr(getArgNo(), Attribute::NoAlias)) 1959 indicateOptimisticFixpoint(); 1960 } 1961 1962 /// See AbstractAttribute::updateImpl(...). 1963 ChangeStatus updateImpl(Attributor &A) override { 1964 // We can deduce "noalias" if the following conditions hold. 1965 // (i) Associated value is assumed to be noalias in the definition. 1966 // (ii) Associated value is assumed to be no-capture in all the uses 1967 // possibly executed before this callsite. 1968 // (iii) There is no other pointer argument which could alias with the 1969 // value. 1970 1971 const Value &V = getAssociatedValue(); 1972 const IRPosition IRP = IRPosition::value(V); 1973 1974 // (i) Check whether noalias holds in the definition. 1975 1976 auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP); 1977 1978 if (!NoAliasAA.isAssumedNoAlias()) 1979 return indicatePessimisticFixpoint(); 1980 1981 LLVM_DEBUG(dbgs() << "[Attributor][AANoAliasCSArg] " << V 1982 << " is assumed NoAlias in the definition\n"); 1983 1984 // (ii) Check whether the value is captured in the scope using AANoCapture. 1985 // FIXME: This is conservative though, it is better to look at CFG and 1986 // check only uses possibly executed before this callsite. 1987 1988 auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP); 1989 if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 1990 LLVM_DEBUG( 1991 dbgs() << "[Attributor][AANoAliasCSArg] " << V 1992 << " cannot be noalias as it is potentially captured\n"); 1993 return indicatePessimisticFixpoint(); 1994 } 1995 1996 // (iii) Check there is no other pointer argument which could alias with the 1997 // value. 1998 ImmutableCallSite ICS(&getAnchorValue()); 1999 for (unsigned i = 0; i < ICS.getNumArgOperands(); i++) { 2000 if (getArgNo() == (int)i) 2001 continue; 2002 const Value *ArgOp = ICS.getArgOperand(i); 2003 if (!ArgOp->getType()->isPointerTy()) 2004 continue; 2005 2006 if (const Function *F = getAnchorScope()) { 2007 if (AAResults *AAR = A.getInfoCache().getAAResultsForFunction(*F)) { 2008 bool IsAliasing = AAR->isNoAlias(&getAssociatedValue(), ArgOp); 2009 LLVM_DEBUG(dbgs() 2010 << "[Attributor][NoAliasCSArg] Check alias between " 2011 "callsite arguments " 2012 << AAR->isNoAlias(&getAssociatedValue(), ArgOp) << " " 2013 << getAssociatedValue() << " " << *ArgOp << " => " 2014 << (IsAliasing ? "" : "no-") << "alias \n"); 2015 2016 if (IsAliasing) 2017 continue; 2018 } 2019 } 2020 return indicatePessimisticFixpoint(); 2021 } 2022 2023 return ChangeStatus::UNCHANGED; 2024 } 2025 2026 /// See AbstractAttribute::trackStatistics() 2027 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) } 2028 }; 2029 2030 /// NoAlias attribute for function return value. 2031 struct AANoAliasReturned final : AANoAliasImpl { 2032 AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 2033 2034 /// See AbstractAttribute::updateImpl(...). 2035 virtual ChangeStatus updateImpl(Attributor &A) override { 2036 2037 auto CheckReturnValue = [&](Value &RV) -> bool { 2038 if (Constant *C = dyn_cast<Constant>(&RV)) 2039 if (C->isNullValue() || isa<UndefValue>(C)) 2040 return true; 2041 2042 /// For now, we can only deduce noalias if we have call sites. 2043 /// FIXME: add more support. 2044 ImmutableCallSite ICS(&RV); 2045 if (!ICS) 2046 return false; 2047 2048 const IRPosition &RVPos = IRPosition::value(RV); 2049 const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos); 2050 if (!NoAliasAA.isAssumedNoAlias()) 2051 return false; 2052 2053 const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos); 2054 return NoCaptureAA.isAssumedNoCaptureMaybeReturned(); 2055 }; 2056 2057 if (!A.checkForAllReturnedValues(CheckReturnValue, *this)) 2058 return indicatePessimisticFixpoint(); 2059 2060 return ChangeStatus::UNCHANGED; 2061 } 2062 2063 /// See AbstractAttribute::trackStatistics() 2064 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) } 2065 }; 2066 2067 /// NoAlias attribute deduction for a call site return value. 2068 struct AANoAliasCallSiteReturned final : AANoAliasImpl { 2069 AANoAliasCallSiteReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 2070 2071 /// See AbstractAttribute::initialize(...). 2072 void initialize(Attributor &A) override { 2073 AANoAliasImpl::initialize(A); 2074 Function *F = getAssociatedFunction(); 2075 if (!F) 2076 indicatePessimisticFixpoint(); 2077 } 2078 2079 /// See AbstractAttribute::updateImpl(...). 2080 ChangeStatus updateImpl(Attributor &A) override { 2081 // TODO: Once we have call site specific value information we can provide 2082 // call site specific liveness information and then it makes 2083 // sense to specialize attributes for call sites arguments instead of 2084 // redirecting requests to the callee argument. 2085 Function *F = getAssociatedFunction(); 2086 const IRPosition &FnPos = IRPosition::returned(*F); 2087 auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos); 2088 return clampStateAndIndicateChange( 2089 getState(), static_cast<const AANoAlias::StateType &>(FnAA.getState())); 2090 } 2091 2092 /// See AbstractAttribute::trackStatistics() 2093 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); } 2094 }; 2095 2096 /// -------------------AAIsDead Function Attribute----------------------- 2097 2098 struct AAIsDeadValueImpl : public AAIsDead { 2099 AAIsDeadValueImpl(const IRPosition &IRP) : AAIsDead(IRP) {} 2100 2101 /// See AAIsDead::isAssumedDead(). 2102 bool isAssumedDead() const override { return getAssumed(); } 2103 2104 /// See AAIsDead::isAssumedDead(BasicBlock *). 2105 bool isAssumedDead(const BasicBlock *BB) const override { return false; } 2106 2107 /// See AAIsDead::isKnownDead(BasicBlock *). 2108 bool isKnownDead(const BasicBlock *BB) const override { return false; } 2109 2110 /// See AAIsDead::isAssumedDead(Instruction *I). 2111 bool isAssumedDead(const Instruction *I) const override { 2112 return I == getCtxI() && isAssumedDead(); 2113 } 2114 2115 /// See AAIsDead::isKnownDead(Instruction *I). 2116 bool isKnownDead(const Instruction *I) const override { 2117 return I == getCtxI() && getKnown(); 2118 } 2119 2120 /// See AbstractAttribute::getAsStr(). 2121 const std::string getAsStr() const override { 2122 return isAssumedDead() ? "assumed-dead" : "assumed-live"; 2123 } 2124 }; 2125 2126 struct AAIsDeadFloating : public AAIsDeadValueImpl { 2127 AAIsDeadFloating(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {} 2128 2129 /// See AbstractAttribute::initialize(...). 2130 void initialize(Attributor &A) override { 2131 if (Instruction *I = dyn_cast<Instruction>(&getAssociatedValue())) 2132 if (!wouldInstructionBeTriviallyDead(I)) 2133 indicatePessimisticFixpoint(); 2134 if (isa<UndefValue>(getAssociatedValue())) 2135 indicatePessimisticFixpoint(); 2136 } 2137 2138 /// See AbstractAttribute::updateImpl(...). 2139 ChangeStatus updateImpl(Attributor &A) override { 2140 auto UsePred = [&](const Use &U, bool &Follow) { 2141 Instruction *UserI = cast<Instruction>(U.getUser()); 2142 if (CallSite CS = CallSite(UserI)) { 2143 if (!CS.isArgOperand(&U)) 2144 return false; 2145 const IRPosition &CSArgPos = 2146 IRPosition::callsite_argument(CS, CS.getArgumentNo(&U)); 2147 const auto &CSArgIsDead = A.getAAFor<AAIsDead>(*this, CSArgPos); 2148 return CSArgIsDead.isAssumedDead(); 2149 } 2150 if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) { 2151 const IRPosition &RetPos = IRPosition::returned(*RI->getFunction()); 2152 const auto &RetIsDeadAA = A.getAAFor<AAIsDead>(*this, RetPos); 2153 return RetIsDeadAA.isAssumedDead(); 2154 } 2155 Follow = true; 2156 return wouldInstructionBeTriviallyDead(UserI); 2157 }; 2158 2159 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) 2160 return indicatePessimisticFixpoint(); 2161 return ChangeStatus::UNCHANGED; 2162 } 2163 2164 /// See AbstractAttribute::manifest(...). 2165 ChangeStatus manifest(Attributor &A) override { 2166 Value &V = getAssociatedValue(); 2167 if (auto *I = dyn_cast<Instruction>(&V)) 2168 if (wouldInstructionBeTriviallyDead(I)) { 2169 A.deleteAfterManifest(*I); 2170 return ChangeStatus::CHANGED; 2171 } 2172 2173 if (V.use_empty()) 2174 return ChangeStatus::UNCHANGED; 2175 2176 UndefValue &UV = *UndefValue::get(V.getType()); 2177 bool AnyChange = false; 2178 for (Use &U : V.uses()) 2179 AnyChange |= A.changeUseAfterManifest(U, UV); 2180 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 2181 } 2182 2183 /// See AbstractAttribute::trackStatistics() 2184 void trackStatistics() const override { 2185 STATS_DECLTRACK_FLOATING_ATTR(IsDead) 2186 } 2187 }; 2188 2189 struct AAIsDeadArgument : public AAIsDeadFloating { 2190 AAIsDeadArgument(const IRPosition &IRP) : AAIsDeadFloating(IRP) {} 2191 2192 /// See AbstractAttribute::initialize(...). 2193 void initialize(Attributor &A) override { 2194 if (!getAssociatedFunction()->hasExactDefinition()) 2195 indicatePessimisticFixpoint(); 2196 } 2197 2198 /// See AbstractAttribute::trackStatistics() 2199 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) } 2200 }; 2201 2202 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl { 2203 AAIsDeadCallSiteArgument(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {} 2204 2205 /// See AbstractAttribute::initialize(...). 2206 void initialize(Attributor &A) override { 2207 if (isa<UndefValue>(getAssociatedValue())) 2208 indicatePessimisticFixpoint(); 2209 } 2210 2211 /// See AbstractAttribute::updateImpl(...). 2212 ChangeStatus updateImpl(Attributor &A) override { 2213 // TODO: Once we have call site specific value information we can provide 2214 // call site specific liveness information and then it makes 2215 // sense to specialize attributes for call sites arguments instead of 2216 // redirecting requests to the callee argument. 2217 Argument *Arg = getAssociatedArgument(); 2218 if (!Arg) 2219 return indicatePessimisticFixpoint(); 2220 const IRPosition &ArgPos = IRPosition::argument(*Arg); 2221 auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos); 2222 return clampStateAndIndicateChange( 2223 getState(), static_cast<const AAIsDead::StateType &>(ArgAA.getState())); 2224 } 2225 2226 /// See AbstractAttribute::manifest(...). 2227 ChangeStatus manifest(Attributor &A) override { 2228 CallBase &CB = cast<CallBase>(getAnchorValue()); 2229 Use &U = CB.getArgOperandUse(getArgNo()); 2230 assert(!isa<UndefValue>(U.get()) && 2231 "Expected undef values to be filtered out!"); 2232 UndefValue &UV = *UndefValue::get(U->getType()); 2233 if (A.changeUseAfterManifest(U, UV)) 2234 return ChangeStatus::CHANGED; 2235 return ChangeStatus::UNCHANGED; 2236 } 2237 2238 /// See AbstractAttribute::trackStatistics() 2239 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) } 2240 }; 2241 2242 struct AAIsDeadReturned : public AAIsDeadValueImpl { 2243 AAIsDeadReturned(const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {} 2244 2245 /// See AbstractAttribute::updateImpl(...). 2246 ChangeStatus updateImpl(Attributor &A) override { 2247 2248 auto PredForCallSite = [&](AbstractCallSite ACS) { 2249 if (ACS.isCallbackCall()) 2250 return false; 2251 const IRPosition &CSRetPos = 2252 IRPosition::callsite_returned(ACS.getCallSite()); 2253 const auto &RetIsDeadAA = A.getAAFor<AAIsDead>(*this, CSRetPos); 2254 return RetIsDeadAA.isAssumedDead(); 2255 }; 2256 2257 if (!A.checkForAllCallSites(PredForCallSite, *this, true)) 2258 return indicatePessimisticFixpoint(); 2259 2260 return ChangeStatus::UNCHANGED; 2261 } 2262 2263 /// See AbstractAttribute::manifest(...). 2264 ChangeStatus manifest(Attributor &A) override { 2265 // TODO: Rewrite the signature to return void? 2266 bool AnyChange = false; 2267 UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType()); 2268 auto RetInstPred = [&](Instruction &I) { 2269 ReturnInst &RI = cast<ReturnInst>(I); 2270 if (!isa<UndefValue>(RI.getReturnValue())) 2271 AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV); 2272 return true; 2273 }; 2274 A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret}); 2275 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 2276 } 2277 2278 /// See AbstractAttribute::trackStatistics() 2279 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) } 2280 }; 2281 2282 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating { 2283 AAIsDeadCallSiteReturned(const IRPosition &IRP) : AAIsDeadFloating(IRP) {} 2284 2285 /// See AbstractAttribute::initialize(...). 2286 void initialize(Attributor &A) override {} 2287 2288 /// See AbstractAttribute::trackStatistics() 2289 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(IsDead) } 2290 }; 2291 2292 struct AAIsDeadFunction : public AAIsDead { 2293 AAIsDeadFunction(const IRPosition &IRP) : AAIsDead(IRP) {} 2294 2295 /// See AbstractAttribute::initialize(...). 2296 void initialize(Attributor &A) override { 2297 const Function *F = getAssociatedFunction(); 2298 if (F && !F->isDeclaration()) { 2299 ToBeExploredFrom.insert(&F->getEntryBlock().front()); 2300 assumeLive(A, F->getEntryBlock()); 2301 } 2302 } 2303 2304 /// See AbstractAttribute::getAsStr(). 2305 const std::string getAsStr() const override { 2306 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" + 2307 std::to_string(getAssociatedFunction()->size()) + "][#TBEP " + 2308 std::to_string(ToBeExploredFrom.size()) + "]"; 2309 } 2310 2311 /// See AbstractAttribute::manifest(...). 2312 ChangeStatus manifest(Attributor &A) override { 2313 assert(getState().isValidState() && 2314 "Attempted to manifest an invalid state!"); 2315 2316 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 2317 Function &F = *getAssociatedFunction(); 2318 2319 if (AssumedLiveBlocks.empty()) { 2320 A.deleteAfterManifest(F); 2321 return ChangeStatus::CHANGED; 2322 } 2323 2324 // Flag to determine if we can change an invoke to a call assuming the 2325 // callee is nounwind. This is not possible if the personality of the 2326 // function allows to catch asynchronous exceptions. 2327 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 2328 2329 for (const Instruction *ExploreEndI : ToBeExploredFrom) { 2330 auto *CB = dyn_cast<CallBase>(ExploreEndI); 2331 if (!CB) 2332 continue; 2333 const auto &NoReturnAA = 2334 A.getAAFor<AANoReturn>(*this, IRPosition::callsite_function(*CB)); 2335 if (!NoReturnAA.isAssumedNoReturn()) 2336 continue; 2337 Instruction *I = const_cast<Instruction *>(ExploreEndI); 2338 BasicBlock *BB = I->getParent(); 2339 Instruction *SplitPos = I->getNextNode(); 2340 // TODO: mark stuff before unreachable instructions as dead. 2341 2342 if (auto *II = dyn_cast<InvokeInst>(I)) { 2343 // If we keep the invoke the split position is at the beginning of the 2344 // normal desitination block (it invokes a noreturn function after all). 2345 BasicBlock *NormalDestBB = II->getNormalDest(); 2346 SplitPos = &NormalDestBB->front(); 2347 2348 /// Invoke is replaced with a call and unreachable is placed after it if 2349 /// the callee is nounwind and noreturn. Otherwise, we keep the invoke 2350 /// and only place an unreachable in the normal successor. 2351 if (Invoke2CallAllowed) { 2352 if (II->getCalledFunction()) { 2353 const IRPosition &IPos = IRPosition::callsite_function(*II); 2354 const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos); 2355 if (AANoUnw.isAssumedNoUnwind()) { 2356 LLVM_DEBUG(dbgs() 2357 << "[AAIsDead] Replace invoke with call inst\n"); 2358 // We do not need an invoke (II) but instead want a call followed 2359 // by an unreachable. However, we do not remove II as other 2360 // abstract attributes might have it cached as part of their 2361 // results. Given that we modify the CFG anyway, we simply keep II 2362 // around but in a new dead block. To avoid II being live through 2363 // a different edge we have to ensure the block we place it in is 2364 // only reached from the current block of II and then not reached 2365 // at all when we insert the unreachable. 2366 SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c"); 2367 CallInst *CI = createCallMatchingInvoke(II); 2368 CI->insertBefore(II); 2369 CI->takeName(II); 2370 II->replaceAllUsesWith(CI); 2371 SplitPos = CI->getNextNode(); 2372 } 2373 } 2374 } 2375 2376 if (SplitPos == &NormalDestBB->front()) { 2377 // If this is an invoke of a noreturn function the edge to the normal 2378 // destination block is dead but not necessarily the block itself. 2379 // TODO: We need to move to an edge based system during deduction and 2380 // also manifest. 2381 assert(!NormalDestBB->isLandingPad() && 2382 "Expected the normal destination not to be a landingpad!"); 2383 if (NormalDestBB->getUniquePredecessor() == BB) { 2384 assumeLive(A, *NormalDestBB); 2385 } else { 2386 BasicBlock *SplitBB = 2387 SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 2388 // The split block is live even if it contains only an unreachable 2389 // instruction at the end. 2390 assumeLive(A, *SplitBB); 2391 SplitPos = SplitBB->getTerminator(); 2392 HasChanged = ChangeStatus::CHANGED; 2393 } 2394 } 2395 } 2396 2397 if (isa_and_nonnull<UnreachableInst>(SplitPos)) 2398 continue; 2399 2400 BB = SplitPos->getParent(); 2401 SplitBlock(BB, SplitPos); 2402 changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false); 2403 HasChanged = ChangeStatus::CHANGED; 2404 } 2405 2406 for (BasicBlock &BB : F) 2407 if (!AssumedLiveBlocks.count(&BB)) 2408 A.deleteAfterManifest(BB); 2409 2410 return HasChanged; 2411 } 2412 2413 /// See AbstractAttribute::updateImpl(...). 2414 ChangeStatus updateImpl(Attributor &A) override; 2415 2416 /// See AbstractAttribute::trackStatistics() 2417 void trackStatistics() const override {} 2418 2419 /// Returns true if the function is assumed dead. 2420 bool isAssumedDead() const override { return false; } 2421 2422 /// See AAIsDead::isAssumedDead(BasicBlock *). 2423 bool isAssumedDead(const BasicBlock *BB) const override { 2424 assert(BB->getParent() == getAssociatedFunction() && 2425 "BB must be in the same anchor scope function."); 2426 2427 if (!getAssumed()) 2428 return false; 2429 return !AssumedLiveBlocks.count(BB); 2430 } 2431 2432 /// See AAIsDead::isKnownDead(BasicBlock *). 2433 bool isKnownDead(const BasicBlock *BB) const override { 2434 return getKnown() && isAssumedDead(BB); 2435 } 2436 2437 /// See AAIsDead::isAssumed(Instruction *I). 2438 bool isAssumedDead(const Instruction *I) const override { 2439 assert(I->getParent()->getParent() == getAssociatedFunction() && 2440 "Instruction must be in the same anchor scope function."); 2441 2442 if (!getAssumed()) 2443 return false; 2444 2445 // If it is not in AssumedLiveBlocks then it for sure dead. 2446 // Otherwise, it can still be after noreturn call in a live block. 2447 if (!AssumedLiveBlocks.count(I->getParent())) 2448 return true; 2449 2450 // If it is not after a liveness barrier it is live. 2451 const Instruction *PrevI = I->getPrevNode(); 2452 while (PrevI) { 2453 if (ToBeExploredFrom.count(PrevI)) 2454 return true; 2455 PrevI = PrevI->getPrevNode(); 2456 } 2457 return false; 2458 } 2459 2460 /// See AAIsDead::isKnownDead(Instruction *I). 2461 bool isKnownDead(const Instruction *I) const override { 2462 return getKnown() && isAssumedDead(I); 2463 } 2464 2465 /// Determine if \p F might catch asynchronous exceptions. 2466 static bool mayCatchAsynchronousExceptions(const Function &F) { 2467 return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F); 2468 } 2469 2470 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A 2471 /// that internal function called from \p BB should now be looked at. 2472 bool assumeLive(Attributor &A, const BasicBlock &BB) { 2473 if (!AssumedLiveBlocks.insert(&BB).second) 2474 return false; 2475 2476 // We assume that all of BB is (probably) live now and if there are calls to 2477 // internal functions we will assume that those are now live as well. This 2478 // is a performance optimization for blocks with calls to a lot of internal 2479 // functions. It can however cause dead functions to be treated as live. 2480 for (const Instruction &I : BB) 2481 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) 2482 if (const Function *F = ICS.getCalledFunction()) 2483 if (F->hasLocalLinkage()) 2484 A.markLiveInternalFunction(*F); 2485 return true; 2486 } 2487 2488 /// Collection of instructions that need to be explored again, e.g., we 2489 /// did assume they do not transfer control to (one of their) successors. 2490 SmallSetVector<const Instruction *, 8> ToBeExploredFrom; 2491 2492 /// Collection of all assumed live BasicBlocks. 2493 DenseSet<const BasicBlock *> AssumedLiveBlocks; 2494 }; 2495 2496 static bool 2497 identifyAliveSuccessors(Attributor &A, const CallBase &CB, 2498 AbstractAttribute &AA, 2499 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 2500 const IRPosition &IPos = IRPosition::callsite_function(CB); 2501 2502 const auto &NoReturnAA = A.getAAFor<AANoReturn>(AA, IPos); 2503 if (NoReturnAA.isAssumedNoReturn()) 2504 return true; 2505 if (CB.isTerminator()) 2506 AliveSuccessors.push_back(&CB.getSuccessor(0)->front()); 2507 else 2508 AliveSuccessors.push_back(CB.getNextNode()); 2509 return false; 2510 } 2511 2512 static bool 2513 identifyAliveSuccessors(Attributor &A, const InvokeInst &II, 2514 AbstractAttribute &AA, 2515 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 2516 bool UsedAssumedInformation = 2517 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors); 2518 2519 // First, determine if we can change an invoke to a call assuming the 2520 // callee is nounwind. This is not possible if the personality of the 2521 // function allows to catch asynchronous exceptions. 2522 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) { 2523 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 2524 } else { 2525 const IRPosition &IPos = IRPosition::callsite_function(II); 2526 const auto &AANoUnw = A.getAAFor<AANoUnwind>(AA, IPos); 2527 if (!AANoUnw.isAssumedNoUnwind()) { 2528 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 2529 UsedAssumedInformation = true; 2530 } 2531 } 2532 return UsedAssumedInformation; 2533 } 2534 2535 static Optional<ConstantInt *> getAssumedConstant(Attributor &A, const Value &V, 2536 AbstractAttribute &AA) { 2537 const auto &ValueSimplifyAA = 2538 A.getAAFor<AAValueSimplify>(AA, IRPosition::value(V)); 2539 Optional<Value *> SimplifiedV = ValueSimplifyAA.getAssumedSimplifiedValue(A); 2540 if (!SimplifiedV.hasValue()) 2541 return llvm::None; 2542 if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) 2543 return llvm::None; 2544 return dyn_cast_or_null<ConstantInt>(SimplifiedV.getValue()); 2545 } 2546 2547 static bool 2548 identifyAliveSuccessors(Attributor &A, const BranchInst &BI, 2549 AbstractAttribute &AA, 2550 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 2551 bool UsedAssumedInformation = false; 2552 if (BI.getNumSuccessors() == 1) { 2553 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 2554 } else { 2555 Optional<ConstantInt *> CI = getAssumedConstant(A, *BI.getCondition(), AA); 2556 if (!CI.hasValue()) { 2557 // No value yet, assume both edges are dead. 2558 } else if (CI.getValue()) { 2559 const BasicBlock *SuccBB = 2560 BI.getSuccessor(1 - CI.getValue()->getZExtValue()); 2561 AliveSuccessors.push_back(&SuccBB->front()); 2562 UsedAssumedInformation = true; 2563 } else { 2564 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 2565 AliveSuccessors.push_back(&BI.getSuccessor(1)->front()); 2566 } 2567 } 2568 return UsedAssumedInformation; 2569 } 2570 2571 static bool 2572 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI, 2573 AbstractAttribute &AA, 2574 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 2575 bool UsedAssumedInformation = false; 2576 Optional<ConstantInt *> CI = getAssumedConstant(A, *SI.getCondition(), AA); 2577 if (!CI.hasValue()) { 2578 // No value yet, assume all edges are dead. 2579 } else if (CI.getValue()) { 2580 for (auto &CaseIt : SI.cases()) { 2581 if (CaseIt.getCaseValue() == CI.getValue()) { 2582 AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front()); 2583 UsedAssumedInformation = true; 2584 break; 2585 } 2586 } 2587 } else { 2588 for (const BasicBlock *SuccBB : successors(SI.getParent())) 2589 AliveSuccessors.push_back(&SuccBB->front()); 2590 } 2591 return UsedAssumedInformation; 2592 } 2593 2594 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) { 2595 ChangeStatus Change = ChangeStatus::UNCHANGED; 2596 2597 LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/" 2598 << getAssociatedFunction()->size() << "] BBs and " 2599 << ToBeExploredFrom.size() << " exploration points\n"); 2600 2601 // Copy and clear the list of instructions we need to explore from. It is 2602 // refilled with instructions the next update has to look at. 2603 SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(), 2604 ToBeExploredFrom.end()); 2605 decltype(ToBeExploredFrom) NewToBeExploredFrom; 2606 2607 SmallVector<const Instruction *, 8> AliveSuccessors; 2608 while (!Worklist.empty()) { 2609 const Instruction *I = Worklist.pop_back_val(); 2610 LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n"); 2611 2612 AliveSuccessors.clear(); 2613 2614 bool UsedAssumedInformation = false; 2615 switch (I->getOpcode()) { 2616 // TODO: look for (assumed) UB to backwards propagate "deadness". 2617 default: 2618 if (I->isTerminator()) { 2619 for (const BasicBlock *SuccBB : successors(I->getParent())) 2620 AliveSuccessors.push_back(&SuccBB->front()); 2621 } else { 2622 AliveSuccessors.push_back(I->getNextNode()); 2623 } 2624 break; 2625 case Instruction::Call: 2626 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I), 2627 *this, AliveSuccessors); 2628 break; 2629 case Instruction::Invoke: 2630 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I), 2631 *this, AliveSuccessors); 2632 break; 2633 case Instruction::Br: 2634 UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I), 2635 *this, AliveSuccessors); 2636 break; 2637 case Instruction::Switch: 2638 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I), 2639 *this, AliveSuccessors); 2640 break; 2641 } 2642 2643 if (UsedAssumedInformation) 2644 NewToBeExploredFrom.insert(I); 2645 else 2646 Change = ChangeStatus::CHANGED; 2647 2648 LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: " 2649 << AliveSuccessors.size() << " UsedAssumedInformation: " 2650 << UsedAssumedInformation << "\n"); 2651 2652 for (const Instruction *AliveSuccessor : AliveSuccessors) { 2653 if (!I->isTerminator()) { 2654 assert(AliveSuccessors.size() == 1 && 2655 "Non-terminator expected to have a single successor!"); 2656 Worklist.push_back(AliveSuccessor); 2657 } else { 2658 if (assumeLive(A, *AliveSuccessor->getParent())) 2659 Worklist.push_back(AliveSuccessor); 2660 } 2661 } 2662 } 2663 2664 ToBeExploredFrom = std::move(NewToBeExploredFrom); 2665 2666 // If we know everything is live there is no need to query for liveness. 2667 // Instead, indicating a pessimistic fixpoint will cause the state to be 2668 // "invalid" and all queries to be answered conservatively. 2669 if (ToBeExploredFrom.empty() && 2670 getAssociatedFunction()->size() == AssumedLiveBlocks.size()) 2671 return indicatePessimisticFixpoint(); 2672 return Change; 2673 } 2674 2675 /// Liveness information for a call sites. 2676 struct AAIsDeadCallSite final : AAIsDeadFunction { 2677 AAIsDeadCallSite(const IRPosition &IRP) : AAIsDeadFunction(IRP) {} 2678 2679 /// See AbstractAttribute::initialize(...). 2680 void initialize(Attributor &A) override { 2681 // TODO: Once we have call site specific value information we can provide 2682 // call site specific liveness information and then it makes 2683 // sense to specialize attributes for call sites instead of 2684 // redirecting requests to the callee. 2685 llvm_unreachable("Abstract attributes for liveness are not " 2686 "supported for call sites yet!"); 2687 } 2688 2689 /// See AbstractAttribute::updateImpl(...). 2690 ChangeStatus updateImpl(Attributor &A) override { 2691 return indicatePessimisticFixpoint(); 2692 } 2693 2694 /// See AbstractAttribute::trackStatistics() 2695 void trackStatistics() const override {} 2696 }; 2697 2698 /// -------------------- Dereferenceable Argument Attribute -------------------- 2699 2700 template <> 2701 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S, 2702 const DerefState &R) { 2703 ChangeStatus CS0 = 2704 clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState); 2705 ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState); 2706 return CS0 | CS1; 2707 } 2708 2709 struct AADereferenceableImpl : AADereferenceable { 2710 AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {} 2711 using StateType = DerefState; 2712 2713 void initialize(Attributor &A) override { 2714 SmallVector<Attribute, 4> Attrs; 2715 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull}, 2716 Attrs); 2717 for (const Attribute &Attr : Attrs) 2718 takeKnownDerefBytesMaximum(Attr.getValueAsInt()); 2719 2720 NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition()); 2721 2722 const IRPosition &IRP = this->getIRPosition(); 2723 bool IsFnInterface = IRP.isFnInterfaceKind(); 2724 const Function *FnScope = IRP.getAnchorScope(); 2725 if (IsFnInterface && (!FnScope || !FnScope->hasExactDefinition())) 2726 indicatePessimisticFixpoint(); 2727 } 2728 2729 /// See AbstractAttribute::getState() 2730 /// { 2731 StateType &getState() override { return *this; } 2732 const StateType &getState() const override { return *this; } 2733 /// } 2734 2735 /// See AAFromMustBeExecutedContext 2736 bool followUse(Attributor &A, const Use *U, const Instruction *I) { 2737 bool IsNonNull = false; 2738 bool TrackUse = false; 2739 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse( 2740 A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse); 2741 takeKnownDerefBytesMaximum(DerefBytes); 2742 return TrackUse; 2743 } 2744 2745 void getDeducedAttributes(LLVMContext &Ctx, 2746 SmallVectorImpl<Attribute> &Attrs) const override { 2747 // TODO: Add *_globally support 2748 if (isAssumedNonNull()) 2749 Attrs.emplace_back(Attribute::getWithDereferenceableBytes( 2750 Ctx, getAssumedDereferenceableBytes())); 2751 else 2752 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( 2753 Ctx, getAssumedDereferenceableBytes())); 2754 } 2755 2756 /// See AbstractAttribute::getAsStr(). 2757 const std::string getAsStr() const override { 2758 if (!getAssumedDereferenceableBytes()) 2759 return "unknown-dereferenceable"; 2760 return std::string("dereferenceable") + 2761 (isAssumedNonNull() ? "" : "_or_null") + 2762 (isAssumedGlobal() ? "_globally" : "") + "<" + 2763 std::to_string(getKnownDereferenceableBytes()) + "-" + 2764 std::to_string(getAssumedDereferenceableBytes()) + ">"; 2765 } 2766 }; 2767 2768 /// Dereferenceable attribute for a floating value. 2769 struct AADereferenceableFloating 2770 : AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl> { 2771 using Base = 2772 AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl>; 2773 AADereferenceableFloating(const IRPosition &IRP) : Base(IRP) {} 2774 2775 /// See AbstractAttribute::updateImpl(...). 2776 ChangeStatus updateImpl(Attributor &A) override { 2777 ChangeStatus Change = Base::updateImpl(A); 2778 2779 const DataLayout &DL = A.getDataLayout(); 2780 2781 auto VisitValueCB = [&](Value &V, DerefState &T, bool Stripped) -> bool { 2782 unsigned IdxWidth = 2783 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); 2784 APInt Offset(IdxWidth, 0); 2785 const Value *Base = 2786 V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset); 2787 2788 const auto &AA = 2789 A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base)); 2790 int64_t DerefBytes = 0; 2791 if (!Stripped && this == &AA) { 2792 // Use IR information if we did not strip anything. 2793 // TODO: track globally. 2794 bool CanBeNull; 2795 DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull); 2796 T.GlobalState.indicatePessimisticFixpoint(); 2797 } else { 2798 const DerefState &DS = static_cast<const DerefState &>(AA.getState()); 2799 DerefBytes = DS.DerefBytesState.getAssumed(); 2800 T.GlobalState &= DS.GlobalState; 2801 } 2802 2803 // For now we do not try to "increase" dereferenceability due to negative 2804 // indices as we first have to come up with code to deal with loops and 2805 // for overflows of the dereferenceable bytes. 2806 int64_t OffsetSExt = Offset.getSExtValue(); 2807 if (OffsetSExt < 0) 2808 OffsetSExt = 0; 2809 2810 T.takeAssumedDerefBytesMinimum( 2811 std::max(int64_t(0), DerefBytes - OffsetSExt)); 2812 2813 if (this == &AA) { 2814 if (!Stripped) { 2815 // If nothing was stripped IR information is all we got. 2816 T.takeKnownDerefBytesMaximum( 2817 std::max(int64_t(0), DerefBytes - OffsetSExt)); 2818 T.indicatePessimisticFixpoint(); 2819 } else if (OffsetSExt > 0) { 2820 // If something was stripped but there is circular reasoning we look 2821 // for the offset. If it is positive we basically decrease the 2822 // dereferenceable bytes in a circluar loop now, which will simply 2823 // drive them down to the known value in a very slow way which we 2824 // can accelerate. 2825 T.indicatePessimisticFixpoint(); 2826 } 2827 } 2828 2829 return T.isValidState(); 2830 }; 2831 2832 DerefState T; 2833 if (!genericValueTraversal<AADereferenceable, DerefState>( 2834 A, getIRPosition(), *this, T, VisitValueCB)) 2835 return indicatePessimisticFixpoint(); 2836 2837 return Change | clampStateAndIndicateChange(getState(), T); 2838 } 2839 2840 /// See AbstractAttribute::trackStatistics() 2841 void trackStatistics() const override { 2842 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable) 2843 } 2844 }; 2845 2846 /// Dereferenceable attribute for a return value. 2847 struct AADereferenceableReturned final 2848 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2849 DerefState> { 2850 AADereferenceableReturned(const IRPosition &IRP) 2851 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2852 DerefState>(IRP) {} 2853 2854 /// See AbstractAttribute::trackStatistics() 2855 void trackStatistics() const override { 2856 STATS_DECLTRACK_FNRET_ATTR(dereferenceable) 2857 } 2858 }; 2859 2860 /// Dereferenceable attribute for an argument 2861 struct AADereferenceableArgument final 2862 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext< 2863 AADereferenceable, AADereferenceableImpl, DerefState> { 2864 using Base = AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext< 2865 AADereferenceable, AADereferenceableImpl, DerefState>; 2866 AADereferenceableArgument(const IRPosition &IRP) : Base(IRP) {} 2867 2868 /// See AbstractAttribute::trackStatistics() 2869 void trackStatistics() const override { 2870 STATS_DECLTRACK_ARG_ATTR(dereferenceable) 2871 } 2872 }; 2873 2874 /// Dereferenceable attribute for a call site argument. 2875 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating { 2876 AADereferenceableCallSiteArgument(const IRPosition &IRP) 2877 : AADereferenceableFloating(IRP) {} 2878 2879 /// See AbstractAttribute::trackStatistics() 2880 void trackStatistics() const override { 2881 STATS_DECLTRACK_CSARG_ATTR(dereferenceable) 2882 } 2883 }; 2884 2885 /// Dereferenceable attribute deduction for a call site return value. 2886 struct AADereferenceableCallSiteReturned final 2887 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext< 2888 AADereferenceable, AADereferenceableImpl> { 2889 using Base = AACallSiteReturnedFromReturnedAndMustBeExecutedContext< 2890 AADereferenceable, AADereferenceableImpl>; 2891 AADereferenceableCallSiteReturned(const IRPosition &IRP) : Base(IRP) {} 2892 2893 /// See AbstractAttribute::initialize(...). 2894 void initialize(Attributor &A) override { 2895 Base::initialize(A); 2896 Function *F = getAssociatedFunction(); 2897 if (!F) 2898 indicatePessimisticFixpoint(); 2899 } 2900 2901 /// See AbstractAttribute::updateImpl(...). 2902 ChangeStatus updateImpl(Attributor &A) override { 2903 // TODO: Once we have call site specific value information we can provide 2904 // call site specific liveness information and then it makes 2905 // sense to specialize attributes for call sites arguments instead of 2906 // redirecting requests to the callee argument. 2907 2908 ChangeStatus Change = Base::updateImpl(A); 2909 Function *F = getAssociatedFunction(); 2910 const IRPosition &FnPos = IRPosition::returned(*F); 2911 auto &FnAA = A.getAAFor<AADereferenceable>(*this, FnPos); 2912 return Change | 2913 clampStateAndIndicateChange( 2914 getState(), static_cast<const DerefState &>(FnAA.getState())); 2915 } 2916 2917 /// See AbstractAttribute::trackStatistics() 2918 void trackStatistics() const override { 2919 STATS_DECLTRACK_CS_ATTR(dereferenceable); 2920 } 2921 }; 2922 2923 // ------------------------ Align Argument Attribute ------------------------ 2924 2925 struct AAAlignImpl : AAAlign { 2926 AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {} 2927 2928 /// See AbstractAttribute::initialize(...). 2929 void initialize(Attributor &A) override { 2930 SmallVector<Attribute, 4> Attrs; 2931 getAttrs({Attribute::Alignment}, Attrs); 2932 for (const Attribute &Attr : Attrs) 2933 takeKnownMaximum(Attr.getValueAsInt()); 2934 2935 if (getIRPosition().isFnInterfaceKind() && 2936 (!getAssociatedFunction() || 2937 !getAssociatedFunction()->hasExactDefinition())) 2938 indicatePessimisticFixpoint(); 2939 } 2940 2941 /// See AbstractAttribute::manifest(...). 2942 ChangeStatus manifest(Attributor &A) override { 2943 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2944 2945 // Check for users that allow alignment annotations. 2946 Value &AnchorVal = getIRPosition().getAnchorValue(); 2947 for (const Use &U : AnchorVal.uses()) { 2948 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) { 2949 if (SI->getPointerOperand() == &AnchorVal) 2950 if (SI->getAlignment() < getAssumedAlign()) { 2951 STATS_DECLTRACK(AAAlign, Store, 2952 "Number of times alignemnt added to a store"); 2953 SI->setAlignment(Align(getAssumedAlign())); 2954 Changed = ChangeStatus::CHANGED; 2955 } 2956 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) { 2957 if (LI->getPointerOperand() == &AnchorVal) 2958 if (LI->getAlignment() < getAssumedAlign()) { 2959 LI->setAlignment(Align(getAssumedAlign())); 2960 STATS_DECLTRACK(AAAlign, Load, 2961 "Number of times alignemnt added to a load"); 2962 Changed = ChangeStatus::CHANGED; 2963 } 2964 } 2965 } 2966 2967 return AAAlign::manifest(A) | Changed; 2968 } 2969 2970 // TODO: Provide a helper to determine the implied ABI alignment and check in 2971 // the existing manifest method and a new one for AAAlignImpl that value 2972 // to avoid making the alignment explicit if it did not improve. 2973 2974 /// See AbstractAttribute::getDeducedAttributes 2975 virtual void 2976 getDeducedAttributes(LLVMContext &Ctx, 2977 SmallVectorImpl<Attribute> &Attrs) const override { 2978 if (getAssumedAlign() > 1) 2979 Attrs.emplace_back( 2980 Attribute::getWithAlignment(Ctx, Align(getAssumedAlign()))); 2981 } 2982 2983 /// See AbstractAttribute::getAsStr(). 2984 const std::string getAsStr() const override { 2985 return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) + 2986 "-" + std::to_string(getAssumedAlign()) + ">") 2987 : "unknown-align"; 2988 } 2989 }; 2990 2991 /// Align attribute for a floating value. 2992 struct AAAlignFloating : AAAlignImpl { 2993 AAAlignFloating(const IRPosition &IRP) : AAAlignImpl(IRP) {} 2994 2995 /// See AbstractAttribute::updateImpl(...). 2996 ChangeStatus updateImpl(Attributor &A) override { 2997 const DataLayout &DL = A.getDataLayout(); 2998 2999 auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, 3000 bool Stripped) -> bool { 3001 const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V)); 3002 if (!Stripped && this == &AA) { 3003 // Use only IR information if we did not strip anything. 3004 const MaybeAlign PA = V.getPointerAlignment(DL); 3005 T.takeKnownMaximum(PA ? PA->value() : 0); 3006 T.indicatePessimisticFixpoint(); 3007 } else { 3008 // Use abstract attribute information. 3009 const AAAlign::StateType &DS = 3010 static_cast<const AAAlign::StateType &>(AA.getState()); 3011 T ^= DS; 3012 } 3013 return T.isValidState(); 3014 }; 3015 3016 StateType T; 3017 if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T, 3018 VisitValueCB)) 3019 return indicatePessimisticFixpoint(); 3020 3021 // TODO: If we know we visited all incoming values, thus no are assumed 3022 // dead, we can take the known information from the state T. 3023 return clampStateAndIndicateChange(getState(), T); 3024 } 3025 3026 /// See AbstractAttribute::trackStatistics() 3027 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) } 3028 }; 3029 3030 /// Align attribute for function return value. 3031 struct AAAlignReturned final 3032 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> { 3033 AAAlignReturned(const IRPosition &IRP) 3034 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {} 3035 3036 /// See AbstractAttribute::trackStatistics() 3037 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) } 3038 }; 3039 3040 /// Align attribute for function argument. 3041 struct AAAlignArgument final 3042 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> { 3043 AAAlignArgument(const IRPosition &IRP) 3044 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>(IRP) {} 3045 3046 /// See AbstractAttribute::trackStatistics() 3047 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) } 3048 }; 3049 3050 struct AAAlignCallSiteArgument final : AAAlignFloating { 3051 AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {} 3052 3053 /// See AbstractAttribute::manifest(...). 3054 ChangeStatus manifest(Attributor &A) override { 3055 return AAAlignImpl::manifest(A); 3056 } 3057 3058 /// See AbstractAttribute::trackStatistics() 3059 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) } 3060 }; 3061 3062 /// Align attribute deduction for a call site return value. 3063 struct AAAlignCallSiteReturned final : AAAlignImpl { 3064 AAAlignCallSiteReturned(const IRPosition &IRP) : AAAlignImpl(IRP) {} 3065 3066 /// See AbstractAttribute::initialize(...). 3067 void initialize(Attributor &A) override { 3068 AAAlignImpl::initialize(A); 3069 Function *F = getAssociatedFunction(); 3070 if (!F) 3071 indicatePessimisticFixpoint(); 3072 } 3073 3074 /// See AbstractAttribute::updateImpl(...). 3075 ChangeStatus updateImpl(Attributor &A) override { 3076 // TODO: Once we have call site specific value information we can provide 3077 // call site specific liveness information and then it makes 3078 // sense to specialize attributes for call sites arguments instead of 3079 // redirecting requests to the callee argument. 3080 Function *F = getAssociatedFunction(); 3081 const IRPosition &FnPos = IRPosition::returned(*F); 3082 auto &FnAA = A.getAAFor<AAAlign>(*this, FnPos); 3083 return clampStateAndIndicateChange( 3084 getState(), static_cast<const AAAlign::StateType &>(FnAA.getState())); 3085 } 3086 3087 /// See AbstractAttribute::trackStatistics() 3088 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); } 3089 }; 3090 3091 /// ------------------ Function No-Return Attribute ---------------------------- 3092 struct AANoReturnImpl : public AANoReturn { 3093 AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {} 3094 3095 /// See AbstractAttribute::initialize(...). 3096 void initialize(Attributor &A) override { 3097 AANoReturn::initialize(A); 3098 Function *F = getAssociatedFunction(); 3099 if (!F || F->hasFnAttribute(Attribute::WillReturn)) 3100 indicatePessimisticFixpoint(); 3101 } 3102 3103 /// See AbstractAttribute::getAsStr(). 3104 const std::string getAsStr() const override { 3105 return getAssumed() ? "noreturn" : "may-return"; 3106 } 3107 3108 /// See AbstractAttribute::updateImpl(Attributor &A). 3109 virtual ChangeStatus updateImpl(Attributor &A) override { 3110 const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, getIRPosition()); 3111 if (WillReturnAA.isKnownWillReturn()) 3112 return indicatePessimisticFixpoint(); 3113 auto CheckForNoReturn = [](Instruction &) { return false; }; 3114 if (!A.checkForAllInstructions(CheckForNoReturn, *this, 3115 {(unsigned)Instruction::Ret})) 3116 return indicatePessimisticFixpoint(); 3117 return ChangeStatus::UNCHANGED; 3118 } 3119 }; 3120 3121 struct AANoReturnFunction final : AANoReturnImpl { 3122 AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {} 3123 3124 /// See AbstractAttribute::trackStatistics() 3125 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) } 3126 }; 3127 3128 /// NoReturn attribute deduction for a call sites. 3129 struct AANoReturnCallSite final : AANoReturnImpl { 3130 AANoReturnCallSite(const IRPosition &IRP) : AANoReturnImpl(IRP) {} 3131 3132 /// See AbstractAttribute::updateImpl(...). 3133 ChangeStatus updateImpl(Attributor &A) override { 3134 // TODO: Once we have call site specific value information we can provide 3135 // call site specific liveness information and then it makes 3136 // sense to specialize attributes for call sites arguments instead of 3137 // redirecting requests to the callee argument. 3138 Function *F = getAssociatedFunction(); 3139 const IRPosition &FnPos = IRPosition::function(*F); 3140 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos); 3141 return clampStateAndIndicateChange( 3142 getState(), 3143 static_cast<const AANoReturn::StateType &>(FnAA.getState())); 3144 } 3145 3146 /// See AbstractAttribute::trackStatistics() 3147 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); } 3148 }; 3149 3150 /// ----------------------- Variable Capturing --------------------------------- 3151 3152 /// A class to hold the state of for no-capture attributes. 3153 struct AANoCaptureImpl : public AANoCapture { 3154 AANoCaptureImpl(const IRPosition &IRP) : AANoCapture(IRP) {} 3155 3156 /// See AbstractAttribute::initialize(...). 3157 void initialize(Attributor &A) override { 3158 AANoCapture::initialize(A); 3159 3160 // You cannot "capture" null in the default address space. 3161 if (isa<ConstantPointerNull>(getAssociatedValue()) && 3162 getAssociatedValue().getType()->getPointerAddressSpace() == 0) { 3163 indicateOptimisticFixpoint(); 3164 return; 3165 } 3166 3167 const IRPosition &IRP = getIRPosition(); 3168 const Function *F = 3169 getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 3170 3171 // Check what state the associated function can actually capture. 3172 if (F) 3173 determineFunctionCaptureCapabilities(IRP, *F, *this); 3174 else 3175 indicatePessimisticFixpoint(); 3176 } 3177 3178 /// See AbstractAttribute::updateImpl(...). 3179 ChangeStatus updateImpl(Attributor &A) override; 3180 3181 /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...). 3182 virtual void 3183 getDeducedAttributes(LLVMContext &Ctx, 3184 SmallVectorImpl<Attribute> &Attrs) const override { 3185 if (!isAssumedNoCaptureMaybeReturned()) 3186 return; 3187 3188 if (getArgNo() >= 0) { 3189 if (isAssumedNoCapture()) 3190 Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture)); 3191 else if (ManifestInternal) 3192 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned")); 3193 } 3194 } 3195 3196 /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known 3197 /// depending on the ability of the function associated with \p IRP to capture 3198 /// state in memory and through "returning/throwing", respectively. 3199 static void determineFunctionCaptureCapabilities(const IRPosition &IRP, 3200 const Function &F, 3201 BitIntegerState &State) { 3202 // TODO: Once we have memory behavior attributes we should use them here. 3203 3204 // If we know we cannot communicate or write to memory, we do not care about 3205 // ptr2int anymore. 3206 if (F.onlyReadsMemory() && F.doesNotThrow() && 3207 F.getReturnType()->isVoidTy()) { 3208 State.addKnownBits(NO_CAPTURE); 3209 return; 3210 } 3211 3212 // A function cannot capture state in memory if it only reads memory, it can 3213 // however return/throw state and the state might be influenced by the 3214 // pointer value, e.g., loading from a returned pointer might reveal a bit. 3215 if (F.onlyReadsMemory()) 3216 State.addKnownBits(NOT_CAPTURED_IN_MEM); 3217 3218 // A function cannot communicate state back if it does not through 3219 // exceptions and doesn not return values. 3220 if (F.doesNotThrow() && F.getReturnType()->isVoidTy()) 3221 State.addKnownBits(NOT_CAPTURED_IN_RET); 3222 3223 // Check existing "returned" attributes. 3224 int ArgNo = IRP.getArgNo(); 3225 if (F.doesNotThrow() && ArgNo >= 0) { 3226 for (unsigned u = 0, e = F.arg_size(); u< e; ++u) 3227 if (F.hasParamAttribute(u, Attribute::Returned)) { 3228 if (u == unsigned(ArgNo)) 3229 State.removeAssumedBits(NOT_CAPTURED_IN_RET); 3230 else if (F.onlyReadsMemory()) 3231 State.addKnownBits(NO_CAPTURE); 3232 else 3233 State.addKnownBits(NOT_CAPTURED_IN_RET); 3234 break; 3235 } 3236 } 3237 } 3238 3239 /// See AbstractState::getAsStr(). 3240 const std::string getAsStr() const override { 3241 if (isKnownNoCapture()) 3242 return "known not-captured"; 3243 if (isAssumedNoCapture()) 3244 return "assumed not-captured"; 3245 if (isKnownNoCaptureMaybeReturned()) 3246 return "known not-captured-maybe-returned"; 3247 if (isAssumedNoCaptureMaybeReturned()) 3248 return "assumed not-captured-maybe-returned"; 3249 return "assumed-captured"; 3250 } 3251 }; 3252 3253 /// Attributor-aware capture tracker. 3254 struct AACaptureUseTracker final : public CaptureTracker { 3255 3256 /// Create a capture tracker that can lookup in-flight abstract attributes 3257 /// through the Attributor \p A. 3258 /// 3259 /// If a use leads to a potential capture, \p CapturedInMemory is set and the 3260 /// search is stopped. If a use leads to a return instruction, 3261 /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed. 3262 /// If a use leads to a ptr2int which may capture the value, 3263 /// \p CapturedInInteger is set. If a use is found that is currently assumed 3264 /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies 3265 /// set. All values in \p PotentialCopies are later tracked as well. For every 3266 /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0, 3267 /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger 3268 /// conservatively set to true. 3269 AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA, 3270 const AAIsDead &IsDeadAA, AANoCapture::StateType &State, 3271 SmallVectorImpl<const Value *> &PotentialCopies, 3272 unsigned &RemainingUsesToExplore) 3273 : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State), 3274 PotentialCopies(PotentialCopies), 3275 RemainingUsesToExplore(RemainingUsesToExplore) {} 3276 3277 /// Determine if \p V maybe captured. *Also updates the state!* 3278 bool valueMayBeCaptured(const Value *V) { 3279 if (V->getType()->isPointerTy()) { 3280 PointerMayBeCaptured(V, this); 3281 } else { 3282 State.indicatePessimisticFixpoint(); 3283 } 3284 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 3285 } 3286 3287 /// See CaptureTracker::tooManyUses(). 3288 void tooManyUses() override { 3289 State.removeAssumedBits(AANoCapture::NO_CAPTURE); 3290 } 3291 3292 bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override { 3293 if (CaptureTracker::isDereferenceableOrNull(O, DL)) 3294 return true; 3295 const auto &DerefAA = 3296 A.getAAFor<AADereferenceable>(NoCaptureAA, IRPosition::value(*O)); 3297 return DerefAA.getAssumedDereferenceableBytes(); 3298 } 3299 3300 /// See CaptureTracker::captured(...). 3301 bool captured(const Use *U) override { 3302 Instruction *UInst = cast<Instruction>(U->getUser()); 3303 LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst 3304 << "\n"); 3305 3306 // Because we may reuse the tracker multiple times we keep track of the 3307 // number of explored uses ourselves as well. 3308 if (RemainingUsesToExplore-- == 0) { 3309 LLVM_DEBUG(dbgs() << " - too many uses to explore!\n"); 3310 return isCapturedIn(/* Memory */ true, /* Integer */ true, 3311 /* Return */ true); 3312 } 3313 3314 // Deal with ptr2int by following uses. 3315 if (isa<PtrToIntInst>(UInst)) { 3316 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n"); 3317 return valueMayBeCaptured(UInst); 3318 } 3319 3320 // Explicitly catch return instructions. 3321 if (isa<ReturnInst>(UInst)) 3322 return isCapturedIn(/* Memory */ false, /* Integer */ false, 3323 /* Return */ true); 3324 3325 // For now we only use special logic for call sites. However, the tracker 3326 // itself knows about a lot of other non-capturing cases already. 3327 CallSite CS(UInst); 3328 if (!CS || !CS.isArgOperand(U)) 3329 return isCapturedIn(/* Memory */ true, /* Integer */ true, 3330 /* Return */ true); 3331 3332 unsigned ArgNo = CS.getArgumentNo(U); 3333 const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo); 3334 // If we have a abstract no-capture attribute for the argument we can use 3335 // it to justify a non-capture attribute here. This allows recursion! 3336 auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos); 3337 if (ArgNoCaptureAA.isAssumedNoCapture()) 3338 return isCapturedIn(/* Memory */ false, /* Integer */ false, 3339 /* Return */ false); 3340 if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 3341 addPotentialCopy(CS); 3342 return isCapturedIn(/* Memory */ false, /* Integer */ false, 3343 /* Return */ false); 3344 } 3345 3346 // Lastly, we could not find a reason no-capture can be assumed so we don't. 3347 return isCapturedIn(/* Memory */ true, /* Integer */ true, 3348 /* Return */ true); 3349 } 3350 3351 /// Register \p CS as potential copy of the value we are checking. 3352 void addPotentialCopy(CallSite CS) { 3353 PotentialCopies.push_back(CS.getInstruction()); 3354 } 3355 3356 /// See CaptureTracker::shouldExplore(...). 3357 bool shouldExplore(const Use *U) override { 3358 // Check liveness. 3359 return !IsDeadAA.isAssumedDead(cast<Instruction>(U->getUser())); 3360 } 3361 3362 /// Update the state according to \p CapturedInMem, \p CapturedInInt, and 3363 /// \p CapturedInRet, then return the appropriate value for use in the 3364 /// CaptureTracker::captured() interface. 3365 bool isCapturedIn(bool CapturedInMem, bool CapturedInInt, 3366 bool CapturedInRet) { 3367 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int " 3368 << CapturedInInt << "|Ret " << CapturedInRet << "]\n"); 3369 if (CapturedInMem) 3370 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM); 3371 if (CapturedInInt) 3372 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT); 3373 if (CapturedInRet) 3374 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET); 3375 return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 3376 } 3377 3378 private: 3379 /// The attributor providing in-flight abstract attributes. 3380 Attributor &A; 3381 3382 /// The abstract attribute currently updated. 3383 AANoCapture &NoCaptureAA; 3384 3385 /// The abstract liveness state. 3386 const AAIsDead &IsDeadAA; 3387 3388 /// The state currently updated. 3389 AANoCapture::StateType &State; 3390 3391 /// Set of potential copies of the tracked value. 3392 SmallVectorImpl<const Value *> &PotentialCopies; 3393 3394 /// Global counter to limit the number of explored uses. 3395 unsigned &RemainingUsesToExplore; 3396 }; 3397 3398 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) { 3399 const IRPosition &IRP = getIRPosition(); 3400 const Value *V = 3401 getArgNo() >= 0 ? IRP.getAssociatedArgument() : &IRP.getAssociatedValue(); 3402 if (!V) 3403 return indicatePessimisticFixpoint(); 3404 3405 const Function *F = 3406 getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 3407 assert(F && "Expected a function!"); 3408 const IRPosition &FnPos = IRPosition::function(*F); 3409 const auto &IsDeadAA = A.getAAFor<AAIsDead>(*this, FnPos); 3410 3411 AANoCapture::StateType T; 3412 3413 // Readonly means we cannot capture through memory. 3414 const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos); 3415 if (FnMemAA.isAssumedReadOnly()) { 3416 T.addKnownBits(NOT_CAPTURED_IN_MEM); 3417 if (FnMemAA.isKnownReadOnly()) 3418 addKnownBits(NOT_CAPTURED_IN_MEM); 3419 } 3420 3421 // Make sure all returned values are different than the underlying value. 3422 // TODO: we could do this in a more sophisticated way inside 3423 // AAReturnedValues, e.g., track all values that escape through returns 3424 // directly somehow. 3425 auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) { 3426 bool SeenConstant = false; 3427 for (auto &It : RVAA.returned_values()) { 3428 if (isa<Constant>(It.first)) { 3429 if (SeenConstant) 3430 return false; 3431 SeenConstant = true; 3432 } else if (!isa<Argument>(It.first) || 3433 It.first == getAssociatedArgument()) 3434 return false; 3435 } 3436 return true; 3437 }; 3438 3439 const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(*this, FnPos); 3440 if (NoUnwindAA.isAssumedNoUnwind()) { 3441 bool IsVoidTy = F->getReturnType()->isVoidTy(); 3442 const AAReturnedValues *RVAA = 3443 IsVoidTy ? nullptr : &A.getAAFor<AAReturnedValues>(*this, FnPos); 3444 if (IsVoidTy || CheckReturnedArgs(*RVAA)) { 3445 T.addKnownBits(NOT_CAPTURED_IN_RET); 3446 if (T.isKnown(NOT_CAPTURED_IN_MEM)) 3447 return ChangeStatus::UNCHANGED; 3448 if (NoUnwindAA.isKnownNoUnwind() && 3449 (IsVoidTy || RVAA->getState().isAtFixpoint())) { 3450 addKnownBits(NOT_CAPTURED_IN_RET); 3451 if (isKnown(NOT_CAPTURED_IN_MEM)) 3452 return indicateOptimisticFixpoint(); 3453 } 3454 } 3455 } 3456 3457 // Use the CaptureTracker interface and logic with the specialized tracker, 3458 // defined in AACaptureUseTracker, that can look at in-flight abstract 3459 // attributes and directly updates the assumed state. 3460 SmallVector<const Value *, 4> PotentialCopies; 3461 unsigned RemainingUsesToExplore = DefaultMaxUsesToExplore; 3462 AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies, 3463 RemainingUsesToExplore); 3464 3465 // Check all potential copies of the associated value until we can assume 3466 // none will be captured or we have to assume at least one might be. 3467 unsigned Idx = 0; 3468 PotentialCopies.push_back(V); 3469 while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size()) 3470 Tracker.valueMayBeCaptured(PotentialCopies[Idx++]); 3471 3472 AANoCapture::StateType &S = getState(); 3473 auto Assumed = S.getAssumed(); 3474 S.intersectAssumedBits(T.getAssumed()); 3475 if (!isAssumedNoCaptureMaybeReturned()) 3476 return indicatePessimisticFixpoint(); 3477 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 3478 : ChangeStatus::CHANGED; 3479 } 3480 3481 /// NoCapture attribute for function arguments. 3482 struct AANoCaptureArgument final : AANoCaptureImpl { 3483 AANoCaptureArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 3484 3485 /// See AbstractAttribute::trackStatistics() 3486 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) } 3487 }; 3488 3489 /// NoCapture attribute for call site arguments. 3490 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl { 3491 AANoCaptureCallSiteArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 3492 3493 /// See AbstractAttribute::updateImpl(...). 3494 ChangeStatus updateImpl(Attributor &A) override { 3495 // TODO: Once we have call site specific value information we can provide 3496 // call site specific liveness information and then it makes 3497 // sense to specialize attributes for call sites arguments instead of 3498 // redirecting requests to the callee argument. 3499 Argument *Arg = getAssociatedArgument(); 3500 if (!Arg) 3501 return indicatePessimisticFixpoint(); 3502 const IRPosition &ArgPos = IRPosition::argument(*Arg); 3503 auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos); 3504 return clampStateAndIndicateChange( 3505 getState(), 3506 static_cast<const AANoCapture::StateType &>(ArgAA.getState())); 3507 } 3508 3509 /// See AbstractAttribute::trackStatistics() 3510 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)}; 3511 }; 3512 3513 /// NoCapture attribute for floating values. 3514 struct AANoCaptureFloating final : AANoCaptureImpl { 3515 AANoCaptureFloating(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 3516 3517 /// See AbstractAttribute::trackStatistics() 3518 void trackStatistics() const override { 3519 STATS_DECLTRACK_FLOATING_ATTR(nocapture) 3520 } 3521 }; 3522 3523 /// NoCapture attribute for function return value. 3524 struct AANoCaptureReturned final : AANoCaptureImpl { 3525 AANoCaptureReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) { 3526 llvm_unreachable("NoCapture is not applicable to function returns!"); 3527 } 3528 3529 /// See AbstractAttribute::initialize(...). 3530 void initialize(Attributor &A) override { 3531 llvm_unreachable("NoCapture is not applicable to function returns!"); 3532 } 3533 3534 /// See AbstractAttribute::updateImpl(...). 3535 ChangeStatus updateImpl(Attributor &A) override { 3536 llvm_unreachable("NoCapture is not applicable to function returns!"); 3537 } 3538 3539 /// See AbstractAttribute::trackStatistics() 3540 void trackStatistics() const override {} 3541 }; 3542 3543 /// NoCapture attribute deduction for a call site return value. 3544 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl { 3545 AANoCaptureCallSiteReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 3546 3547 /// See AbstractAttribute::trackStatistics() 3548 void trackStatistics() const override { 3549 STATS_DECLTRACK_CSRET_ATTR(nocapture) 3550 } 3551 }; 3552 3553 /// ------------------ Value Simplify Attribute ---------------------------- 3554 struct AAValueSimplifyImpl : AAValueSimplify { 3555 AAValueSimplifyImpl(const IRPosition &IRP) : AAValueSimplify(IRP) {} 3556 3557 /// See AbstractAttribute::getAsStr(). 3558 const std::string getAsStr() const override { 3559 return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple") 3560 : "not-simple"; 3561 } 3562 3563 /// See AbstractAttribute::trackStatistics() 3564 void trackStatistics() const override {} 3565 3566 /// See AAValueSimplify::getAssumedSimplifiedValue() 3567 Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override { 3568 if (!getAssumed()) 3569 return const_cast<Value *>(&getAssociatedValue()); 3570 return SimplifiedAssociatedValue; 3571 } 3572 void initialize(Attributor &A) override {} 3573 3574 /// Helper function for querying AAValueSimplify and updating candicate. 3575 /// \param QueryingValue Value trying to unify with SimplifiedValue 3576 /// \param AccumulatedSimplifiedValue Current simplification result. 3577 static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA, 3578 Value &QueryingValue, 3579 Optional<Value *> &AccumulatedSimplifiedValue) { 3580 // FIXME: Add a typecast support. 3581 3582 auto &ValueSimpifyAA = A.getAAFor<AAValueSimplify>( 3583 QueryingAA, IRPosition::value(QueryingValue)); 3584 3585 Optional<Value *> QueryingValueSimplified = 3586 ValueSimpifyAA.getAssumedSimplifiedValue(A); 3587 3588 if (!QueryingValueSimplified.hasValue()) 3589 return true; 3590 3591 if (!QueryingValueSimplified.getValue()) 3592 return false; 3593 3594 Value &QueryingValueSimplifiedUnwrapped = 3595 *QueryingValueSimplified.getValue(); 3596 3597 if (isa<UndefValue>(QueryingValueSimplifiedUnwrapped)) 3598 return true; 3599 3600 if (AccumulatedSimplifiedValue.hasValue()) 3601 return AccumulatedSimplifiedValue == QueryingValueSimplified; 3602 3603 LLVM_DEBUG(dbgs() << "[Attributor][ValueSimplify] " << QueryingValue 3604 << " is assumed to be " 3605 << QueryingValueSimplifiedUnwrapped << "\n"); 3606 3607 AccumulatedSimplifiedValue = QueryingValueSimplified; 3608 return true; 3609 } 3610 3611 /// See AbstractAttribute::manifest(...). 3612 ChangeStatus manifest(Attributor &A) override { 3613 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3614 3615 if (!SimplifiedAssociatedValue.hasValue() || 3616 !SimplifiedAssociatedValue.getValue()) 3617 return Changed; 3618 3619 if (auto *C = dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())) { 3620 // We can replace the AssociatedValue with the constant. 3621 Value &V = getAssociatedValue(); 3622 if (!V.user_empty() && &V != C && V.getType() == C->getType()) { 3623 LLVM_DEBUG(dbgs() << "[Attributor][ValueSimplify] " << V << " -> " << *C 3624 << "\n"); 3625 V.replaceAllUsesWith(C); 3626 Changed = ChangeStatus::CHANGED; 3627 } 3628 } 3629 3630 return Changed | AAValueSimplify::manifest(A); 3631 } 3632 3633 protected: 3634 // An assumed simplified value. Initially, it is set to Optional::None, which 3635 // means that the value is not clear under current assumption. If in the 3636 // pessimistic state, getAssumedSimplifiedValue doesn't return this value but 3637 // returns orignal associated value. 3638 Optional<Value *> SimplifiedAssociatedValue; 3639 }; 3640 3641 struct AAValueSimplifyArgument final : AAValueSimplifyImpl { 3642 AAValueSimplifyArgument(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3643 3644 /// See AbstractAttribute::updateImpl(...). 3645 ChangeStatus updateImpl(Attributor &A) override { 3646 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3647 3648 auto PredForCallSite = [&](AbstractCallSite ACS) { 3649 // Check if we have an associated argument or not (which can happen for 3650 // callback calls). 3651 if (Value *ArgOp = ACS.getCallArgOperand(getArgNo())) 3652 return checkAndUpdate(A, *this, *ArgOp, SimplifiedAssociatedValue); 3653 return false; 3654 }; 3655 3656 if (!A.checkForAllCallSites(PredForCallSite, *this, true)) 3657 return indicatePessimisticFixpoint(); 3658 3659 // If a candicate was found in this update, return CHANGED. 3660 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3661 ? ChangeStatus::UNCHANGED 3662 : ChangeStatus ::CHANGED; 3663 } 3664 3665 /// See AbstractAttribute::trackStatistics() 3666 void trackStatistics() const override { 3667 STATS_DECLTRACK_ARG_ATTR(value_simplify) 3668 } 3669 }; 3670 3671 struct AAValueSimplifyReturned : AAValueSimplifyImpl { 3672 AAValueSimplifyReturned(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3673 3674 /// See AbstractAttribute::updateImpl(...). 3675 ChangeStatus updateImpl(Attributor &A) override { 3676 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3677 3678 auto PredForReturned = [&](Value &V) { 3679 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 3680 }; 3681 3682 if (!A.checkForAllReturnedValues(PredForReturned, *this)) 3683 return indicatePessimisticFixpoint(); 3684 3685 // If a candicate was found in this update, return CHANGED. 3686 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3687 ? ChangeStatus::UNCHANGED 3688 : ChangeStatus ::CHANGED; 3689 } 3690 /// See AbstractAttribute::trackStatistics() 3691 void trackStatistics() const override { 3692 STATS_DECLTRACK_FNRET_ATTR(value_simplify) 3693 } 3694 }; 3695 3696 struct AAValueSimplifyFloating : AAValueSimplifyImpl { 3697 AAValueSimplifyFloating(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3698 3699 /// See AbstractAttribute::initialize(...). 3700 void initialize(Attributor &A) override { 3701 Value &V = getAnchorValue(); 3702 3703 // TODO: add other stuffs 3704 if (isa<Constant>(V) || isa<UndefValue>(V)) 3705 indicatePessimisticFixpoint(); 3706 } 3707 3708 /// See AbstractAttribute::updateImpl(...). 3709 ChangeStatus updateImpl(Attributor &A) override { 3710 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3711 3712 auto VisitValueCB = [&](Value &V, BooleanState, bool Stripped) -> bool { 3713 auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V)); 3714 if (!Stripped && this == &AA) { 3715 // TODO: Look the instruction and check recursively. 3716 LLVM_DEBUG( 3717 dbgs() << "[Attributor][ValueSimplify] Can't be stripped more : " 3718 << V << "\n"); 3719 indicatePessimisticFixpoint(); 3720 return false; 3721 } 3722 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 3723 }; 3724 3725 if (!genericValueTraversal<AAValueSimplify, BooleanState>( 3726 A, getIRPosition(), *this, static_cast<BooleanState &>(*this), 3727 VisitValueCB)) 3728 return indicatePessimisticFixpoint(); 3729 3730 // If a candicate was found in this update, return CHANGED. 3731 3732 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3733 ? ChangeStatus::UNCHANGED 3734 : ChangeStatus ::CHANGED; 3735 } 3736 3737 /// See AbstractAttribute::trackStatistics() 3738 void trackStatistics() const override { 3739 STATS_DECLTRACK_FLOATING_ATTR(value_simplify) 3740 } 3741 }; 3742 3743 struct AAValueSimplifyFunction : AAValueSimplifyImpl { 3744 AAValueSimplifyFunction(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3745 3746 /// See AbstractAttribute::initialize(...). 3747 void initialize(Attributor &A) override { 3748 SimplifiedAssociatedValue = &getAnchorValue(); 3749 indicateOptimisticFixpoint(); 3750 } 3751 /// See AbstractAttribute::initialize(...). 3752 ChangeStatus updateImpl(Attributor &A) override { 3753 llvm_unreachable( 3754 "AAValueSimplify(Function|CallSite)::updateImpl will not be called"); 3755 } 3756 /// See AbstractAttribute::trackStatistics() 3757 void trackStatistics() const override { 3758 STATS_DECLTRACK_FN_ATTR(value_simplify) 3759 } 3760 }; 3761 3762 struct AAValueSimplifyCallSite : AAValueSimplifyFunction { 3763 AAValueSimplifyCallSite(const IRPosition &IRP) 3764 : AAValueSimplifyFunction(IRP) {} 3765 /// See AbstractAttribute::trackStatistics() 3766 void trackStatistics() const override { 3767 STATS_DECLTRACK_CS_ATTR(value_simplify) 3768 } 3769 }; 3770 3771 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned { 3772 AAValueSimplifyCallSiteReturned(const IRPosition &IRP) 3773 : AAValueSimplifyReturned(IRP) {} 3774 3775 void trackStatistics() const override { 3776 STATS_DECLTRACK_CSRET_ATTR(value_simplify) 3777 } 3778 }; 3779 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating { 3780 AAValueSimplifyCallSiteArgument(const IRPosition &IRP) 3781 : AAValueSimplifyFloating(IRP) {} 3782 3783 void trackStatistics() const override { 3784 STATS_DECLTRACK_CSARG_ATTR(value_simplify) 3785 } 3786 }; 3787 3788 /// ----------------------- Heap-To-Stack Conversion --------------------------- 3789 struct AAHeapToStackImpl : public AAHeapToStack { 3790 AAHeapToStackImpl(const IRPosition &IRP) : AAHeapToStack(IRP) {} 3791 3792 const std::string getAsStr() const override { 3793 return "[H2S] Mallocs: " + std::to_string(MallocCalls.size()); 3794 } 3795 3796 ChangeStatus manifest(Attributor &A) override { 3797 assert(getState().isValidState() && 3798 "Attempted to manifest an invalid state!"); 3799 3800 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 3801 Function *F = getAssociatedFunction(); 3802 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 3803 3804 for (Instruction *MallocCall : MallocCalls) { 3805 // This malloc cannot be replaced. 3806 if (BadMallocCalls.count(MallocCall)) 3807 continue; 3808 3809 for (Instruction *FreeCall : FreesForMalloc[MallocCall]) { 3810 LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n"); 3811 A.deleteAfterManifest(*FreeCall); 3812 HasChanged = ChangeStatus::CHANGED; 3813 } 3814 3815 LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall 3816 << "\n"); 3817 3818 Constant *Size; 3819 if (isCallocLikeFn(MallocCall, TLI)) { 3820 auto *Num = cast<ConstantInt>(MallocCall->getOperand(0)); 3821 auto *SizeT = dyn_cast<ConstantInt>(MallocCall->getOperand(1)); 3822 APInt TotalSize = SizeT->getValue() * Num->getValue(); 3823 Size = 3824 ConstantInt::get(MallocCall->getOperand(0)->getType(), TotalSize); 3825 } else { 3826 Size = cast<ConstantInt>(MallocCall->getOperand(0)); 3827 } 3828 3829 unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace(); 3830 Instruction *AI = new AllocaInst(Type::getInt8Ty(F->getContext()), AS, 3831 Size, "", MallocCall->getNextNode()); 3832 3833 if (AI->getType() != MallocCall->getType()) 3834 AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc", 3835 AI->getNextNode()); 3836 3837 MallocCall->replaceAllUsesWith(AI); 3838 3839 if (auto *II = dyn_cast<InvokeInst>(MallocCall)) { 3840 auto *NBB = II->getNormalDest(); 3841 BranchInst::Create(NBB, MallocCall->getParent()); 3842 A.deleteAfterManifest(*MallocCall); 3843 } else { 3844 A.deleteAfterManifest(*MallocCall); 3845 } 3846 3847 if (isCallocLikeFn(MallocCall, TLI)) { 3848 auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc", 3849 AI->getNextNode()); 3850 Value *Ops[] = { 3851 BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size, 3852 ConstantInt::get(Type::getInt1Ty(F->getContext()), false)}; 3853 3854 Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()}; 3855 Module *M = F->getParent(); 3856 Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys); 3857 CallInst::Create(Fn, Ops, "", BI->getNextNode()); 3858 } 3859 HasChanged = ChangeStatus::CHANGED; 3860 } 3861 3862 return HasChanged; 3863 } 3864 3865 /// Collection of all malloc calls in a function. 3866 SmallSetVector<Instruction *, 4> MallocCalls; 3867 3868 /// Collection of malloc calls that cannot be converted. 3869 DenseSet<const Instruction *> BadMallocCalls; 3870 3871 /// A map for each malloc call to the set of associated free calls. 3872 DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc; 3873 3874 ChangeStatus updateImpl(Attributor &A) override; 3875 }; 3876 3877 ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) { 3878 const Function *F = getAssociatedFunction(); 3879 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 3880 3881 MustBeExecutedContextExplorer &Explorer = 3882 A.getInfoCache().getMustBeExecutedContextExplorer(); 3883 3884 auto FreeCheck = [&](Instruction &I) { 3885 const auto &Frees = FreesForMalloc.lookup(&I); 3886 if (Frees.size() != 1) 3887 return false; 3888 Instruction *UniqueFree = *Frees.begin(); 3889 return Explorer.findInContextOf(UniqueFree, I.getNextNode()); 3890 }; 3891 3892 auto UsesCheck = [&](Instruction &I) { 3893 bool ValidUsesOnly = true; 3894 bool MustUse = true; 3895 3896 SmallPtrSet<const Use *, 8> Visited; 3897 SmallVector<const Use *, 8> Worklist; 3898 3899 for (Use &U : I.uses()) 3900 Worklist.push_back(&U); 3901 3902 while (!Worklist.empty()) { 3903 const Use *U = Worklist.pop_back_val(); 3904 if (!Visited.insert(U).second) 3905 continue; 3906 3907 auto *UserI = U->getUser(); 3908 3909 if (isa<LoadInst>(UserI)) 3910 continue; 3911 if (auto *SI = dyn_cast<StoreInst>(UserI)) { 3912 if (SI->getValueOperand() == U->get()) { 3913 LLVM_DEBUG(dbgs() 3914 << "[H2S] escaping store to memory: " << *UserI << "\n"); 3915 ValidUsesOnly = false; 3916 } else { 3917 // A store into the malloc'ed memory is fine. 3918 } 3919 continue; 3920 } 3921 3922 // NOTE: Right now, if a function that has malloc pointer as an argument 3923 // frees memory, we assume that the malloc pointer is freed. 3924 3925 // TODO: Add nofree callsite argument attribute to indicate that pointer 3926 // argument is not freed. 3927 if (auto *CB = dyn_cast<CallBase>(UserI)) { 3928 if (!CB->isArgOperand(U)) 3929 continue; 3930 3931 if (CB->isLifetimeStartOrEnd()) 3932 continue; 3933 3934 // Record malloc. 3935 if (isFreeCall(UserI, TLI)) { 3936 if (MustUse) { 3937 FreesForMalloc[&I].insert( 3938 cast<Instruction>(const_cast<User *>(UserI))); 3939 } else { 3940 LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: " 3941 << *UserI << "\n"); 3942 ValidUsesOnly = false; 3943 } 3944 continue; 3945 } 3946 3947 // If a function does not free memory we are fine 3948 const auto &NoFreeAA = 3949 A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(*CB)); 3950 3951 unsigned ArgNo = U - CB->arg_begin(); 3952 const auto &NoCaptureAA = A.getAAFor<AANoCapture>( 3953 *this, IRPosition::callsite_argument(*CB, ArgNo)); 3954 3955 if (!NoCaptureAA.isAssumedNoCapture() || !NoFreeAA.isAssumedNoFree()) { 3956 LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n"); 3957 ValidUsesOnly = false; 3958 } 3959 continue; 3960 } 3961 3962 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) || 3963 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 3964 MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI)); 3965 for (Use &U : UserI->uses()) 3966 Worklist.push_back(&U); 3967 continue; 3968 } 3969 3970 // Unknown user for which we can not track uses further (in a way that 3971 // makes sense). 3972 LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n"); 3973 ValidUsesOnly = false; 3974 } 3975 return ValidUsesOnly; 3976 }; 3977 3978 auto MallocCallocCheck = [&](Instruction &I) { 3979 if (BadMallocCalls.count(&I)) 3980 return true; 3981 3982 bool IsMalloc = isMallocLikeFn(&I, TLI); 3983 bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI); 3984 if (!IsMalloc && !IsCalloc) { 3985 BadMallocCalls.insert(&I); 3986 return true; 3987 } 3988 3989 if (IsMalloc) { 3990 if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0))) 3991 if (Size->getValue().sle(MaxHeapToStackSize)) 3992 if (UsesCheck(I) || FreeCheck(I)) { 3993 MallocCalls.insert(&I); 3994 return true; 3995 } 3996 } else if (IsCalloc) { 3997 bool Overflow = false; 3998 if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0))) 3999 if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1))) 4000 if ((Size->getValue().umul_ov(Num->getValue(), Overflow)) 4001 .sle(MaxHeapToStackSize)) 4002 if (!Overflow && (UsesCheck(I) || FreeCheck(I))) { 4003 MallocCalls.insert(&I); 4004 return true; 4005 } 4006 } 4007 4008 BadMallocCalls.insert(&I); 4009 return true; 4010 }; 4011 4012 size_t NumBadMallocs = BadMallocCalls.size(); 4013 4014 A.checkForAllCallLikeInstructions(MallocCallocCheck, *this); 4015 4016 if (NumBadMallocs != BadMallocCalls.size()) 4017 return ChangeStatus::CHANGED; 4018 4019 return ChangeStatus::UNCHANGED; 4020 } 4021 4022 struct AAHeapToStackFunction final : public AAHeapToStackImpl { 4023 AAHeapToStackFunction(const IRPosition &IRP) : AAHeapToStackImpl(IRP) {} 4024 4025 /// See AbstractAttribute::trackStatistics() 4026 void trackStatistics() const override { 4027 STATS_DECL(MallocCalls, Function, 4028 "Number of malloc calls converted to allocas"); 4029 for (auto *C : MallocCalls) 4030 if (!BadMallocCalls.count(C)) 4031 ++BUILD_STAT_NAME(MallocCalls, Function); 4032 } 4033 }; 4034 4035 /// -------------------- Memory Behavior Attributes ---------------------------- 4036 /// Includes read-none, read-only, and write-only. 4037 /// ---------------------------------------------------------------------------- 4038 struct AAMemoryBehaviorImpl : public AAMemoryBehavior { 4039 AAMemoryBehaviorImpl(const IRPosition &IRP) : AAMemoryBehavior(IRP) {} 4040 4041 /// See AbstractAttribute::initialize(...). 4042 void initialize(Attributor &A) override { 4043 intersectAssumedBits(BEST_STATE); 4044 getKnownStateFromValue(getIRPosition(), getState()); 4045 IRAttribute::initialize(A); 4046 } 4047 4048 /// Return the memory behavior information encoded in the IR for \p IRP. 4049 static void getKnownStateFromValue(const IRPosition &IRP, 4050 BitIntegerState &State) { 4051 SmallVector<Attribute, 2> Attrs; 4052 IRP.getAttrs(AttrKinds, Attrs); 4053 for (const Attribute &Attr : Attrs) { 4054 switch (Attr.getKindAsEnum()) { 4055 case Attribute::ReadNone: 4056 State.addKnownBits(NO_ACCESSES); 4057 break; 4058 case Attribute::ReadOnly: 4059 State.addKnownBits(NO_WRITES); 4060 break; 4061 case Attribute::WriteOnly: 4062 State.addKnownBits(NO_READS); 4063 break; 4064 default: 4065 llvm_unreachable("Unexpcted attribute!"); 4066 } 4067 } 4068 4069 if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) { 4070 if (!I->mayReadFromMemory()) 4071 State.addKnownBits(NO_READS); 4072 if (!I->mayWriteToMemory()) 4073 State.addKnownBits(NO_WRITES); 4074 } 4075 } 4076 4077 /// See AbstractAttribute::getDeducedAttributes(...). 4078 void getDeducedAttributes(LLVMContext &Ctx, 4079 SmallVectorImpl<Attribute> &Attrs) const override { 4080 assert(Attrs.size() == 0); 4081 if (isAssumedReadNone()) 4082 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 4083 else if (isAssumedReadOnly()) 4084 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly)); 4085 else if (isAssumedWriteOnly()) 4086 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly)); 4087 assert(Attrs.size() <= 1); 4088 } 4089 4090 /// See AbstractAttribute::manifest(...). 4091 ChangeStatus manifest(Attributor &A) override { 4092 const IRPosition &IRP = getIRPosition(); 4093 4094 // Check if we would improve the existing attributes first. 4095 SmallVector<Attribute, 4> DeducedAttrs; 4096 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 4097 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 4098 return IRP.hasAttr(Attr.getKindAsEnum(), 4099 /* IgnoreSubsumingPositions */ true); 4100 })) 4101 return ChangeStatus::UNCHANGED; 4102 4103 // Clear existing attributes. 4104 IRP.removeAttrs(AttrKinds); 4105 4106 // Use the generic manifest method. 4107 return IRAttribute::manifest(A); 4108 } 4109 4110 /// See AbstractState::getAsStr(). 4111 const std::string getAsStr() const override { 4112 if (isAssumedReadNone()) 4113 return "readnone"; 4114 if (isAssumedReadOnly()) 4115 return "readonly"; 4116 if (isAssumedWriteOnly()) 4117 return "writeonly"; 4118 return "may-read/write"; 4119 } 4120 4121 /// The set of IR attributes AAMemoryBehavior deals with. 4122 static const Attribute::AttrKind AttrKinds[3]; 4123 }; 4124 4125 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = { 4126 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly}; 4127 4128 /// Memory behavior attribute for a floating value. 4129 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl { 4130 AAMemoryBehaviorFloating(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {} 4131 4132 /// See AbstractAttribute::initialize(...). 4133 void initialize(Attributor &A) override { 4134 AAMemoryBehaviorImpl::initialize(A); 4135 // Initialize the use vector with all direct uses of the associated value. 4136 for (const Use &U : getAssociatedValue().uses()) 4137 Uses.insert(&U); 4138 } 4139 4140 /// See AbstractAttribute::updateImpl(...). 4141 ChangeStatus updateImpl(Attributor &A) override; 4142 4143 /// See AbstractAttribute::trackStatistics() 4144 void trackStatistics() const override { 4145 if (isAssumedReadNone()) 4146 STATS_DECLTRACK_FLOATING_ATTR(readnone) 4147 else if (isAssumedReadOnly()) 4148 STATS_DECLTRACK_FLOATING_ATTR(readonly) 4149 else if (isAssumedWriteOnly()) 4150 STATS_DECLTRACK_FLOATING_ATTR(writeonly) 4151 } 4152 4153 private: 4154 /// Return true if users of \p UserI might access the underlying 4155 /// variable/location described by \p U and should therefore be analyzed. 4156 bool followUsersOfUseIn(Attributor &A, const Use *U, 4157 const Instruction *UserI); 4158 4159 /// Update the state according to the effect of use \p U in \p UserI. 4160 void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI); 4161 4162 protected: 4163 /// Container for (transitive) uses of the associated argument. 4164 SetVector<const Use *> Uses; 4165 }; 4166 4167 /// Memory behavior attribute for function argument. 4168 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating { 4169 AAMemoryBehaviorArgument(const IRPosition &IRP) 4170 : AAMemoryBehaviorFloating(IRP) {} 4171 4172 /// See AbstractAttribute::initialize(...). 4173 void initialize(Attributor &A) override { 4174 AAMemoryBehaviorFloating::initialize(A); 4175 4176 // Initialize the use vector with all direct uses of the associated value. 4177 Argument *Arg = getAssociatedArgument(); 4178 if (!Arg || !Arg->getParent()->hasExactDefinition()) 4179 indicatePessimisticFixpoint(); 4180 } 4181 4182 ChangeStatus manifest(Attributor &A) override { 4183 // TODO: From readattrs.ll: "inalloca parameters are always 4184 // considered written" 4185 if (hasAttr({Attribute::InAlloca})) { 4186 removeKnownBits(NO_WRITES); 4187 removeAssumedBits(NO_WRITES); 4188 } 4189 return AAMemoryBehaviorFloating::manifest(A); 4190 } 4191 4192 4193 /// See AbstractAttribute::trackStatistics() 4194 void trackStatistics() const override { 4195 if (isAssumedReadNone()) 4196 STATS_DECLTRACK_ARG_ATTR(readnone) 4197 else if (isAssumedReadOnly()) 4198 STATS_DECLTRACK_ARG_ATTR(readonly) 4199 else if (isAssumedWriteOnly()) 4200 STATS_DECLTRACK_ARG_ATTR(writeonly) 4201 } 4202 }; 4203 4204 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument { 4205 AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP) 4206 : AAMemoryBehaviorArgument(IRP) {} 4207 4208 /// See AbstractAttribute::updateImpl(...). 4209 ChangeStatus updateImpl(Attributor &A) override { 4210 // TODO: Once we have call site specific value information we can provide 4211 // call site specific liveness liveness information and then it makes 4212 // sense to specialize attributes for call sites arguments instead of 4213 // redirecting requests to the callee argument. 4214 Argument *Arg = getAssociatedArgument(); 4215 const IRPosition &ArgPos = IRPosition::argument(*Arg); 4216 auto &ArgAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos); 4217 return clampStateAndIndicateChange( 4218 getState(), 4219 static_cast<const AAMemoryBehavior::StateType &>(ArgAA.getState())); 4220 } 4221 4222 /// See AbstractAttribute::trackStatistics() 4223 void trackStatistics() const override { 4224 if (isAssumedReadNone()) 4225 STATS_DECLTRACK_CSARG_ATTR(readnone) 4226 else if (isAssumedReadOnly()) 4227 STATS_DECLTRACK_CSARG_ATTR(readonly) 4228 else if (isAssumedWriteOnly()) 4229 STATS_DECLTRACK_CSARG_ATTR(writeonly) 4230 } 4231 }; 4232 4233 /// Memory behavior attribute for a call site return position. 4234 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating { 4235 AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP) 4236 : AAMemoryBehaviorFloating(IRP) {} 4237 4238 /// See AbstractAttribute::manifest(...). 4239 ChangeStatus manifest(Attributor &A) override { 4240 // We do not annotate returned values. 4241 return ChangeStatus::UNCHANGED; 4242 } 4243 4244 /// See AbstractAttribute::trackStatistics() 4245 void trackStatistics() const override {} 4246 }; 4247 4248 /// An AA to represent the memory behavior function attributes. 4249 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl { 4250 AAMemoryBehaviorFunction(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {} 4251 4252 /// See AbstractAttribute::updateImpl(Attributor &A). 4253 virtual ChangeStatus updateImpl(Attributor &A) override; 4254 4255 /// See AbstractAttribute::manifest(...). 4256 ChangeStatus manifest(Attributor &A) override { 4257 Function &F = cast<Function>(getAnchorValue()); 4258 if (isAssumedReadNone()) { 4259 F.removeFnAttr(Attribute::ArgMemOnly); 4260 F.removeFnAttr(Attribute::InaccessibleMemOnly); 4261 F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly); 4262 } 4263 return AAMemoryBehaviorImpl::manifest(A); 4264 } 4265 4266 /// See AbstractAttribute::trackStatistics() 4267 void trackStatistics() const override { 4268 if (isAssumedReadNone()) 4269 STATS_DECLTRACK_FN_ATTR(readnone) 4270 else if (isAssumedReadOnly()) 4271 STATS_DECLTRACK_FN_ATTR(readonly) 4272 else if (isAssumedWriteOnly()) 4273 STATS_DECLTRACK_FN_ATTR(writeonly) 4274 } 4275 }; 4276 4277 /// AAMemoryBehavior attribute for call sites. 4278 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl { 4279 AAMemoryBehaviorCallSite(const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {} 4280 4281 /// See AbstractAttribute::initialize(...). 4282 void initialize(Attributor &A) override { 4283 AAMemoryBehaviorImpl::initialize(A); 4284 Function *F = getAssociatedFunction(); 4285 if (!F || !F->hasExactDefinition()) 4286 indicatePessimisticFixpoint(); 4287 } 4288 4289 /// See AbstractAttribute::updateImpl(...). 4290 ChangeStatus updateImpl(Attributor &A) override { 4291 // TODO: Once we have call site specific value information we can provide 4292 // call site specific liveness liveness information and then it makes 4293 // sense to specialize attributes for call sites arguments instead of 4294 // redirecting requests to the callee argument. 4295 Function *F = getAssociatedFunction(); 4296 const IRPosition &FnPos = IRPosition::function(*F); 4297 auto &FnAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos); 4298 return clampStateAndIndicateChange( 4299 getState(), 4300 static_cast<const AAMemoryBehavior::StateType &>(FnAA.getState())); 4301 } 4302 4303 /// See AbstractAttribute::trackStatistics() 4304 void trackStatistics() const override { 4305 if (isAssumedReadNone()) 4306 STATS_DECLTRACK_CS_ATTR(readnone) 4307 else if (isAssumedReadOnly()) 4308 STATS_DECLTRACK_CS_ATTR(readonly) 4309 else if (isAssumedWriteOnly()) 4310 STATS_DECLTRACK_CS_ATTR(writeonly) 4311 } 4312 }; 4313 } // namespace 4314 4315 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) { 4316 4317 // The current assumed state used to determine a change. 4318 auto AssumedState = getAssumed(); 4319 4320 auto CheckRWInst = [&](Instruction &I) { 4321 // If the instruction has an own memory behavior state, use it to restrict 4322 // the local state. No further analysis is required as the other memory 4323 // state is as optimistic as it gets. 4324 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 4325 const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 4326 *this, IRPosition::callsite_function(ICS)); 4327 intersectAssumedBits(MemBehaviorAA.getAssumed()); 4328 return !isAtFixpoint(); 4329 } 4330 4331 // Remove access kind modifiers if necessary. 4332 if (I.mayReadFromMemory()) 4333 removeAssumedBits(NO_READS); 4334 if (I.mayWriteToMemory()) 4335 removeAssumedBits(NO_WRITES); 4336 return !isAtFixpoint(); 4337 }; 4338 4339 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this)) 4340 return indicatePessimisticFixpoint(); 4341 4342 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 4343 : ChangeStatus::UNCHANGED; 4344 } 4345 4346 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) { 4347 4348 const IRPosition &IRP = getIRPosition(); 4349 const IRPosition &FnPos = IRPosition::function_scope(IRP); 4350 AAMemoryBehavior::StateType &S = getState(); 4351 4352 // First, check the function scope. We take the known information and we avoid 4353 // work if the assumed information implies the current assumed information for 4354 // this attribute. 4355 const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos); 4356 S.addKnownBits(FnMemAA.getKnown()); 4357 if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed()) 4358 return ChangeStatus::UNCHANGED; 4359 4360 // Make sure the value is not captured (except through "return"), if 4361 // it is, any information derived would be irrelevant anyway as we cannot 4362 // check the potential aliases introduced by the capture. However, no need 4363 // to fall back to anythign less optimistic than the function state. 4364 const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP); 4365 if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 4366 S.intersectAssumedBits(FnMemAA.getAssumed()); 4367 return ChangeStatus::CHANGED; 4368 } 4369 4370 // The current assumed state used to determine a change. 4371 auto AssumedState = S.getAssumed(); 4372 4373 // Liveness information to exclude dead users. 4374 // TODO: Take the FnPos once we have call site specific liveness information. 4375 const auto &LivenessAA = A.getAAFor<AAIsDead>( 4376 *this, IRPosition::function(*IRP.getAssociatedFunction())); 4377 4378 // Visit and expand uses until all are analyzed or a fixpoint is reached. 4379 for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) { 4380 const Use *U = Uses[i]; 4381 Instruction *UserI = cast<Instruction>(U->getUser()); 4382 LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI 4383 << " [Dead: " << (LivenessAA.isAssumedDead(UserI)) 4384 << "]\n"); 4385 if (LivenessAA.isAssumedDead(UserI)) 4386 continue; 4387 4388 // Check if the users of UserI should also be visited. 4389 if (followUsersOfUseIn(A, U, UserI)) 4390 for (const Use &UserIUse : UserI->uses()) 4391 Uses.insert(&UserIUse); 4392 4393 // If UserI might touch memory we analyze the use in detail. 4394 if (UserI->mayReadOrWriteMemory()) 4395 analyzeUseIn(A, U, UserI); 4396 } 4397 4398 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 4399 : ChangeStatus::UNCHANGED; 4400 } 4401 4402 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U, 4403 const Instruction *UserI) { 4404 // The loaded value is unrelated to the pointer argument, no need to 4405 // follow the users of the load. 4406 if (isa<LoadInst>(UserI)) 4407 return false; 4408 4409 // By default we follow all uses assuming UserI might leak information on U, 4410 // we have special handling for call sites operands though. 4411 ImmutableCallSite ICS(UserI); 4412 if (!ICS || !ICS.isArgOperand(U)) 4413 return true; 4414 4415 // If the use is a call argument known not to be captured, the users of 4416 // the call do not need to be visited because they have to be unrelated to 4417 // the input. Note that this check is not trivial even though we disallow 4418 // general capturing of the underlying argument. The reason is that the 4419 // call might the argument "through return", which we allow and for which we 4420 // need to check call users. 4421 unsigned ArgNo = ICS.getArgumentNo(U); 4422 const auto &ArgNoCaptureAA = 4423 A.getAAFor<AANoCapture>(*this, IRPosition::callsite_argument(ICS, ArgNo)); 4424 return !ArgNoCaptureAA.isAssumedNoCapture(); 4425 } 4426 4427 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U, 4428 const Instruction *UserI) { 4429 assert(UserI->mayReadOrWriteMemory()); 4430 4431 switch (UserI->getOpcode()) { 4432 default: 4433 // TODO: Handle all atomics and other side-effect operations we know of. 4434 break; 4435 case Instruction::Load: 4436 // Loads cause the NO_READS property to disappear. 4437 removeAssumedBits(NO_READS); 4438 return; 4439 4440 case Instruction::Store: 4441 // Stores cause the NO_WRITES property to disappear if the use is the 4442 // pointer operand. Note that we do assume that capturing was taken care of 4443 // somewhere else. 4444 if (cast<StoreInst>(UserI)->getPointerOperand() == U->get()) 4445 removeAssumedBits(NO_WRITES); 4446 return; 4447 4448 case Instruction::Call: 4449 case Instruction::CallBr: 4450 case Instruction::Invoke: { 4451 // For call sites we look at the argument memory behavior attribute (this 4452 // could be recursive!) in order to restrict our own state. 4453 ImmutableCallSite ICS(UserI); 4454 4455 // Give up on operand bundles. 4456 if (ICS.isBundleOperand(U)) { 4457 indicatePessimisticFixpoint(); 4458 return; 4459 } 4460 4461 // Calling a function does read the function pointer, maybe write it if the 4462 // function is self-modifying. 4463 if (ICS.isCallee(U)) { 4464 removeAssumedBits(NO_READS); 4465 break; 4466 } 4467 4468 // Adjust the possible access behavior based on the information on the 4469 // argument. 4470 unsigned ArgNo = ICS.getArgumentNo(U); 4471 const IRPosition &ArgPos = IRPosition::callsite_argument(ICS, ArgNo); 4472 const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos); 4473 // "assumed" has at most the same bits as the MemBehaviorAA assumed 4474 // and at least "known". 4475 intersectAssumedBits(MemBehaviorAA.getAssumed()); 4476 return; 4477 } 4478 }; 4479 4480 // Generally, look at the "may-properties" and adjust the assumed state if we 4481 // did not trigger special handling before. 4482 if (UserI->mayReadFromMemory()) 4483 removeAssumedBits(NO_READS); 4484 if (UserI->mayWriteToMemory()) 4485 removeAssumedBits(NO_WRITES); 4486 } 4487 4488 /// ---------------------------------------------------------------------------- 4489 /// Attributor 4490 /// ---------------------------------------------------------------------------- 4491 4492 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 4493 const AAIsDead *LivenessAA) { 4494 const Instruction *CtxI = AA.getIRPosition().getCtxI(); 4495 if (!CtxI) 4496 return false; 4497 4498 // TODO: Find a good way to utilize fine and coarse grained liveness 4499 // information. 4500 if (!LivenessAA) 4501 LivenessAA = 4502 &getAAFor<AAIsDead>(AA, IRPosition::function(*CtxI->getFunction()), 4503 /* TrackDependence */ false); 4504 4505 // Don't check liveness for AAIsDead. 4506 if (&AA == LivenessAA) 4507 return false; 4508 4509 if (!LivenessAA->isAssumedDead(CtxI)) 4510 return false; 4511 4512 // We actually used liveness information so we have to record a dependence. 4513 recordDependence(*LivenessAA, AA); 4514 4515 return true; 4516 } 4517 4518 bool Attributor::checkForAllUses( 4519 const function_ref<bool(const Use &, bool &)> &Pred, 4520 const AbstractAttribute &QueryingAA, const Value &V) { 4521 const IRPosition &IRP = QueryingAA.getIRPosition(); 4522 SmallVector<const Use *, 16> Worklist; 4523 SmallPtrSet<const Use *, 16> Visited; 4524 4525 for (const Use &U : V.uses()) 4526 Worklist.push_back(&U); 4527 4528 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size() 4529 << " initial uses to check\n"); 4530 4531 if (Worklist.empty()) 4532 return true; 4533 4534 bool AnyDead = false; 4535 const Function *ScopeFn = IRP.getAnchorScope(); 4536 const auto *LivenessAA = 4537 ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn), 4538 /* TrackDependence */ false) 4539 : nullptr; 4540 4541 while (!Worklist.empty()) { 4542 const Use *U = Worklist.pop_back_val(); 4543 if (!Visited.insert(U).second) 4544 continue; 4545 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << "\n"); 4546 if (Instruction *UserI = dyn_cast<Instruction>(U->getUser())) 4547 if (LivenessAA && LivenessAA->isAssumedDead(UserI)) { 4548 LLVM_DEBUG(dbgs() << "[Attributor] Dead user: " << *UserI << ": " 4549 << static_cast<const AbstractAttribute &>(*LivenessAA) 4550 << "\n"); 4551 AnyDead = true; 4552 continue; 4553 } 4554 4555 bool Follow = false; 4556 if (!Pred(*U, Follow)) 4557 return false; 4558 if (!Follow) 4559 continue; 4560 for (const Use &UU : U->getUser()->uses()) 4561 Worklist.push_back(&UU); 4562 } 4563 4564 if (AnyDead) 4565 recordDependence(*LivenessAA, QueryingAA); 4566 4567 return true; 4568 } 4569 4570 bool Attributor::checkForAllCallSites( 4571 const function_ref<bool(AbstractCallSite)> &Pred, 4572 const AbstractAttribute &QueryingAA, bool RequireAllCallSites) { 4573 // We can try to determine information from 4574 // the call sites. However, this is only possible all call sites are known, 4575 // hence the function has internal linkage. 4576 const IRPosition &IRP = QueryingAA.getIRPosition(); 4577 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 4578 if (!AssociatedFunction) { 4579 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP 4580 << "\n"); 4581 return false; 4582 } 4583 4584 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites, 4585 &QueryingAA); 4586 } 4587 4588 bool Attributor::checkForAllCallSites( 4589 const function_ref<bool(AbstractCallSite)> &Pred, const Function &Fn, 4590 bool RequireAllCallSites, const AbstractAttribute *QueryingAA) { 4591 if (RequireAllCallSites && !Fn.hasLocalLinkage()) { 4592 LLVM_DEBUG( 4593 dbgs() 4594 << "[Attributor] Function " << Fn.getName() 4595 << " has no internal linkage, hence not all call sites are known\n"); 4596 return false; 4597 } 4598 4599 for (const Use &U : Fn.uses()) { 4600 AbstractCallSite ACS(&U); 4601 if (!ACS) { 4602 LLVM_DEBUG(dbgs() << "[Attributor] Function " 4603 << Fn.getName() 4604 << " has non call site use " << *U.get() << " in " 4605 << *U.getUser() << "\n"); 4606 return false; 4607 } 4608 4609 Instruction *I = ACS.getInstruction(); 4610 Function *Caller = I->getFunction(); 4611 4612 const auto *LivenessAA = 4613 lookupAAFor<AAIsDead>(IRPosition::function(*Caller), QueryingAA, 4614 /* TrackDependence */ false); 4615 4616 // Skip dead calls. 4617 if (LivenessAA && LivenessAA->isAssumedDead(I)) { 4618 // We actually used liveness information so we have to record a 4619 // dependence. 4620 if (QueryingAA) 4621 recordDependence(*LivenessAA, *QueryingAA); 4622 continue; 4623 } 4624 4625 const Use *EffectiveUse = 4626 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U; 4627 if (!ACS.isCallee(EffectiveUse)) { 4628 if (!RequireAllCallSites) 4629 continue; 4630 LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser() 4631 << " is an invalid use of " 4632 << Fn.getName() << "\n"); 4633 return false; 4634 } 4635 4636 if (Pred(ACS)) 4637 continue; 4638 4639 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 4640 << *ACS.getInstruction() << "\n"); 4641 return false; 4642 } 4643 4644 return true; 4645 } 4646 4647 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 4648 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 4649 &Pred, 4650 const AbstractAttribute &QueryingAA) { 4651 4652 const IRPosition &IRP = QueryingAA.getIRPosition(); 4653 // Since we need to provide return instructions we have to have an exact 4654 // definition. 4655 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 4656 if (!AssociatedFunction) 4657 return false; 4658 4659 // If this is a call site query we use the call site specific return values 4660 // and liveness information. 4661 // TODO: use the function scope once we have call site AAReturnedValues. 4662 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 4663 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 4664 if (!AARetVal.getState().isValidState()) 4665 return false; 4666 4667 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 4668 } 4669 4670 bool Attributor::checkForAllReturnedValues( 4671 const function_ref<bool(Value &)> &Pred, 4672 const AbstractAttribute &QueryingAA) { 4673 4674 const IRPosition &IRP = QueryingAA.getIRPosition(); 4675 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 4676 if (!AssociatedFunction) 4677 return false; 4678 4679 // TODO: use the function scope once we have call site AAReturnedValues. 4680 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 4681 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 4682 if (!AARetVal.getState().isValidState()) 4683 return false; 4684 4685 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 4686 [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) { 4687 return Pred(RV); 4688 }); 4689 } 4690 4691 static bool 4692 checkForAllInstructionsImpl(InformationCache::OpcodeInstMapTy &OpcodeInstMap, 4693 const function_ref<bool(Instruction &)> &Pred, 4694 const AAIsDead *LivenessAA, bool &AnyDead, 4695 const ArrayRef<unsigned> &Opcodes) { 4696 for (unsigned Opcode : Opcodes) { 4697 for (Instruction *I : OpcodeInstMap[Opcode]) { 4698 // Skip dead instructions. 4699 if (LivenessAA && LivenessAA->isAssumedDead(I)) { 4700 AnyDead = true; 4701 continue; 4702 } 4703 4704 if (!Pred(*I)) 4705 return false; 4706 } 4707 } 4708 return true; 4709 } 4710 4711 bool Attributor::checkForAllInstructions( 4712 const llvm::function_ref<bool(Instruction &)> &Pred, 4713 const AbstractAttribute &QueryingAA, const ArrayRef<unsigned> &Opcodes) { 4714 4715 const IRPosition &IRP = QueryingAA.getIRPosition(); 4716 // Since we need to provide instructions we have to have an exact definition. 4717 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 4718 if (!AssociatedFunction) 4719 return false; 4720 4721 // TODO: use the function scope once we have call site AAReturnedValues. 4722 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 4723 const auto &LivenessAA = 4724 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 4725 bool AnyDead = false; 4726 4727 auto &OpcodeInstMap = 4728 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 4729 if (!checkForAllInstructionsImpl(OpcodeInstMap, Pred, &LivenessAA, AnyDead, 4730 Opcodes)) 4731 return false; 4732 4733 // If we actually used liveness information so we have to record a dependence. 4734 if (AnyDead) 4735 recordDependence(LivenessAA, QueryingAA); 4736 4737 return true; 4738 } 4739 4740 bool Attributor::checkForAllReadWriteInstructions( 4741 const llvm::function_ref<bool(Instruction &)> &Pred, 4742 AbstractAttribute &QueryingAA) { 4743 4744 const Function *AssociatedFunction = 4745 QueryingAA.getIRPosition().getAssociatedFunction(); 4746 if (!AssociatedFunction) 4747 return false; 4748 4749 // TODO: use the function scope once we have call site AAReturnedValues. 4750 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 4751 const auto &LivenessAA = 4752 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 4753 bool AnyDead = false; 4754 4755 for (Instruction *I : 4756 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 4757 // Skip dead instructions. 4758 if (LivenessAA.isAssumedDead(I)) { 4759 AnyDead = true; 4760 continue; 4761 } 4762 4763 if (!Pred(*I)) 4764 return false; 4765 } 4766 4767 // If we actually used liveness information so we have to record a dependence. 4768 if (AnyDead) 4769 recordDependence(LivenessAA, QueryingAA); 4770 4771 return true; 4772 } 4773 4774 ChangeStatus Attributor::run(Module &M) { 4775 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 4776 << AllAbstractAttributes.size() 4777 << " abstract attributes.\n"); 4778 4779 // Now that all abstract attributes are collected and initialized we start 4780 // the abstract analysis. 4781 4782 unsigned IterationCounter = 1; 4783 4784 SmallVector<AbstractAttribute *, 64> ChangedAAs; 4785 SetVector<AbstractAttribute *> Worklist; 4786 Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end()); 4787 4788 bool RecomputeDependences = false; 4789 4790 do { 4791 // Remember the size to determine new attributes. 4792 size_t NumAAs = AllAbstractAttributes.size(); 4793 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 4794 << ", Worklist size: " << Worklist.size() << "\n"); 4795 4796 // If dependences (=QueryMap) are recomputed we have to look at all abstract 4797 // attributes again, regardless of what changed in the last iteration. 4798 if (RecomputeDependences) { 4799 LLVM_DEBUG( 4800 dbgs() << "[Attributor] Run all AAs to recompute dependences\n"); 4801 QueryMap.clear(); 4802 ChangedAAs.clear(); 4803 Worklist.insert(AllAbstractAttributes.begin(), 4804 AllAbstractAttributes.end()); 4805 } 4806 4807 // Add all abstract attributes that are potentially dependent on one that 4808 // changed to the work list. 4809 for (AbstractAttribute *ChangedAA : ChangedAAs) { 4810 auto &QuerriedAAs = QueryMap[ChangedAA]; 4811 Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end()); 4812 } 4813 4814 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter 4815 << ", Worklist+Dependent size: " << Worklist.size() 4816 << "\n"); 4817 4818 // Reset the changed set. 4819 ChangedAAs.clear(); 4820 4821 // Update all abstract attribute in the work list and record the ones that 4822 // changed. 4823 for (AbstractAttribute *AA : Worklist) 4824 if (!AA->getState().isAtFixpoint() && !isAssumedDead(*AA, nullptr)) { 4825 QueriedNonFixAA = false; 4826 if (AA->update(*this) == ChangeStatus::CHANGED) { 4827 ChangedAAs.push_back(AA); 4828 } else if (!QueriedNonFixAA) { 4829 // If the attribute did not query any non-fix information, the state 4830 // will not change and we can indicate that right away. 4831 AA->getState().indicateOptimisticFixpoint(); 4832 } 4833 } 4834 4835 // Check if we recompute the dependences in the next iteration. 4836 RecomputeDependences = (DepRecomputeInterval > 0 && 4837 IterationCounter % DepRecomputeInterval == 0); 4838 4839 // Add attributes to the changed set if they have been created in the last 4840 // iteration. 4841 ChangedAAs.append(AllAbstractAttributes.begin() + NumAAs, 4842 AllAbstractAttributes.end()); 4843 4844 // Reset the work list and repopulate with the changed abstract attributes. 4845 // Note that dependent ones are added above. 4846 Worklist.clear(); 4847 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 4848 4849 } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations || 4850 VerifyMaxFixpointIterations)); 4851 4852 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 4853 << IterationCounter << "/" << MaxFixpointIterations 4854 << " iterations\n"); 4855 4856 size_t NumFinalAAs = AllAbstractAttributes.size(); 4857 4858 // Reset abstract arguments not settled in a sound fixpoint by now. This 4859 // happens when we stopped the fixpoint iteration early. Note that only the 4860 // ones marked as "changed" *and* the ones transitively depending on them 4861 // need to be reverted to a pessimistic state. Others might not be in a 4862 // fixpoint state but we can use the optimistic results for them anyway. 4863 SmallPtrSet<AbstractAttribute *, 32> Visited; 4864 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 4865 AbstractAttribute *ChangedAA = ChangedAAs[u]; 4866 if (!Visited.insert(ChangedAA).second) 4867 continue; 4868 4869 AbstractState &State = ChangedAA->getState(); 4870 if (!State.isAtFixpoint()) { 4871 State.indicatePessimisticFixpoint(); 4872 4873 NumAttributesTimedOut++; 4874 } 4875 4876 auto &QuerriedAAs = QueryMap[ChangedAA]; 4877 ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end()); 4878 } 4879 4880 LLVM_DEBUG({ 4881 if (!Visited.empty()) 4882 dbgs() << "\n[Attributor] Finalized " << Visited.size() 4883 << " abstract attributes.\n"; 4884 }); 4885 4886 unsigned NumManifested = 0; 4887 unsigned NumAtFixpoint = 0; 4888 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 4889 for (AbstractAttribute *AA : AllAbstractAttributes) { 4890 AbstractState &State = AA->getState(); 4891 4892 // If there is not already a fixpoint reached, we can now take the 4893 // optimistic state. This is correct because we enforced a pessimistic one 4894 // on abstract attributes that were transitively dependent on a changed one 4895 // already above. 4896 if (!State.isAtFixpoint()) 4897 State.indicateOptimisticFixpoint(); 4898 4899 // If the state is invalid, we do not try to manifest it. 4900 if (!State.isValidState()) 4901 continue; 4902 4903 // Skip dead code. 4904 if (isAssumedDead(*AA, nullptr)) 4905 continue; 4906 // Manifest the state and record if we changed the IR. 4907 ChangeStatus LocalChange = AA->manifest(*this); 4908 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 4909 AA->trackStatistics(); 4910 4911 ManifestChange = ManifestChange | LocalChange; 4912 4913 NumAtFixpoint++; 4914 NumManifested += (LocalChange == ChangeStatus::CHANGED); 4915 } 4916 4917 (void)NumManifested; 4918 (void)NumAtFixpoint; 4919 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 4920 << " arguments while " << NumAtFixpoint 4921 << " were in a valid fixpoint state\n"); 4922 4923 NumAttributesManifested += NumManifested; 4924 NumAttributesValidFixpoint += NumAtFixpoint; 4925 4926 (void)NumFinalAAs; 4927 assert( 4928 NumFinalAAs == AllAbstractAttributes.size() && 4929 "Expected the final number of abstract attributes to remain unchanged!"); 4930 4931 // Delete stuff at the end to avoid invalid references and a nice order. 4932 { 4933 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least " 4934 << ToBeDeletedFunctions.size() << " functions and " 4935 << ToBeDeletedBlocks.size() << " blocks and " 4936 << ToBeDeletedInsts.size() << " instructions and " 4937 << ToBeChangedUses.size() << " uses\n"); 4938 4939 SmallVector<Instruction *, 32> DeadInsts; 4940 SmallVector<Instruction *, 32> TerminatorsToFold; 4941 SmallVector<Instruction *, 32> UnreachablesToInsert; 4942 4943 for (auto &It : ToBeChangedUses) { 4944 Use *U = It.first; 4945 Value *NewV = It.second; 4946 Value *OldV = U->get(); 4947 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser() 4948 << " instead of " << *OldV << "\n"); 4949 U->set(NewV); 4950 if (Instruction *I = dyn_cast<Instruction>(OldV)) 4951 if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) && isInstructionTriviallyDead(I)) { 4952 DeadInsts.push_back(I); 4953 } 4954 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) { 4955 Instruction *UserI = cast<Instruction>(U->getUser()); 4956 if (isa<UndefValue>(NewV)) { 4957 UnreachablesToInsert.push_back(UserI); 4958 } else { 4959 TerminatorsToFold.push_back(UserI); 4960 } 4961 } 4962 } 4963 for (Instruction *I : UnreachablesToInsert) 4964 changeToUnreachable(I, /* UseLLVMTrap */ false); 4965 for (Instruction *I : TerminatorsToFold) 4966 ConstantFoldTerminator(I->getParent()); 4967 4968 for (Instruction *I : ToBeDeletedInsts) { 4969 I->replaceAllUsesWith(UndefValue::get(I->getType())); 4970 if (!isa<PHINode>(I) && isInstructionTriviallyDead(I)) 4971 DeadInsts.push_back(I); 4972 else 4973 I->eraseFromParent(); 4974 } 4975 4976 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 4977 4978 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 4979 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 4980 ToBeDeletedBBs.reserve(NumDeadBlocks); 4981 ToBeDeletedBBs.append(ToBeDeletedBlocks.begin(), ToBeDeletedBlocks.end()); 4982 // Actually we do not delete the blocks but squash them into a single 4983 // unreachable but untangling branches that jump here is something we need 4984 // to do in a more generic way. 4985 DetatchDeadBlocks(ToBeDeletedBBs, nullptr); 4986 STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted."); 4987 BUILD_STAT_NAME(AAIsDead, BasicBlock) += ToBeDeletedBlocks.size(); 4988 } 4989 4990 STATS_DECL(AAIsDead, Function, "Number of dead functions deleted."); 4991 for (Function *Fn : ToBeDeletedFunctions) { 4992 Fn->replaceAllUsesWith(UndefValue::get(Fn->getType())); 4993 Fn->eraseFromParent(); 4994 STATS_TRACK(AAIsDead, Function); 4995 } 4996 4997 // Identify dead internal functions and delete them. This happens outside 4998 // the other fixpoint analysis as we might treat potentially dead functions 4999 // as live to lower the number of iterations. If they happen to be dead, the 5000 // below fixpoint loop will identify and eliminate them. 5001 SmallVector<Function *, 8> InternalFns; 5002 for (Function &F : M) 5003 if (F.hasLocalLinkage()) 5004 InternalFns.push_back(&F); 5005 5006 bool FoundDeadFn = true; 5007 while (FoundDeadFn) { 5008 FoundDeadFn = false; 5009 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 5010 Function *F = InternalFns[u]; 5011 if (!F) 5012 continue; 5013 5014 if (!checkForAllCallSites([](AbstractCallSite ACS) { return false; }, 5015 *F, true, nullptr)) 5016 continue; 5017 5018 STATS_TRACK(AAIsDead, Function); 5019 ToBeDeletedFunctions.insert(F); 5020 F->replaceAllUsesWith(UndefValue::get(F->getType())); 5021 F->eraseFromParent(); 5022 InternalFns[u] = nullptr; 5023 FoundDeadFn = true; 5024 } 5025 } 5026 } 5027 5028 if (VerifyMaxFixpointIterations && 5029 IterationCounter != MaxFixpointIterations) { 5030 errs() << "\n[Attributor] Fixpoint iteration done after: " 5031 << IterationCounter << "/" << MaxFixpointIterations 5032 << " iterations\n"; 5033 llvm_unreachable("The fixpoint was not reached with exactly the number of " 5034 "specified iterations!"); 5035 } 5036 5037 return ManifestChange; 5038 } 5039 5040 void Attributor::initializeInformationCache(Function &F) { 5041 5042 // Walk all instructions to find interesting instructions that might be 5043 // queried by abstract attributes during their initialization or update. 5044 // This has to happen before we create attributes. 5045 auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F]; 5046 auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F]; 5047 5048 for (Instruction &I : instructions(&F)) { 5049 bool IsInterestingOpcode = false; 5050 5051 // To allow easy access to all instructions in a function with a given 5052 // opcode we store them in the InfoCache. As not all opcodes are interesting 5053 // to concrete attributes we only cache the ones that are as identified in 5054 // the following switch. 5055 // Note: There are no concrete attributes now so this is initially empty. 5056 switch (I.getOpcode()) { 5057 default: 5058 assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) && 5059 "New call site/base instruction type needs to be known int the " 5060 "Attributor."); 5061 break; 5062 case Instruction::Load: 5063 // The alignment of a pointer is interesting for loads. 5064 case Instruction::Store: 5065 // The alignment of a pointer is interesting for stores. 5066 case Instruction::Call: 5067 case Instruction::CallBr: 5068 case Instruction::Invoke: 5069 case Instruction::CleanupRet: 5070 case Instruction::CatchSwitch: 5071 case Instruction::Resume: 5072 case Instruction::Ret: 5073 IsInterestingOpcode = true; 5074 } 5075 if (IsInterestingOpcode) 5076 InstOpcodeMap[I.getOpcode()].push_back(&I); 5077 if (I.mayReadOrWriteMemory()) 5078 ReadOrWriteInsts.push_back(&I); 5079 } 5080 } 5081 5082 void Attributor::recordDependence(const AbstractAttribute &FromAA, 5083 const AbstractAttribute &ToAA) { 5084 if (FromAA.getState().isAtFixpoint()) 5085 return; 5086 5087 QueryMap[&FromAA].insert(const_cast<AbstractAttribute *>(&ToAA)); 5088 QueriedNonFixAA = true; 5089 } 5090 5091 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 5092 if (!VisitedFunctions.insert(&F).second) 5093 return; 5094 5095 IRPosition FPos = IRPosition::function(F); 5096 5097 // Check for dead BasicBlocks in every function. 5098 // We need dead instruction detection because we do not want to deal with 5099 // broken IR in which SSA rules do not apply. 5100 getOrCreateAAFor<AAIsDead>(FPos); 5101 5102 // Every function might be "will-return". 5103 getOrCreateAAFor<AAWillReturn>(FPos); 5104 5105 // Every function can be nounwind. 5106 getOrCreateAAFor<AANoUnwind>(FPos); 5107 5108 // Every function might be marked "nosync" 5109 getOrCreateAAFor<AANoSync>(FPos); 5110 5111 // Every function might be "no-free". 5112 getOrCreateAAFor<AANoFree>(FPos); 5113 5114 // Every function might be "no-return". 5115 getOrCreateAAFor<AANoReturn>(FPos); 5116 5117 // Every function might be "no-recurse". 5118 getOrCreateAAFor<AANoRecurse>(FPos); 5119 5120 // Every function might be "readnone/readonly/writeonly/...". 5121 getOrCreateAAFor<AAMemoryBehavior>(FPos); 5122 5123 // Every function might be applicable for Heap-To-Stack conversion. 5124 if (EnableHeapToStack) 5125 getOrCreateAAFor<AAHeapToStack>(FPos); 5126 5127 // Return attributes are only appropriate if the return type is non void. 5128 Type *ReturnType = F.getReturnType(); 5129 if (!ReturnType->isVoidTy()) { 5130 // Argument attribute "returned" --- Create only one per function even 5131 // though it is an argument attribute. 5132 getOrCreateAAFor<AAReturnedValues>(FPos); 5133 5134 IRPosition RetPos = IRPosition::returned(F); 5135 5136 // Every returned value might be dead. 5137 getOrCreateAAFor<AAIsDead>(RetPos); 5138 5139 // Every function might be simplified. 5140 getOrCreateAAFor<AAValueSimplify>(RetPos); 5141 5142 if (ReturnType->isPointerTy()) { 5143 5144 // Every function with pointer return type might be marked align. 5145 getOrCreateAAFor<AAAlign>(RetPos); 5146 5147 // Every function with pointer return type might be marked nonnull. 5148 getOrCreateAAFor<AANonNull>(RetPos); 5149 5150 // Every function with pointer return type might be marked noalias. 5151 getOrCreateAAFor<AANoAlias>(RetPos); 5152 5153 // Every function with pointer return type might be marked 5154 // dereferenceable. 5155 getOrCreateAAFor<AADereferenceable>(RetPos); 5156 } 5157 } 5158 5159 for (Argument &Arg : F.args()) { 5160 IRPosition ArgPos = IRPosition::argument(Arg); 5161 5162 // Every argument might be simplified. 5163 getOrCreateAAFor<AAValueSimplify>(ArgPos); 5164 5165 if (Arg.getType()->isPointerTy()) { 5166 // Every argument with pointer type might be marked nonnull. 5167 getOrCreateAAFor<AANonNull>(ArgPos); 5168 5169 // Every argument with pointer type might be marked noalias. 5170 getOrCreateAAFor<AANoAlias>(ArgPos); 5171 5172 // Every argument with pointer type might be marked dereferenceable. 5173 getOrCreateAAFor<AADereferenceable>(ArgPos); 5174 5175 // Every argument with pointer type might be marked align. 5176 getOrCreateAAFor<AAAlign>(ArgPos); 5177 5178 // Every argument with pointer type might be marked nocapture. 5179 getOrCreateAAFor<AANoCapture>(ArgPos); 5180 5181 // Every argument with pointer type might be marked 5182 // "readnone/readonly/writeonly/..." 5183 getOrCreateAAFor<AAMemoryBehavior>(ArgPos); 5184 } 5185 } 5186 5187 auto CallSitePred = [&](Instruction &I) -> bool { 5188 CallSite CS(&I); 5189 if (Function *Callee = CS.getCalledFunction()) { 5190 if (!Callee->getReturnType()->isVoidTy()) { 5191 IRPosition CSRetPos = IRPosition::callsite_returned(CS); 5192 5193 // Call site return values might be dead. 5194 getOrCreateAAFor<AAIsDead>(CSRetPos); 5195 } 5196 5197 for (int i = 0, e = Callee->arg_size(); i < e; i++) { 5198 5199 IRPosition CSArgPos = IRPosition::callsite_argument(CS, i); 5200 5201 // Every call site argument might be dead. 5202 getOrCreateAAFor<AAIsDead>(CSArgPos); 5203 5204 // Call site argument might be simplified. 5205 getOrCreateAAFor<AAValueSimplify>(CSArgPos); 5206 5207 if (!CS.getArgument(i)->getType()->isPointerTy()) 5208 continue; 5209 5210 // Call site argument attribute "non-null". 5211 getOrCreateAAFor<AANonNull>(CSArgPos); 5212 5213 // Call site argument attribute "no-alias". 5214 getOrCreateAAFor<AANoAlias>(CSArgPos); 5215 5216 // Call site argument attribute "dereferenceable". 5217 getOrCreateAAFor<AADereferenceable>(CSArgPos); 5218 5219 // Call site argument attribute "align". 5220 getOrCreateAAFor<AAAlign>(CSArgPos); 5221 } 5222 } 5223 return true; 5224 }; 5225 5226 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); 5227 bool Success, AnyDead = false; 5228 Success = checkForAllInstructionsImpl( 5229 OpcodeInstMap, CallSitePred, nullptr, AnyDead, 5230 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 5231 (unsigned)Instruction::Call}); 5232 (void)Success; 5233 assert(Success && !AnyDead && "Expected the check call to be successful!"); 5234 5235 auto LoadStorePred = [&](Instruction &I) -> bool { 5236 if (isa<LoadInst>(I)) 5237 getOrCreateAAFor<AAAlign>( 5238 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 5239 else 5240 getOrCreateAAFor<AAAlign>( 5241 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 5242 return true; 5243 }; 5244 Success = checkForAllInstructionsImpl( 5245 OpcodeInstMap, LoadStorePred, nullptr, AnyDead, 5246 {(unsigned)Instruction::Load, (unsigned)Instruction::Store}); 5247 (void)Success; 5248 assert(Success && !AnyDead && "Expected the check call to be successful!"); 5249 } 5250 5251 /// Helpers to ease debugging through output streams and print calls. 5252 /// 5253 ///{ 5254 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 5255 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 5256 } 5257 5258 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 5259 switch (AP) { 5260 case IRPosition::IRP_INVALID: 5261 return OS << "inv"; 5262 case IRPosition::IRP_FLOAT: 5263 return OS << "flt"; 5264 case IRPosition::IRP_RETURNED: 5265 return OS << "fn_ret"; 5266 case IRPosition::IRP_CALL_SITE_RETURNED: 5267 return OS << "cs_ret"; 5268 case IRPosition::IRP_FUNCTION: 5269 return OS << "fn"; 5270 case IRPosition::IRP_CALL_SITE: 5271 return OS << "cs"; 5272 case IRPosition::IRP_ARGUMENT: 5273 return OS << "arg"; 5274 case IRPosition::IRP_CALL_SITE_ARGUMENT: 5275 return OS << "cs_arg"; 5276 } 5277 llvm_unreachable("Unknown attribute position!"); 5278 } 5279 5280 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 5281 const Value &AV = Pos.getAssociatedValue(); 5282 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 5283 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 5284 } 5285 5286 template <typename base_ty, base_ty BestState, base_ty WorstState> 5287 raw_ostream &llvm:: 5288 operator<<(raw_ostream &OS, 5289 const IntegerStateBase<base_ty, BestState, WorstState> &S) { 5290 return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")" 5291 << static_cast<const AbstractState &>(S); 5292 } 5293 5294 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 5295 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 5296 } 5297 5298 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 5299 AA.print(OS); 5300 return OS; 5301 } 5302 5303 void AbstractAttribute::print(raw_ostream &OS) const { 5304 OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState() 5305 << "]"; 5306 } 5307 ///} 5308 5309 /// ---------------------------------------------------------------------------- 5310 /// Pass (Manager) Boilerplate 5311 /// ---------------------------------------------------------------------------- 5312 5313 static bool runAttributorOnModule(Module &M, AnalysisGetter &AG) { 5314 if (DisableAttributor) 5315 return false; 5316 5317 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size() 5318 << " functions.\n"); 5319 5320 // Create an Attributor and initially empty information cache that is filled 5321 // while we identify default attribute opportunities. 5322 InformationCache InfoCache(M, AG); 5323 Attributor A(InfoCache, DepRecInterval); 5324 5325 for (Function &F : M) 5326 A.initializeInformationCache(F); 5327 5328 for (Function &F : M) { 5329 if (F.hasExactDefinition()) 5330 NumFnWithExactDefinition++; 5331 else 5332 NumFnWithoutExactDefinition++; 5333 5334 // We look at internal functions only on-demand but if any use is not a 5335 // direct call, we have to do it eagerly. 5336 if (F.hasLocalLinkage()) { 5337 if (llvm::all_of(F.uses(), [](const Use &U) { 5338 return ImmutableCallSite(U.getUser()) && 5339 ImmutableCallSite(U.getUser()).isCallee(&U); 5340 })) 5341 continue; 5342 } 5343 5344 // Populate the Attributor with abstract attribute opportunities in the 5345 // function and the information cache with IR information. 5346 A.identifyDefaultAbstractAttributes(F); 5347 } 5348 5349 return A.run(M) == ChangeStatus::CHANGED; 5350 } 5351 5352 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 5353 AnalysisGetter AG(AM); 5354 if (runAttributorOnModule(M, AG)) { 5355 // FIXME: Think about passes we will preserve and add them here. 5356 return PreservedAnalyses::none(); 5357 } 5358 return PreservedAnalyses::all(); 5359 } 5360 5361 namespace { 5362 5363 struct AttributorLegacyPass : public ModulePass { 5364 static char ID; 5365 5366 AttributorLegacyPass() : ModulePass(ID) { 5367 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 5368 } 5369 5370 bool runOnModule(Module &M) override { 5371 if (skipModule(M)) 5372 return false; 5373 5374 AnalysisGetter AG; 5375 return runAttributorOnModule(M, AG); 5376 } 5377 5378 void getAnalysisUsage(AnalysisUsage &AU) const override { 5379 // FIXME: Think about passes we will preserve and add them here. 5380 AU.addRequired<TargetLibraryInfoWrapperPass>(); 5381 } 5382 }; 5383 5384 } // end anonymous namespace 5385 5386 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 5387 5388 char AttributorLegacyPass::ID = 0; 5389 5390 const char AAReturnedValues::ID = 0; 5391 const char AANoUnwind::ID = 0; 5392 const char AANoSync::ID = 0; 5393 const char AANoFree::ID = 0; 5394 const char AANonNull::ID = 0; 5395 const char AANoRecurse::ID = 0; 5396 const char AAWillReturn::ID = 0; 5397 const char AANoAlias::ID = 0; 5398 const char AANoReturn::ID = 0; 5399 const char AAIsDead::ID = 0; 5400 const char AADereferenceable::ID = 0; 5401 const char AAAlign::ID = 0; 5402 const char AANoCapture::ID = 0; 5403 const char AAValueSimplify::ID = 0; 5404 const char AAHeapToStack::ID = 0; 5405 const char AAMemoryBehavior::ID = 0; 5406 5407 // Macro magic to create the static generator function for attributes that 5408 // follow the naming scheme. 5409 5410 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 5411 case IRPosition::PK: \ 5412 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 5413 5414 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 5415 case IRPosition::PK: \ 5416 AA = new CLASS##SUFFIX(IRP); \ 5417 break; 5418 5419 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 5420 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 5421 CLASS *AA = nullptr; \ 5422 switch (IRP.getPositionKind()) { \ 5423 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 5424 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 5425 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 5426 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 5427 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 5428 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 5429 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 5430 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 5431 } \ 5432 return *AA; \ 5433 } 5434 5435 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 5436 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 5437 CLASS *AA = nullptr; \ 5438 switch (IRP.getPositionKind()) { \ 5439 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 5440 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 5441 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 5442 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 5443 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 5444 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 5445 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 5446 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 5447 } \ 5448 return *AA; \ 5449 } 5450 5451 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 5452 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 5453 CLASS *AA = nullptr; \ 5454 switch (IRP.getPositionKind()) { \ 5455 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 5456 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 5457 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 5458 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 5459 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 5460 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 5461 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 5462 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 5463 } \ 5464 return *AA; \ 5465 } 5466 5467 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 5468 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 5469 CLASS *AA = nullptr; \ 5470 switch (IRP.getPositionKind()) { \ 5471 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 5472 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 5473 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 5474 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 5475 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 5476 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 5477 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 5478 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 5479 } \ 5480 return *AA; \ 5481 } 5482 5483 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 5484 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 5485 CLASS *AA = nullptr; \ 5486 switch (IRP.getPositionKind()) { \ 5487 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 5488 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 5489 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 5490 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 5491 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 5492 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 5493 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 5494 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 5495 } \ 5496 return *AA; \ 5497 } 5498 5499 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 5500 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 5501 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 5502 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 5503 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 5504 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 5505 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 5506 5507 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 5508 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 5509 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 5510 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 5511 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture) 5512 5513 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify) 5514 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 5515 5516 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack) 5517 5518 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior) 5519 5520 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION 5521 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 5522 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION 5523 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 5524 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 5525 #undef SWITCH_PK_CREATE 5526 #undef SWITCH_PK_INV 5527 5528 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 5529 "Deduce and propagate attributes", false, false) 5530 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 5531 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 5532 "Deduce and propagate attributes", false, false) 5533