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/ValueTracking.h" 28 #include "llvm/IR/Argument.h" 29 #include "llvm/IR/Attributes.h" 30 #include "llvm/IR/CFG.h" 31 #include "llvm/IR/InstIterator.h" 32 #include "llvm/IR/IntrinsicInst.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 39 #include <cassert> 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "attributor" 44 45 STATISTIC(NumFnWithExactDefinition, 46 "Number of function with exact definitions"); 47 STATISTIC(NumFnWithoutExactDefinition, 48 "Number of function without exact definitions"); 49 STATISTIC(NumAttributesTimedOut, 50 "Number of abstract attributes timed out before fixpoint"); 51 STATISTIC(NumAttributesValidFixpoint, 52 "Number of abstract attributes in a valid fixpoint state"); 53 STATISTIC(NumAttributesManifested, 54 "Number of abstract attributes manifested in IR"); 55 56 // Some helper macros to deal with statistics tracking. 57 // 58 // Usage: 59 // For simple IR attribute tracking overload trackStatistics in the abstract 60 // attribute and choose the right STATS_DECLTRACK_********* macro, 61 // e.g.,: 62 // void trackStatistics() const override { 63 // STATS_DECLTRACK_ARG_ATTR(returned) 64 // } 65 // If there is a single "increment" side one can use the macro 66 // STATS_DECLTRACK with a custom message. If there are multiple increment 67 // sides, STATS_DECL and STATS_TRACK can also be used separatly. 68 // 69 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 70 ("Number of " #TYPE " marked '" #NAME "'") 71 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 72 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG); 73 #define STATS_DECL(NAME, TYPE, MSG) \ 74 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG); 75 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 76 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 77 { \ 78 STATS_DECL(NAME, TYPE, MSG) \ 79 STATS_TRACK(NAME, TYPE) \ 80 } 81 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 82 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 83 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 84 STATS_DECLTRACK(NAME, CSArguments, \ 85 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 86 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 87 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 88 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 89 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 90 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 91 STATS_DECLTRACK(NAME, FunctionReturn, \ 92 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 93 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 94 STATS_DECLTRACK(NAME, CSReturn, \ 95 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 96 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 97 STATS_DECLTRACK(NAME, Floating, \ 98 ("Number of floating values known to be '" #NAME "'")) 99 100 // TODO: Determine a good default value. 101 // 102 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 103 // (when run with the first 5 abstract attributes). The results also indicate 104 // that we never reach 32 iterations but always find a fixpoint sooner. 105 // 106 // This will become more evolved once we perform two interleaved fixpoint 107 // iterations: bottom-up and top-down. 108 static cl::opt<unsigned> 109 MaxFixpointIterations("attributor-max-iterations", cl::Hidden, 110 cl::desc("Maximal number of fixpoint iterations."), 111 cl::init(32)); 112 static cl::opt<bool> VerifyMaxFixpointIterations( 113 "attributor-max-iterations-verify", cl::Hidden, 114 cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), 115 cl::init(false)); 116 117 static cl::opt<bool> DisableAttributor( 118 "attributor-disable", cl::Hidden, 119 cl::desc("Disable the attributor inter-procedural deduction pass."), 120 cl::init(true)); 121 122 static cl::opt<bool> ManifestInternal( 123 "attributor-manifest-internal", cl::Hidden, 124 cl::desc("Manifest Attributor internal string attributes."), 125 cl::init(false)); 126 127 static cl::opt<bool> VerifyAttributor( 128 "attributor-verify", cl::Hidden, 129 cl::desc("Verify the Attributor deduction and " 130 "manifestation of attributes -- may issue false-positive errors"), 131 cl::init(false)); 132 133 static cl::opt<unsigned> DepRecInterval( 134 "attributor-dependence-recompute-interval", cl::Hidden, 135 cl::desc("Number of iterations until dependences are recomputed."), 136 cl::init(4)); 137 138 /// Logic operators for the change status enum class. 139 /// 140 ///{ 141 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { 142 return l == ChangeStatus::CHANGED ? l : r; 143 } 144 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { 145 return l == ChangeStatus::UNCHANGED ? l : r; 146 } 147 ///} 148 149 /// Recursively visit all values that might become \p IRP at some point. This 150 /// will be done by looking through cast instructions, selects, phis, and calls 151 /// with the "returned" attribute. Once we cannot look through the value any 152 /// further, the callback \p VisitValueCB is invoked and passed the current 153 /// value, the \p State, and a flag to indicate if we stripped anything. To 154 /// limit how much effort is invested, we will never visit more values than 155 /// specified by \p MaxValues. 156 template <typename AAType, typename StateTy> 157 bool genericValueTraversal( 158 Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State, 159 const function_ref<bool(Value &, StateTy &, bool)> &VisitValueCB, 160 int MaxValues = 8) { 161 162 const AAIsDead *LivenessAA = nullptr; 163 if (IRP.getAnchorScope()) 164 LivenessAA = &A.getAAFor<AAIsDead>( 165 QueryingAA, IRPosition::function(*IRP.getAnchorScope()), 166 /* TrackDependence */ false); 167 bool AnyDead = false; 168 169 // TODO: Use Positions here to allow context sensitivity in VisitValueCB 170 SmallPtrSet<Value *, 16> Visited; 171 SmallVector<Value *, 16> Worklist; 172 Worklist.push_back(&IRP.getAssociatedValue()); 173 174 int Iteration = 0; 175 do { 176 Value *V = Worklist.pop_back_val(); 177 178 // Check if we should process the current value. To prevent endless 179 // recursion keep a record of the values we followed! 180 if (!Visited.insert(V).second) 181 continue; 182 183 // Make sure we limit the compile time for complex expressions. 184 if (Iteration++ >= MaxValues) 185 return false; 186 187 // Explicitly look through calls with a "returned" attribute if we do 188 // not have a pointer as stripPointerCasts only works on them. 189 Value *NewV = nullptr; 190 if (V->getType()->isPointerTy()) { 191 NewV = V->stripPointerCasts(); 192 } else { 193 CallSite CS(V); 194 if (CS && CS.getCalledFunction()) { 195 for (Argument &Arg : CS.getCalledFunction()->args()) 196 if (Arg.hasReturnedAttr()) { 197 NewV = CS.getArgOperand(Arg.getArgNo()); 198 break; 199 } 200 } 201 } 202 if (NewV && NewV != V) { 203 Worklist.push_back(NewV); 204 continue; 205 } 206 207 // Look through select instructions, visit both potential values. 208 if (auto *SI = dyn_cast<SelectInst>(V)) { 209 Worklist.push_back(SI->getTrueValue()); 210 Worklist.push_back(SI->getFalseValue()); 211 continue; 212 } 213 214 // Look through phi nodes, visit all live operands. 215 if (auto *PHI = dyn_cast<PHINode>(V)) { 216 assert(LivenessAA && 217 "Expected liveness in the presence of instructions!"); 218 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) { 219 const BasicBlock *IncomingBB = PHI->getIncomingBlock(u); 220 if (LivenessAA->isAssumedDead(IncomingBB->getTerminator())) { 221 AnyDead = true; 222 continue; 223 } 224 Worklist.push_back(PHI->getIncomingValue(u)); 225 } 226 continue; 227 } 228 229 // Once a leaf is reached we inform the user through the callback. 230 if (!VisitValueCB(*V, State, Iteration > 1)) 231 return false; 232 } while (!Worklist.empty()); 233 234 // If we actually used liveness information so we have to record a dependence. 235 if (AnyDead) 236 A.recordDependence(*LivenessAA, QueryingAA); 237 238 // All values have been visited. 239 return true; 240 } 241 242 /// Return true if \p New is equal or worse than \p Old. 243 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 244 if (!Old.isIntAttribute()) 245 return true; 246 247 return Old.getValueAsInt() >= New.getValueAsInt(); 248 } 249 250 /// Return true if the information provided by \p Attr was added to the 251 /// attribute list \p Attrs. This is only the case if it was not already present 252 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 253 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 254 AttributeList &Attrs, int AttrIdx) { 255 256 if (Attr.isEnumAttribute()) { 257 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 258 if (Attrs.hasAttribute(AttrIdx, Kind)) 259 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 260 return false; 261 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 262 return true; 263 } 264 if (Attr.isStringAttribute()) { 265 StringRef Kind = Attr.getKindAsString(); 266 if (Attrs.hasAttribute(AttrIdx, Kind)) 267 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 268 return false; 269 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 270 return true; 271 } 272 if (Attr.isIntAttribute()) { 273 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 274 if (Attrs.hasAttribute(AttrIdx, Kind)) 275 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 276 return false; 277 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 278 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 279 return true; 280 } 281 282 llvm_unreachable("Expected enum or string attribute!"); 283 } 284 285 ChangeStatus AbstractAttribute::update(Attributor &A) { 286 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 287 if (getState().isAtFixpoint()) 288 return HasChanged; 289 290 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 291 292 HasChanged = updateImpl(A); 293 294 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 295 << "\n"); 296 297 return HasChanged; 298 } 299 300 ChangeStatus 301 IRAttributeManifest::manifestAttrs(Attributor &A, IRPosition &IRP, 302 const ArrayRef<Attribute> &DeducedAttrs) { 303 Function *ScopeFn = IRP.getAssociatedFunction(); 304 IRPosition::Kind PK = IRP.getPositionKind(); 305 306 // In the following some generic code that will manifest attributes in 307 // DeducedAttrs if they improve the current IR. Due to the different 308 // annotation positions we use the underlying AttributeList interface. 309 310 AttributeList Attrs; 311 switch (PK) { 312 case IRPosition::IRP_INVALID: 313 case IRPosition::IRP_FLOAT: 314 return ChangeStatus::UNCHANGED; 315 case IRPosition::IRP_ARGUMENT: 316 case IRPosition::IRP_FUNCTION: 317 case IRPosition::IRP_RETURNED: 318 Attrs = ScopeFn->getAttributes(); 319 break; 320 case IRPosition::IRP_CALL_SITE: 321 case IRPosition::IRP_CALL_SITE_RETURNED: 322 case IRPosition::IRP_CALL_SITE_ARGUMENT: 323 Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes(); 324 break; 325 } 326 327 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 328 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 329 for (const Attribute &Attr : DeducedAttrs) { 330 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 331 continue; 332 333 HasChanged = ChangeStatus::CHANGED; 334 } 335 336 if (HasChanged == ChangeStatus::UNCHANGED) 337 return HasChanged; 338 339 switch (PK) { 340 case IRPosition::IRP_ARGUMENT: 341 case IRPosition::IRP_FUNCTION: 342 case IRPosition::IRP_RETURNED: 343 ScopeFn->setAttributes(Attrs); 344 break; 345 case IRPosition::IRP_CALL_SITE: 346 case IRPosition::IRP_CALL_SITE_RETURNED: 347 case IRPosition::IRP_CALL_SITE_ARGUMENT: 348 CallSite(&IRP.getAnchorValue()).setAttributes(Attrs); 349 break; 350 case IRPosition::IRP_INVALID: 351 case IRPosition::IRP_FLOAT: 352 break; 353 } 354 355 return HasChanged; 356 } 357 358 const IRPosition IRPosition::EmptyKey(255); 359 const IRPosition IRPosition::TombstoneKey(256); 360 361 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 362 IRPositions.emplace_back(IRP); 363 364 ImmutableCallSite ICS(&IRP.getAnchorValue()); 365 switch (IRP.getPositionKind()) { 366 case IRPosition::IRP_INVALID: 367 case IRPosition::IRP_FLOAT: 368 case IRPosition::IRP_FUNCTION: 369 return; 370 case IRPosition::IRP_ARGUMENT: 371 case IRPosition::IRP_RETURNED: 372 IRPositions.emplace_back( 373 IRPosition::function(*IRP.getAssociatedFunction())); 374 return; 375 case IRPosition::IRP_CALL_SITE: 376 assert(ICS && "Expected call site!"); 377 // TODO: We need to look at the operand bundles similar to the redirection 378 // in CallBase. 379 if (!ICS.hasOperandBundles()) 380 if (const Function *Callee = ICS.getCalledFunction()) 381 IRPositions.emplace_back(IRPosition::function(*Callee)); 382 return; 383 case IRPosition::IRP_CALL_SITE_RETURNED: 384 assert(ICS && "Expected call site!"); 385 // TODO: We need to look at the operand bundles similar to the redirection 386 // in CallBase. 387 if (!ICS.hasOperandBundles()) { 388 if (const Function *Callee = ICS.getCalledFunction()) { 389 IRPositions.emplace_back(IRPosition::returned(*Callee)); 390 IRPositions.emplace_back(IRPosition::function(*Callee)); 391 } 392 } 393 IRPositions.emplace_back( 394 IRPosition::callsite_function(cast<CallBase>(*ICS.getInstruction()))); 395 return; 396 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 397 int ArgNo = IRP.getArgNo(); 398 assert(ICS && ArgNo >= 0 && "Expected call site!"); 399 // TODO: We need to look at the operand bundles similar to the redirection 400 // in CallBase. 401 if (!ICS.hasOperandBundles()) { 402 const Function *Callee = ICS.getCalledFunction(); 403 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 404 IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo))); 405 if (Callee) 406 IRPositions.emplace_back(IRPosition::function(*Callee)); 407 } 408 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 409 return; 410 } 411 } 412 } 413 414 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs) const { 415 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) 416 for (Attribute::AttrKind AK : AKs) 417 if (EquivIRP.getAttr(AK).getKindAsEnum() == AK) 418 return true; 419 return false; 420 } 421 422 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 423 SmallVectorImpl<Attribute> &Attrs) const { 424 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) 425 for (Attribute::AttrKind AK : AKs) { 426 const Attribute &Attr = EquivIRP.getAttr(AK); 427 if (Attr.getKindAsEnum() == AK) 428 Attrs.push_back(Attr); 429 } 430 } 431 432 void IRPosition::verify() { 433 switch (KindOrArgNo) { 434 default: 435 assert(KindOrArgNo >= 0 && "Expected argument or call site argument!"); 436 assert((isa<CallBase>(AnchorVal) || isa<Argument>(AnchorVal)) && 437 "Expected call base or argument for positive attribute index!"); 438 if (isa<Argument>(AnchorVal)) { 439 assert(cast<Argument>(AnchorVal)->getArgNo() == unsigned(getArgNo()) && 440 "Argument number mismatch!"); 441 assert(cast<Argument>(AnchorVal) == &getAssociatedValue() && 442 "Associated value mismatch!"); 443 } else { 444 assert(cast<CallBase>(*AnchorVal).arg_size() > unsigned(getArgNo()) && 445 "Call site argument number mismatch!"); 446 assert(cast<CallBase>(*AnchorVal).getArgOperand(getArgNo()) == 447 &getAssociatedValue() && 448 "Associated value mismatch!"); 449 } 450 break; 451 case IRP_INVALID: 452 assert(!AnchorVal && "Expected no value for an invalid position!"); 453 break; 454 case IRP_FLOAT: 455 assert((!isa<CallBase>(&getAssociatedValue()) && 456 !isa<Argument>(&getAssociatedValue())) && 457 "Expected specialized kind for call base and argument values!"); 458 break; 459 case IRP_RETURNED: 460 assert(isa<Function>(AnchorVal) && 461 "Expected function for a 'returned' position!"); 462 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 463 break; 464 case IRP_CALL_SITE_RETURNED: 465 assert((isa<CallBase>(AnchorVal)) && 466 "Expected call base for 'call site returned' position!"); 467 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 468 break; 469 case IRP_CALL_SITE: 470 assert((isa<CallBase>(AnchorVal)) && 471 "Expected call base for 'call site function' position!"); 472 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 473 break; 474 case IRP_FUNCTION: 475 assert(isa<Function>(AnchorVal) && 476 "Expected function for a 'function' position!"); 477 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 478 break; 479 } 480 } 481 482 /// Helper functions to clamp a state \p S of type \p StateType with the 483 /// information in \p R and indicate/return if \p S did change (as-in update is 484 /// required to be run again). 485 /// 486 ///{ 487 template <typename StateType> 488 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R); 489 490 template <> 491 ChangeStatus clampStateAndIndicateChange<IntegerState>(IntegerState &S, 492 const IntegerState &R) { 493 auto Assumed = S.getAssumed(); 494 S ^= R; 495 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 496 : ChangeStatus::CHANGED; 497 } 498 499 template <> 500 ChangeStatus clampStateAndIndicateChange<BooleanState>(BooleanState &S, 501 const BooleanState &R) { 502 return clampStateAndIndicateChange<IntegerState>(S, R); 503 } 504 ///} 505 506 /// Clamp the information known for all returned values of a function 507 /// (identified by \p QueryingAA) into \p S. 508 template <typename AAType, typename StateType = typename AAType::StateType> 509 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA, 510 StateType &S) { 511 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for " 512 << static_cast<const AbstractAttribute &>(QueryingAA) 513 << " into " << S << "\n"); 514 515 assert((QueryingAA.getIRPosition().getPositionKind() == 516 IRPosition::IRP_RETURNED || 517 QueryingAA.getIRPosition().getPositionKind() == 518 IRPosition::IRP_CALL_SITE_RETURNED) && 519 "Can only clamp returned value states for a function returned or call " 520 "site returned position!"); 521 522 // Use an optional state as there might not be any return values and we want 523 // to join (IntegerState::operator&) the state of all there are. 524 Optional<StateType> T; 525 526 // Callback for each possibly returned value. 527 auto CheckReturnValue = [&](Value &RV) -> bool { 528 const IRPosition &RVPos = IRPosition::value(RV); 529 const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos); 530 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr() 531 << " @ " << RVPos << "\n"); 532 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 533 if (T.hasValue()) 534 *T &= AAS; 535 else 536 T = AAS; 537 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T 538 << "\n"); 539 return T->isValidState(); 540 }; 541 542 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA)) 543 S.indicatePessimisticFixpoint(); 544 else if (T.hasValue()) 545 S ^= *T; 546 } 547 548 /// Helper class for generic deduction: return value -> returned position. 549 template <typename AAType, typename Base, 550 typename StateType = typename AAType::StateType> 551 struct AAReturnedFromReturnedValues : public Base { 552 AAReturnedFromReturnedValues(const IRPosition &IRP) : Base(IRP) {} 553 554 /// See AbstractAttribute::updateImpl(...). 555 ChangeStatus updateImpl(Attributor &A) override { 556 StateType S; 557 clampReturnedValueStates<AAType, StateType>(A, *this, S); 558 // TODO: If we know we visited all returned values, thus no are assumed 559 // dead, we can take the known information from the state T. 560 return clampStateAndIndicateChange<StateType>(this->getState(), S); 561 } 562 }; 563 564 /// Clamp the information known at all call sites for a given argument 565 /// (identified by \p QueryingAA) into \p S. 566 template <typename AAType, typename StateType = typename AAType::StateType> 567 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA, 568 StateType &S) { 569 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for " 570 << static_cast<const AbstractAttribute &>(QueryingAA) 571 << " into " << S << "\n"); 572 573 assert(QueryingAA.getIRPosition().getPositionKind() == 574 IRPosition::IRP_ARGUMENT && 575 "Can only clamp call site argument states for an argument position!"); 576 577 // Use an optional state as there might not be any return values and we want 578 // to join (IntegerState::operator&) the state of all there are. 579 Optional<StateType> T; 580 581 // The argument number which is also the call site argument number. 582 unsigned ArgNo = QueryingAA.getIRPosition().getArgNo(); 583 584 auto CallSiteCheck = [&](CallSite CS) { 585 const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo); 586 const AAType &AA = A.getAAFor<AAType>(QueryingAA, CSArgPos); 587 LLVM_DEBUG(dbgs() << "[Attributor] CS: " << *CS.getInstruction() 588 << " AA: " << AA.getAsStr() << " @" << CSArgPos << "\n"); 589 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 590 if (T.hasValue()) 591 *T &= AAS; 592 else 593 T = AAS; 594 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T 595 << "\n"); 596 return T->isValidState(); 597 }; 598 599 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true)) 600 S.indicatePessimisticFixpoint(); 601 else if (T.hasValue()) 602 S ^= *T; 603 } 604 605 /// Helper class for generic deduction: call site argument -> argument position. 606 template <typename AAType, typename Base, 607 typename StateType = typename AAType::StateType> 608 struct AAArgumentFromCallSiteArguments : public Base { 609 AAArgumentFromCallSiteArguments(const IRPosition &IRP) : Base(IRP) {} 610 611 /// See AbstractAttribute::updateImpl(...). 612 ChangeStatus updateImpl(Attributor &A) override { 613 StateType S; 614 clampCallSiteArgumentStates<AAType, StateType>(A, *this, S); 615 // TODO: If we know we visited all incoming values, thus no are assumed 616 // dead, we can take the known information from the state T. 617 return clampStateAndIndicateChange<StateType>(this->getState(), S); 618 } 619 }; 620 621 /// Helper class for generic replication: function returned -> cs returned. 622 template <typename AAType, typename Base> 623 struct AACallSiteReturnedFromReturned : public Base { 624 AACallSiteReturnedFromReturned(const IRPosition &IRP) : Base(IRP) {} 625 626 /// See AbstractAttribute::updateImpl(...). 627 ChangeStatus updateImpl(Attributor &A) override { 628 assert(this->getIRPosition().getPositionKind() == 629 IRPosition::IRP_CALL_SITE_RETURNED && 630 "Can only wrap function returned positions for call site returned " 631 "positions!"); 632 auto &S = this->getState(); 633 634 const Function *AssociatedFunction = 635 this->getIRPosition().getAssociatedFunction(); 636 if (!AssociatedFunction) 637 return S.indicatePessimisticFixpoint(); 638 639 IRPosition FnPos = IRPosition::returned(*AssociatedFunction); 640 const AAType &AA = A.getAAFor<AAType>(*this, FnPos); 641 return clampStateAndIndicateChange( 642 S, static_cast<const typename AAType::StateType &>(AA.getState())); 643 } 644 }; 645 646 /// -----------------------NoUnwind Function Attribute-------------------------- 647 648 struct AANoUnwindImpl : AANoUnwind { 649 AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {} 650 651 const std::string getAsStr() const override { 652 return getAssumed() ? "nounwind" : "may-unwind"; 653 } 654 655 /// See AbstractAttribute::updateImpl(...). 656 ChangeStatus updateImpl(Attributor &A) override { 657 auto Opcodes = { 658 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 659 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, 660 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; 661 662 auto CheckForNoUnwind = [&](Instruction &I) { 663 if (!I.mayThrow()) 664 return true; 665 666 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 667 const auto &NoUnwindAA = 668 A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(ICS)); 669 return NoUnwindAA.isAssumedNoUnwind(); 670 } 671 return false; 672 }; 673 674 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes)) 675 return indicatePessimisticFixpoint(); 676 677 return ChangeStatus::UNCHANGED; 678 } 679 }; 680 681 struct AANoUnwindFunction final : public AANoUnwindImpl { 682 AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {} 683 684 /// See AbstractAttribute::trackStatistics() 685 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) } 686 }; 687 688 /// NoUnwind attribute deduction for a call sites. 689 struct AANoUnwindCallSite final : AANoUnwindImpl { 690 AANoUnwindCallSite(const IRPosition &IRP) : AANoUnwindImpl(IRP) {} 691 692 /// See AbstractAttribute::initialize(...). 693 void initialize(Attributor &A) override { 694 AANoUnwindImpl::initialize(A); 695 Function *F = getAssociatedFunction(); 696 if (!F) 697 indicatePessimisticFixpoint(); 698 } 699 700 /// See AbstractAttribute::updateImpl(...). 701 ChangeStatus updateImpl(Attributor &A) override { 702 // TODO: Once we have call site specific value information we can provide 703 // call site specific liveness information and then it makes 704 // sense to specialize attributes for call sites arguments instead of 705 // redirecting requests to the callee argument. 706 Function *F = getAssociatedFunction(); 707 const IRPosition &FnPos = IRPosition::function(*F); 708 auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos); 709 return clampStateAndIndicateChange( 710 getState(), 711 static_cast<const AANoUnwind::StateType &>(FnAA.getState())); 712 } 713 714 /// See AbstractAttribute::trackStatistics() 715 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); } 716 }; 717 718 /// --------------------- Function Return Values ------------------------------- 719 720 /// "Attribute" that collects all potential returned values and the return 721 /// instructions that they arise from. 722 /// 723 /// If there is a unique returned value R, the manifest method will: 724 /// - mark R with the "returned" attribute, if R is an argument. 725 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState { 726 727 /// Mapping of values potentially returned by the associated function to the 728 /// return instructions that might return them. 729 MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues; 730 731 /// Mapping to remember the number of returned values for a call site such 732 /// that we can avoid updates if nothing changed. 733 DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA; 734 735 /// Set of unresolved calls returned by the associated function. 736 SmallSetVector<CallBase *, 4> UnresolvedCalls; 737 738 /// State flags 739 /// 740 ///{ 741 bool IsFixed = false; 742 bool IsValidState = true; 743 ///} 744 745 public: 746 AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {} 747 748 /// See AbstractAttribute::initialize(...). 749 void initialize(Attributor &A) override { 750 // Reset the state. 751 IsFixed = false; 752 IsValidState = true; 753 ReturnedValues.clear(); 754 755 Function *F = getAssociatedFunction(); 756 if (!F) { 757 indicatePessimisticFixpoint(); 758 return; 759 } 760 761 // The map from instruction opcodes to those instructions in the function. 762 auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F); 763 764 // Look through all arguments, if one is marked as returned we are done. 765 for (Argument &Arg : F->args()) { 766 if (Arg.hasReturnedAttr()) { 767 auto &ReturnInstSet = ReturnedValues[&Arg]; 768 for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) 769 ReturnInstSet.insert(cast<ReturnInst>(RI)); 770 771 indicateOptimisticFixpoint(); 772 return; 773 } 774 } 775 776 if (!F->hasExactDefinition()) 777 indicatePessimisticFixpoint(); 778 } 779 780 /// See AbstractAttribute::manifest(...). 781 ChangeStatus manifest(Attributor &A) override; 782 783 /// See AbstractAttribute::getState(...). 784 AbstractState &getState() override { return *this; } 785 786 /// See AbstractAttribute::getState(...). 787 const AbstractState &getState() const override { return *this; } 788 789 /// See AbstractAttribute::updateImpl(Attributor &A). 790 ChangeStatus updateImpl(Attributor &A) override; 791 792 llvm::iterator_range<iterator> returned_values() override { 793 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 794 } 795 796 llvm::iterator_range<const_iterator> returned_values() const override { 797 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 798 } 799 800 const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override { 801 return UnresolvedCalls; 802 } 803 804 /// Return the number of potential return values, -1 if unknown. 805 size_t getNumReturnValues() const override { 806 return isValidState() ? ReturnedValues.size() : -1; 807 } 808 809 /// Return an assumed unique return value if a single candidate is found. If 810 /// there cannot be one, return a nullptr. If it is not clear yet, return the 811 /// Optional::NoneType. 812 Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const; 813 814 /// See AbstractState::checkForAllReturnedValues(...). 815 bool checkForAllReturnedValuesAndReturnInsts( 816 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 817 &Pred) const override; 818 819 /// Pretty print the attribute similar to the IR representation. 820 const std::string getAsStr() const override; 821 822 /// See AbstractState::isAtFixpoint(). 823 bool isAtFixpoint() const override { return IsFixed; } 824 825 /// See AbstractState::isValidState(). 826 bool isValidState() const override { return IsValidState; } 827 828 /// See AbstractState::indicateOptimisticFixpoint(...). 829 ChangeStatus indicateOptimisticFixpoint() override { 830 IsFixed = true; 831 return ChangeStatus::UNCHANGED; 832 } 833 834 ChangeStatus indicatePessimisticFixpoint() override { 835 IsFixed = true; 836 IsValidState = false; 837 return ChangeStatus::CHANGED; 838 } 839 }; 840 841 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { 842 ChangeStatus Changed = ChangeStatus::UNCHANGED; 843 844 // Bookkeeping. 845 assert(isValidState()); 846 STATS_DECLTRACK(KnownReturnValues, FunctionReturn, 847 "Number of function with known return values"); 848 849 // Check if we have an assumed unique return value that we could manifest. 850 Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); 851 852 if (!UniqueRV.hasValue() || !UniqueRV.getValue()) 853 return Changed; 854 855 // Bookkeeping. 856 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, 857 "Number of function with unique return"); 858 859 // Callback to replace the uses of CB with the constant C. 860 auto ReplaceCallSiteUsersWith = [](CallBase &CB, Constant &C) { 861 if (CB.getNumUses() == 0) 862 return ChangeStatus::UNCHANGED; 863 CB.replaceAllUsesWith(&C); 864 return ChangeStatus::CHANGED; 865 }; 866 867 // If the assumed unique return value is an argument, annotate it. 868 if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { 869 getIRPosition() = IRPosition::argument(*UniqueRVArg); 870 Changed = IRAttribute::manifest(A); 871 } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) { 872 // We can replace the returned value with the unique returned constant. 873 Value &AnchorValue = getAnchorValue(); 874 if (Function *F = dyn_cast<Function>(&AnchorValue)) { 875 for (const Use &U : F->uses()) 876 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) 877 if (CB->isCallee(&U)) 878 Changed = ReplaceCallSiteUsersWith(*CB, *RVC) | Changed; 879 } else { 880 assert(isa<CallBase>(AnchorValue) && 881 "Expcected a function or call base anchor!"); 882 Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVC); 883 } 884 if (Changed == ChangeStatus::CHANGED) 885 STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn, 886 "Number of function returns replaced by constant return"); 887 } 888 889 return Changed; 890 } 891 892 const std::string AAReturnedValuesImpl::getAsStr() const { 893 return (isAtFixpoint() ? "returns(#" : "may-return(#") + 894 (isValidState() ? std::to_string(getNumReturnValues()) : "?") + 895 ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]"; 896 } 897 898 Optional<Value *> 899 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const { 900 // If checkForAllReturnedValues provides a unique value, ignoring potential 901 // undef values that can also be present, it is assumed to be the actual 902 // return value and forwarded to the caller of this method. If there are 903 // multiple, a nullptr is returned indicating there cannot be a unique 904 // returned value. 905 Optional<Value *> UniqueRV; 906 907 auto Pred = [&](Value &RV) -> bool { 908 // If we found a second returned value and neither the current nor the saved 909 // one is an undef, there is no unique returned value. Undefs are special 910 // since we can pretend they have any value. 911 if (UniqueRV.hasValue() && UniqueRV != &RV && 912 !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) { 913 UniqueRV = nullptr; 914 return false; 915 } 916 917 // Do not overwrite a value with an undef. 918 if (!UniqueRV.hasValue() || !isa<UndefValue>(RV)) 919 UniqueRV = &RV; 920 921 return true; 922 }; 923 924 if (!A.checkForAllReturnedValues(Pred, *this)) 925 UniqueRV = nullptr; 926 927 return UniqueRV; 928 } 929 930 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts( 931 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 932 &Pred) const { 933 if (!isValidState()) 934 return false; 935 936 // Check all returned values but ignore call sites as long as we have not 937 // encountered an overdefined one during an update. 938 for (auto &It : ReturnedValues) { 939 Value *RV = It.first; 940 941 CallBase *CB = dyn_cast<CallBase>(RV); 942 if (CB && !UnresolvedCalls.count(CB)) 943 continue; 944 945 if (!Pred(*RV, It.second)) 946 return false; 947 } 948 949 return true; 950 } 951 952 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { 953 size_t NumUnresolvedCalls = UnresolvedCalls.size(); 954 bool Changed = false; 955 956 // State used in the value traversals starting in returned values. 957 struct RVState { 958 // The map in which we collect return values -> return instrs. 959 decltype(ReturnedValues) &RetValsMap; 960 // The flag to indicate a change. 961 bool &Changed; 962 // The return instrs we come from. 963 SmallSetVector<ReturnInst *, 4> RetInsts; 964 }; 965 966 // Callback for a leaf value returned by the associated function. 967 auto VisitValueCB = [](Value &Val, RVState &RVS, bool) -> bool { 968 auto Size = RVS.RetValsMap[&Val].size(); 969 RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end()); 970 bool Inserted = RVS.RetValsMap[&Val].size() != Size; 971 RVS.Changed |= Inserted; 972 LLVM_DEBUG({ 973 if (Inserted) 974 dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val 975 << " => " << RVS.RetInsts.size() << "\n"; 976 }); 977 return true; 978 }; 979 980 // Helper method to invoke the generic value traversal. 981 auto VisitReturnedValue = [&](Value &RV, RVState &RVS) { 982 IRPosition RetValPos = IRPosition::value(RV); 983 return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *this, 984 RVS, VisitValueCB); 985 }; 986 987 // Callback for all "return intructions" live in the associated function. 988 auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) { 989 ReturnInst &Ret = cast<ReturnInst>(I); 990 RVState RVS({ReturnedValues, Changed, {}}); 991 RVS.RetInsts.insert(&Ret); 992 return VisitReturnedValue(*Ret.getReturnValue(), RVS); 993 }; 994 995 // Start by discovering returned values from all live returned instructions in 996 // the associated function. 997 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret})) 998 return indicatePessimisticFixpoint(); 999 1000 // Once returned values "directly" present in the code are handled we try to 1001 // resolve returned calls. 1002 decltype(ReturnedValues) NewRVsMap; 1003 for (auto &It : ReturnedValues) { 1004 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first 1005 << " by #" << It.second.size() << " RIs\n"); 1006 CallBase *CB = dyn_cast<CallBase>(It.first); 1007 if (!CB || UnresolvedCalls.count(CB)) 1008 continue; 1009 1010 if (!CB->getCalledFunction()) { 1011 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1012 << "\n"); 1013 UnresolvedCalls.insert(CB); 1014 continue; 1015 } 1016 1017 // TODO: use the function scope once we have call site AAReturnedValues. 1018 const auto &RetValAA = A.getAAFor<AAReturnedValues>( 1019 *this, IRPosition::function(*CB->getCalledFunction())); 1020 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: " 1021 << static_cast<const AbstractAttribute &>(RetValAA) 1022 << "\n"); 1023 1024 // Skip dead ends, thus if we do not know anything about the returned 1025 // call we mark it as unresolved and it will stay that way. 1026 if (!RetValAA.getState().isValidState()) { 1027 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1028 << "\n"); 1029 UnresolvedCalls.insert(CB); 1030 continue; 1031 } 1032 1033 // Do not try to learn partial information. If the callee has unresolved 1034 // return values we will treat the call as unresolved/opaque. 1035 auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls(); 1036 if (!RetValAAUnresolvedCalls.empty()) { 1037 UnresolvedCalls.insert(CB); 1038 continue; 1039 } 1040 1041 // Now check if we can track transitively returned values. If possible, thus 1042 // if all return value can be represented in the current scope, do so. 1043 bool Unresolved = false; 1044 for (auto &RetValAAIt : RetValAA.returned_values()) { 1045 Value *RetVal = RetValAAIt.first; 1046 if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) || 1047 isa<Constant>(RetVal)) 1048 continue; 1049 // Anything that did not fit in the above categories cannot be resolved, 1050 // mark the call as unresolved. 1051 LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value " 1052 "cannot be translated: " 1053 << *RetVal << "\n"); 1054 UnresolvedCalls.insert(CB); 1055 Unresolved = true; 1056 break; 1057 } 1058 1059 if (Unresolved) 1060 continue; 1061 1062 // Now track transitively returned values. 1063 unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB]; 1064 if (NumRetAA == RetValAA.getNumReturnValues()) { 1065 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not " 1066 "changed since it was seen last\n"); 1067 continue; 1068 } 1069 NumRetAA = RetValAA.getNumReturnValues(); 1070 1071 for (auto &RetValAAIt : RetValAA.returned_values()) { 1072 Value *RetVal = RetValAAIt.first; 1073 if (Argument *Arg = dyn_cast<Argument>(RetVal)) { 1074 // Arguments are mapped to call site operands and we begin the traversal 1075 // again. 1076 bool Unused = false; 1077 RVState RVS({NewRVsMap, Unused, RetValAAIt.second}); 1078 VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS); 1079 continue; 1080 } else if (isa<CallBase>(RetVal)) { 1081 // Call sites are resolved by the callee attribute over time, no need to 1082 // do anything for us. 1083 continue; 1084 } else if (isa<Constant>(RetVal)) { 1085 // Constants are valid everywhere, we can simply take them. 1086 NewRVsMap[RetVal].insert(It.second.begin(), It.second.end()); 1087 continue; 1088 } 1089 } 1090 } 1091 1092 // To avoid modifications to the ReturnedValues map while we iterate over it 1093 // we kept record of potential new entries in a copy map, NewRVsMap. 1094 for (auto &It : NewRVsMap) { 1095 assert(!It.second.empty() && "Entry does not add anything."); 1096 auto &ReturnInsts = ReturnedValues[It.first]; 1097 for (ReturnInst *RI : It.second) 1098 if (ReturnInsts.insert(RI)) { 1099 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value " 1100 << *It.first << " => " << *RI << "\n"); 1101 Changed = true; 1102 } 1103 } 1104 1105 Changed |= (NumUnresolvedCalls != UnresolvedCalls.size()); 1106 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 1107 } 1108 1109 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl { 1110 AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {} 1111 1112 /// See AbstractAttribute::trackStatistics() 1113 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) } 1114 }; 1115 1116 /// Returned values information for a call sites. 1117 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl { 1118 AAReturnedValuesCallSite(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {} 1119 1120 /// See AbstractAttribute::initialize(...). 1121 void initialize(Attributor &A) override { 1122 // TODO: Once we have call site specific value information we can provide 1123 // call site specific liveness information and then it makes 1124 // sense to specialize attributes for call sites instead of 1125 // redirecting requests to the callee. 1126 llvm_unreachable("Abstract attributes for returned values are not " 1127 "supported for call sites yet!"); 1128 } 1129 1130 /// See AbstractAttribute::updateImpl(...). 1131 ChangeStatus updateImpl(Attributor &A) override { 1132 return indicatePessimisticFixpoint(); 1133 } 1134 1135 /// See AbstractAttribute::trackStatistics() 1136 void trackStatistics() const override {} 1137 }; 1138 1139 /// ------------------------ NoSync Function Attribute ------------------------- 1140 1141 struct AANoSyncImpl : AANoSync { 1142 AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {} 1143 1144 const std::string getAsStr() const override { 1145 return getAssumed() ? "nosync" : "may-sync"; 1146 } 1147 1148 /// See AbstractAttribute::updateImpl(...). 1149 ChangeStatus updateImpl(Attributor &A) override; 1150 1151 /// Helper function used to determine whether an instruction is non-relaxed 1152 /// atomic. In other words, if an atomic instruction does not have unordered 1153 /// or monotonic ordering 1154 static bool isNonRelaxedAtomic(Instruction *I); 1155 1156 /// Helper function used to determine whether an instruction is volatile. 1157 static bool isVolatile(Instruction *I); 1158 1159 /// Helper function uset to check if intrinsic is volatile (memcpy, memmove, 1160 /// memset). 1161 static bool isNoSyncIntrinsic(Instruction *I); 1162 }; 1163 1164 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) { 1165 if (!I->isAtomic()) 1166 return false; 1167 1168 AtomicOrdering Ordering; 1169 switch (I->getOpcode()) { 1170 case Instruction::AtomicRMW: 1171 Ordering = cast<AtomicRMWInst>(I)->getOrdering(); 1172 break; 1173 case Instruction::Store: 1174 Ordering = cast<StoreInst>(I)->getOrdering(); 1175 break; 1176 case Instruction::Load: 1177 Ordering = cast<LoadInst>(I)->getOrdering(); 1178 break; 1179 case Instruction::Fence: { 1180 auto *FI = cast<FenceInst>(I); 1181 if (FI->getSyncScopeID() == SyncScope::SingleThread) 1182 return false; 1183 Ordering = FI->getOrdering(); 1184 break; 1185 } 1186 case Instruction::AtomicCmpXchg: { 1187 AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering(); 1188 AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering(); 1189 // Only if both are relaxed, than it can be treated as relaxed. 1190 // Otherwise it is non-relaxed. 1191 if (Success != AtomicOrdering::Unordered && 1192 Success != AtomicOrdering::Monotonic) 1193 return true; 1194 if (Failure != AtomicOrdering::Unordered && 1195 Failure != AtomicOrdering::Monotonic) 1196 return true; 1197 return false; 1198 } 1199 default: 1200 llvm_unreachable( 1201 "New atomic operations need to be known in the attributor."); 1202 } 1203 1204 // Relaxed. 1205 if (Ordering == AtomicOrdering::Unordered || 1206 Ordering == AtomicOrdering::Monotonic) 1207 return false; 1208 return true; 1209 } 1210 1211 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics. 1212 /// FIXME: We should ipmrove the handling of intrinsics. 1213 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) { 1214 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1215 switch (II->getIntrinsicID()) { 1216 /// Element wise atomic memory intrinsics are can only be unordered, 1217 /// therefore nosync. 1218 case Intrinsic::memset_element_unordered_atomic: 1219 case Intrinsic::memmove_element_unordered_atomic: 1220 case Intrinsic::memcpy_element_unordered_atomic: 1221 return true; 1222 case Intrinsic::memset: 1223 case Intrinsic::memmove: 1224 case Intrinsic::memcpy: 1225 if (!cast<MemIntrinsic>(II)->isVolatile()) 1226 return true; 1227 return false; 1228 default: 1229 return false; 1230 } 1231 } 1232 return false; 1233 } 1234 1235 bool AANoSyncImpl::isVolatile(Instruction *I) { 1236 assert(!ImmutableCallSite(I) && !isa<CallBase>(I) && 1237 "Calls should not be checked here"); 1238 1239 switch (I->getOpcode()) { 1240 case Instruction::AtomicRMW: 1241 return cast<AtomicRMWInst>(I)->isVolatile(); 1242 case Instruction::Store: 1243 return cast<StoreInst>(I)->isVolatile(); 1244 case Instruction::Load: 1245 return cast<LoadInst>(I)->isVolatile(); 1246 case Instruction::AtomicCmpXchg: 1247 return cast<AtomicCmpXchgInst>(I)->isVolatile(); 1248 default: 1249 return false; 1250 } 1251 } 1252 1253 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) { 1254 1255 auto CheckRWInstForNoSync = [&](Instruction &I) { 1256 /// We are looking for volatile instructions or Non-Relaxed atomics. 1257 /// FIXME: We should ipmrove the handling of intrinsics. 1258 1259 if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I)) 1260 return true; 1261 1262 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 1263 if (ICS.hasFnAttr(Attribute::NoSync)) 1264 return true; 1265 1266 const auto &NoSyncAA = 1267 A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(ICS)); 1268 if (NoSyncAA.isAssumedNoSync()) 1269 return true; 1270 return false; 1271 } 1272 1273 if (!isVolatile(&I) && !isNonRelaxedAtomic(&I)) 1274 return true; 1275 1276 return false; 1277 }; 1278 1279 auto CheckForNoSync = [&](Instruction &I) { 1280 // At this point we handled all read/write effects and they are all 1281 // nosync, so they can be skipped. 1282 if (I.mayReadOrWriteMemory()) 1283 return true; 1284 1285 // non-convergent and readnone imply nosync. 1286 return !ImmutableCallSite(&I).isConvergent(); 1287 }; 1288 1289 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) || 1290 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this)) 1291 return indicatePessimisticFixpoint(); 1292 1293 return ChangeStatus::UNCHANGED; 1294 } 1295 1296 struct AANoSyncFunction final : public AANoSyncImpl { 1297 AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {} 1298 1299 /// See AbstractAttribute::trackStatistics() 1300 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) } 1301 }; 1302 1303 /// NoSync attribute deduction for a call sites. 1304 struct AANoSyncCallSite final : AANoSyncImpl { 1305 AANoSyncCallSite(const IRPosition &IRP) : AANoSyncImpl(IRP) {} 1306 1307 /// See AbstractAttribute::initialize(...). 1308 void initialize(Attributor &A) override { 1309 AANoSyncImpl::initialize(A); 1310 Function *F = getAssociatedFunction(); 1311 if (!F) 1312 indicatePessimisticFixpoint(); 1313 } 1314 1315 /// See AbstractAttribute::updateImpl(...). 1316 ChangeStatus updateImpl(Attributor &A) override { 1317 // TODO: Once we have call site specific value information we can provide 1318 // call site specific liveness information and then it makes 1319 // sense to specialize attributes for call sites arguments instead of 1320 // redirecting requests to the callee argument. 1321 Function *F = getAssociatedFunction(); 1322 const IRPosition &FnPos = IRPosition::function(*F); 1323 auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos); 1324 return clampStateAndIndicateChange( 1325 getState(), static_cast<const AANoSync::StateType &>(FnAA.getState())); 1326 } 1327 1328 /// See AbstractAttribute::trackStatistics() 1329 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); } 1330 }; 1331 1332 /// ------------------------ No-Free Attributes ---------------------------- 1333 1334 struct AANoFreeImpl : public AANoFree { 1335 AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {} 1336 1337 /// See AbstractAttribute::updateImpl(...). 1338 ChangeStatus updateImpl(Attributor &A) override { 1339 auto CheckForNoFree = [&](Instruction &I) { 1340 ImmutableCallSite ICS(&I); 1341 if (ICS.hasFnAttr(Attribute::NoFree)) 1342 return true; 1343 1344 const auto &NoFreeAA = 1345 A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(ICS)); 1346 return NoFreeAA.isAssumedNoFree(); 1347 }; 1348 1349 if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this)) 1350 return indicatePessimisticFixpoint(); 1351 return ChangeStatus::UNCHANGED; 1352 } 1353 1354 /// See AbstractAttribute::getAsStr(). 1355 const std::string getAsStr() const override { 1356 return getAssumed() ? "nofree" : "may-free"; 1357 } 1358 }; 1359 1360 struct AANoFreeFunction final : public AANoFreeImpl { 1361 AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {} 1362 1363 /// See AbstractAttribute::trackStatistics() 1364 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) } 1365 }; 1366 1367 /// NoFree attribute deduction for a call sites. 1368 struct AANoFreeCallSite final : AANoFreeImpl { 1369 AANoFreeCallSite(const IRPosition &IRP) : AANoFreeImpl(IRP) {} 1370 1371 /// See AbstractAttribute::initialize(...). 1372 void initialize(Attributor &A) override { 1373 AANoFreeImpl::initialize(A); 1374 Function *F = getAssociatedFunction(); 1375 if (!F) 1376 indicatePessimisticFixpoint(); 1377 } 1378 1379 /// See AbstractAttribute::updateImpl(...). 1380 ChangeStatus updateImpl(Attributor &A) override { 1381 // TODO: Once we have call site specific value information we can provide 1382 // call site specific liveness information and then it makes 1383 // sense to specialize attributes for call sites arguments instead of 1384 // redirecting requests to the callee argument. 1385 Function *F = getAssociatedFunction(); 1386 const IRPosition &FnPos = IRPosition::function(*F); 1387 auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos); 1388 return clampStateAndIndicateChange( 1389 getState(), static_cast<const AANoFree::StateType &>(FnAA.getState())); 1390 } 1391 1392 /// See AbstractAttribute::trackStatistics() 1393 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); } 1394 }; 1395 1396 /// ------------------------ NonNull Argument Attribute ------------------------ 1397 struct AANonNullImpl : AANonNull { 1398 AANonNullImpl(const IRPosition &IRP) : AANonNull(IRP) {} 1399 1400 /// See AbstractAttribute::initialize(...). 1401 void initialize(Attributor &A) override { 1402 if (hasAttr({Attribute::NonNull, Attribute::Dereferenceable})) 1403 indicateOptimisticFixpoint(); 1404 else 1405 AANonNull::initialize(A); 1406 } 1407 1408 /// See AbstractAttribute::getAsStr(). 1409 const std::string getAsStr() const override { 1410 return getAssumed() ? "nonnull" : "may-null"; 1411 } 1412 }; 1413 1414 /// NonNull attribute for a floating value. 1415 struct AANonNullFloating : AANonNullImpl { 1416 AANonNullFloating(const IRPosition &IRP) : AANonNullImpl(IRP) {} 1417 1418 /// See AbstractAttribute::initialize(...). 1419 void initialize(Attributor &A) override { 1420 AANonNullImpl::initialize(A); 1421 1422 if (isAtFixpoint()) 1423 return; 1424 1425 const IRPosition &IRP = getIRPosition(); 1426 const Value &V = IRP.getAssociatedValue(); 1427 const DataLayout &DL = A.getDataLayout(); 1428 1429 // TODO: This context sensitive query should be removed once we can do 1430 // context sensitive queries in the genericValueTraversal below. 1431 if (isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, IRP.getCtxI(), 1432 /* TODO: DT */ nullptr)) 1433 indicateOptimisticFixpoint(); 1434 } 1435 1436 /// See AbstractAttribute::updateImpl(...). 1437 ChangeStatus updateImpl(Attributor &A) override { 1438 const DataLayout &DL = A.getDataLayout(); 1439 1440 auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, 1441 bool Stripped) -> bool { 1442 const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V)); 1443 if (!Stripped && this == &AA) { 1444 if (!isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, 1445 /* TODO: CtxI */ nullptr, 1446 /* TODO: DT */ nullptr)) 1447 T.indicatePessimisticFixpoint(); 1448 } else { 1449 // Use abstract attribute information. 1450 const AANonNull::StateType &NS = 1451 static_cast<const AANonNull::StateType &>(AA.getState()); 1452 T ^= NS; 1453 } 1454 return T.isValidState(); 1455 }; 1456 1457 StateType T; 1458 if (!genericValueTraversal<AANonNull, StateType>(A, getIRPosition(), *this, 1459 T, VisitValueCB)) 1460 return indicatePessimisticFixpoint(); 1461 1462 return clampStateAndIndicateChange(getState(), T); 1463 } 1464 1465 /// See AbstractAttribute::trackStatistics() 1466 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1467 }; 1468 1469 /// NonNull attribute for function return value. 1470 struct AANonNullReturned final 1471 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> { 1472 AANonNullReturned(const IRPosition &IRP) 1473 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {} 1474 1475 /// See AbstractAttribute::trackStatistics() 1476 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1477 }; 1478 1479 /// NonNull attribute for function argument. 1480 struct AANonNullArgument final 1481 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> { 1482 AANonNullArgument(const IRPosition &IRP) 1483 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP) {} 1484 1485 /// See AbstractAttribute::trackStatistics() 1486 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) } 1487 }; 1488 1489 struct AANonNullCallSiteArgument final : AANonNullFloating { 1490 AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullFloating(IRP) {} 1491 1492 /// See AbstractAttribute::trackStatistics() 1493 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) } 1494 }; 1495 1496 /// NonNull attribute for a call site return position. 1497 struct AANonNullCallSiteReturned final 1498 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> { 1499 AANonNullCallSiteReturned(const IRPosition &IRP) 1500 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP) {} 1501 1502 /// See AbstractAttribute::trackStatistics() 1503 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) } 1504 }; 1505 1506 /// ------------------------ No-Recurse Attributes ---------------------------- 1507 1508 struct AANoRecurseImpl : public AANoRecurse { 1509 AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {} 1510 1511 /// See AbstractAttribute::getAsStr() 1512 const std::string getAsStr() const override { 1513 return getAssumed() ? "norecurse" : "may-recurse"; 1514 } 1515 }; 1516 1517 struct AANoRecurseFunction final : AANoRecurseImpl { 1518 AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {} 1519 1520 /// See AbstractAttribute::updateImpl(...). 1521 ChangeStatus updateImpl(Attributor &A) override { 1522 // TODO: Implement this. 1523 return indicatePessimisticFixpoint(); 1524 } 1525 1526 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) } 1527 }; 1528 1529 /// NoRecurse attribute deduction for a call sites. 1530 struct AANoRecurseCallSite final : AANoRecurseImpl { 1531 AANoRecurseCallSite(const IRPosition &IRP) : AANoRecurseImpl(IRP) {} 1532 1533 /// See AbstractAttribute::initialize(...). 1534 void initialize(Attributor &A) override { 1535 AANoRecurseImpl::initialize(A); 1536 Function *F = getAssociatedFunction(); 1537 if (!F) 1538 indicatePessimisticFixpoint(); 1539 } 1540 1541 /// See AbstractAttribute::updateImpl(...). 1542 ChangeStatus updateImpl(Attributor &A) override { 1543 // TODO: Once we have call site specific value information we can provide 1544 // call site specific liveness information and then it makes 1545 // sense to specialize attributes for call sites arguments instead of 1546 // redirecting requests to the callee argument. 1547 Function *F = getAssociatedFunction(); 1548 const IRPosition &FnPos = IRPosition::function(*F); 1549 auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos); 1550 return clampStateAndIndicateChange( 1551 getState(), 1552 static_cast<const AANoRecurse::StateType &>(FnAA.getState())); 1553 } 1554 1555 /// See AbstractAttribute::trackStatistics() 1556 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); } 1557 }; 1558 1559 /// ------------------------ Will-Return Attributes ---------------------------- 1560 1561 // Helper function that checks whether a function has any cycle. 1562 // TODO: Replace with more efficent code 1563 static bool containsCycle(Function &F) { 1564 SmallPtrSet<BasicBlock *, 32> Visited; 1565 1566 // Traverse BB by dfs and check whether successor is already visited. 1567 for (BasicBlock *BB : depth_first(&F)) { 1568 Visited.insert(BB); 1569 for (auto *SuccBB : successors(BB)) { 1570 if (Visited.count(SuccBB)) 1571 return true; 1572 } 1573 } 1574 return false; 1575 } 1576 1577 // Helper function that checks the function have a loop which might become an 1578 // endless loop 1579 // FIXME: Any cycle is regarded as endless loop for now. 1580 // We have to allow some patterns. 1581 static bool containsPossiblyEndlessLoop(Function *F) { 1582 return !F || !F->hasExactDefinition() || containsCycle(*F); 1583 } 1584 1585 struct AAWillReturnImpl : public AAWillReturn { 1586 AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {} 1587 1588 /// See AbstractAttribute::initialize(...). 1589 void initialize(Attributor &A) override { 1590 AAWillReturn::initialize(A); 1591 1592 Function *F = getAssociatedFunction(); 1593 if (containsPossiblyEndlessLoop(F)) 1594 indicatePessimisticFixpoint(); 1595 } 1596 1597 /// See AbstractAttribute::updateImpl(...). 1598 ChangeStatus updateImpl(Attributor &A) override { 1599 auto CheckForWillReturn = [&](Instruction &I) { 1600 IRPosition IPos = IRPosition::callsite_function(ImmutableCallSite(&I)); 1601 const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos); 1602 if (WillReturnAA.isKnownWillReturn()) 1603 return true; 1604 if (!WillReturnAA.isAssumedWillReturn()) 1605 return false; 1606 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos); 1607 return NoRecurseAA.isAssumedNoRecurse(); 1608 }; 1609 1610 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this)) 1611 return indicatePessimisticFixpoint(); 1612 1613 return ChangeStatus::UNCHANGED; 1614 } 1615 1616 /// See AbstractAttribute::getAsStr() 1617 const std::string getAsStr() const override { 1618 return getAssumed() ? "willreturn" : "may-noreturn"; 1619 } 1620 }; 1621 1622 struct AAWillReturnFunction final : AAWillReturnImpl { 1623 AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {} 1624 1625 /// See AbstractAttribute::trackStatistics() 1626 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) } 1627 }; 1628 1629 /// WillReturn attribute deduction for a call sites. 1630 struct AAWillReturnCallSite final : AAWillReturnImpl { 1631 AAWillReturnCallSite(const IRPosition &IRP) : AAWillReturnImpl(IRP) {} 1632 1633 /// See AbstractAttribute::initialize(...). 1634 void initialize(Attributor &A) override { 1635 AAWillReturnImpl::initialize(A); 1636 Function *F = getAssociatedFunction(); 1637 if (!F) 1638 indicatePessimisticFixpoint(); 1639 } 1640 1641 /// See AbstractAttribute::updateImpl(...). 1642 ChangeStatus updateImpl(Attributor &A) override { 1643 // TODO: Once we have call site specific value information we can provide 1644 // call site specific liveness information and then it makes 1645 // sense to specialize attributes for call sites arguments instead of 1646 // redirecting requests to the callee argument. 1647 Function *F = getAssociatedFunction(); 1648 const IRPosition &FnPos = IRPosition::function(*F); 1649 auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos); 1650 return clampStateAndIndicateChange( 1651 getState(), 1652 static_cast<const AAWillReturn::StateType &>(FnAA.getState())); 1653 } 1654 1655 /// See AbstractAttribute::trackStatistics() 1656 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); } 1657 }; 1658 1659 /// ------------------------ NoAlias Argument Attribute ------------------------ 1660 1661 struct AANoAliasImpl : AANoAlias { 1662 AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {} 1663 1664 const std::string getAsStr() const override { 1665 return getAssumed() ? "noalias" : "may-alias"; 1666 } 1667 }; 1668 1669 /// NoAlias attribute for a floating value. 1670 struct AANoAliasFloating final : AANoAliasImpl { 1671 AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1672 1673 /// See AbstractAttribute::initialize(...). 1674 void initialize(Attributor &A) override { 1675 AANoAliasImpl::initialize(A); 1676 if (isa<AllocaInst>(getAnchorValue())) 1677 indicateOptimisticFixpoint(); 1678 } 1679 1680 /// See AbstractAttribute::updateImpl(...). 1681 ChangeStatus updateImpl(Attributor &A) override { 1682 // TODO: Implement this. 1683 return indicatePessimisticFixpoint(); 1684 } 1685 1686 /// See AbstractAttribute::trackStatistics() 1687 void trackStatistics() const override { 1688 STATS_DECLTRACK_FLOATING_ATTR(noalias) 1689 } 1690 }; 1691 1692 /// NoAlias attribute for an argument. 1693 struct AANoAliasArgument final 1694 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> { 1695 AANoAliasArgument(const IRPosition &IRP) 1696 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>(IRP) {} 1697 1698 /// See AbstractAttribute::trackStatistics() 1699 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 1700 }; 1701 1702 struct AANoAliasCallSiteArgument final : AANoAliasImpl { 1703 AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1704 1705 /// See AbstractAttribute::initialize(...). 1706 void initialize(Attributor &A) override { 1707 // See callsite argument attribute and callee argument attribute. 1708 ImmutableCallSite ICS(&getAnchorValue()); 1709 if (ICS.paramHasAttr(getArgNo(), Attribute::NoAlias)) 1710 indicateOptimisticFixpoint(); 1711 } 1712 1713 /// See AbstractAttribute::updateImpl(...). 1714 ChangeStatus updateImpl(Attributor &A) override { 1715 // We can deduce "noalias" if the following conditions hold. 1716 // (i) Associated value is assumed to be noalias in the definition. 1717 // (ii) Associated value is assumed to be no-capture in all the uses 1718 // possibly executed before this callsite. 1719 // (iii) There is no other pointer argument which could alias with the 1720 // value. 1721 1722 const Value &V = getAssociatedValue(); 1723 const IRPosition IRP = IRPosition::value(V); 1724 1725 // (i) Check whether noalias holds in the definition. 1726 1727 auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP); 1728 1729 if (!NoAliasAA.isAssumedNoAlias()) 1730 return indicatePessimisticFixpoint(); 1731 1732 LLVM_DEBUG(dbgs() << "[Attributor][AANoAliasCSArg] " << V 1733 << " is assumed NoAlias in the definition\n"); 1734 1735 // (ii) Check whether the value is captured in the scope using AANoCapture. 1736 // FIXME: This is conservative though, it is better to look at CFG and 1737 // check only uses possibly executed before this callsite. 1738 1739 auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP); 1740 if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) 1741 return indicatePessimisticFixpoint(); 1742 1743 // (iii) Check there is no other pointer argument which could alias with the 1744 // value. 1745 ImmutableCallSite ICS(&getAnchorValue()); 1746 for (unsigned i = 0; i < ICS.getNumArgOperands(); i++) { 1747 if (getArgNo() == (int)i) 1748 continue; 1749 const Value *ArgOp = ICS.getArgOperand(i); 1750 if (!ArgOp->getType()->isPointerTy()) 1751 continue; 1752 1753 // TODO: Use AliasAnalysis 1754 // AAResults& AAR = ..; 1755 // if(AAR.isNoAlias(&getAssociatedValue(), ArgOp)) 1756 // return indicatePessimitisicFixpoint(); 1757 1758 return indicatePessimisticFixpoint(); 1759 } 1760 1761 return ChangeStatus::UNCHANGED; 1762 } 1763 1764 /// See AbstractAttribute::trackStatistics() 1765 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) } 1766 }; 1767 1768 /// NoAlias attribute for function return value. 1769 struct AANoAliasReturned final : AANoAliasImpl { 1770 AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1771 1772 /// See AbstractAttribute::updateImpl(...). 1773 virtual ChangeStatus updateImpl(Attributor &A) override { 1774 1775 auto CheckReturnValue = [&](Value &RV) -> bool { 1776 if (Constant *C = dyn_cast<Constant>(&RV)) 1777 if (C->isNullValue() || isa<UndefValue>(C)) 1778 return true; 1779 1780 /// For now, we can only deduce noalias if we have call sites. 1781 /// FIXME: add more support. 1782 ImmutableCallSite ICS(&RV); 1783 if (!ICS) 1784 return false; 1785 1786 const IRPosition &RVPos = IRPosition::value(RV); 1787 const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos); 1788 if (!NoAliasAA.isAssumedNoAlias()) 1789 return false; 1790 1791 const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos); 1792 return NoCaptureAA.isAssumedNoCaptureMaybeReturned(); 1793 }; 1794 1795 if (!A.checkForAllReturnedValues(CheckReturnValue, *this)) 1796 return indicatePessimisticFixpoint(); 1797 1798 return ChangeStatus::UNCHANGED; 1799 } 1800 1801 /// See AbstractAttribute::trackStatistics() 1802 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) } 1803 }; 1804 1805 /// NoAlias attribute deduction for a call site return value. 1806 struct AANoAliasCallSiteReturned final : AANoAliasImpl { 1807 AANoAliasCallSiteReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1808 1809 /// See AbstractAttribute::initialize(...). 1810 void initialize(Attributor &A) override { 1811 AANoAliasImpl::initialize(A); 1812 Function *F = getAssociatedFunction(); 1813 if (!F) 1814 indicatePessimisticFixpoint(); 1815 } 1816 1817 /// See AbstractAttribute::updateImpl(...). 1818 ChangeStatus updateImpl(Attributor &A) override { 1819 // TODO: Once we have call site specific value information we can provide 1820 // call site specific liveness information and then it makes 1821 // sense to specialize attributes for call sites arguments instead of 1822 // redirecting requests to the callee argument. 1823 Function *F = getAssociatedFunction(); 1824 const IRPosition &FnPos = IRPosition::returned(*F); 1825 auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos); 1826 return clampStateAndIndicateChange( 1827 getState(), static_cast<const AANoAlias::StateType &>(FnAA.getState())); 1828 } 1829 1830 /// See AbstractAttribute::trackStatistics() 1831 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); } 1832 }; 1833 1834 /// -------------------AAIsDead Function Attribute----------------------- 1835 1836 struct AAIsDeadImpl : public AAIsDead { 1837 AAIsDeadImpl(const IRPosition &IRP) : AAIsDead(IRP) {} 1838 1839 void initialize(Attributor &A) override { 1840 const Function *F = getAssociatedFunction(); 1841 if (F && !F->isDeclaration()) 1842 exploreFromEntry(A, F); 1843 } 1844 1845 void exploreFromEntry(Attributor &A, const Function *F) { 1846 ToBeExploredPaths.insert(&(F->getEntryBlock().front())); 1847 assumeLive(A, F->getEntryBlock()); 1848 1849 for (size_t i = 0; i < ToBeExploredPaths.size(); ++i) 1850 if (const Instruction *NextNoReturnI = 1851 findNextNoReturn(A, ToBeExploredPaths[i])) 1852 NoReturnCalls.insert(NextNoReturnI); 1853 } 1854 1855 /// Find the next assumed noreturn instruction in the block of \p I starting 1856 /// from, thus including, \p I. 1857 /// 1858 /// The caller is responsible to monitor the ToBeExploredPaths set as new 1859 /// instructions discovered in other basic block will be placed in there. 1860 /// 1861 /// \returns The next assumed noreturn instructions in the block of \p I 1862 /// starting from, thus including, \p I. 1863 const Instruction *findNextNoReturn(Attributor &A, const Instruction *I); 1864 1865 /// See AbstractAttribute::getAsStr(). 1866 const std::string getAsStr() const override { 1867 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" + 1868 std::to_string(getAssociatedFunction()->size()) + "][#NRI " + 1869 std::to_string(NoReturnCalls.size()) + "]"; 1870 } 1871 1872 /// See AbstractAttribute::manifest(...). 1873 ChangeStatus manifest(Attributor &A) override { 1874 assert(getState().isValidState() && 1875 "Attempted to manifest an invalid state!"); 1876 1877 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 1878 Function &F = *getAssociatedFunction(); 1879 1880 if (AssumedLiveBlocks.empty()) { 1881 A.deleteAfterManifest(F); 1882 return ChangeStatus::CHANGED; 1883 } 1884 1885 // Flag to determine if we can change an invoke to a call assuming the 1886 // callee is nounwind. This is not possible if the personality of the 1887 // function allows to catch asynchronous exceptions. 1888 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 1889 1890 for (const Instruction *NRC : NoReturnCalls) { 1891 Instruction *I = const_cast<Instruction *>(NRC); 1892 BasicBlock *BB = I->getParent(); 1893 Instruction *SplitPos = I->getNextNode(); 1894 // TODO: mark stuff before unreachable instructions as dead. 1895 if (isa_and_nonnull<UnreachableInst>(SplitPos)) 1896 continue; 1897 1898 if (auto *II = dyn_cast<InvokeInst>(I)) { 1899 // If we keep the invoke the split position is at the beginning of the 1900 // normal desitination block (it invokes a noreturn function after all). 1901 BasicBlock *NormalDestBB = II->getNormalDest(); 1902 SplitPos = &NormalDestBB->front(); 1903 1904 /// Invoke is replaced with a call and unreachable is placed after it if 1905 /// the callee is nounwind and noreturn. Otherwise, we keep the invoke 1906 /// and only place an unreachable in the normal successor. 1907 if (Invoke2CallAllowed) { 1908 if (II->getCalledFunction()) { 1909 const IRPosition &IPos = IRPosition::callsite_function(*II); 1910 const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos); 1911 if (AANoUnw.isAssumedNoUnwind()) { 1912 LLVM_DEBUG(dbgs() 1913 << "[AAIsDead] Replace invoke with call inst\n"); 1914 // We do not need an invoke (II) but instead want a call followed 1915 // by an unreachable. However, we do not remove II as other 1916 // abstract attributes might have it cached as part of their 1917 // results. Given that we modify the CFG anyway, we simply keep II 1918 // around but in a new dead block. To avoid II being live through 1919 // a different edge we have to ensure the block we place it in is 1920 // only reached from the current block of II and then not reached 1921 // at all when we insert the unreachable. 1922 SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c"); 1923 CallInst *CI = createCallMatchingInvoke(II); 1924 CI->insertBefore(II); 1925 CI->takeName(II); 1926 II->replaceAllUsesWith(CI); 1927 SplitPos = CI->getNextNode(); 1928 } 1929 } 1930 } 1931 1932 if (SplitPos == &NormalDestBB->front()) { 1933 // If this is an invoke of a noreturn function the edge to the normal 1934 // destination block is dead but not necessarily the block itself. 1935 // TODO: We need to move to an edge based system during deduction and 1936 // also manifest. 1937 assert(!NormalDestBB->isLandingPad() && 1938 "Expected the normal destination not to be a landingpad!"); 1939 BasicBlock *SplitBB = 1940 SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 1941 // The split block is live even if it contains only an unreachable 1942 // instruction at the end. 1943 assumeLive(A, *SplitBB); 1944 SplitPos = SplitBB->getTerminator(); 1945 } 1946 } 1947 1948 BB = SplitPos->getParent(); 1949 SplitBlock(BB, SplitPos); 1950 changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false); 1951 HasChanged = ChangeStatus::CHANGED; 1952 } 1953 1954 for (BasicBlock &BB : F) 1955 if (!AssumedLiveBlocks.count(&BB)) 1956 A.deleteAfterManifest(BB); 1957 1958 return HasChanged; 1959 } 1960 1961 /// See AbstractAttribute::updateImpl(...). 1962 ChangeStatus updateImpl(Attributor &A) override; 1963 1964 /// See AAIsDead::isAssumedDead(BasicBlock *). 1965 bool isAssumedDead(const BasicBlock *BB) const override { 1966 assert(BB->getParent() == getAssociatedFunction() && 1967 "BB must be in the same anchor scope function."); 1968 1969 if (!getAssumed()) 1970 return false; 1971 return !AssumedLiveBlocks.count(BB); 1972 } 1973 1974 /// See AAIsDead::isKnownDead(BasicBlock *). 1975 bool isKnownDead(const BasicBlock *BB) const override { 1976 return getKnown() && isAssumedDead(BB); 1977 } 1978 1979 /// See AAIsDead::isAssumed(Instruction *I). 1980 bool isAssumedDead(const Instruction *I) const override { 1981 assert(I->getParent()->getParent() == getAssociatedFunction() && 1982 "Instruction must be in the same anchor scope function."); 1983 1984 if (!getAssumed()) 1985 return false; 1986 1987 // If it is not in AssumedLiveBlocks then it for sure dead. 1988 // Otherwise, it can still be after noreturn call in a live block. 1989 if (!AssumedLiveBlocks.count(I->getParent())) 1990 return true; 1991 1992 // If it is not after a noreturn call, than it is live. 1993 return isAfterNoReturn(I); 1994 } 1995 1996 /// See AAIsDead::isKnownDead(Instruction *I). 1997 bool isKnownDead(const Instruction *I) const override { 1998 return getKnown() && isAssumedDead(I); 1999 } 2000 2001 /// Check if instruction is after noreturn call, in other words, assumed dead. 2002 bool isAfterNoReturn(const Instruction *I) const; 2003 2004 /// Determine if \p F might catch asynchronous exceptions. 2005 static bool mayCatchAsynchronousExceptions(const Function &F) { 2006 return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F); 2007 } 2008 2009 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A 2010 /// that internal function called from \p BB should now be looked at. 2011 void assumeLive(Attributor &A, const BasicBlock &BB) { 2012 if (!AssumedLiveBlocks.insert(&BB).second) 2013 return; 2014 2015 // We assume that all of BB is (probably) live now and if there are calls to 2016 // internal functions we will assume that those are now live as well. This 2017 // is a performance optimization for blocks with calls to a lot of internal 2018 // functions. It can however cause dead functions to be treated as live. 2019 for (const Instruction &I : BB) 2020 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) 2021 if (const Function *F = ICS.getCalledFunction()) 2022 if (F->hasInternalLinkage()) 2023 A.markLiveInternalFunction(*F); 2024 } 2025 2026 /// Collection of to be explored paths. 2027 SmallSetVector<const Instruction *, 8> ToBeExploredPaths; 2028 2029 /// Collection of all assumed live BasicBlocks. 2030 DenseSet<const BasicBlock *> AssumedLiveBlocks; 2031 2032 /// Collection of calls with noreturn attribute, assumed or knwon. 2033 SmallSetVector<const Instruction *, 4> NoReturnCalls; 2034 }; 2035 2036 struct AAIsDeadFunction final : public AAIsDeadImpl { 2037 AAIsDeadFunction(const IRPosition &IRP) : AAIsDeadImpl(IRP) {} 2038 2039 /// See AbstractAttribute::trackStatistics() 2040 void trackStatistics() const override { 2041 STATS_DECL(PartiallyDeadBlocks, Function, 2042 "Number of basic blocks classified as partially dead"); 2043 BUILD_STAT_NAME(PartiallyDeadBlocks, Function) += NoReturnCalls.size(); 2044 } 2045 }; 2046 2047 bool AAIsDeadImpl::isAfterNoReturn(const Instruction *I) const { 2048 const Instruction *PrevI = I->getPrevNode(); 2049 while (PrevI) { 2050 if (NoReturnCalls.count(PrevI)) 2051 return true; 2052 PrevI = PrevI->getPrevNode(); 2053 } 2054 return false; 2055 } 2056 2057 const Instruction *AAIsDeadImpl::findNextNoReturn(Attributor &A, 2058 const Instruction *I) { 2059 const BasicBlock *BB = I->getParent(); 2060 const Function &F = *BB->getParent(); 2061 2062 // Flag to determine if we can change an invoke to a call assuming the callee 2063 // is nounwind. This is not possible if the personality of the function allows 2064 // to catch asynchronous exceptions. 2065 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 2066 2067 // TODO: We should have a function that determines if an "edge" is dead. 2068 // Edges could be from an instruction to the next or from a terminator 2069 // to the successor. For now, we need to special case the unwind block 2070 // of InvokeInst below. 2071 2072 while (I) { 2073 ImmutableCallSite ICS(I); 2074 2075 if (ICS) { 2076 const IRPosition &IPos = IRPosition::callsite_function(ICS); 2077 // Regarless of the no-return property of an invoke instruction we only 2078 // learn that the regular successor is not reachable through this 2079 // instruction but the unwind block might still be. 2080 if (auto *Invoke = dyn_cast<InvokeInst>(I)) { 2081 // Use nounwind to justify the unwind block is dead as well. 2082 const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos); 2083 if (!Invoke2CallAllowed || !AANoUnw.isAssumedNoUnwind()) { 2084 assumeLive(A, *Invoke->getUnwindDest()); 2085 ToBeExploredPaths.insert(&Invoke->getUnwindDest()->front()); 2086 } 2087 } 2088 2089 const auto &NoReturnAA = A.getAAFor<AANoReturn>(*this, IPos); 2090 if (NoReturnAA.isAssumedNoReturn()) 2091 return I; 2092 } 2093 2094 I = I->getNextNode(); 2095 } 2096 2097 // get new paths (reachable blocks). 2098 for (const BasicBlock *SuccBB : successors(BB)) { 2099 assumeLive(A, *SuccBB); 2100 ToBeExploredPaths.insert(&SuccBB->front()); 2101 } 2102 2103 // No noreturn instruction found. 2104 return nullptr; 2105 } 2106 2107 ChangeStatus AAIsDeadImpl::updateImpl(Attributor &A) { 2108 ChangeStatus Status = ChangeStatus::UNCHANGED; 2109 2110 // Temporary collection to iterate over existing noreturn instructions. This 2111 // will alow easier modification of NoReturnCalls collection 2112 SmallVector<const Instruction *, 8> NoReturnChanged; 2113 2114 for (const Instruction *I : NoReturnCalls) 2115 NoReturnChanged.push_back(I); 2116 2117 for (const Instruction *I : NoReturnChanged) { 2118 size_t Size = ToBeExploredPaths.size(); 2119 2120 const Instruction *NextNoReturnI = findNextNoReturn(A, I); 2121 if (NextNoReturnI != I) { 2122 Status = ChangeStatus::CHANGED; 2123 NoReturnCalls.remove(I); 2124 if (NextNoReturnI) 2125 NoReturnCalls.insert(NextNoReturnI); 2126 } 2127 2128 // Explore new paths. 2129 while (Size != ToBeExploredPaths.size()) { 2130 Status = ChangeStatus::CHANGED; 2131 if (const Instruction *NextNoReturnI = 2132 findNextNoReturn(A, ToBeExploredPaths[Size++])) 2133 NoReturnCalls.insert(NextNoReturnI); 2134 } 2135 } 2136 2137 LLVM_DEBUG(dbgs() << "[AAIsDead] AssumedLiveBlocks: " 2138 << AssumedLiveBlocks.size() << " Total number of blocks: " 2139 << getAssociatedFunction()->size() << "\n"); 2140 2141 // If we know everything is live there is no need to query for liveness. 2142 if (NoReturnCalls.empty() && 2143 getAssociatedFunction()->size() == AssumedLiveBlocks.size()) { 2144 // Indicating a pessimistic fixpoint will cause the state to be "invalid" 2145 // which will cause the Attributor to not return the AAIsDead on request, 2146 // which will prevent us from querying isAssumedDead(). 2147 indicatePessimisticFixpoint(); 2148 assert(!isValidState() && "Expected an invalid state!"); 2149 Status = ChangeStatus::CHANGED; 2150 } 2151 2152 return Status; 2153 } 2154 2155 /// Liveness information for a call sites. 2156 struct AAIsDeadCallSite final : AAIsDeadImpl { 2157 AAIsDeadCallSite(const IRPosition &IRP) : AAIsDeadImpl(IRP) {} 2158 2159 /// See AbstractAttribute::initialize(...). 2160 void initialize(Attributor &A) override { 2161 // TODO: Once we have call site specific value information we can provide 2162 // call site specific liveness information and then it makes 2163 // sense to specialize attributes for call sites instead of 2164 // redirecting requests to the callee. 2165 llvm_unreachable("Abstract attributes for liveness are not " 2166 "supported for call sites yet!"); 2167 } 2168 2169 /// See AbstractAttribute::updateImpl(...). 2170 ChangeStatus updateImpl(Attributor &A) override { 2171 return indicatePessimisticFixpoint(); 2172 } 2173 2174 /// See AbstractAttribute::trackStatistics() 2175 void trackStatistics() const override {} 2176 }; 2177 2178 /// -------------------- Dereferenceable Argument Attribute -------------------- 2179 2180 template <> 2181 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S, 2182 const DerefState &R) { 2183 ChangeStatus CS0 = clampStateAndIndicateChange<IntegerState>( 2184 S.DerefBytesState, R.DerefBytesState); 2185 ChangeStatus CS1 = 2186 clampStateAndIndicateChange<IntegerState>(S.GlobalState, R.GlobalState); 2187 return CS0 | CS1; 2188 } 2189 2190 struct AADereferenceableImpl : AADereferenceable { 2191 AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {} 2192 using StateType = DerefState; 2193 2194 void initialize(Attributor &A) override { 2195 SmallVector<Attribute, 4> Attrs; 2196 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull}, 2197 Attrs); 2198 for (const Attribute &Attr : Attrs) 2199 takeKnownDerefBytesMaximum(Attr.getValueAsInt()); 2200 2201 NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition()); 2202 2203 const IRPosition &IRP = this->getIRPosition(); 2204 bool IsFnInterface = IRP.isFnInterfaceKind(); 2205 const Function *FnScope = IRP.getAnchorScope(); 2206 if (IsFnInterface && (!FnScope || !FnScope->hasExactDefinition())) 2207 indicatePessimisticFixpoint(); 2208 } 2209 2210 /// See AbstractAttribute::getState() 2211 /// { 2212 StateType &getState() override { return *this; } 2213 const StateType &getState() const override { return *this; } 2214 /// } 2215 2216 void getDeducedAttributes(LLVMContext &Ctx, 2217 SmallVectorImpl<Attribute> &Attrs) const override { 2218 // TODO: Add *_globally support 2219 if (isAssumedNonNull()) 2220 Attrs.emplace_back(Attribute::getWithDereferenceableBytes( 2221 Ctx, getAssumedDereferenceableBytes())); 2222 else 2223 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( 2224 Ctx, getAssumedDereferenceableBytes())); 2225 } 2226 2227 /// See AbstractAttribute::getAsStr(). 2228 const std::string getAsStr() const override { 2229 if (!getAssumedDereferenceableBytes()) 2230 return "unknown-dereferenceable"; 2231 return std::string("dereferenceable") + 2232 (isAssumedNonNull() ? "" : "_or_null") + 2233 (isAssumedGlobal() ? "_globally" : "") + "<" + 2234 std::to_string(getKnownDereferenceableBytes()) + "-" + 2235 std::to_string(getAssumedDereferenceableBytes()) + ">"; 2236 } 2237 }; 2238 2239 /// Dereferenceable attribute for a floating value. 2240 struct AADereferenceableFloating : AADereferenceableImpl { 2241 AADereferenceableFloating(const IRPosition &IRP) 2242 : AADereferenceableImpl(IRP) {} 2243 2244 /// See AbstractAttribute::updateImpl(...). 2245 ChangeStatus updateImpl(Attributor &A) override { 2246 const DataLayout &DL = A.getDataLayout(); 2247 2248 auto VisitValueCB = [&](Value &V, DerefState &T, bool Stripped) -> bool { 2249 unsigned IdxWidth = 2250 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); 2251 APInt Offset(IdxWidth, 0); 2252 const Value *Base = 2253 V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset); 2254 2255 const auto &AA = 2256 A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base)); 2257 int64_t DerefBytes = 0; 2258 if (!Stripped && this == &AA) { 2259 // Use IR information if we did not strip anything. 2260 // TODO: track globally. 2261 bool CanBeNull; 2262 DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull); 2263 T.GlobalState.indicatePessimisticFixpoint(); 2264 } else { 2265 const DerefState &DS = static_cast<const DerefState &>(AA.getState()); 2266 DerefBytes = DS.DerefBytesState.getAssumed(); 2267 T.GlobalState &= DS.GlobalState; 2268 } 2269 2270 // For now we do not try to "increase" dereferenceability due to negative 2271 // indices as we first have to come up with code to deal with loops and 2272 // for overflows of the dereferenceable bytes. 2273 int64_t OffsetSExt = Offset.getSExtValue(); 2274 if (OffsetSExt < 0) 2275 Offset = 0; 2276 2277 T.takeAssumedDerefBytesMinimum( 2278 std::max(int64_t(0), DerefBytes - OffsetSExt)); 2279 2280 if (this == &AA) { 2281 if (!Stripped) { 2282 // If nothing was stripped IR information is all we got. 2283 T.takeKnownDerefBytesMaximum( 2284 std::max(int64_t(0), DerefBytes - OffsetSExt)); 2285 T.indicatePessimisticFixpoint(); 2286 } else if (OffsetSExt > 0) { 2287 // If something was stripped but there is circular reasoning we look 2288 // for the offset. If it is positive we basically decrease the 2289 // dereferenceable bytes in a circluar loop now, which will simply 2290 // drive them down to the known value in a very slow way which we 2291 // can accelerate. 2292 T.indicatePessimisticFixpoint(); 2293 } 2294 } 2295 2296 return T.isValidState(); 2297 }; 2298 2299 DerefState T; 2300 if (!genericValueTraversal<AADereferenceable, DerefState>( 2301 A, getIRPosition(), *this, T, VisitValueCB)) 2302 return indicatePessimisticFixpoint(); 2303 2304 return clampStateAndIndicateChange(getState(), T); 2305 } 2306 2307 /// See AbstractAttribute::trackStatistics() 2308 void trackStatistics() const override { 2309 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable) 2310 } 2311 }; 2312 2313 /// Dereferenceable attribute for a return value. 2314 struct AADereferenceableReturned final 2315 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2316 DerefState> { 2317 AADereferenceableReturned(const IRPosition &IRP) 2318 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2319 DerefState>(IRP) {} 2320 2321 /// See AbstractAttribute::trackStatistics() 2322 void trackStatistics() const override { 2323 STATS_DECLTRACK_FNRET_ATTR(dereferenceable) 2324 } 2325 }; 2326 2327 /// Dereferenceable attribute for an argument 2328 struct AADereferenceableArgument final 2329 : AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl, 2330 DerefState> { 2331 AADereferenceableArgument(const IRPosition &IRP) 2332 : AAArgumentFromCallSiteArguments<AADereferenceable, 2333 AADereferenceableImpl, DerefState>( 2334 IRP) {} 2335 2336 /// See AbstractAttribute::trackStatistics() 2337 void trackStatistics() const override { 2338 STATS_DECLTRACK_ARG_ATTR(dereferenceable) 2339 } 2340 }; 2341 2342 /// Dereferenceable attribute for a call site argument. 2343 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating { 2344 AADereferenceableCallSiteArgument(const IRPosition &IRP) 2345 : AADereferenceableFloating(IRP) {} 2346 2347 /// See AbstractAttribute::trackStatistics() 2348 void trackStatistics() const override { 2349 STATS_DECLTRACK_CSARG_ATTR(dereferenceable) 2350 } 2351 }; 2352 2353 /// Dereferenceable attribute deduction for a call site return value. 2354 struct AADereferenceableCallSiteReturned final : AADereferenceableImpl { 2355 AADereferenceableCallSiteReturned(const IRPosition &IRP) 2356 : AADereferenceableImpl(IRP) {} 2357 2358 /// See AbstractAttribute::initialize(...). 2359 void initialize(Attributor &A) override { 2360 AADereferenceableImpl::initialize(A); 2361 Function *F = getAssociatedFunction(); 2362 if (!F) 2363 indicatePessimisticFixpoint(); 2364 } 2365 2366 /// See AbstractAttribute::updateImpl(...). 2367 ChangeStatus updateImpl(Attributor &A) override { 2368 // TODO: Once we have call site specific value information we can provide 2369 // call site specific liveness information and then it makes 2370 // sense to specialize attributes for call sites arguments instead of 2371 // redirecting requests to the callee argument. 2372 Function *F = getAssociatedFunction(); 2373 const IRPosition &FnPos = IRPosition::returned(*F); 2374 auto &FnAA = A.getAAFor<AADereferenceable>(*this, FnPos); 2375 return clampStateAndIndicateChange( 2376 getState(), static_cast<const DerefState &>(FnAA.getState())); 2377 } 2378 2379 /// See AbstractAttribute::trackStatistics() 2380 void trackStatistics() const override { 2381 STATS_DECLTRACK_CS_ATTR(dereferenceable); 2382 } 2383 }; 2384 2385 // ------------------------ Align Argument Attribute ------------------------ 2386 2387 struct AAAlignImpl : AAAlign { 2388 AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {} 2389 2390 // Max alignemnt value allowed in IR 2391 static const unsigned MAX_ALIGN = 1U << 29; 2392 2393 /// See AbstractAttribute::initialize(...). 2394 void initialize(Attributor &A) override { 2395 takeAssumedMinimum(MAX_ALIGN); 2396 2397 SmallVector<Attribute, 4> Attrs; 2398 getAttrs({Attribute::Alignment}, Attrs); 2399 for (const Attribute &Attr : Attrs) 2400 takeKnownMaximum(Attr.getValueAsInt()); 2401 2402 if (getIRPosition().isFnInterfaceKind() && 2403 (!getAssociatedFunction() || 2404 !getAssociatedFunction()->hasExactDefinition())) 2405 indicatePessimisticFixpoint(); 2406 } 2407 2408 /// See AbstractAttribute::manifest(...). 2409 ChangeStatus manifest(Attributor &A) override { 2410 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2411 2412 // Check for users that allow alignment annotations. 2413 Value &AnchorVal = getIRPosition().getAnchorValue(); 2414 for (const Use &U : AnchorVal.uses()) { 2415 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) { 2416 if (SI->getPointerOperand() == &AnchorVal) 2417 if (SI->getAlignment() < getAssumedAlign()) { 2418 STATS_DECLTRACK(AAAlign, Store, 2419 "Number of times alignemnt added to a store"); 2420 SI->setAlignment(getAssumedAlign()); 2421 Changed = ChangeStatus::CHANGED; 2422 } 2423 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) { 2424 if (LI->getPointerOperand() == &AnchorVal) 2425 if (LI->getAlignment() < getAssumedAlign()) { 2426 LI->setAlignment(getAssumedAlign()); 2427 STATS_DECLTRACK(AAAlign, Load, 2428 "Number of times alignemnt added to a load"); 2429 Changed = ChangeStatus::CHANGED; 2430 } 2431 } 2432 } 2433 2434 return AAAlign::manifest(A) | Changed; 2435 } 2436 2437 // TODO: Provide a helper to determine the implied ABI alignment and check in 2438 // the existing manifest method and a new one for AAAlignImpl that value 2439 // to avoid making the alignment explicit if it did not improve. 2440 2441 /// See AbstractAttribute::getDeducedAttributes 2442 virtual void 2443 getDeducedAttributes(LLVMContext &Ctx, 2444 SmallVectorImpl<Attribute> &Attrs) const override { 2445 if (getAssumedAlign() > 1) 2446 Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign())); 2447 } 2448 2449 /// See AbstractAttribute::getAsStr(). 2450 const std::string getAsStr() const override { 2451 return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) + 2452 "-" + std::to_string(getAssumedAlign()) + ">") 2453 : "unknown-align"; 2454 } 2455 }; 2456 2457 /// Align attribute for a floating value. 2458 struct AAAlignFloating : AAAlignImpl { 2459 AAAlignFloating(const IRPosition &IRP) : AAAlignImpl(IRP) {} 2460 2461 /// See AbstractAttribute::updateImpl(...). 2462 ChangeStatus updateImpl(Attributor &A) override { 2463 const DataLayout &DL = A.getDataLayout(); 2464 2465 auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, 2466 bool Stripped) -> bool { 2467 const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V)); 2468 if (!Stripped && this == &AA) { 2469 // Use only IR information if we did not strip anything. 2470 T.takeKnownMaximum(V.getPointerAlignment(DL)); 2471 T.indicatePessimisticFixpoint(); 2472 } else { 2473 // Use abstract attribute information. 2474 const AAAlign::StateType &DS = 2475 static_cast<const AAAlign::StateType &>(AA.getState()); 2476 T ^= DS; 2477 } 2478 return T.isValidState(); 2479 }; 2480 2481 StateType T; 2482 if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T, 2483 VisitValueCB)) 2484 return indicatePessimisticFixpoint(); 2485 2486 // TODO: If we know we visited all incoming values, thus no are assumed 2487 // dead, we can take the known information from the state T. 2488 return clampStateAndIndicateChange(getState(), T); 2489 } 2490 2491 /// See AbstractAttribute::trackStatistics() 2492 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) } 2493 }; 2494 2495 /// Align attribute for function return value. 2496 struct AAAlignReturned final 2497 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> { 2498 AAAlignReturned(const IRPosition &IRP) 2499 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {} 2500 2501 /// See AbstractAttribute::trackStatistics() 2502 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) } 2503 }; 2504 2505 /// Align attribute for function argument. 2506 struct AAAlignArgument final 2507 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> { 2508 AAAlignArgument(const IRPosition &IRP) 2509 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>(IRP) {} 2510 2511 /// See AbstractAttribute::trackStatistics() 2512 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) } 2513 }; 2514 2515 struct AAAlignCallSiteArgument final : AAAlignFloating { 2516 AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {} 2517 2518 /// See AbstractAttribute::manifest(...). 2519 ChangeStatus manifest(Attributor &A) override { 2520 return AAAlignImpl::manifest(A); 2521 } 2522 2523 /// See AbstractAttribute::trackStatistics() 2524 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) } 2525 }; 2526 2527 /// Align attribute deduction for a call site return value. 2528 struct AAAlignCallSiteReturned final : AAAlignImpl { 2529 AAAlignCallSiteReturned(const IRPosition &IRP) : AAAlignImpl(IRP) {} 2530 2531 /// See AbstractAttribute::initialize(...). 2532 void initialize(Attributor &A) override { 2533 AAAlignImpl::initialize(A); 2534 Function *F = getAssociatedFunction(); 2535 if (!F) 2536 indicatePessimisticFixpoint(); 2537 } 2538 2539 /// See AbstractAttribute::updateImpl(...). 2540 ChangeStatus updateImpl(Attributor &A) override { 2541 // TODO: Once we have call site specific value information we can provide 2542 // call site specific liveness information and then it makes 2543 // sense to specialize attributes for call sites arguments instead of 2544 // redirecting requests to the callee argument. 2545 Function *F = getAssociatedFunction(); 2546 const IRPosition &FnPos = IRPosition::returned(*F); 2547 auto &FnAA = A.getAAFor<AAAlign>(*this, FnPos); 2548 return clampStateAndIndicateChange( 2549 getState(), static_cast<const AAAlign::StateType &>(FnAA.getState())); 2550 } 2551 2552 /// See AbstractAttribute::trackStatistics() 2553 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); } 2554 }; 2555 2556 /// ------------------ Function No-Return Attribute ---------------------------- 2557 struct AANoReturnImpl : public AANoReturn { 2558 AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {} 2559 2560 /// See AbstractAttribute::getAsStr(). 2561 const std::string getAsStr() const override { 2562 return getAssumed() ? "noreturn" : "may-return"; 2563 } 2564 2565 /// See AbstractAttribute::updateImpl(Attributor &A). 2566 virtual ChangeStatus updateImpl(Attributor &A) override { 2567 auto CheckForNoReturn = [](Instruction &) { return false; }; 2568 if (!A.checkForAllInstructions(CheckForNoReturn, *this, 2569 {(unsigned)Instruction::Ret})) 2570 return indicatePessimisticFixpoint(); 2571 return ChangeStatus::UNCHANGED; 2572 } 2573 }; 2574 2575 struct AANoReturnFunction final : AANoReturnImpl { 2576 AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {} 2577 2578 /// See AbstractAttribute::trackStatistics() 2579 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) } 2580 }; 2581 2582 /// NoReturn attribute deduction for a call sites. 2583 struct AANoReturnCallSite final : AANoReturnImpl { 2584 AANoReturnCallSite(const IRPosition &IRP) : AANoReturnImpl(IRP) {} 2585 2586 /// See AbstractAttribute::initialize(...). 2587 void initialize(Attributor &A) override { 2588 AANoReturnImpl::initialize(A); 2589 Function *F = getAssociatedFunction(); 2590 if (!F) 2591 indicatePessimisticFixpoint(); 2592 } 2593 2594 /// See AbstractAttribute::updateImpl(...). 2595 ChangeStatus updateImpl(Attributor &A) override { 2596 // TODO: Once we have call site specific value information we can provide 2597 // call site specific liveness information and then it makes 2598 // sense to specialize attributes for call sites arguments instead of 2599 // redirecting requests to the callee argument. 2600 Function *F = getAssociatedFunction(); 2601 const IRPosition &FnPos = IRPosition::function(*F); 2602 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos); 2603 return clampStateAndIndicateChange( 2604 getState(), 2605 static_cast<const AANoReturn::StateType &>(FnAA.getState())); 2606 } 2607 2608 /// See AbstractAttribute::trackStatistics() 2609 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); } 2610 }; 2611 2612 /// ----------------------- Variable Capturing --------------------------------- 2613 2614 /// A class to hold the state of for no-capture attributes. 2615 struct AANoCaptureImpl : public AANoCapture { 2616 AANoCaptureImpl(const IRPosition &IRP) : AANoCapture(IRP) {} 2617 2618 /// See AbstractAttribute::initialize(...). 2619 void initialize(Attributor &A) override { 2620 AANoCapture::initialize(A); 2621 2622 const IRPosition &IRP = getIRPosition(); 2623 const Function *F = 2624 getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 2625 2626 // Check what state the associated function can actually capture. 2627 if (F) 2628 determineFunctionCaptureCapabilities(*F, *this); 2629 else 2630 indicatePessimisticFixpoint(); 2631 } 2632 2633 /// See AbstractAttribute::updateImpl(...). 2634 ChangeStatus updateImpl(Attributor &A) override; 2635 2636 /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...). 2637 virtual void 2638 getDeducedAttributes(LLVMContext &Ctx, 2639 SmallVectorImpl<Attribute> &Attrs) const override { 2640 if (!isAssumedNoCaptureMaybeReturned()) 2641 return; 2642 2643 if (getArgNo() >= 0) { 2644 if (isAssumedNoCapture()) 2645 Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture)); 2646 else if (ManifestInternal) 2647 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned")); 2648 } 2649 } 2650 2651 /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known 2652 /// depending on the ability of the function associated with \p IRP to capture 2653 /// state in memory and through "returning/throwing", respectively. 2654 static void determineFunctionCaptureCapabilities(const Function &F, 2655 IntegerState &State) { 2656 // TODO: Once we have memory behavior attributes we should use them here. 2657 2658 // If we know we cannot communicate or write to memory, we do not care about 2659 // ptr2int anymore. 2660 if (F.onlyReadsMemory() && F.doesNotThrow() && 2661 F.getReturnType()->isVoidTy()) { 2662 State.addKnownBits(NO_CAPTURE); 2663 return; 2664 } 2665 2666 // A function cannot capture state in memory if it only reads memory, it can 2667 // however return/throw state and the state might be influenced by the 2668 // pointer value, e.g., loading from a returned pointer might reveal a bit. 2669 if (F.onlyReadsMemory()) 2670 State.addKnownBits(NOT_CAPTURED_IN_MEM); 2671 2672 // A function cannot communicate state back if it does not through 2673 // exceptions and doesn not return values. 2674 if (F.doesNotThrow() && F.getReturnType()->isVoidTy()) 2675 State.addKnownBits(NOT_CAPTURED_IN_RET); 2676 } 2677 2678 /// See AbstractState::getAsStr(). 2679 const std::string getAsStr() const override { 2680 if (isKnownNoCapture()) 2681 return "known not-captured"; 2682 if (isAssumedNoCapture()) 2683 return "assumed not-captured"; 2684 if (isKnownNoCaptureMaybeReturned()) 2685 return "known not-captured-maybe-returned"; 2686 if (isAssumedNoCaptureMaybeReturned()) 2687 return "assumed not-captured-maybe-returned"; 2688 return "assumed-captured"; 2689 } 2690 }; 2691 2692 /// Attributor-aware capture tracker. 2693 struct AACaptureUseTracker final : public CaptureTracker { 2694 2695 /// Create a capture tracker that can lookup in-flight abstract attributes 2696 /// through the Attributor \p A. 2697 /// 2698 /// If a use leads to a potential capture, \p CapturedInMemory is set and the 2699 /// search is stopped. If a use leads to a return instruction, 2700 /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed. 2701 /// If a use leads to a ptr2int which may capture the value, 2702 /// \p CapturedInInteger is set. If a use is found that is currently assumed 2703 /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies 2704 /// set. All values in \p PotentialCopies are later tracked as well. For every 2705 /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0, 2706 /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger 2707 /// conservatively set to true. 2708 AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA, 2709 const AAIsDead &IsDeadAA, IntegerState &State, 2710 SmallVectorImpl<const Value *> &PotentialCopies, 2711 unsigned &RemainingUsesToExplore) 2712 : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State), 2713 PotentialCopies(PotentialCopies), 2714 RemainingUsesToExplore(RemainingUsesToExplore) {} 2715 2716 /// Determine if \p V maybe captured. *Also updates the state!* 2717 bool valueMayBeCaptured(const Value *V) { 2718 if (V->getType()->isPointerTy()) { 2719 PointerMayBeCaptured(V, this); 2720 } else { 2721 State.indicatePessimisticFixpoint(); 2722 } 2723 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 2724 } 2725 2726 /// See CaptureTracker::tooManyUses(). 2727 void tooManyUses() override { 2728 State.removeAssumedBits(AANoCapture::NO_CAPTURE); 2729 } 2730 2731 bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override { 2732 if (CaptureTracker::isDereferenceableOrNull(O, DL)) 2733 return true; 2734 const auto &DerefAA = 2735 A.getAAFor<AADereferenceable>(NoCaptureAA, IRPosition::value(*O)); 2736 return DerefAA.getAssumedDereferenceableBytes(); 2737 } 2738 2739 /// See CaptureTracker::captured(...). 2740 bool captured(const Use *U) override { 2741 Instruction *UInst = cast<Instruction>(U->getUser()); 2742 LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst 2743 << "\n"); 2744 2745 // Because we may reuse the tracker multiple times we keep track of the 2746 // number of explored uses ourselves as well. 2747 if (RemainingUsesToExplore-- == 0) { 2748 LLVM_DEBUG(dbgs() << " - too many uses to explore!\n"); 2749 return isCapturedIn(/* Memory */ true, /* Integer */ true, 2750 /* Return */ true); 2751 } 2752 2753 // Deal with ptr2int by following uses. 2754 if (isa<PtrToIntInst>(UInst)) { 2755 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n"); 2756 return valueMayBeCaptured(UInst); 2757 } 2758 2759 // Explicitly catch return instructions. 2760 if (isa<ReturnInst>(UInst)) 2761 return isCapturedIn(/* Memory */ false, /* Integer */ false, 2762 /* Return */ true); 2763 2764 // For now we only use special logic for call sites. However, the tracker 2765 // itself knows about a lot of other non-capturing cases already. 2766 CallSite CS(UInst); 2767 if (!CS || !CS.isArgOperand(U)) 2768 return isCapturedIn(/* Memory */ true, /* Integer */ true, 2769 /* Return */ true); 2770 2771 unsigned ArgNo = CS.getArgumentNo(U); 2772 const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo); 2773 // If we have a abstract no-capture attribute for the argument we can use 2774 // it to justify a non-capture attribute here. This allows recursion! 2775 auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos); 2776 if (ArgNoCaptureAA.isAssumedNoCapture()) 2777 return isCapturedIn(/* Memory */ false, /* Integer */ false, 2778 /* Return */ false); 2779 if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 2780 addPotentialCopy(CS); 2781 return isCapturedIn(/* Memory */ false, /* Integer */ false, 2782 /* Return */ false); 2783 } 2784 2785 // Lastly, we could not find a reason no-capture can be assumed so we don't. 2786 return isCapturedIn(/* Memory */ true, /* Integer */ true, 2787 /* Return */ true); 2788 } 2789 2790 /// Register \p CS as potential copy of the value we are checking. 2791 void addPotentialCopy(CallSite CS) { 2792 PotentialCopies.push_back(CS.getInstruction()); 2793 } 2794 2795 /// See CaptureTracker::shouldExplore(...). 2796 bool shouldExplore(const Use *U) override { 2797 // Check liveness. 2798 return !IsDeadAA.isAssumedDead(cast<Instruction>(U->getUser())); 2799 } 2800 2801 /// Update the state according to \p CapturedInMem, \p CapturedInInt, and 2802 /// \p CapturedInRet, then return the appropriate value for use in the 2803 /// CaptureTracker::captured() interface. 2804 bool isCapturedIn(bool CapturedInMem, bool CapturedInInt, 2805 bool CapturedInRet) { 2806 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int " 2807 << CapturedInInt << "|Ret " << CapturedInRet << "]\n"); 2808 if (CapturedInMem) 2809 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM); 2810 if (CapturedInInt) 2811 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT); 2812 if (CapturedInRet) 2813 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET); 2814 return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 2815 } 2816 2817 private: 2818 /// The attributor providing in-flight abstract attributes. 2819 Attributor &A; 2820 2821 /// The abstract attribute currently updated. 2822 AANoCapture &NoCaptureAA; 2823 2824 /// The abstract liveness state. 2825 const AAIsDead &IsDeadAA; 2826 2827 /// The state currently updated. 2828 IntegerState &State; 2829 2830 /// Set of potential copies of the tracked value. 2831 SmallVectorImpl<const Value *> &PotentialCopies; 2832 2833 /// Global counter to limit the number of explored uses. 2834 unsigned &RemainingUsesToExplore; 2835 }; 2836 2837 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) { 2838 const IRPosition &IRP = getIRPosition(); 2839 const Value *V = 2840 getArgNo() >= 0 ? IRP.getAssociatedArgument() : &IRP.getAssociatedValue(); 2841 if (!V) 2842 return indicatePessimisticFixpoint(); 2843 2844 const Function *F = 2845 getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 2846 assert(F && "Expected a function!"); 2847 const auto &IsDeadAA = A.getAAFor<AAIsDead>(*this, IRPosition::function(*F)); 2848 2849 AANoCapture::StateType T; 2850 // TODO: Once we have memory behavior attributes we should use them here 2851 // similar to the reasoning in 2852 // AANoCaptureImpl::determineFunctionCaptureCapabilities(...). 2853 2854 // TODO: Use the AAReturnedValues to learn if the argument can return or 2855 // not. 2856 2857 // Use the CaptureTracker interface and logic with the specialized tracker, 2858 // defined in AACaptureUseTracker, that can look at in-flight abstract 2859 // attributes and directly updates the assumed state. 2860 SmallVector<const Value *, 4> PotentialCopies; 2861 unsigned RemainingUsesToExplore = DefaultMaxUsesToExplore; 2862 AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies, 2863 RemainingUsesToExplore); 2864 2865 // Check all potential copies of the associated value until we can assume 2866 // none will be captured or we have to assume at least one might be. 2867 unsigned Idx = 0; 2868 PotentialCopies.push_back(V); 2869 while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size()) 2870 Tracker.valueMayBeCaptured(PotentialCopies[Idx++]); 2871 2872 AAAlign::StateType &S = getState(); 2873 auto Assumed = S.getAssumed(); 2874 S.intersectAssumedBits(T.getAssumed()); 2875 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 2876 : ChangeStatus::CHANGED; 2877 } 2878 2879 /// NoCapture attribute for function arguments. 2880 struct AANoCaptureArgument final : AANoCaptureImpl { 2881 AANoCaptureArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 2882 2883 /// See AbstractAttribute::trackStatistics() 2884 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) } 2885 }; 2886 2887 /// NoCapture attribute for call site arguments. 2888 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl { 2889 AANoCaptureCallSiteArgument(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 2890 2891 /// See AbstractAttribute::updateImpl(...). 2892 ChangeStatus updateImpl(Attributor &A) override { 2893 // TODO: Once we have call site specific value information we can provide 2894 // call site specific liveness information and then it makes 2895 // sense to specialize attributes for call sites arguments instead of 2896 // redirecting requests to the callee argument. 2897 Argument *Arg = getAssociatedArgument(); 2898 if (!Arg) 2899 return indicatePessimisticFixpoint(); 2900 const IRPosition &ArgPos = IRPosition::argument(*Arg); 2901 auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos); 2902 return clampStateAndIndicateChange( 2903 getState(), 2904 static_cast<const AANoCapture::StateType &>(ArgAA.getState())); 2905 } 2906 2907 /// See AbstractAttribute::trackStatistics() 2908 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)}; 2909 }; 2910 2911 /// NoCapture attribute for floating values. 2912 struct AANoCaptureFloating final : AANoCaptureImpl { 2913 AANoCaptureFloating(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 2914 2915 /// See AbstractAttribute::trackStatistics() 2916 void trackStatistics() const override { 2917 STATS_DECLTRACK_FLOATING_ATTR(nocapture) 2918 } 2919 }; 2920 2921 /// NoCapture attribute for function return value. 2922 struct AANoCaptureReturned final : AANoCaptureImpl { 2923 AANoCaptureReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) { 2924 llvm_unreachable("NoCapture is not applicable to function returns!"); 2925 } 2926 2927 /// See AbstractAttribute::initialize(...). 2928 void initialize(Attributor &A) override { 2929 llvm_unreachable("NoCapture is not applicable to function returns!"); 2930 } 2931 2932 /// See AbstractAttribute::updateImpl(...). 2933 ChangeStatus updateImpl(Attributor &A) override { 2934 llvm_unreachable("NoCapture is not applicable to function returns!"); 2935 } 2936 2937 /// See AbstractAttribute::trackStatistics() 2938 void trackStatistics() const override {} 2939 }; 2940 2941 /// NoCapture attribute deduction for a call site return value. 2942 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl { 2943 AANoCaptureCallSiteReturned(const IRPosition &IRP) : AANoCaptureImpl(IRP) {} 2944 2945 /// See AbstractAttribute::trackStatistics() 2946 void trackStatistics() const override { 2947 STATS_DECLTRACK_CSRET_ATTR(nocapture) 2948 } 2949 }; 2950 2951 /// ------------------ Value Simplify Attribute ---------------------------- 2952 struct AAValueSimplifyImpl : AAValueSimplify { 2953 AAValueSimplifyImpl(const IRPosition &IRP) : AAValueSimplify(IRP) {} 2954 2955 /// See AbstractAttribute::getAsStr(). 2956 const std::string getAsStr() const override { 2957 return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple") 2958 : "not-simple"; 2959 } 2960 2961 /// See AbstractAttribute::trackStatistics() 2962 void trackStatistics() const override {} 2963 2964 /// See AAValueSimplify::getAssumedSimplifiedValue() 2965 Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override { 2966 if (!getAssumed()) 2967 return const_cast<Value *>(&getAssociatedValue()); 2968 return SimplifiedAssociatedValue; 2969 } 2970 void initialize(Attributor &A) override {} 2971 2972 /// Helper function for querying AAValueSimplify and updating candicate. 2973 /// \param QueryingValue Value trying to unify with SimplifiedValue 2974 /// \param AccumulatedSimplifiedValue Current simplification result. 2975 static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA, 2976 Value &QueryingValue, 2977 Optional<Value *> &AccumulatedSimplifiedValue) { 2978 // FIXME: Add a typecast support. 2979 2980 auto &ValueSimpifyAA = A.getAAFor<AAValueSimplify>( 2981 QueryingAA, IRPosition::value(QueryingValue)); 2982 2983 Optional<Value *> QueryingValueSimplified = 2984 ValueSimpifyAA.getAssumedSimplifiedValue(A); 2985 2986 if (!QueryingValueSimplified.hasValue()) 2987 return true; 2988 2989 if (!QueryingValueSimplified.getValue()) 2990 return false; 2991 2992 Value &QueryingValueSimplifiedUnwrapped = 2993 *QueryingValueSimplified.getValue(); 2994 2995 if (isa<UndefValue>(QueryingValueSimplifiedUnwrapped)) 2996 return true; 2997 2998 if (AccumulatedSimplifiedValue.hasValue()) 2999 return AccumulatedSimplifiedValue == QueryingValueSimplified; 3000 3001 LLVM_DEBUG(dbgs() << "[Attributor][ValueSimplify] " << QueryingValue 3002 << " is assumed to be " 3003 << QueryingValueSimplifiedUnwrapped << "\n"); 3004 3005 AccumulatedSimplifiedValue = QueryingValueSimplified; 3006 return true; 3007 } 3008 3009 /// See AbstractAttribute::manifest(...). 3010 ChangeStatus manifest(Attributor &A) override { 3011 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3012 3013 if (!SimplifiedAssociatedValue.hasValue() || 3014 !SimplifiedAssociatedValue.getValue()) 3015 return Changed; 3016 3017 if (auto *C = dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())) { 3018 // We can replace the AssociatedValue with the constant. 3019 Value &V = getAssociatedValue(); 3020 if (!V.user_empty() && &V != C && V.getType() == C->getType()) { 3021 LLVM_DEBUG(dbgs() << "[Attributor][ValueSimplify] " << V << " -> " << *C 3022 << "\n"); 3023 V.replaceAllUsesWith(C); 3024 Changed = ChangeStatus::CHANGED; 3025 } 3026 } 3027 3028 return Changed | AAValueSimplify::manifest(A); 3029 } 3030 3031 protected: 3032 // An assumed simplified value. Initially, it is set to Optional::None, which 3033 // means that the value is not clear under current assumption. If in the 3034 // pessimistic state, getAssumedSimplifiedValue doesn't return this value but 3035 // returns orignal associated value. 3036 Optional<Value *> SimplifiedAssociatedValue; 3037 }; 3038 3039 struct AAValueSimplifyArgument final : AAValueSimplifyImpl { 3040 AAValueSimplifyArgument(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3041 3042 /// See AbstractAttribute::updateImpl(...). 3043 ChangeStatus updateImpl(Attributor &A) override { 3044 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3045 3046 auto PredForCallSite = [&](CallSite CS) { 3047 return checkAndUpdate(A, *this, *CS.getArgOperand(getArgNo()), 3048 SimplifiedAssociatedValue); 3049 }; 3050 3051 if (!A.checkForAllCallSites(PredForCallSite, *this, true)) 3052 return indicatePessimisticFixpoint(); 3053 3054 // If a candicate was found in this update, return CHANGED. 3055 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3056 ? ChangeStatus::UNCHANGED 3057 : ChangeStatus ::CHANGED; 3058 } 3059 3060 /// See AbstractAttribute::trackStatistics() 3061 void trackStatistics() const override { 3062 STATS_DECLTRACK_ARG_ATTR(value_simplify) 3063 } 3064 }; 3065 3066 struct AAValueSimplifyReturned : AAValueSimplifyImpl { 3067 AAValueSimplifyReturned(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3068 3069 /// See AbstractAttribute::updateImpl(...). 3070 ChangeStatus updateImpl(Attributor &A) override { 3071 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3072 3073 auto PredForReturned = [&](Value &V) { 3074 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 3075 }; 3076 3077 if (!A.checkForAllReturnedValues(PredForReturned, *this)) 3078 return indicatePessimisticFixpoint(); 3079 3080 // If a candicate was found in this update, return CHANGED. 3081 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3082 ? ChangeStatus::UNCHANGED 3083 : ChangeStatus ::CHANGED; 3084 } 3085 /// See AbstractAttribute::trackStatistics() 3086 void trackStatistics() const override { 3087 STATS_DECLTRACK_FNRET_ATTR(value_simplify) 3088 } 3089 }; 3090 3091 struct AAValueSimplifyFloating : AAValueSimplifyImpl { 3092 AAValueSimplifyFloating(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3093 3094 /// See AbstractAttribute::initialize(...). 3095 void initialize(Attributor &A) override { 3096 Value &V = getAnchorValue(); 3097 3098 // TODO: add other stuffs 3099 if (isa<Constant>(V) || isa<UndefValue>(V)) 3100 indicatePessimisticFixpoint(); 3101 } 3102 3103 /// See AbstractAttribute::updateImpl(...). 3104 ChangeStatus updateImpl(Attributor &A) override { 3105 bool HasValueBefore = SimplifiedAssociatedValue.hasValue(); 3106 3107 auto VisitValueCB = [&](Value &V, BooleanState, bool Stripped) -> bool { 3108 auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V)); 3109 if (!Stripped && this == &AA) { 3110 // TODO: Look the instruction and check recursively. 3111 LLVM_DEBUG( 3112 dbgs() << "[Attributor][ValueSimplify] Can't be stripped more : " 3113 << V << "\n"); 3114 indicatePessimisticFixpoint(); 3115 return false; 3116 } 3117 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 3118 }; 3119 3120 if (!genericValueTraversal<AAValueSimplify, BooleanState>( 3121 A, getIRPosition(), *this, static_cast<BooleanState &>(*this), 3122 VisitValueCB)) 3123 return indicatePessimisticFixpoint(); 3124 3125 // If a candicate was found in this update, return CHANGED. 3126 3127 return HasValueBefore == SimplifiedAssociatedValue.hasValue() 3128 ? ChangeStatus::UNCHANGED 3129 : ChangeStatus ::CHANGED; 3130 } 3131 3132 /// See AbstractAttribute::trackStatistics() 3133 void trackStatistics() const override { 3134 STATS_DECLTRACK_FLOATING_ATTR(value_simplify) 3135 } 3136 }; 3137 3138 struct AAValueSimplifyFunction : AAValueSimplifyImpl { 3139 AAValueSimplifyFunction(const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {} 3140 3141 /// See AbstractAttribute::initialize(...). 3142 void initialize(Attributor &A) override { 3143 SimplifiedAssociatedValue = &getAnchorValue(); 3144 indicateOptimisticFixpoint(); 3145 } 3146 /// See AbstractAttribute::initialize(...). 3147 ChangeStatus updateImpl(Attributor &A) override { 3148 llvm_unreachable( 3149 "AAValueSimplify(Function|CallSite)::updateImpl will not be called"); 3150 } 3151 /// See AbstractAttribute::trackStatistics() 3152 void trackStatistics() const override { 3153 STATS_DECLTRACK_FN_ATTR(value_simplify) 3154 } 3155 }; 3156 3157 struct AAValueSimplifyCallSite : AAValueSimplifyFunction { 3158 AAValueSimplifyCallSite(const IRPosition &IRP) 3159 : AAValueSimplifyFunction(IRP) {} 3160 /// See AbstractAttribute::trackStatistics() 3161 void trackStatistics() const override { 3162 STATS_DECLTRACK_CS_ATTR(value_simplify) 3163 } 3164 }; 3165 3166 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned { 3167 AAValueSimplifyCallSiteReturned(const IRPosition &IRP) 3168 : AAValueSimplifyReturned(IRP) {} 3169 3170 void trackStatistics() const override { 3171 STATS_DECLTRACK_CSRET_ATTR(value_simplify) 3172 } 3173 }; 3174 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating { 3175 AAValueSimplifyCallSiteArgument(const IRPosition &IRP) 3176 : AAValueSimplifyFloating(IRP) {} 3177 3178 void trackStatistics() const override { 3179 STATS_DECLTRACK_CSARG_ATTR(value_simplify) 3180 } 3181 }; 3182 3183 /// ---------------------------------------------------------------------------- 3184 /// Attributor 3185 /// ---------------------------------------------------------------------------- 3186 3187 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 3188 const AAIsDead *LivenessAA) { 3189 const Instruction *CtxI = AA.getIRPosition().getCtxI(); 3190 if (!CtxI) 3191 return false; 3192 3193 if (!LivenessAA) 3194 LivenessAA = 3195 &getAAFor<AAIsDead>(AA, IRPosition::function(*CtxI->getFunction()), 3196 /* TrackDependence */ false); 3197 3198 // Don't check liveness for AAIsDead. 3199 if (&AA == LivenessAA) 3200 return false; 3201 3202 if (!LivenessAA->isAssumedDead(CtxI)) 3203 return false; 3204 3205 // We actually used liveness information so we have to record a dependence. 3206 recordDependence(*LivenessAA, AA); 3207 3208 return true; 3209 } 3210 3211 bool Attributor::checkForAllCallSites(const function_ref<bool(CallSite)> &Pred, 3212 const AbstractAttribute &QueryingAA, 3213 bool RequireAllCallSites) { 3214 // We can try to determine information from 3215 // the call sites. However, this is only possible all call sites are known, 3216 // hence the function has internal linkage. 3217 const IRPosition &IRP = QueryingAA.getIRPosition(); 3218 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 3219 if (!AssociatedFunction) 3220 return false; 3221 3222 if (RequireAllCallSites && !AssociatedFunction->hasInternalLinkage()) { 3223 LLVM_DEBUG( 3224 dbgs() 3225 << "[Attributor] Function " << AssociatedFunction->getName() 3226 << " has no internal linkage, hence not all call sites are known\n"); 3227 return false; 3228 } 3229 3230 for (const Use &U : AssociatedFunction->uses()) { 3231 Instruction *I = dyn_cast<Instruction>(U.getUser()); 3232 // TODO: Deal with abstract call sites here. 3233 if (!I) 3234 return false; 3235 3236 Function *Caller = I->getFunction(); 3237 3238 const auto &LivenessAA = getAAFor<AAIsDead>( 3239 QueryingAA, IRPosition::function(*Caller), /* TrackDependence */ false); 3240 3241 // Skip dead calls. 3242 if (LivenessAA.isAssumedDead(I)) { 3243 // We actually used liveness information so we have to record a 3244 // dependence. 3245 recordDependence(LivenessAA, QueryingAA); 3246 continue; 3247 } 3248 3249 CallSite CS(U.getUser()); 3250 if (!CS || !CS.isCallee(&U)) { 3251 if (!RequireAllCallSites) 3252 continue; 3253 3254 LLVM_DEBUG(dbgs() << "[Attributor] User " << *U.getUser() 3255 << " is an invalid use of " 3256 << AssociatedFunction->getName() << "\n"); 3257 return false; 3258 } 3259 3260 if (Pred(CS)) 3261 continue; 3262 3263 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 3264 << *CS.getInstruction() << "\n"); 3265 return false; 3266 } 3267 3268 return true; 3269 } 3270 3271 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 3272 const function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> 3273 &Pred, 3274 const AbstractAttribute &QueryingAA) { 3275 3276 const IRPosition &IRP = QueryingAA.getIRPosition(); 3277 // Since we need to provide return instructions we have to have an exact 3278 // definition. 3279 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 3280 if (!AssociatedFunction) 3281 return false; 3282 3283 // If this is a call site query we use the call site specific return values 3284 // and liveness information. 3285 // TODO: use the function scope once we have call site AAReturnedValues. 3286 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 3287 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 3288 if (!AARetVal.getState().isValidState()) 3289 return false; 3290 3291 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 3292 } 3293 3294 bool Attributor::checkForAllReturnedValues( 3295 const function_ref<bool(Value &)> &Pred, 3296 const AbstractAttribute &QueryingAA) { 3297 3298 const IRPosition &IRP = QueryingAA.getIRPosition(); 3299 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 3300 if (!AssociatedFunction) 3301 return false; 3302 3303 // TODO: use the function scope once we have call site AAReturnedValues. 3304 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 3305 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 3306 if (!AARetVal.getState().isValidState()) 3307 return false; 3308 3309 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 3310 [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) { 3311 return Pred(RV); 3312 }); 3313 } 3314 3315 bool Attributor::checkForAllInstructions( 3316 const llvm::function_ref<bool(Instruction &)> &Pred, 3317 const AbstractAttribute &QueryingAA, const ArrayRef<unsigned> &Opcodes) { 3318 3319 const IRPosition &IRP = QueryingAA.getIRPosition(); 3320 // Since we need to provide instructions we have to have an exact definition. 3321 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 3322 if (!AssociatedFunction) 3323 return false; 3324 3325 // TODO: use the function scope once we have call site AAReturnedValues. 3326 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 3327 const auto &LivenessAA = 3328 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 3329 bool AnyDead = false; 3330 3331 auto &OpcodeInstMap = 3332 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 3333 for (unsigned Opcode : Opcodes) { 3334 for (Instruction *I : OpcodeInstMap[Opcode]) { 3335 // Skip dead instructions. 3336 if (LivenessAA.isAssumedDead(I)) { 3337 AnyDead = true; 3338 continue; 3339 } 3340 3341 if (!Pred(*I)) 3342 return false; 3343 } 3344 } 3345 3346 // If we actually used liveness information so we have to record a dependence. 3347 if (AnyDead) 3348 recordDependence(LivenessAA, QueryingAA); 3349 3350 return true; 3351 } 3352 3353 bool Attributor::checkForAllReadWriteInstructions( 3354 const llvm::function_ref<bool(Instruction &)> &Pred, 3355 AbstractAttribute &QueryingAA) { 3356 3357 const Function *AssociatedFunction = 3358 QueryingAA.getIRPosition().getAssociatedFunction(); 3359 if (!AssociatedFunction) 3360 return false; 3361 3362 // TODO: use the function scope once we have call site AAReturnedValues. 3363 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 3364 const auto &LivenessAA = 3365 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 3366 bool AnyDead = false; 3367 3368 for (Instruction *I : 3369 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 3370 // Skip dead instructions. 3371 if (LivenessAA.isAssumedDead(I)) { 3372 AnyDead = true; 3373 continue; 3374 } 3375 3376 if (!Pred(*I)) 3377 return false; 3378 } 3379 3380 // If we actually used liveness information so we have to record a dependence. 3381 if (AnyDead) 3382 recordDependence(LivenessAA, QueryingAA); 3383 3384 return true; 3385 } 3386 3387 ChangeStatus Attributor::run(Module &M) { 3388 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 3389 << AllAbstractAttributes.size() 3390 << " abstract attributes.\n"); 3391 3392 // Now that all abstract attributes are collected and initialized we start 3393 // the abstract analysis. 3394 3395 unsigned IterationCounter = 1; 3396 3397 SmallVector<AbstractAttribute *, 64> ChangedAAs; 3398 SetVector<AbstractAttribute *> Worklist; 3399 Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end()); 3400 3401 bool RecomputeDependences = false; 3402 3403 do { 3404 // Remember the size to determine new attributes. 3405 size_t NumAAs = AllAbstractAttributes.size(); 3406 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 3407 << ", Worklist size: " << Worklist.size() << "\n"); 3408 3409 // If dependences (=QueryMap) are recomputed we have to look at all abstract 3410 // attributes again, regardless of what changed in the last iteration. 3411 if (RecomputeDependences) { 3412 LLVM_DEBUG( 3413 dbgs() << "[Attributor] Run all AAs to recompute dependences\n"); 3414 QueryMap.clear(); 3415 ChangedAAs.clear(); 3416 Worklist.insert(AllAbstractAttributes.begin(), 3417 AllAbstractAttributes.end()); 3418 } 3419 3420 // Add all abstract attributes that are potentially dependent on one that 3421 // changed to the work list. 3422 for (AbstractAttribute *ChangedAA : ChangedAAs) { 3423 auto &QuerriedAAs = QueryMap[ChangedAA]; 3424 Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end()); 3425 } 3426 3427 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter 3428 << ", Worklist+Dependent size: " << Worklist.size() 3429 << "\n"); 3430 3431 // Reset the changed set. 3432 ChangedAAs.clear(); 3433 3434 // Update all abstract attribute in the work list and record the ones that 3435 // changed. 3436 for (AbstractAttribute *AA : Worklist) 3437 if (!isAssumedDead(*AA, nullptr)) 3438 if (AA->update(*this) == ChangeStatus::CHANGED) 3439 ChangedAAs.push_back(AA); 3440 3441 // Check if we recompute the dependences in the next iteration. 3442 RecomputeDependences = (DepRecomputeInterval > 0 && 3443 IterationCounter % DepRecomputeInterval == 0); 3444 3445 // Add attributes to the changed set if they have been created in the last 3446 // iteration. 3447 ChangedAAs.append(AllAbstractAttributes.begin() + NumAAs, 3448 AllAbstractAttributes.end()); 3449 3450 // Reset the work list and repopulate with the changed abstract attributes. 3451 // Note that dependent ones are added above. 3452 Worklist.clear(); 3453 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 3454 3455 } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations || 3456 VerifyMaxFixpointIterations)); 3457 3458 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 3459 << IterationCounter << "/" << MaxFixpointIterations 3460 << " iterations\n"); 3461 3462 size_t NumFinalAAs = AllAbstractAttributes.size(); 3463 3464 bool FinishedAtFixpoint = Worklist.empty(); 3465 3466 // Reset abstract arguments not settled in a sound fixpoint by now. This 3467 // happens when we stopped the fixpoint iteration early. Note that only the 3468 // ones marked as "changed" *and* the ones transitively depending on them 3469 // need to be reverted to a pessimistic state. Others might not be in a 3470 // fixpoint state but we can use the optimistic results for them anyway. 3471 SmallPtrSet<AbstractAttribute *, 32> Visited; 3472 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 3473 AbstractAttribute *ChangedAA = ChangedAAs[u]; 3474 if (!Visited.insert(ChangedAA).second) 3475 continue; 3476 3477 AbstractState &State = ChangedAA->getState(); 3478 if (!State.isAtFixpoint()) { 3479 State.indicatePessimisticFixpoint(); 3480 3481 NumAttributesTimedOut++; 3482 } 3483 3484 auto &QuerriedAAs = QueryMap[ChangedAA]; 3485 ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end()); 3486 } 3487 3488 LLVM_DEBUG({ 3489 if (!Visited.empty()) 3490 dbgs() << "\n[Attributor] Finalized " << Visited.size() 3491 << " abstract attributes.\n"; 3492 }); 3493 3494 unsigned NumManifested = 0; 3495 unsigned NumAtFixpoint = 0; 3496 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 3497 for (AbstractAttribute *AA : AllAbstractAttributes) { 3498 AbstractState &State = AA->getState(); 3499 3500 // If there is not already a fixpoint reached, we can now take the 3501 // optimistic state. This is correct because we enforced a pessimistic one 3502 // on abstract attributes that were transitively dependent on a changed one 3503 // already above. 3504 if (!State.isAtFixpoint()) 3505 State.indicateOptimisticFixpoint(); 3506 3507 // If the state is invalid, we do not try to manifest it. 3508 if (!State.isValidState()) 3509 continue; 3510 3511 // Skip dead code. 3512 if (isAssumedDead(*AA, nullptr)) 3513 continue; 3514 // Manifest the state and record if we changed the IR. 3515 ChangeStatus LocalChange = AA->manifest(*this); 3516 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 3517 AA->trackStatistics(); 3518 3519 ManifestChange = ManifestChange | LocalChange; 3520 3521 NumAtFixpoint++; 3522 NumManifested += (LocalChange == ChangeStatus::CHANGED); 3523 } 3524 3525 (void)NumManifested; 3526 (void)NumAtFixpoint; 3527 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 3528 << " arguments while " << NumAtFixpoint 3529 << " were in a valid fixpoint state\n"); 3530 3531 // If verification is requested, we finished this run at a fixpoint, and the 3532 // IR was changed, we re-run the whole fixpoint analysis, starting at 3533 // re-initialization of the arguments. This re-run should not result in an IR 3534 // change. Though, the (virtual) state of attributes at the end of the re-run 3535 // might be more optimistic than the known state or the IR state if the better 3536 // state cannot be manifested. 3537 if (VerifyAttributor && FinishedAtFixpoint && 3538 ManifestChange == ChangeStatus::CHANGED) { 3539 VerifyAttributor = false; 3540 ChangeStatus VerifyStatus = run(M); 3541 if (VerifyStatus != ChangeStatus::UNCHANGED) 3542 llvm_unreachable( 3543 "Attributor verification failed, re-run did result in an IR change " 3544 "even after a fixpoint was reached in the original run. (False " 3545 "positives possible!)"); 3546 VerifyAttributor = true; 3547 } 3548 3549 NumAttributesManifested += NumManifested; 3550 NumAttributesValidFixpoint += NumAtFixpoint; 3551 3552 (void)NumFinalAAs; 3553 assert( 3554 NumFinalAAs == AllAbstractAttributes.size() && 3555 "Expected the final number of abstract attributes to remain unchanged!"); 3556 3557 // Delete stuff at the end to avoid invalid references and a nice order. 3558 { 3559 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least " 3560 << ToBeDeletedFunctions.size() << " functions and " 3561 << ToBeDeletedBlocks.size() << " blocks and " 3562 << ToBeDeletedInsts.size() << " instructions\n"); 3563 for (Instruction *I : ToBeDeletedInsts) { 3564 if (!I->use_empty()) 3565 I->replaceAllUsesWith(UndefValue::get(I->getType())); 3566 I->eraseFromParent(); 3567 } 3568 3569 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 3570 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 3571 ToBeDeletedBBs.reserve(NumDeadBlocks); 3572 ToBeDeletedBBs.append(ToBeDeletedBlocks.begin(), ToBeDeletedBlocks.end()); 3573 DeleteDeadBlocks(ToBeDeletedBBs); 3574 STATS_DECLTRACK(AAIsDead, BasicBlock, 3575 "Number of dead basic blocks deleted."); 3576 } 3577 3578 STATS_DECL(AAIsDead, Function, "Number of dead functions deleted."); 3579 for (Function *Fn : ToBeDeletedFunctions) { 3580 Fn->replaceAllUsesWith(UndefValue::get(Fn->getType())); 3581 Fn->eraseFromParent(); 3582 STATS_TRACK(AAIsDead, Function); 3583 } 3584 3585 // Identify dead internal functions and delete them. This happens outside 3586 // the other fixpoint analysis as we might treat potentially dead functions 3587 // as live to lower the number of iterations. If they happen to be dead, the 3588 // below fixpoint loop will identify and eliminate them. 3589 SmallVector<Function *, 8> InternalFns; 3590 for (Function &F : M) 3591 if (F.hasInternalLinkage()) 3592 InternalFns.push_back(&F); 3593 3594 bool FoundDeadFn = true; 3595 while (FoundDeadFn) { 3596 FoundDeadFn = false; 3597 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 3598 Function *F = InternalFns[u]; 3599 if (!F) 3600 continue; 3601 3602 const auto *LivenessAA = 3603 lookupAAFor<AAIsDead>(IRPosition::function(*F)); 3604 if (LivenessAA && 3605 !checkForAllCallSites([](CallSite CS) { return false; }, 3606 *LivenessAA, true)) 3607 continue; 3608 3609 STATS_TRACK(AAIsDead, Function); 3610 F->replaceAllUsesWith(UndefValue::get(F->getType())); 3611 F->eraseFromParent(); 3612 InternalFns[u] = nullptr; 3613 FoundDeadFn = true; 3614 } 3615 } 3616 } 3617 3618 if (VerifyMaxFixpointIterations && 3619 IterationCounter != MaxFixpointIterations) { 3620 errs() << "\n[Attributor] Fixpoint iteration done after: " 3621 << IterationCounter << "/" << MaxFixpointIterations 3622 << " iterations\n"; 3623 llvm_unreachable("The fixpoint was not reached with exactly the number of " 3624 "specified iterations!"); 3625 } 3626 3627 return ManifestChange; 3628 } 3629 3630 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 3631 if (!VisitedFunctions.insert(&F).second) 3632 return; 3633 3634 IRPosition FPos = IRPosition::function(F); 3635 3636 // Check for dead BasicBlocks in every function. 3637 // We need dead instruction detection because we do not want to deal with 3638 // broken IR in which SSA rules do not apply. 3639 getOrCreateAAFor<AAIsDead>(FPos); 3640 3641 // Every function might be "will-return". 3642 getOrCreateAAFor<AAWillReturn>(FPos); 3643 3644 // Every function can be nounwind. 3645 getOrCreateAAFor<AANoUnwind>(FPos); 3646 3647 // Every function might be marked "nosync" 3648 getOrCreateAAFor<AANoSync>(FPos); 3649 3650 // Every function might be "no-free". 3651 getOrCreateAAFor<AANoFree>(FPos); 3652 3653 // Every function might be "no-return". 3654 getOrCreateAAFor<AANoReturn>(FPos); 3655 3656 // Return attributes are only appropriate if the return type is non void. 3657 Type *ReturnType = F.getReturnType(); 3658 if (!ReturnType->isVoidTy()) { 3659 // Argument attribute "returned" --- Create only one per function even 3660 // though it is an argument attribute. 3661 getOrCreateAAFor<AAReturnedValues>(FPos); 3662 3663 IRPosition RetPos = IRPosition::returned(F); 3664 3665 // Every function might be simplified. 3666 getOrCreateAAFor<AAValueSimplify>(RetPos); 3667 3668 if (ReturnType->isPointerTy()) { 3669 3670 // Every function with pointer return type might be marked align. 3671 getOrCreateAAFor<AAAlign>(RetPos); 3672 3673 // Every function with pointer return type might be marked nonnull. 3674 getOrCreateAAFor<AANonNull>(RetPos); 3675 3676 // Every function with pointer return type might be marked noalias. 3677 getOrCreateAAFor<AANoAlias>(RetPos); 3678 3679 // Every function with pointer return type might be marked 3680 // dereferenceable. 3681 getOrCreateAAFor<AADereferenceable>(RetPos); 3682 } 3683 } 3684 3685 for (Argument &Arg : F.args()) { 3686 IRPosition ArgPos = IRPosition::argument(Arg); 3687 3688 // Every argument might be simplified. 3689 getOrCreateAAFor<AAValueSimplify>(ArgPos); 3690 3691 if (Arg.getType()->isPointerTy()) { 3692 // Every argument with pointer type might be marked nonnull. 3693 getOrCreateAAFor<AANonNull>(ArgPos); 3694 3695 // Every argument with pointer type might be marked noalias. 3696 getOrCreateAAFor<AANoAlias>(ArgPos); 3697 3698 // Every argument with pointer type might be marked dereferenceable. 3699 getOrCreateAAFor<AADereferenceable>(ArgPos); 3700 3701 // Every argument with pointer type might be marked align. 3702 getOrCreateAAFor<AAAlign>(ArgPos); 3703 3704 // Every argument with pointer type might be marked nocapture. 3705 getOrCreateAAFor<AANoCapture>(ArgPos); 3706 } 3707 } 3708 3709 // Walk all instructions to find more attribute opportunities and also 3710 // interesting instructions that might be queried by abstract attributes 3711 // during their initialization or update. 3712 auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F]; 3713 auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F]; 3714 3715 for (Instruction &I : instructions(&F)) { 3716 bool IsInterestingOpcode = false; 3717 3718 // To allow easy access to all instructions in a function with a given 3719 // opcode we store them in the InfoCache. As not all opcodes are interesting 3720 // to concrete attributes we only cache the ones that are as identified in 3721 // the following switch. 3722 // Note: There are no concrete attributes now so this is initially empty. 3723 switch (I.getOpcode()) { 3724 default: 3725 assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) && 3726 "New call site/base instruction type needs to be known int the " 3727 "attributor."); 3728 break; 3729 case Instruction::Load: 3730 // The alignment of a pointer is interesting for loads. 3731 getOrCreateAAFor<AAAlign>( 3732 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 3733 break; 3734 case Instruction::Store: 3735 // The alignment of a pointer is interesting for stores. 3736 getOrCreateAAFor<AAAlign>( 3737 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 3738 break; 3739 case Instruction::Call: 3740 case Instruction::CallBr: 3741 case Instruction::Invoke: 3742 case Instruction::CleanupRet: 3743 case Instruction::CatchSwitch: 3744 case Instruction::Resume: 3745 case Instruction::Ret: 3746 IsInterestingOpcode = true; 3747 } 3748 if (IsInterestingOpcode) 3749 InstOpcodeMap[I.getOpcode()].push_back(&I); 3750 if (I.mayReadOrWriteMemory()) 3751 ReadOrWriteInsts.push_back(&I); 3752 3753 CallSite CS(&I); 3754 if (CS && CS.getCalledFunction()) { 3755 for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) { 3756 3757 IRPosition CSArgPos = IRPosition::callsite_argument(CS, i); 3758 3759 // Call site argument might be simplified. 3760 getOrCreateAAFor<AAValueSimplify>(CSArgPos); 3761 3762 if (!CS.getArgument(i)->getType()->isPointerTy()) 3763 continue; 3764 3765 // Call site argument attribute "non-null". 3766 getOrCreateAAFor<AANonNull>(CSArgPos); 3767 3768 // Call site argument attribute "no-alias". 3769 getOrCreateAAFor<AANoAlias>(CSArgPos); 3770 3771 // Call site argument attribute "dereferenceable". 3772 getOrCreateAAFor<AADereferenceable>(CSArgPos); 3773 3774 // Call site argument attribute "align". 3775 getOrCreateAAFor<AAAlign>(CSArgPos); 3776 } 3777 } 3778 } 3779 } 3780 3781 /// Helpers to ease debugging through output streams and print calls. 3782 /// 3783 ///{ 3784 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 3785 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 3786 } 3787 3788 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 3789 switch (AP) { 3790 case IRPosition::IRP_INVALID: 3791 return OS << "inv"; 3792 case IRPosition::IRP_FLOAT: 3793 return OS << "flt"; 3794 case IRPosition::IRP_RETURNED: 3795 return OS << "fn_ret"; 3796 case IRPosition::IRP_CALL_SITE_RETURNED: 3797 return OS << "cs_ret"; 3798 case IRPosition::IRP_FUNCTION: 3799 return OS << "fn"; 3800 case IRPosition::IRP_CALL_SITE: 3801 return OS << "cs"; 3802 case IRPosition::IRP_ARGUMENT: 3803 return OS << "arg"; 3804 case IRPosition::IRP_CALL_SITE_ARGUMENT: 3805 return OS << "cs_arg"; 3806 } 3807 llvm_unreachable("Unknown attribute position!"); 3808 } 3809 3810 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 3811 const Value &AV = Pos.getAssociatedValue(); 3812 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 3813 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 3814 } 3815 3816 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerState &S) { 3817 return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")" 3818 << static_cast<const AbstractState &>(S); 3819 } 3820 3821 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 3822 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 3823 } 3824 3825 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 3826 AA.print(OS); 3827 return OS; 3828 } 3829 3830 void AbstractAttribute::print(raw_ostream &OS) const { 3831 OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState() 3832 << "]"; 3833 } 3834 ///} 3835 3836 /// ---------------------------------------------------------------------------- 3837 /// Pass (Manager) Boilerplate 3838 /// ---------------------------------------------------------------------------- 3839 3840 static bool runAttributorOnModule(Module &M) { 3841 if (DisableAttributor) 3842 return false; 3843 3844 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size() 3845 << " functions.\n"); 3846 3847 // Create an Attributor and initially empty information cache that is filled 3848 // while we identify default attribute opportunities. 3849 InformationCache InfoCache(M.getDataLayout()); 3850 Attributor A(InfoCache, DepRecInterval); 3851 3852 for (Function &F : M) { 3853 if (F.hasExactDefinition()) 3854 NumFnWithExactDefinition++; 3855 else 3856 NumFnWithoutExactDefinition++; 3857 3858 // For now we ignore naked and optnone functions. 3859 if (F.hasFnAttribute(Attribute::Naked) || 3860 F.hasFnAttribute(Attribute::OptimizeNone)) 3861 continue; 3862 3863 // We look at internal functions only on-demand but if any use is not a 3864 // direct call, we have to do it eagerly. 3865 if (F.hasInternalLinkage()) { 3866 if (llvm::all_of(F.uses(), [](const Use &U) { 3867 return ImmutableCallSite(U.getUser()) && 3868 ImmutableCallSite(U.getUser()).isCallee(&U); 3869 })) 3870 continue; 3871 } 3872 3873 // Populate the Attributor with abstract attribute opportunities in the 3874 // function and the information cache with IR information. 3875 A.identifyDefaultAbstractAttributes(F); 3876 } 3877 3878 return A.run(M) == ChangeStatus::CHANGED; 3879 } 3880 3881 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 3882 if (runAttributorOnModule(M)) { 3883 // FIXME: Think about passes we will preserve and add them here. 3884 return PreservedAnalyses::none(); 3885 } 3886 return PreservedAnalyses::all(); 3887 } 3888 3889 namespace { 3890 3891 struct AttributorLegacyPass : public ModulePass { 3892 static char ID; 3893 3894 AttributorLegacyPass() : ModulePass(ID) { 3895 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 3896 } 3897 3898 bool runOnModule(Module &M) override { 3899 if (skipModule(M)) 3900 return false; 3901 return runAttributorOnModule(M); 3902 } 3903 3904 void getAnalysisUsage(AnalysisUsage &AU) const override { 3905 // FIXME: Think about passes we will preserve and add them here. 3906 } 3907 }; 3908 3909 } // end anonymous namespace 3910 3911 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 3912 3913 char AttributorLegacyPass::ID = 0; 3914 3915 const char AAReturnedValues::ID = 0; 3916 const char AANoUnwind::ID = 0; 3917 const char AANoSync::ID = 0; 3918 const char AANoFree::ID = 0; 3919 const char AANonNull::ID = 0; 3920 const char AANoRecurse::ID = 0; 3921 const char AAWillReturn::ID = 0; 3922 const char AANoAlias::ID = 0; 3923 const char AANoReturn::ID = 0; 3924 const char AAIsDead::ID = 0; 3925 const char AADereferenceable::ID = 0; 3926 const char AAAlign::ID = 0; 3927 const char AANoCapture::ID = 0; 3928 const char AAValueSimplify::ID = 0; 3929 3930 // Macro magic to create the static generator function for attributes that 3931 // follow the naming scheme. 3932 3933 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 3934 case IRPosition::PK: \ 3935 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 3936 3937 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 3938 case IRPosition::PK: \ 3939 AA = new CLASS##SUFFIX(IRP); \ 3940 break; 3941 3942 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 3943 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 3944 CLASS *AA = nullptr; \ 3945 switch (IRP.getPositionKind()) { \ 3946 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 3947 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 3948 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 3949 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 3950 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 3951 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 3952 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 3953 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 3954 } \ 3955 return *AA; \ 3956 } 3957 3958 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 3959 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 3960 CLASS *AA = nullptr; \ 3961 switch (IRP.getPositionKind()) { \ 3962 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 3963 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 3964 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 3965 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 3966 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 3967 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 3968 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 3969 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 3970 } \ 3971 return *AA; \ 3972 } 3973 3974 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 3975 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 3976 CLASS *AA = nullptr; \ 3977 switch (IRP.getPositionKind()) { \ 3978 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 3979 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 3980 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 3981 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 3982 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 3983 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 3984 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 3985 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 3986 } \ 3987 return *AA; \ 3988 } 3989 3990 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 3991 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 3992 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 3993 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 3994 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 3995 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 3996 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 3997 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 3998 3999 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 4000 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 4001 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 4002 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 4003 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture) 4004 4005 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify) 4006 4007 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 4008 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 4009 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 4010 #undef SWITCH_PK_CREATE 4011 #undef SWITCH_PK_INV 4012 4013 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 4014 "Deduce and propagate attributes", false, false) 4015 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 4016 "Deduce and propagate attributes", false, false) 4017