1 //===- AttributorAttributes.cpp - Attributes for Attributor 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 // See the Attributor.h file comment and the class descriptions in that file for 10 // more information. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/Attributor.h" 15 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/DenseMapInfo.h" 18 #include "llvm/ADT/MapVector.h" 19 #include "llvm/ADT/SCCIterator.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SetOperations.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/AssumeBundleQueries.h" 28 #include "llvm/Analysis/AssumptionCache.h" 29 #include "llvm/Analysis/CaptureTracking.h" 30 #include "llvm/Analysis/InstructionSimplify.h" 31 #include "llvm/Analysis/LazyValueInfo.h" 32 #include "llvm/Analysis/MemoryBuiltins.h" 33 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 34 #include "llvm/Analysis/ScalarEvolution.h" 35 #include "llvm/Analysis/TargetTransformInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/IR/Argument.h" 38 #include "llvm/IR/Assumptions.h" 39 #include "llvm/IR/BasicBlock.h" 40 #include "llvm/IR/Constant.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DataLayout.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/IRBuilder.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/NoFolder.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/IR/ValueHandle.h" 53 #include "llvm/Support/Alignment.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/ErrorHandling.h" 57 #include "llvm/Support/GraphWriter.h" 58 #include "llvm/Support/MathExtras.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Utils/Local.h" 61 #include "llvm/Transforms/Utils/ValueMapper.h" 62 #include <cassert> 63 64 using namespace llvm; 65 66 #define DEBUG_TYPE "attributor" 67 68 static cl::opt<bool> ManifestInternal( 69 "attributor-manifest-internal", cl::Hidden, 70 cl::desc("Manifest Attributor internal string attributes."), 71 cl::init(false)); 72 73 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128), 74 cl::Hidden); 75 76 template <> 77 unsigned llvm::PotentialConstantIntValuesState::MaxPotentialValues = 0; 78 79 template <> unsigned llvm::PotentialLLVMValuesState::MaxPotentialValues = -1; 80 81 static cl::opt<unsigned, true> MaxPotentialValues( 82 "attributor-max-potential-values", cl::Hidden, 83 cl::desc("Maximum number of potential values to be " 84 "tracked for each position."), 85 cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues), 86 cl::init(7)); 87 88 static cl::opt<int> MaxPotentialValuesIterations( 89 "attributor-max-potential-values-iterations", cl::Hidden, 90 cl::desc( 91 "Maximum number of iterations we keep dismantling potential values."), 92 cl::init(64)); 93 94 static cl::opt<unsigned> MaxInterferingAccesses( 95 "attributor-max-interfering-accesses", cl::Hidden, 96 cl::desc("Maximum number of interfering accesses to " 97 "check before assuming all might interfere."), 98 cl::init(6)); 99 100 STATISTIC(NumAAs, "Number of abstract attributes created"); 101 102 // Some helper macros to deal with statistics tracking. 103 // 104 // Usage: 105 // For simple IR attribute tracking overload trackStatistics in the abstract 106 // attribute and choose the right STATS_DECLTRACK_********* macro, 107 // e.g.,: 108 // void trackStatistics() const override { 109 // STATS_DECLTRACK_ARG_ATTR(returned) 110 // } 111 // If there is a single "increment" side one can use the macro 112 // STATS_DECLTRACK with a custom message. If there are multiple increment 113 // sides, STATS_DECL and STATS_TRACK can also be used separately. 114 // 115 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 116 ("Number of " #TYPE " marked '" #NAME "'") 117 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 118 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG); 119 #define STATS_DECL(NAME, TYPE, MSG) \ 120 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG); 121 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 122 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 123 { \ 124 STATS_DECL(NAME, TYPE, MSG) \ 125 STATS_TRACK(NAME, TYPE) \ 126 } 127 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 128 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 129 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 130 STATS_DECLTRACK(NAME, CSArguments, \ 131 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 132 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 133 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 134 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 135 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 136 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 137 STATS_DECLTRACK(NAME, FunctionReturn, \ 138 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 139 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 140 STATS_DECLTRACK(NAME, CSReturn, \ 141 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 142 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 143 STATS_DECLTRACK(NAME, Floating, \ 144 ("Number of floating values known to be '" #NAME "'")) 145 146 // Specialization of the operator<< for abstract attributes subclasses. This 147 // disambiguates situations where multiple operators are applicable. 148 namespace llvm { 149 #define PIPE_OPERATOR(CLASS) \ 150 raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \ 151 return OS << static_cast<const AbstractAttribute &>(AA); \ 152 } 153 154 PIPE_OPERATOR(AAIsDead) 155 PIPE_OPERATOR(AANoUnwind) 156 PIPE_OPERATOR(AANoSync) 157 PIPE_OPERATOR(AANoRecurse) 158 PIPE_OPERATOR(AAWillReturn) 159 PIPE_OPERATOR(AANoReturn) 160 PIPE_OPERATOR(AAReturnedValues) 161 PIPE_OPERATOR(AANonNull) 162 PIPE_OPERATOR(AANoAlias) 163 PIPE_OPERATOR(AADereferenceable) 164 PIPE_OPERATOR(AAAlign) 165 PIPE_OPERATOR(AAInstanceInfo) 166 PIPE_OPERATOR(AANoCapture) 167 PIPE_OPERATOR(AAValueSimplify) 168 PIPE_OPERATOR(AANoFree) 169 PIPE_OPERATOR(AAHeapToStack) 170 PIPE_OPERATOR(AAReachability) 171 PIPE_OPERATOR(AAMemoryBehavior) 172 PIPE_OPERATOR(AAMemoryLocation) 173 PIPE_OPERATOR(AAValueConstantRange) 174 PIPE_OPERATOR(AAPrivatizablePtr) 175 PIPE_OPERATOR(AAUndefinedBehavior) 176 PIPE_OPERATOR(AAPotentialConstantValues) 177 PIPE_OPERATOR(AAPotentialValues) 178 PIPE_OPERATOR(AANoUndef) 179 PIPE_OPERATOR(AACallEdges) 180 PIPE_OPERATOR(AAFunctionReachability) 181 PIPE_OPERATOR(AAPointerInfo) 182 PIPE_OPERATOR(AAAssumptionInfo) 183 184 #undef PIPE_OPERATOR 185 186 template <> 187 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S, 188 const DerefState &R) { 189 ChangeStatus CS0 = 190 clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState); 191 ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState); 192 return CS0 | CS1; 193 } 194 195 } // namespace llvm 196 197 /// Checks if a type could have padding bytes. 198 static bool isDenselyPacked(Type *Ty, const DataLayout &DL) { 199 // There is no size information, so be conservative. 200 if (!Ty->isSized()) 201 return false; 202 203 // If the alloc size is not equal to the storage size, then there are padding 204 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128. 205 if (DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty)) 206 return false; 207 208 // FIXME: This isn't the right way to check for padding in vectors with 209 // non-byte-size elements. 210 if (VectorType *SeqTy = dyn_cast<VectorType>(Ty)) 211 return isDenselyPacked(SeqTy->getElementType(), DL); 212 213 // For array types, check for padding within members. 214 if (ArrayType *SeqTy = dyn_cast<ArrayType>(Ty)) 215 return isDenselyPacked(SeqTy->getElementType(), DL); 216 217 if (!isa<StructType>(Ty)) 218 return true; 219 220 // Check for padding within and between elements of a struct. 221 StructType *StructTy = cast<StructType>(Ty); 222 const StructLayout *Layout = DL.getStructLayout(StructTy); 223 uint64_t StartPos = 0; 224 for (unsigned I = 0, E = StructTy->getNumElements(); I < E; ++I) { 225 Type *ElTy = StructTy->getElementType(I); 226 if (!isDenselyPacked(ElTy, DL)) 227 return false; 228 if (StartPos != Layout->getElementOffsetInBits(I)) 229 return false; 230 StartPos += DL.getTypeAllocSizeInBits(ElTy); 231 } 232 233 return true; 234 } 235 236 /// Get pointer operand of memory accessing instruction. If \p I is 237 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile, 238 /// is set to false and the instruction is volatile, return nullptr. 239 static const Value *getPointerOperand(const Instruction *I, 240 bool AllowVolatile) { 241 if (!AllowVolatile && I->isVolatile()) 242 return nullptr; 243 244 if (auto *LI = dyn_cast<LoadInst>(I)) { 245 return LI->getPointerOperand(); 246 } 247 248 if (auto *SI = dyn_cast<StoreInst>(I)) { 249 return SI->getPointerOperand(); 250 } 251 252 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) { 253 return CXI->getPointerOperand(); 254 } 255 256 if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) { 257 return RMWI->getPointerOperand(); 258 } 259 260 return nullptr; 261 } 262 263 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and 264 /// advanced by \p Offset bytes. To aid later analysis the method tries to build 265 /// getelement pointer instructions that traverse the natural type of \p Ptr if 266 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence 267 /// through a cast to i8*. 268 /// 269 /// TODO: This could probably live somewhere more prominantly if it doesn't 270 /// already exist. 271 static Value *constructPointer(Type *ResTy, Type *PtrElemTy, Value *Ptr, 272 int64_t Offset, IRBuilder<NoFolder> &IRB, 273 const DataLayout &DL) { 274 assert(Offset >= 0 && "Negative offset not supported yet!"); 275 LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset 276 << "-bytes as " << *ResTy << "\n"); 277 278 if (Offset) { 279 Type *Ty = PtrElemTy; 280 APInt IntOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), Offset); 281 SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(Ty, IntOffset); 282 283 SmallVector<Value *, 4> ValIndices; 284 std::string GEPName = Ptr->getName().str(); 285 for (const APInt &Index : IntIndices) { 286 ValIndices.push_back(IRB.getInt(Index)); 287 GEPName += "." + std::to_string(Index.getZExtValue()); 288 } 289 290 // Create a GEP for the indices collected above. 291 Ptr = IRB.CreateGEP(PtrElemTy, Ptr, ValIndices, GEPName); 292 293 // If an offset is left we use byte-wise adjustment. 294 if (IntOffset != 0) { 295 Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy()); 296 Ptr = IRB.CreateGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(IntOffset), 297 GEPName + ".b" + Twine(IntOffset.getZExtValue())); 298 } 299 } 300 301 // Ensure the result has the requested type. 302 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, ResTy, 303 Ptr->getName() + ".cast"); 304 305 LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n"); 306 return Ptr; 307 } 308 309 bool AA::getAssumedUnderlyingObjects(Attributor &A, const Value &Ptr, 310 SmallSetVector<Value *, 8> &Objects, 311 const AbstractAttribute &QueryingAA, 312 const Instruction *CtxI, 313 bool &UsedAssumedInformation, 314 AA::ValueScope S, 315 SmallPtrSetImpl<Value *> *SeenObjects) { 316 SmallPtrSet<Value *, 8> LocalSeenObjects; 317 if (!SeenObjects) 318 SeenObjects = &LocalSeenObjects; 319 320 SmallVector<AA::ValueAndContext> Values; 321 if (!A.getAssumedSimplifiedValues(IRPosition::value(Ptr), &QueryingAA, Values, 322 S, UsedAssumedInformation)) { 323 Objects.insert(const_cast<Value *>(&Ptr)); 324 return true; 325 } 326 327 for (auto &VAC : Values) { 328 Value *UO = getUnderlyingObject(VAC.getValue()); 329 if (UO && UO != VAC.getValue() && SeenObjects->insert(UO).second) { 330 if (!getAssumedUnderlyingObjects(A, *UO, Objects, QueryingAA, 331 VAC.getCtxI(), UsedAssumedInformation, S, 332 SeenObjects)) 333 return false; 334 continue; 335 } 336 Objects.insert(VAC.getValue()); 337 } 338 return true; 339 } 340 341 static const Value * 342 stripAndAccumulateOffsets(Attributor &A, const AbstractAttribute &QueryingAA, 343 const Value *Val, const DataLayout &DL, APInt &Offset, 344 bool GetMinOffset, bool AllowNonInbounds, 345 bool UseAssumed = false) { 346 347 auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool { 348 const IRPosition &Pos = IRPosition::value(V); 349 // Only track dependence if we are going to use the assumed info. 350 const AAValueConstantRange &ValueConstantRangeAA = 351 A.getAAFor<AAValueConstantRange>(QueryingAA, Pos, 352 UseAssumed ? DepClassTy::OPTIONAL 353 : DepClassTy::NONE); 354 ConstantRange Range = UseAssumed ? ValueConstantRangeAA.getAssumed() 355 : ValueConstantRangeAA.getKnown(); 356 if (Range.isFullSet()) 357 return false; 358 359 // We can only use the lower part of the range because the upper part can 360 // be higher than what the value can really be. 361 if (GetMinOffset) 362 ROffset = Range.getSignedMin(); 363 else 364 ROffset = Range.getSignedMax(); 365 return true; 366 }; 367 368 return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds, 369 /* AllowInvariant */ true, 370 AttributorAnalysis); 371 } 372 373 static const Value * 374 getMinimalBaseOfPointer(Attributor &A, const AbstractAttribute &QueryingAA, 375 const Value *Ptr, int64_t &BytesOffset, 376 const DataLayout &DL, bool AllowNonInbounds = false) { 377 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 378 const Value *Base = 379 stripAndAccumulateOffsets(A, QueryingAA, Ptr, DL, OffsetAPInt, 380 /* GetMinOffset */ true, AllowNonInbounds); 381 382 BytesOffset = OffsetAPInt.getSExtValue(); 383 return Base; 384 } 385 386 /// Clamp the information known for all returned values of a function 387 /// (identified by \p QueryingAA) into \p S. 388 template <typename AAType, typename StateType = typename AAType::StateType> 389 static void clampReturnedValueStates( 390 Attributor &A, const AAType &QueryingAA, StateType &S, 391 const IRPosition::CallBaseContext *CBContext = nullptr) { 392 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for " 393 << QueryingAA << " into " << S << "\n"); 394 395 assert((QueryingAA.getIRPosition().getPositionKind() == 396 IRPosition::IRP_RETURNED || 397 QueryingAA.getIRPosition().getPositionKind() == 398 IRPosition::IRP_CALL_SITE_RETURNED) && 399 "Can only clamp returned value states for a function returned or call " 400 "site returned position!"); 401 402 // Use an optional state as there might not be any return values and we want 403 // to join (IntegerState::operator&) the state of all there are. 404 Optional<StateType> T; 405 406 // Callback for each possibly returned value. 407 auto CheckReturnValue = [&](Value &RV) -> bool { 408 const IRPosition &RVPos = IRPosition::value(RV, CBContext); 409 const AAType &AA = 410 A.getAAFor<AAType>(QueryingAA, RVPos, DepClassTy::REQUIRED); 411 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr() 412 << " @ " << RVPos << "\n"); 413 const StateType &AAS = AA.getState(); 414 if (!T) 415 T = StateType::getBestState(AAS); 416 *T &= AAS; 417 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T 418 << "\n"); 419 return T->isValidState(); 420 }; 421 422 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA)) 423 S.indicatePessimisticFixpoint(); 424 else if (T) 425 S ^= *T; 426 } 427 428 namespace { 429 /// Helper class for generic deduction: return value -> returned position. 430 template <typename AAType, typename BaseType, 431 typename StateType = typename BaseType::StateType, 432 bool PropagateCallBaseContext = false> 433 struct AAReturnedFromReturnedValues : public BaseType { 434 AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A) 435 : BaseType(IRP, A) {} 436 437 /// See AbstractAttribute::updateImpl(...). 438 ChangeStatus updateImpl(Attributor &A) override { 439 StateType S(StateType::getBestState(this->getState())); 440 clampReturnedValueStates<AAType, StateType>( 441 A, *this, S, 442 PropagateCallBaseContext ? this->getCallBaseContext() : nullptr); 443 // TODO: If we know we visited all returned values, thus no are assumed 444 // dead, we can take the known information from the state T. 445 return clampStateAndIndicateChange<StateType>(this->getState(), S); 446 } 447 }; 448 449 /// Clamp the information known at all call sites for a given argument 450 /// (identified by \p QueryingAA) into \p S. 451 template <typename AAType, typename StateType = typename AAType::StateType> 452 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA, 453 StateType &S) { 454 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for " 455 << QueryingAA << " into " << S << "\n"); 456 457 assert(QueryingAA.getIRPosition().getPositionKind() == 458 IRPosition::IRP_ARGUMENT && 459 "Can only clamp call site argument states for an argument position!"); 460 461 // Use an optional state as there might not be any return values and we want 462 // to join (IntegerState::operator&) the state of all there are. 463 Optional<StateType> T; 464 465 // The argument number which is also the call site argument number. 466 unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo(); 467 468 auto CallSiteCheck = [&](AbstractCallSite ACS) { 469 const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo); 470 // Check if a coresponding argument was found or if it is on not associated 471 // (which can happen for callback calls). 472 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 473 return false; 474 475 const AAType &AA = 476 A.getAAFor<AAType>(QueryingAA, ACSArgPos, DepClassTy::REQUIRED); 477 LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction() 478 << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n"); 479 const StateType &AAS = AA.getState(); 480 if (!T) 481 T = StateType::getBestState(AAS); 482 *T &= AAS; 483 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T 484 << "\n"); 485 return T->isValidState(); 486 }; 487 488 bool UsedAssumedInformation = false; 489 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true, 490 UsedAssumedInformation)) 491 S.indicatePessimisticFixpoint(); 492 else if (T) 493 S ^= *T; 494 } 495 496 /// This function is the bridge between argument position and the call base 497 /// context. 498 template <typename AAType, typename BaseType, 499 typename StateType = typename AAType::StateType> 500 bool getArgumentStateFromCallBaseContext(Attributor &A, 501 BaseType &QueryingAttribute, 502 IRPosition &Pos, StateType &State) { 503 assert((Pos.getPositionKind() == IRPosition::IRP_ARGUMENT) && 504 "Expected an 'argument' position !"); 505 const CallBase *CBContext = Pos.getCallBaseContext(); 506 if (!CBContext) 507 return false; 508 509 int ArgNo = Pos.getCallSiteArgNo(); 510 assert(ArgNo >= 0 && "Invalid Arg No!"); 511 512 const auto &AA = A.getAAFor<AAType>( 513 QueryingAttribute, IRPosition::callsite_argument(*CBContext, ArgNo), 514 DepClassTy::REQUIRED); 515 const StateType &CBArgumentState = 516 static_cast<const StateType &>(AA.getState()); 517 518 LLVM_DEBUG(dbgs() << "[Attributor] Briding Call site context to argument" 519 << "Position:" << Pos << "CB Arg state:" << CBArgumentState 520 << "\n"); 521 522 // NOTE: If we want to do call site grouping it should happen here. 523 State ^= CBArgumentState; 524 return true; 525 } 526 527 /// Helper class for generic deduction: call site argument -> argument position. 528 template <typename AAType, typename BaseType, 529 typename StateType = typename AAType::StateType, 530 bool BridgeCallBaseContext = false> 531 struct AAArgumentFromCallSiteArguments : public BaseType { 532 AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A) 533 : BaseType(IRP, A) {} 534 535 /// See AbstractAttribute::updateImpl(...). 536 ChangeStatus updateImpl(Attributor &A) override { 537 StateType S = StateType::getBestState(this->getState()); 538 539 if (BridgeCallBaseContext) { 540 bool Success = 541 getArgumentStateFromCallBaseContext<AAType, BaseType, StateType>( 542 A, *this, this->getIRPosition(), S); 543 if (Success) 544 return clampStateAndIndicateChange<StateType>(this->getState(), S); 545 } 546 clampCallSiteArgumentStates<AAType, StateType>(A, *this, S); 547 548 // TODO: If we know we visited all incoming values, thus no are assumed 549 // dead, we can take the known information from the state T. 550 return clampStateAndIndicateChange<StateType>(this->getState(), S); 551 } 552 }; 553 554 /// Helper class for generic replication: function returned -> cs returned. 555 template <typename AAType, typename BaseType, 556 typename StateType = typename BaseType::StateType, 557 bool IntroduceCallBaseContext = false> 558 struct AACallSiteReturnedFromReturned : public BaseType { 559 AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A) 560 : BaseType(IRP, A) {} 561 562 /// See AbstractAttribute::updateImpl(...). 563 ChangeStatus updateImpl(Attributor &A) override { 564 assert(this->getIRPosition().getPositionKind() == 565 IRPosition::IRP_CALL_SITE_RETURNED && 566 "Can only wrap function returned positions for call site returned " 567 "positions!"); 568 auto &S = this->getState(); 569 570 const Function *AssociatedFunction = 571 this->getIRPosition().getAssociatedFunction(); 572 if (!AssociatedFunction) 573 return S.indicatePessimisticFixpoint(); 574 575 CallBase &CBContext = cast<CallBase>(this->getAnchorValue()); 576 if (IntroduceCallBaseContext) 577 LLVM_DEBUG(dbgs() << "[Attributor] Introducing call base context:" 578 << CBContext << "\n"); 579 580 IRPosition FnPos = IRPosition::returned( 581 *AssociatedFunction, IntroduceCallBaseContext ? &CBContext : nullptr); 582 const AAType &AA = A.getAAFor<AAType>(*this, FnPos, DepClassTy::REQUIRED); 583 return clampStateAndIndicateChange(S, AA.getState()); 584 } 585 }; 586 587 /// Helper function to accumulate uses. 588 template <class AAType, typename StateType = typename AAType::StateType> 589 static void followUsesInContext(AAType &AA, Attributor &A, 590 MustBeExecutedContextExplorer &Explorer, 591 const Instruction *CtxI, 592 SetVector<const Use *> &Uses, 593 StateType &State) { 594 auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI); 595 for (unsigned u = 0; u < Uses.size(); ++u) { 596 const Use *U = Uses[u]; 597 if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) { 598 bool Found = Explorer.findInContextOf(UserI, EIt, EEnd); 599 if (Found && AA.followUseInMBEC(A, U, UserI, State)) 600 for (const Use &Us : UserI->uses()) 601 Uses.insert(&Us); 602 } 603 } 604 } 605 606 /// Use the must-be-executed-context around \p I to add information into \p S. 607 /// The AAType class is required to have `followUseInMBEC` method with the 608 /// following signature and behaviour: 609 /// 610 /// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I) 611 /// U - Underlying use. 612 /// I - The user of the \p U. 613 /// Returns true if the value should be tracked transitively. 614 /// 615 template <class AAType, typename StateType = typename AAType::StateType> 616 static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S, 617 Instruction &CtxI) { 618 619 // Container for (transitive) uses of the associated value. 620 SetVector<const Use *> Uses; 621 for (const Use &U : AA.getIRPosition().getAssociatedValue().uses()) 622 Uses.insert(&U); 623 624 MustBeExecutedContextExplorer &Explorer = 625 A.getInfoCache().getMustBeExecutedContextExplorer(); 626 627 followUsesInContext<AAType>(AA, A, Explorer, &CtxI, Uses, S); 628 629 if (S.isAtFixpoint()) 630 return; 631 632 SmallVector<const BranchInst *, 4> BrInsts; 633 auto Pred = [&](const Instruction *I) { 634 if (const BranchInst *Br = dyn_cast<BranchInst>(I)) 635 if (Br->isConditional()) 636 BrInsts.push_back(Br); 637 return true; 638 }; 639 640 // Here, accumulate conditional branch instructions in the context. We 641 // explore the child paths and collect the known states. The disjunction of 642 // those states can be merged to its own state. Let ParentState_i be a state 643 // to indicate the known information for an i-th branch instruction in the 644 // context. ChildStates are created for its successors respectively. 645 // 646 // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1} 647 // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2} 648 // ... 649 // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m} 650 // 651 // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m 652 // 653 // FIXME: Currently, recursive branches are not handled. For example, we 654 // can't deduce that ptr must be dereferenced in below function. 655 // 656 // void f(int a, int c, int *ptr) { 657 // if(a) 658 // if (b) { 659 // *ptr = 0; 660 // } else { 661 // *ptr = 1; 662 // } 663 // else { 664 // if (b) { 665 // *ptr = 0; 666 // } else { 667 // *ptr = 1; 668 // } 669 // } 670 // } 671 672 Explorer.checkForAllContext(&CtxI, Pred); 673 for (const BranchInst *Br : BrInsts) { 674 StateType ParentState; 675 676 // The known state of the parent state is a conjunction of children's 677 // known states so it is initialized with a best state. 678 ParentState.indicateOptimisticFixpoint(); 679 680 for (const BasicBlock *BB : Br->successors()) { 681 StateType ChildState; 682 683 size_t BeforeSize = Uses.size(); 684 followUsesInContext(AA, A, Explorer, &BB->front(), Uses, ChildState); 685 686 // Erase uses which only appear in the child. 687 for (auto It = Uses.begin() + BeforeSize; It != Uses.end();) 688 It = Uses.erase(It); 689 690 ParentState &= ChildState; 691 } 692 693 // Use only known state. 694 S += ParentState; 695 } 696 } 697 } // namespace 698 699 /// ------------------------ PointerInfo --------------------------------------- 700 701 namespace llvm { 702 namespace AA { 703 namespace PointerInfo { 704 705 struct State; 706 707 } // namespace PointerInfo 708 } // namespace AA 709 710 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage. 711 template <> 712 struct DenseMapInfo<AAPointerInfo::Access> : DenseMapInfo<Instruction *> { 713 using Access = AAPointerInfo::Access; 714 static inline Access getEmptyKey(); 715 static inline Access getTombstoneKey(); 716 static unsigned getHashValue(const Access &A); 717 static bool isEqual(const Access &LHS, const Access &RHS); 718 }; 719 720 /// Helper that allows OffsetAndSize as a key in a DenseMap. 721 template <> 722 struct DenseMapInfo<AAPointerInfo ::OffsetAndSize> 723 : DenseMapInfo<std::pair<int64_t, int64_t>> {}; 724 725 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage ignoring everythign 726 /// but the instruction 727 struct AccessAsInstructionInfo : DenseMapInfo<Instruction *> { 728 using Base = DenseMapInfo<Instruction *>; 729 using Access = AAPointerInfo::Access; 730 static inline Access getEmptyKey(); 731 static inline Access getTombstoneKey(); 732 static unsigned getHashValue(const Access &A); 733 static bool isEqual(const Access &LHS, const Access &RHS); 734 }; 735 736 } // namespace llvm 737 738 /// A type to track pointer/struct usage and accesses for AAPointerInfo. 739 struct AA::PointerInfo::State : public AbstractState { 740 741 ~State() { 742 // We do not delete the Accesses objects but need to destroy them still. 743 for (auto &It : AccessBins) 744 It.second->~Accesses(); 745 } 746 747 /// Return the best possible representable state. 748 static State getBestState(const State &SIS) { return State(); } 749 750 /// Return the worst possible representable state. 751 static State getWorstState(const State &SIS) { 752 State R; 753 R.indicatePessimisticFixpoint(); 754 return R; 755 } 756 757 State() = default; 758 State(State &&SIS) : AccessBins(std::move(SIS.AccessBins)) { 759 SIS.AccessBins.clear(); 760 } 761 762 const State &getAssumed() const { return *this; } 763 764 /// See AbstractState::isValidState(). 765 bool isValidState() const override { return BS.isValidState(); } 766 767 /// See AbstractState::isAtFixpoint(). 768 bool isAtFixpoint() const override { return BS.isAtFixpoint(); } 769 770 /// See AbstractState::indicateOptimisticFixpoint(). 771 ChangeStatus indicateOptimisticFixpoint() override { 772 BS.indicateOptimisticFixpoint(); 773 return ChangeStatus::UNCHANGED; 774 } 775 776 /// See AbstractState::indicatePessimisticFixpoint(). 777 ChangeStatus indicatePessimisticFixpoint() override { 778 BS.indicatePessimisticFixpoint(); 779 return ChangeStatus::CHANGED; 780 } 781 782 State &operator=(const State &R) { 783 if (this == &R) 784 return *this; 785 BS = R.BS; 786 AccessBins = R.AccessBins; 787 return *this; 788 } 789 790 State &operator=(State &&R) { 791 if (this == &R) 792 return *this; 793 std::swap(BS, R.BS); 794 std::swap(AccessBins, R.AccessBins); 795 return *this; 796 } 797 798 bool operator==(const State &R) const { 799 if (BS != R.BS) 800 return false; 801 if (AccessBins.size() != R.AccessBins.size()) 802 return false; 803 auto It = begin(), RIt = R.begin(), E = end(); 804 while (It != E) { 805 if (It->getFirst() != RIt->getFirst()) 806 return false; 807 auto &Accs = It->getSecond(); 808 auto &RAccs = RIt->getSecond(); 809 if (Accs->size() != RAccs->size()) 810 return false; 811 for (const auto &ZipIt : llvm::zip(*Accs, *RAccs)) 812 if (std::get<0>(ZipIt) != std::get<1>(ZipIt)) 813 return false; 814 ++It; 815 ++RIt; 816 } 817 return true; 818 } 819 bool operator!=(const State &R) const { return !(*this == R); } 820 821 /// We store accesses in a set with the instruction as key. 822 struct Accesses { 823 SmallVector<AAPointerInfo::Access, 4> Accesses; 824 DenseMap<const Instruction *, unsigned> Map; 825 826 unsigned size() const { return Accesses.size(); } 827 828 using vec_iterator = decltype(Accesses)::iterator; 829 vec_iterator begin() { return Accesses.begin(); } 830 vec_iterator end() { return Accesses.end(); } 831 832 using iterator = decltype(Map)::const_iterator; 833 iterator find(AAPointerInfo::Access &Acc) { 834 return Map.find(Acc.getRemoteInst()); 835 } 836 iterator find_end() { return Map.end(); } 837 838 AAPointerInfo::Access &get(iterator &It) { 839 return Accesses[It->getSecond()]; 840 } 841 842 void insert(AAPointerInfo::Access &Acc) { 843 Map[Acc.getRemoteInst()] = Accesses.size(); 844 Accesses.push_back(Acc); 845 } 846 }; 847 848 /// We store all accesses in bins denoted by their offset and size. 849 using AccessBinsTy = DenseMap<AAPointerInfo::OffsetAndSize, Accesses *>; 850 851 AccessBinsTy::const_iterator begin() const { return AccessBins.begin(); } 852 AccessBinsTy::const_iterator end() const { return AccessBins.end(); } 853 854 protected: 855 /// The bins with all the accesses for the associated pointer. 856 AccessBinsTy AccessBins; 857 858 /// Add a new access to the state at offset \p Offset and with size \p Size. 859 /// The access is associated with \p I, writes \p Content (if anything), and 860 /// is of kind \p Kind. 861 /// \Returns CHANGED, if the state changed, UNCHANGED otherwise. 862 ChangeStatus addAccess(Attributor &A, int64_t Offset, int64_t Size, 863 Instruction &I, Optional<Value *> Content, 864 AAPointerInfo::AccessKind Kind, Type *Ty, 865 Instruction *RemoteI = nullptr, 866 Accesses *BinPtr = nullptr) { 867 AAPointerInfo::OffsetAndSize Key{Offset, Size}; 868 Accesses *&Bin = BinPtr ? BinPtr : AccessBins[Key]; 869 if (!Bin) 870 Bin = new (A.Allocator) Accesses; 871 AAPointerInfo::Access Acc(&I, RemoteI ? RemoteI : &I, Content, Kind, Ty); 872 // Check if we have an access for this instruction in this bin, if not, 873 // simply add it. 874 auto It = Bin->find(Acc); 875 if (It == Bin->find_end()) { 876 Bin->insert(Acc); 877 return ChangeStatus::CHANGED; 878 } 879 // If the existing access is the same as then new one, nothing changed. 880 AAPointerInfo::Access &Current = Bin->get(It); 881 AAPointerInfo::Access Before = Current; 882 // The new one will be combined with the existing one. 883 Current &= Acc; 884 return Current == Before ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED; 885 } 886 887 /// See AAPointerInfo::forallInterferingAccesses. 888 bool forallInterferingAccesses( 889 AAPointerInfo::OffsetAndSize OAS, 890 function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const { 891 if (!isValidState()) 892 return false; 893 894 for (auto &It : AccessBins) { 895 AAPointerInfo::OffsetAndSize ItOAS = It.getFirst(); 896 if (!OAS.mayOverlap(ItOAS)) 897 continue; 898 bool IsExact = OAS == ItOAS && !OAS.offsetOrSizeAreUnknown(); 899 for (auto &Access : *It.getSecond()) 900 if (!CB(Access, IsExact)) 901 return false; 902 } 903 return true; 904 } 905 906 /// See AAPointerInfo::forallInterferingAccesses. 907 bool forallInterferingAccesses( 908 Instruction &I, 909 function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const { 910 if (!isValidState()) 911 return false; 912 913 // First find the offset and size of I. 914 AAPointerInfo::OffsetAndSize OAS(-1, -1); 915 for (auto &It : AccessBins) { 916 for (auto &Access : *It.getSecond()) { 917 if (Access.getRemoteInst() == &I) { 918 OAS = It.getFirst(); 919 break; 920 } 921 } 922 if (OAS.getSize() != -1) 923 break; 924 } 925 // No access for I was found, we are done. 926 if (OAS.getSize() == -1) 927 return true; 928 929 // Now that we have an offset and size, find all overlapping ones and use 930 // the callback on the accesses. 931 return forallInterferingAccesses(OAS, CB); 932 } 933 934 private: 935 /// State to track fixpoint and validity. 936 BooleanState BS; 937 }; 938 939 namespace { 940 struct AAPointerInfoImpl 941 : public StateWrapper<AA::PointerInfo::State, AAPointerInfo> { 942 using BaseTy = StateWrapper<AA::PointerInfo::State, AAPointerInfo>; 943 AAPointerInfoImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {} 944 945 /// See AbstractAttribute::getAsStr(). 946 const std::string getAsStr() const override { 947 return std::string("PointerInfo ") + 948 (isValidState() ? (std::string("#") + 949 std::to_string(AccessBins.size()) + " bins") 950 : "<invalid>"); 951 } 952 953 /// See AbstractAttribute::manifest(...). 954 ChangeStatus manifest(Attributor &A) override { 955 return AAPointerInfo::manifest(A); 956 } 957 958 bool forallInterferingAccesses( 959 OffsetAndSize OAS, 960 function_ref<bool(const AAPointerInfo::Access &, bool)> CB) 961 const override { 962 return State::forallInterferingAccesses(OAS, CB); 963 } 964 965 bool 966 forallInterferingAccesses(Attributor &A, const AbstractAttribute &QueryingAA, 967 Instruction &I, 968 function_ref<bool(const Access &, bool)> UserCB, 969 bool &HasBeenWrittenTo) const override { 970 HasBeenWrittenTo = false; 971 972 SmallPtrSet<const Access *, 8> DominatingWrites; 973 SmallVector<std::pair<const Access *, bool>, 8> InterferingAccesses; 974 975 Function &Scope = *I.getFunction(); 976 const auto &NoSyncAA = A.getAAFor<AANoSync>( 977 QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL); 978 const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>( 979 IRPosition::function(Scope), &QueryingAA, DepClassTy::OPTIONAL); 980 const bool NoSync = NoSyncAA.isAssumedNoSync(); 981 982 // Helper to determine if we need to consider threading, which we cannot 983 // right now. However, if the function is (assumed) nosync or the thread 984 // executing all instructions is the main thread only we can ignore 985 // threading. 986 auto CanIgnoreThreading = [&](const Instruction &I) -> bool { 987 if (NoSync) 988 return true; 989 if (ExecDomainAA && ExecDomainAA->isExecutedByInitialThreadOnly(I)) 990 return true; 991 return false; 992 }; 993 994 // Helper to determine if the access is executed by the same thread as the 995 // load, for now it is sufficient to avoid any potential threading effects 996 // as we cannot deal with them anyway. 997 auto IsSameThreadAsLoad = [&](const Access &Acc) -> bool { 998 return CanIgnoreThreading(*Acc.getLocalInst()); 999 }; 1000 1001 // TODO: Use inter-procedural reachability and dominance. 1002 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 1003 QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL); 1004 1005 const bool FindInterferingWrites = I.mayReadFromMemory(); 1006 const bool FindInterferingReads = I.mayWriteToMemory(); 1007 const bool UseDominanceReasoning = 1008 FindInterferingWrites && NoRecurseAA.isKnownNoRecurse(); 1009 const bool CanUseCFGResoning = CanIgnoreThreading(I); 1010 InformationCache &InfoCache = A.getInfoCache(); 1011 const DominatorTree *DT = 1012 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(Scope); 1013 1014 enum GPUAddressSpace : unsigned { 1015 Generic = 0, 1016 Global = 1, 1017 Shared = 3, 1018 Constant = 4, 1019 Local = 5, 1020 }; 1021 1022 // Helper to check if a value has "kernel lifetime", that is it will not 1023 // outlive a GPU kernel. This is true for shared, constant, and local 1024 // globals on AMD and NVIDIA GPUs. 1025 auto HasKernelLifetime = [&](Value *V, Module &M) { 1026 Triple T(M.getTargetTriple()); 1027 if (!(T.isAMDGPU() || T.isNVPTX())) 1028 return false; 1029 switch (V->getType()->getPointerAddressSpace()) { 1030 case GPUAddressSpace::Shared: 1031 case GPUAddressSpace::Constant: 1032 case GPUAddressSpace::Local: 1033 return true; 1034 default: 1035 return false; 1036 }; 1037 }; 1038 1039 // The IsLiveInCalleeCB will be used by the AA::isPotentiallyReachable query 1040 // to determine if we should look at reachability from the callee. For 1041 // certain pointers we know the lifetime and we do not have to step into the 1042 // callee to determine reachability as the pointer would be dead in the 1043 // callee. See the conditional initialization below. 1044 std::function<bool(const Function &)> IsLiveInCalleeCB; 1045 1046 if (auto *AI = dyn_cast<AllocaInst>(&getAssociatedValue())) { 1047 // If the alloca containing function is not recursive the alloca 1048 // must be dead in the callee. 1049 const Function *AIFn = AI->getFunction(); 1050 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 1051 *this, IRPosition::function(*AIFn), DepClassTy::OPTIONAL); 1052 if (NoRecurseAA.isAssumedNoRecurse()) { 1053 IsLiveInCalleeCB = [AIFn](const Function &Fn) { return AIFn != &Fn; }; 1054 } 1055 } else if (auto *GV = dyn_cast<GlobalValue>(&getAssociatedValue())) { 1056 // If the global has kernel lifetime we can stop if we reach a kernel 1057 // as it is "dead" in the (unknown) callees. 1058 if (HasKernelLifetime(GV, *GV->getParent())) 1059 IsLiveInCalleeCB = [](const Function &Fn) { 1060 return !Fn.hasFnAttribute("kernel"); 1061 }; 1062 } 1063 1064 auto AccessCB = [&](const Access &Acc, bool Exact) { 1065 if ((!FindInterferingWrites || !Acc.isWrite()) && 1066 (!FindInterferingReads || !Acc.isRead())) 1067 return true; 1068 1069 bool Dominates = DT && Exact && Acc.isMustAccess() && 1070 (Acc.getLocalInst()->getFunction() == &Scope) && 1071 DT->dominates(Acc.getRemoteInst(), &I); 1072 if (Dominates) 1073 HasBeenWrittenTo = true; 1074 1075 // For now we only filter accesses based on CFG reasoning which does not 1076 // work yet if we have threading effects, or the access is complicated. 1077 if (CanUseCFGResoning && Dominates && UseDominanceReasoning && 1078 IsSameThreadAsLoad(Acc)) 1079 DominatingWrites.insert(&Acc); 1080 1081 InterferingAccesses.push_back({&Acc, Exact}); 1082 return true; 1083 }; 1084 if (!State::forallInterferingAccesses(I, AccessCB)) 1085 return false; 1086 1087 if (HasBeenWrittenTo) { 1088 const Function *ScopePtr = &Scope; 1089 IsLiveInCalleeCB = [ScopePtr](const Function &Fn) { 1090 return ScopePtr != &Fn; 1091 }; 1092 } 1093 1094 // Helper to determine if we can skip a specific write access. This is in 1095 // the worst case quadratic as we are looking for another write that will 1096 // hide the effect of this one. 1097 auto CanSkipAccess = [&](const Access &Acc, bool Exact) { 1098 if ((!Acc.isWrite() || 1099 !AA::isPotentiallyReachable(A, *Acc.getLocalInst(), I, QueryingAA, 1100 IsLiveInCalleeCB)) && 1101 (!Acc.isRead() || 1102 !AA::isPotentiallyReachable(A, I, *Acc.getLocalInst(), QueryingAA, 1103 IsLiveInCalleeCB))) 1104 return true; 1105 1106 if (!DT || !UseDominanceReasoning) 1107 return false; 1108 if (!IsSameThreadAsLoad(Acc)) 1109 return false; 1110 if (!DominatingWrites.count(&Acc)) 1111 return false; 1112 for (const Access *DomAcc : DominatingWrites) { 1113 assert(Acc.getLocalInst()->getFunction() == 1114 DomAcc->getLocalInst()->getFunction() && 1115 "Expected dominating writes to be in the same function!"); 1116 1117 if (DomAcc != &Acc && 1118 DT->dominates(Acc.getLocalInst(), DomAcc->getLocalInst())) { 1119 return true; 1120 } 1121 } 1122 return false; 1123 }; 1124 1125 // Run the user callback on all accesses we cannot skip and return if that 1126 // succeeded for all or not. 1127 unsigned NumInterferingAccesses = InterferingAccesses.size(); 1128 for (auto &It : InterferingAccesses) { 1129 if (NumInterferingAccesses > MaxInterferingAccesses || 1130 !CanSkipAccess(*It.first, It.second)) { 1131 if (!UserCB(*It.first, It.second)) 1132 return false; 1133 } 1134 } 1135 return true; 1136 } 1137 1138 ChangeStatus translateAndAddState(Attributor &A, const AAPointerInfo &OtherAA, 1139 int64_t Offset, CallBase &CB, 1140 bool FromCallee = false) { 1141 using namespace AA::PointerInfo; 1142 if (!OtherAA.getState().isValidState() || !isValidState()) 1143 return indicatePessimisticFixpoint(); 1144 1145 const auto &OtherAAImpl = static_cast<const AAPointerInfoImpl &>(OtherAA); 1146 bool IsByval = 1147 FromCallee && OtherAAImpl.getAssociatedArgument()->hasByValAttr(); 1148 1149 // Combine the accesses bin by bin. 1150 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1151 for (auto &It : OtherAAImpl.getState()) { 1152 OffsetAndSize OAS = OffsetAndSize::getUnknown(); 1153 if (Offset != OffsetAndSize::Unknown) 1154 OAS = OffsetAndSize(It.first.getOffset() + Offset, It.first.getSize()); 1155 Accesses *Bin = AccessBins.lookup(OAS); 1156 for (const AAPointerInfo::Access &RAcc : *It.second) { 1157 if (IsByval && !RAcc.isRead()) 1158 continue; 1159 bool UsedAssumedInformation = false; 1160 AccessKind AK = RAcc.getKind(); 1161 Optional<Value *> Content = RAcc.getContent(); 1162 if (FromCallee) { 1163 Content = A.translateArgumentToCallSiteContent( 1164 RAcc.getContent(), CB, *this, UsedAssumedInformation); 1165 AK = 1166 AccessKind(AK & (IsByval ? AccessKind::AK_R : AccessKind::AK_RW)); 1167 AK = AccessKind(AK | (RAcc.isMayAccess() ? AK_MAY : AK_MUST)); 1168 } 1169 Changed = 1170 Changed | addAccess(A, OAS.getOffset(), OAS.getSize(), CB, Content, 1171 AK, RAcc.getType(), RAcc.getRemoteInst(), Bin); 1172 } 1173 } 1174 return Changed; 1175 } 1176 1177 /// Statistic tracking for all AAPointerInfo implementations. 1178 /// See AbstractAttribute::trackStatistics(). 1179 void trackPointerInfoStatistics(const IRPosition &IRP) const {} 1180 1181 /// Dump the state into \p O. 1182 void dumpState(raw_ostream &O) { 1183 for (auto &It : AccessBins) { 1184 O << "[" << It.first.getOffset() << "-" 1185 << It.first.getOffset() + It.first.getSize() 1186 << "] : " << It.getSecond()->size() << "\n"; 1187 for (auto &Acc : *It.getSecond()) { 1188 O << " - " << Acc.getKind() << " - " << *Acc.getLocalInst() << "\n"; 1189 if (Acc.getLocalInst() != Acc.getRemoteInst()) 1190 O << " --> " << *Acc.getRemoteInst() 1191 << "\n"; 1192 if (!Acc.isWrittenValueYetUndetermined()) { 1193 if (Acc.getWrittenValue()) 1194 O << " - c: " << *Acc.getWrittenValue() << "\n"; 1195 else 1196 O << " - c: <unknown>\n"; 1197 } 1198 } 1199 } 1200 } 1201 }; 1202 1203 struct AAPointerInfoFloating : public AAPointerInfoImpl { 1204 using AccessKind = AAPointerInfo::AccessKind; 1205 AAPointerInfoFloating(const IRPosition &IRP, Attributor &A) 1206 : AAPointerInfoImpl(IRP, A) {} 1207 1208 /// Deal with an access and signal if it was handled successfully. 1209 bool handleAccess(Attributor &A, Instruction &I, Value &Ptr, 1210 Optional<Value *> Content, AccessKind Kind, int64_t Offset, 1211 ChangeStatus &Changed, Type *Ty, 1212 int64_t Size = OffsetAndSize::Unknown) { 1213 using namespace AA::PointerInfo; 1214 // No need to find a size if one is given or the offset is unknown. 1215 if (Offset != OffsetAndSize::Unknown && Size == OffsetAndSize::Unknown && 1216 Ty) { 1217 const DataLayout &DL = A.getDataLayout(); 1218 TypeSize AccessSize = DL.getTypeStoreSize(Ty); 1219 if (!AccessSize.isScalable()) 1220 Size = AccessSize.getFixedSize(); 1221 } 1222 Changed = Changed | addAccess(A, Offset, Size, I, Content, Kind, Ty); 1223 return true; 1224 }; 1225 1226 /// Helper struct, will support ranges eventually. 1227 struct OffsetInfo { 1228 int64_t Offset = OffsetAndSize::Unknown; 1229 1230 bool operator==(const OffsetInfo &OI) const { return Offset == OI.Offset; } 1231 }; 1232 1233 /// See AbstractAttribute::updateImpl(...). 1234 ChangeStatus updateImpl(Attributor &A) override { 1235 using namespace AA::PointerInfo; 1236 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1237 Value &AssociatedValue = getAssociatedValue(); 1238 1239 const DataLayout &DL = A.getDataLayout(); 1240 DenseMap<Value *, OffsetInfo> OffsetInfoMap; 1241 OffsetInfoMap[&AssociatedValue] = OffsetInfo{0}; 1242 1243 auto HandlePassthroughUser = [&](Value *Usr, OffsetInfo PtrOI, 1244 bool &Follow) { 1245 OffsetInfo &UsrOI = OffsetInfoMap[Usr]; 1246 UsrOI = PtrOI; 1247 Follow = true; 1248 return true; 1249 }; 1250 1251 const auto *TLI = getAnchorScope() 1252 ? A.getInfoCache().getTargetLibraryInfoForFunction( 1253 *getAnchorScope()) 1254 : nullptr; 1255 auto UsePred = [&](const Use &U, bool &Follow) -> bool { 1256 Value *CurPtr = U.get(); 1257 User *Usr = U.getUser(); 1258 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Analyze " << *CurPtr << " in " 1259 << *Usr << "\n"); 1260 assert(OffsetInfoMap.count(CurPtr) && 1261 "The current pointer offset should have been seeded!"); 1262 1263 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Usr)) { 1264 if (CE->isCast()) 1265 return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow); 1266 if (CE->isCompare()) 1267 return true; 1268 if (!isa<GEPOperator>(CE)) { 1269 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled constant user " << *CE 1270 << "\n"); 1271 return false; 1272 } 1273 } 1274 if (auto *GEP = dyn_cast<GEPOperator>(Usr)) { 1275 // Note the order here, the Usr access might change the map, CurPtr is 1276 // already in it though. 1277 OffsetInfo &UsrOI = OffsetInfoMap[Usr]; 1278 OffsetInfo &PtrOI = OffsetInfoMap[CurPtr]; 1279 UsrOI = PtrOI; 1280 1281 // TODO: Use range information. 1282 if (PtrOI.Offset == OffsetAndSize::Unknown || 1283 !GEP->hasAllConstantIndices()) { 1284 UsrOI.Offset = OffsetAndSize::Unknown; 1285 Follow = true; 1286 return true; 1287 } 1288 1289 SmallVector<Value *, 8> Indices; 1290 for (Use &Idx : GEP->indices()) { 1291 if (auto *CIdx = dyn_cast<ConstantInt>(Idx)) { 1292 Indices.push_back(CIdx); 1293 continue; 1294 } 1295 1296 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Non constant GEP index " << *GEP 1297 << " : " << *Idx << "\n"); 1298 return false; 1299 } 1300 UsrOI.Offset = PtrOI.Offset + DL.getIndexedOffsetInType( 1301 GEP->getSourceElementType(), Indices); 1302 Follow = true; 1303 return true; 1304 } 1305 if (isa<CastInst>(Usr) || isa<SelectInst>(Usr) || isa<ReturnInst>(Usr)) 1306 return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow); 1307 1308 // For PHIs we need to take care of the recurrence explicitly as the value 1309 // might change while we iterate through a loop. For now, we give up if 1310 // the PHI is not invariant. 1311 if (isa<PHINode>(Usr)) { 1312 // Note the order here, the Usr access might change the map, CurPtr is 1313 // already in it though. 1314 bool IsFirstPHIUser = !OffsetInfoMap.count(Usr); 1315 OffsetInfo &UsrOI = OffsetInfoMap[Usr]; 1316 OffsetInfo &PtrOI = OffsetInfoMap[CurPtr]; 1317 // Check if the PHI is invariant (so far). 1318 if (UsrOI == PtrOI) 1319 return true; 1320 1321 // Check if the PHI operand has already an unknown offset as we can't 1322 // improve on that anymore. 1323 if (PtrOI.Offset == OffsetAndSize::Unknown) { 1324 UsrOI = PtrOI; 1325 Follow = true; 1326 return true; 1327 } 1328 1329 // Check if the PHI operand is not dependent on the PHI itself. 1330 APInt Offset( 1331 DL.getIndexSizeInBits(CurPtr->getType()->getPointerAddressSpace()), 1332 0); 1333 Value *CurPtrBase = CurPtr->stripAndAccumulateConstantOffsets( 1334 DL, Offset, /* AllowNonInbounds */ true); 1335 auto It = OffsetInfoMap.find(CurPtrBase); 1336 if (It != OffsetInfoMap.end()) { 1337 Offset += It->getSecond().Offset; 1338 if (IsFirstPHIUser || Offset == UsrOI.Offset) 1339 return HandlePassthroughUser(Usr, PtrOI, Follow); 1340 LLVM_DEBUG(dbgs() 1341 << "[AAPointerInfo] PHI operand pointer offset mismatch " 1342 << *CurPtr << " in " << *Usr << "\n"); 1343 } else { 1344 LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI operand is too complex " 1345 << *CurPtr << " in " << *Usr << "\n"); 1346 } 1347 1348 // TODO: Approximate in case we know the direction of the recurrence. 1349 UsrOI = PtrOI; 1350 UsrOI.Offset = OffsetAndSize::Unknown; 1351 Follow = true; 1352 return true; 1353 } 1354 1355 if (auto *LoadI = dyn_cast<LoadInst>(Usr)) { 1356 // If the access is to a pointer that may or may not be the associated 1357 // value, e.g. due to a PHI, we cannot assume it will be read. 1358 AccessKind AK = AccessKind::AK_R; 1359 if (getUnderlyingObject(CurPtr) == &AssociatedValue) 1360 AK = AccessKind(AK | AccessKind::AK_MUST); 1361 else 1362 AK = AccessKind(AK | AccessKind::AK_MAY); 1363 return handleAccess(A, *LoadI, *CurPtr, /* Content */ nullptr, AK, 1364 OffsetInfoMap[CurPtr].Offset, Changed, 1365 LoadI->getType()); 1366 } 1367 1368 if (auto *StoreI = dyn_cast<StoreInst>(Usr)) { 1369 if (StoreI->getValueOperand() == CurPtr) { 1370 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Escaping use in store " 1371 << *StoreI << "\n"); 1372 return false; 1373 } 1374 // If the access is to a pointer that may or may not be the associated 1375 // value, e.g. due to a PHI, we cannot assume it will be written. 1376 AccessKind AK = AccessKind::AK_W; 1377 if (getUnderlyingObject(CurPtr) == &AssociatedValue) 1378 AK = AccessKind(AK | AccessKind::AK_MUST); 1379 else 1380 AK = AccessKind(AK | AccessKind::AK_MAY); 1381 bool UsedAssumedInformation = false; 1382 Optional<Value *> Content = 1383 A.getAssumedSimplified(*StoreI->getValueOperand(), *this, 1384 UsedAssumedInformation, AA::Interprocedural); 1385 return handleAccess(A, *StoreI, *CurPtr, Content, AK, 1386 OffsetInfoMap[CurPtr].Offset, Changed, 1387 StoreI->getValueOperand()->getType()); 1388 } 1389 if (auto *CB = dyn_cast<CallBase>(Usr)) { 1390 if (CB->isLifetimeStartOrEnd()) 1391 return true; 1392 if (getFreedOperand(CB, TLI) == U) 1393 return true; 1394 if (CB->isArgOperand(&U)) { 1395 unsigned ArgNo = CB->getArgOperandNo(&U); 1396 const auto &CSArgPI = A.getAAFor<AAPointerInfo>( 1397 *this, IRPosition::callsite_argument(*CB, ArgNo), 1398 DepClassTy::REQUIRED); 1399 Changed = translateAndAddState(A, CSArgPI, 1400 OffsetInfoMap[CurPtr].Offset, *CB) | 1401 Changed; 1402 return isValidState(); 1403 } 1404 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Call user not handled " << *CB 1405 << "\n"); 1406 // TODO: Allow some call uses 1407 return false; 1408 } 1409 1410 LLVM_DEBUG(dbgs() << "[AAPointerInfo] User not handled " << *Usr << "\n"); 1411 return false; 1412 }; 1413 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) { 1414 if (OffsetInfoMap.count(NewU)) { 1415 LLVM_DEBUG({ 1416 if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) { 1417 dbgs() << "[AAPointerInfo] Equivalent use callback failed: " 1418 << OffsetInfoMap[NewU].Offset << " vs " 1419 << OffsetInfoMap[OldU].Offset << "\n"; 1420 } 1421 }); 1422 return OffsetInfoMap[NewU] == OffsetInfoMap[OldU]; 1423 } 1424 OffsetInfoMap[NewU] = OffsetInfoMap[OldU]; 1425 return true; 1426 }; 1427 if (!A.checkForAllUses(UsePred, *this, AssociatedValue, 1428 /* CheckBBLivenessOnly */ true, DepClassTy::OPTIONAL, 1429 /* IgnoreDroppableUses */ true, EquivalentUseCB)) { 1430 LLVM_DEBUG( 1431 dbgs() << "[AAPointerInfo] Check for all uses failed, abort!\n"); 1432 return indicatePessimisticFixpoint(); 1433 } 1434 1435 LLVM_DEBUG({ 1436 dbgs() << "Accesses by bin after update:\n"; 1437 dumpState(dbgs()); 1438 }); 1439 1440 return Changed; 1441 } 1442 1443 /// See AbstractAttribute::trackStatistics() 1444 void trackStatistics() const override { 1445 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition()); 1446 } 1447 }; 1448 1449 struct AAPointerInfoReturned final : AAPointerInfoImpl { 1450 AAPointerInfoReturned(const IRPosition &IRP, Attributor &A) 1451 : AAPointerInfoImpl(IRP, A) {} 1452 1453 /// See AbstractAttribute::updateImpl(...). 1454 ChangeStatus updateImpl(Attributor &A) override { 1455 return indicatePessimisticFixpoint(); 1456 } 1457 1458 /// See AbstractAttribute::trackStatistics() 1459 void trackStatistics() const override { 1460 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition()); 1461 } 1462 }; 1463 1464 struct AAPointerInfoArgument final : AAPointerInfoFloating { 1465 AAPointerInfoArgument(const IRPosition &IRP, Attributor &A) 1466 : AAPointerInfoFloating(IRP, A) {} 1467 1468 /// See AbstractAttribute::initialize(...). 1469 void initialize(Attributor &A) override { 1470 AAPointerInfoFloating::initialize(A); 1471 if (getAnchorScope()->isDeclaration()) 1472 indicatePessimisticFixpoint(); 1473 } 1474 1475 /// See AbstractAttribute::trackStatistics() 1476 void trackStatistics() const override { 1477 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition()); 1478 } 1479 }; 1480 1481 struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating { 1482 AAPointerInfoCallSiteArgument(const IRPosition &IRP, Attributor &A) 1483 : AAPointerInfoFloating(IRP, A) {} 1484 1485 /// See AbstractAttribute::updateImpl(...). 1486 ChangeStatus updateImpl(Attributor &A) override { 1487 using namespace AA::PointerInfo; 1488 // We handle memory intrinsics explicitly, at least the first (= 1489 // destination) and second (=source) arguments as we know how they are 1490 // accessed. 1491 if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) { 1492 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 1493 int64_t LengthVal = OffsetAndSize::Unknown; 1494 if (Length) 1495 LengthVal = Length->getSExtValue(); 1496 Value &Ptr = getAssociatedValue(); 1497 unsigned ArgNo = getIRPosition().getCallSiteArgNo(); 1498 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1499 if (ArgNo == 0) { 1500 handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_MUST_WRITE, 0, 1501 Changed, nullptr, LengthVal); 1502 } else if (ArgNo == 1) { 1503 handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_MUST_READ, 0, Changed, 1504 nullptr, LengthVal); 1505 } else { 1506 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled memory intrinsic " 1507 << *MI << "\n"); 1508 return indicatePessimisticFixpoint(); 1509 } 1510 1511 LLVM_DEBUG({ 1512 dbgs() << "Accesses by bin after update:\n"; 1513 dumpState(dbgs()); 1514 }); 1515 1516 return Changed; 1517 } 1518 1519 // TODO: Once we have call site specific value information we can provide 1520 // call site specific liveness information and then it makes 1521 // sense to specialize attributes for call sites arguments instead of 1522 // redirecting requests to the callee argument. 1523 Argument *Arg = getAssociatedArgument(); 1524 if (!Arg) 1525 return indicatePessimisticFixpoint(); 1526 const IRPosition &ArgPos = IRPosition::argument(*Arg); 1527 auto &ArgAA = 1528 A.getAAFor<AAPointerInfo>(*this, ArgPos, DepClassTy::REQUIRED); 1529 return translateAndAddState(A, ArgAA, 0, *cast<CallBase>(getCtxI()), 1530 /* FromCallee */ true); 1531 } 1532 1533 /// See AbstractAttribute::trackStatistics() 1534 void trackStatistics() const override { 1535 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition()); 1536 } 1537 }; 1538 1539 struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating { 1540 AAPointerInfoCallSiteReturned(const IRPosition &IRP, Attributor &A) 1541 : AAPointerInfoFloating(IRP, A) {} 1542 1543 /// See AbstractAttribute::trackStatistics() 1544 void trackStatistics() const override { 1545 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition()); 1546 } 1547 }; 1548 } // namespace 1549 1550 /// -----------------------NoUnwind Function Attribute-------------------------- 1551 1552 namespace { 1553 struct AANoUnwindImpl : AANoUnwind { 1554 AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {} 1555 1556 const std::string getAsStr() const override { 1557 return getAssumed() ? "nounwind" : "may-unwind"; 1558 } 1559 1560 /// See AbstractAttribute::updateImpl(...). 1561 ChangeStatus updateImpl(Attributor &A) override { 1562 auto Opcodes = { 1563 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 1564 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, 1565 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; 1566 1567 auto CheckForNoUnwind = [&](Instruction &I) { 1568 if (!I.mayThrow()) 1569 return true; 1570 1571 if (const auto *CB = dyn_cast<CallBase>(&I)) { 1572 const auto &NoUnwindAA = A.getAAFor<AANoUnwind>( 1573 *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED); 1574 return NoUnwindAA.isAssumedNoUnwind(); 1575 } 1576 return false; 1577 }; 1578 1579 bool UsedAssumedInformation = false; 1580 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes, 1581 UsedAssumedInformation)) 1582 return indicatePessimisticFixpoint(); 1583 1584 return ChangeStatus::UNCHANGED; 1585 } 1586 }; 1587 1588 struct AANoUnwindFunction final : public AANoUnwindImpl { 1589 AANoUnwindFunction(const IRPosition &IRP, Attributor &A) 1590 : AANoUnwindImpl(IRP, A) {} 1591 1592 /// See AbstractAttribute::trackStatistics() 1593 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) } 1594 }; 1595 1596 /// NoUnwind attribute deduction for a call sites. 1597 struct AANoUnwindCallSite final : AANoUnwindImpl { 1598 AANoUnwindCallSite(const IRPosition &IRP, Attributor &A) 1599 : AANoUnwindImpl(IRP, A) {} 1600 1601 /// See AbstractAttribute::initialize(...). 1602 void initialize(Attributor &A) override { 1603 AANoUnwindImpl::initialize(A); 1604 Function *F = getAssociatedFunction(); 1605 if (!F || F->isDeclaration()) 1606 indicatePessimisticFixpoint(); 1607 } 1608 1609 /// See AbstractAttribute::updateImpl(...). 1610 ChangeStatus updateImpl(Attributor &A) override { 1611 // TODO: Once we have call site specific value information we can provide 1612 // call site specific liveness information and then it makes 1613 // sense to specialize attributes for call sites arguments instead of 1614 // redirecting requests to the callee argument. 1615 Function *F = getAssociatedFunction(); 1616 const IRPosition &FnPos = IRPosition::function(*F); 1617 auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::REQUIRED); 1618 return clampStateAndIndicateChange(getState(), FnAA.getState()); 1619 } 1620 1621 /// See AbstractAttribute::trackStatistics() 1622 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); } 1623 }; 1624 } // namespace 1625 1626 /// --------------------- Function Return Values ------------------------------- 1627 1628 namespace { 1629 /// "Attribute" that collects all potential returned values and the return 1630 /// instructions that they arise from. 1631 /// 1632 /// If there is a unique returned value R, the manifest method will: 1633 /// - mark R with the "returned" attribute, if R is an argument. 1634 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState { 1635 1636 /// Mapping of values potentially returned by the associated function to the 1637 /// return instructions that might return them. 1638 MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues; 1639 1640 /// State flags 1641 /// 1642 ///{ 1643 bool IsFixed = false; 1644 bool IsValidState = true; 1645 ///} 1646 1647 public: 1648 AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A) 1649 : AAReturnedValues(IRP, A) {} 1650 1651 /// See AbstractAttribute::initialize(...). 1652 void initialize(Attributor &A) override { 1653 // Reset the state. 1654 IsFixed = false; 1655 IsValidState = true; 1656 ReturnedValues.clear(); 1657 1658 Function *F = getAssociatedFunction(); 1659 if (!F || F->isDeclaration()) { 1660 indicatePessimisticFixpoint(); 1661 return; 1662 } 1663 assert(!F->getReturnType()->isVoidTy() && 1664 "Did not expect a void return type!"); 1665 1666 // The map from instruction opcodes to those instructions in the function. 1667 auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F); 1668 1669 // Look through all arguments, if one is marked as returned we are done. 1670 for (Argument &Arg : F->args()) { 1671 if (Arg.hasReturnedAttr()) { 1672 auto &ReturnInstSet = ReturnedValues[&Arg]; 1673 if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret)) 1674 for (Instruction *RI : *Insts) 1675 ReturnInstSet.insert(cast<ReturnInst>(RI)); 1676 1677 indicateOptimisticFixpoint(); 1678 return; 1679 } 1680 } 1681 1682 if (!A.isFunctionIPOAmendable(*F)) 1683 indicatePessimisticFixpoint(); 1684 } 1685 1686 /// See AbstractAttribute::manifest(...). 1687 ChangeStatus manifest(Attributor &A) override; 1688 1689 /// See AbstractAttribute::getState(...). 1690 AbstractState &getState() override { return *this; } 1691 1692 /// See AbstractAttribute::getState(...). 1693 const AbstractState &getState() const override { return *this; } 1694 1695 /// See AbstractAttribute::updateImpl(Attributor &A). 1696 ChangeStatus updateImpl(Attributor &A) override; 1697 1698 llvm::iterator_range<iterator> returned_values() override { 1699 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 1700 } 1701 1702 llvm::iterator_range<const_iterator> returned_values() const override { 1703 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 1704 } 1705 1706 /// Return the number of potential return values, -1 if unknown. 1707 size_t getNumReturnValues() const override { 1708 return isValidState() ? ReturnedValues.size() : -1; 1709 } 1710 1711 /// Return an assumed unique return value if a single candidate is found. If 1712 /// there cannot be one, return a nullptr. If it is not clear yet, return the 1713 /// Optional::NoneType. 1714 Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const; 1715 1716 /// See AbstractState::checkForAllReturnedValues(...). 1717 bool checkForAllReturnedValuesAndReturnInsts( 1718 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred) 1719 const override; 1720 1721 /// Pretty print the attribute similar to the IR representation. 1722 const std::string getAsStr() const override; 1723 1724 /// See AbstractState::isAtFixpoint(). 1725 bool isAtFixpoint() const override { return IsFixed; } 1726 1727 /// See AbstractState::isValidState(). 1728 bool isValidState() const override { return IsValidState; } 1729 1730 /// See AbstractState::indicateOptimisticFixpoint(...). 1731 ChangeStatus indicateOptimisticFixpoint() override { 1732 IsFixed = true; 1733 return ChangeStatus::UNCHANGED; 1734 } 1735 1736 ChangeStatus indicatePessimisticFixpoint() override { 1737 IsFixed = true; 1738 IsValidState = false; 1739 return ChangeStatus::CHANGED; 1740 } 1741 }; 1742 1743 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { 1744 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1745 1746 // Bookkeeping. 1747 assert(isValidState()); 1748 STATS_DECLTRACK(KnownReturnValues, FunctionReturn, 1749 "Number of function with known return values"); 1750 1751 // Check if we have an assumed unique return value that we could manifest. 1752 Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); 1753 1754 if (!UniqueRV || !UniqueRV.value()) 1755 return Changed; 1756 1757 // Bookkeeping. 1758 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, 1759 "Number of function with unique return"); 1760 // If the assumed unique return value is an argument, annotate it. 1761 if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.value())) { 1762 if (UniqueRVArg->getType()->canLosslesslyBitCastTo( 1763 getAssociatedFunction()->getReturnType())) { 1764 getIRPosition() = IRPosition::argument(*UniqueRVArg); 1765 Changed = IRAttribute::manifest(A); 1766 } 1767 } 1768 return Changed; 1769 } 1770 1771 const std::string AAReturnedValuesImpl::getAsStr() const { 1772 return (isAtFixpoint() ? "returns(#" : "may-return(#") + 1773 (isValidState() ? std::to_string(getNumReturnValues()) : "?") + ")"; 1774 } 1775 1776 Optional<Value *> 1777 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const { 1778 // If checkForAllReturnedValues provides a unique value, ignoring potential 1779 // undef values that can also be present, it is assumed to be the actual 1780 // return value and forwarded to the caller of this method. If there are 1781 // multiple, a nullptr is returned indicating there cannot be a unique 1782 // returned value. 1783 Optional<Value *> UniqueRV; 1784 Type *Ty = getAssociatedFunction()->getReturnType(); 1785 1786 auto Pred = [&](Value &RV) -> bool { 1787 UniqueRV = AA::combineOptionalValuesInAAValueLatice(UniqueRV, &RV, Ty); 1788 return UniqueRV != Optional<Value *>(nullptr); 1789 }; 1790 1791 if (!A.checkForAllReturnedValues(Pred, *this)) 1792 UniqueRV = nullptr; 1793 1794 return UniqueRV; 1795 } 1796 1797 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts( 1798 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred) 1799 const { 1800 if (!isValidState()) 1801 return false; 1802 1803 // Check all returned values but ignore call sites as long as we have not 1804 // encountered an overdefined one during an update. 1805 for (auto &It : ReturnedValues) { 1806 Value *RV = It.first; 1807 if (!Pred(*RV, It.second)) 1808 return false; 1809 } 1810 1811 return true; 1812 } 1813 1814 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { 1815 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1816 1817 SmallVector<AA::ValueAndContext> Values; 1818 bool UsedAssumedInformation = false; 1819 auto ReturnInstCB = [&](Instruction &I) { 1820 ReturnInst &Ret = cast<ReturnInst>(I); 1821 Values.clear(); 1822 if (!A.getAssumedSimplifiedValues(IRPosition::value(*Ret.getReturnValue()), 1823 *this, Values, AA::Intraprocedural, 1824 UsedAssumedInformation)) 1825 Values.push_back({*Ret.getReturnValue(), Ret}); 1826 1827 for (auto &VAC : Values) { 1828 assert(AA::isValidInScope(*VAC.getValue(), Ret.getFunction()) && 1829 "Assumed returned value should be valid in function scope!"); 1830 if (ReturnedValues[VAC.getValue()].insert(&Ret)) 1831 Changed = ChangeStatus::CHANGED; 1832 } 1833 return true; 1834 }; 1835 1836 // Discover returned values from all live returned instructions in the 1837 // associated function. 1838 if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret}, 1839 UsedAssumedInformation)) 1840 return indicatePessimisticFixpoint(); 1841 return Changed; 1842 } 1843 1844 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl { 1845 AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A) 1846 : AAReturnedValuesImpl(IRP, A) {} 1847 1848 /// See AbstractAttribute::trackStatistics() 1849 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) } 1850 }; 1851 1852 /// Returned values information for a call sites. 1853 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl { 1854 AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A) 1855 : AAReturnedValuesImpl(IRP, A) {} 1856 1857 /// See AbstractAttribute::initialize(...). 1858 void initialize(Attributor &A) override { 1859 // TODO: Once we have call site specific value information we can provide 1860 // call site specific liveness information and then it makes 1861 // sense to specialize attributes for call sites instead of 1862 // redirecting requests to the callee. 1863 llvm_unreachable("Abstract attributes for returned values are not " 1864 "supported for call sites yet!"); 1865 } 1866 1867 /// See AbstractAttribute::updateImpl(...). 1868 ChangeStatus updateImpl(Attributor &A) override { 1869 return indicatePessimisticFixpoint(); 1870 } 1871 1872 /// See AbstractAttribute::trackStatistics() 1873 void trackStatistics() const override {} 1874 }; 1875 } // namespace 1876 1877 /// ------------------------ NoSync Function Attribute ------------------------- 1878 1879 bool AANoSync::isNonRelaxedAtomic(const Instruction *I) { 1880 if (!I->isAtomic()) 1881 return false; 1882 1883 if (auto *FI = dyn_cast<FenceInst>(I)) 1884 // All legal orderings for fence are stronger than monotonic. 1885 return FI->getSyncScopeID() != SyncScope::SingleThread; 1886 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) { 1887 // Unordered is not a legal ordering for cmpxchg. 1888 return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic || 1889 AI->getFailureOrdering() != AtomicOrdering::Monotonic); 1890 } 1891 1892 AtomicOrdering Ordering; 1893 switch (I->getOpcode()) { 1894 case Instruction::AtomicRMW: 1895 Ordering = cast<AtomicRMWInst>(I)->getOrdering(); 1896 break; 1897 case Instruction::Store: 1898 Ordering = cast<StoreInst>(I)->getOrdering(); 1899 break; 1900 case Instruction::Load: 1901 Ordering = cast<LoadInst>(I)->getOrdering(); 1902 break; 1903 default: 1904 llvm_unreachable( 1905 "New atomic operations need to be known in the attributor."); 1906 } 1907 1908 return (Ordering != AtomicOrdering::Unordered && 1909 Ordering != AtomicOrdering::Monotonic); 1910 } 1911 1912 /// Return true if this intrinsic is nosync. This is only used for intrinsics 1913 /// which would be nosync except that they have a volatile flag. All other 1914 /// intrinsics are simply annotated with the nosync attribute in Intrinsics.td. 1915 bool AANoSync::isNoSyncIntrinsic(const Instruction *I) { 1916 if (auto *MI = dyn_cast<MemIntrinsic>(I)) 1917 return !MI->isVolatile(); 1918 return false; 1919 } 1920 1921 namespace { 1922 struct AANoSyncImpl : AANoSync { 1923 AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {} 1924 1925 const std::string getAsStr() const override { 1926 return getAssumed() ? "nosync" : "may-sync"; 1927 } 1928 1929 /// See AbstractAttribute::updateImpl(...). 1930 ChangeStatus updateImpl(Attributor &A) override; 1931 }; 1932 1933 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) { 1934 1935 auto CheckRWInstForNoSync = [&](Instruction &I) { 1936 return AA::isNoSyncInst(A, I, *this); 1937 }; 1938 1939 auto CheckForNoSync = [&](Instruction &I) { 1940 // At this point we handled all read/write effects and they are all 1941 // nosync, so they can be skipped. 1942 if (I.mayReadOrWriteMemory()) 1943 return true; 1944 1945 // non-convergent and readnone imply nosync. 1946 return !cast<CallBase>(I).isConvergent(); 1947 }; 1948 1949 bool UsedAssumedInformation = false; 1950 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this, 1951 UsedAssumedInformation) || 1952 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this, 1953 UsedAssumedInformation)) 1954 return indicatePessimisticFixpoint(); 1955 1956 return ChangeStatus::UNCHANGED; 1957 } 1958 1959 struct AANoSyncFunction final : public AANoSyncImpl { 1960 AANoSyncFunction(const IRPosition &IRP, Attributor &A) 1961 : AANoSyncImpl(IRP, A) {} 1962 1963 /// See AbstractAttribute::trackStatistics() 1964 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) } 1965 }; 1966 1967 /// NoSync attribute deduction for a call sites. 1968 struct AANoSyncCallSite final : AANoSyncImpl { 1969 AANoSyncCallSite(const IRPosition &IRP, Attributor &A) 1970 : AANoSyncImpl(IRP, A) {} 1971 1972 /// See AbstractAttribute::initialize(...). 1973 void initialize(Attributor &A) override { 1974 AANoSyncImpl::initialize(A); 1975 Function *F = getAssociatedFunction(); 1976 if (!F || F->isDeclaration()) 1977 indicatePessimisticFixpoint(); 1978 } 1979 1980 /// See AbstractAttribute::updateImpl(...). 1981 ChangeStatus updateImpl(Attributor &A) override { 1982 // TODO: Once we have call site specific value information we can provide 1983 // call site specific liveness information and then it makes 1984 // sense to specialize attributes for call sites arguments instead of 1985 // redirecting requests to the callee argument. 1986 Function *F = getAssociatedFunction(); 1987 const IRPosition &FnPos = IRPosition::function(*F); 1988 auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos, DepClassTy::REQUIRED); 1989 return clampStateAndIndicateChange(getState(), FnAA.getState()); 1990 } 1991 1992 /// See AbstractAttribute::trackStatistics() 1993 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); } 1994 }; 1995 } // namespace 1996 1997 /// ------------------------ No-Free Attributes ---------------------------- 1998 1999 namespace { 2000 struct AANoFreeImpl : public AANoFree { 2001 AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {} 2002 2003 /// See AbstractAttribute::updateImpl(...). 2004 ChangeStatus updateImpl(Attributor &A) override { 2005 auto CheckForNoFree = [&](Instruction &I) { 2006 const auto &CB = cast<CallBase>(I); 2007 if (CB.hasFnAttr(Attribute::NoFree)) 2008 return true; 2009 2010 const auto &NoFreeAA = A.getAAFor<AANoFree>( 2011 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 2012 return NoFreeAA.isAssumedNoFree(); 2013 }; 2014 2015 bool UsedAssumedInformation = false; 2016 if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this, 2017 UsedAssumedInformation)) 2018 return indicatePessimisticFixpoint(); 2019 return ChangeStatus::UNCHANGED; 2020 } 2021 2022 /// See AbstractAttribute::getAsStr(). 2023 const std::string getAsStr() const override { 2024 return getAssumed() ? "nofree" : "may-free"; 2025 } 2026 }; 2027 2028 struct AANoFreeFunction final : public AANoFreeImpl { 2029 AANoFreeFunction(const IRPosition &IRP, Attributor &A) 2030 : AANoFreeImpl(IRP, A) {} 2031 2032 /// See AbstractAttribute::trackStatistics() 2033 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) } 2034 }; 2035 2036 /// NoFree attribute deduction for a call sites. 2037 struct AANoFreeCallSite final : AANoFreeImpl { 2038 AANoFreeCallSite(const IRPosition &IRP, Attributor &A) 2039 : AANoFreeImpl(IRP, A) {} 2040 2041 /// See AbstractAttribute::initialize(...). 2042 void initialize(Attributor &A) override { 2043 AANoFreeImpl::initialize(A); 2044 Function *F = getAssociatedFunction(); 2045 if (!F || F->isDeclaration()) 2046 indicatePessimisticFixpoint(); 2047 } 2048 2049 /// See AbstractAttribute::updateImpl(...). 2050 ChangeStatus updateImpl(Attributor &A) override { 2051 // TODO: Once we have call site specific value information we can provide 2052 // call site specific liveness information and then it makes 2053 // sense to specialize attributes for call sites arguments instead of 2054 // redirecting requests to the callee argument. 2055 Function *F = getAssociatedFunction(); 2056 const IRPosition &FnPos = IRPosition::function(*F); 2057 auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos, DepClassTy::REQUIRED); 2058 return clampStateAndIndicateChange(getState(), FnAA.getState()); 2059 } 2060 2061 /// See AbstractAttribute::trackStatistics() 2062 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); } 2063 }; 2064 2065 /// NoFree attribute for floating values. 2066 struct AANoFreeFloating : AANoFreeImpl { 2067 AANoFreeFloating(const IRPosition &IRP, Attributor &A) 2068 : AANoFreeImpl(IRP, A) {} 2069 2070 /// See AbstractAttribute::trackStatistics() 2071 void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)} 2072 2073 /// See Abstract Attribute::updateImpl(...). 2074 ChangeStatus updateImpl(Attributor &A) override { 2075 const IRPosition &IRP = getIRPosition(); 2076 2077 const auto &NoFreeAA = A.getAAFor<AANoFree>( 2078 *this, IRPosition::function_scope(IRP), DepClassTy::OPTIONAL); 2079 if (NoFreeAA.isAssumedNoFree()) 2080 return ChangeStatus::UNCHANGED; 2081 2082 Value &AssociatedValue = getIRPosition().getAssociatedValue(); 2083 auto Pred = [&](const Use &U, bool &Follow) -> bool { 2084 Instruction *UserI = cast<Instruction>(U.getUser()); 2085 if (auto *CB = dyn_cast<CallBase>(UserI)) { 2086 if (CB->isBundleOperand(&U)) 2087 return false; 2088 if (!CB->isArgOperand(&U)) 2089 return true; 2090 unsigned ArgNo = CB->getArgOperandNo(&U); 2091 2092 const auto &NoFreeArg = A.getAAFor<AANoFree>( 2093 *this, IRPosition::callsite_argument(*CB, ArgNo), 2094 DepClassTy::REQUIRED); 2095 return NoFreeArg.isAssumedNoFree(); 2096 } 2097 2098 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) || 2099 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 2100 Follow = true; 2101 return true; 2102 } 2103 if (isa<StoreInst>(UserI) || isa<LoadInst>(UserI) || 2104 isa<ReturnInst>(UserI)) 2105 return true; 2106 2107 // Unknown user. 2108 return false; 2109 }; 2110 if (!A.checkForAllUses(Pred, *this, AssociatedValue)) 2111 return indicatePessimisticFixpoint(); 2112 2113 return ChangeStatus::UNCHANGED; 2114 } 2115 }; 2116 2117 /// NoFree attribute for a call site argument. 2118 struct AANoFreeArgument final : AANoFreeFloating { 2119 AANoFreeArgument(const IRPosition &IRP, Attributor &A) 2120 : AANoFreeFloating(IRP, A) {} 2121 2122 /// See AbstractAttribute::trackStatistics() 2123 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) } 2124 }; 2125 2126 /// NoFree attribute for call site arguments. 2127 struct AANoFreeCallSiteArgument final : AANoFreeFloating { 2128 AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A) 2129 : AANoFreeFloating(IRP, A) {} 2130 2131 /// See AbstractAttribute::updateImpl(...). 2132 ChangeStatus updateImpl(Attributor &A) override { 2133 // TODO: Once we have call site specific value information we can provide 2134 // call site specific liveness information and then it makes 2135 // sense to specialize attributes for call sites arguments instead of 2136 // redirecting requests to the callee argument. 2137 Argument *Arg = getAssociatedArgument(); 2138 if (!Arg) 2139 return indicatePessimisticFixpoint(); 2140 const IRPosition &ArgPos = IRPosition::argument(*Arg); 2141 auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos, DepClassTy::REQUIRED); 2142 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 2143 } 2144 2145 /// See AbstractAttribute::trackStatistics() 2146 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)}; 2147 }; 2148 2149 /// NoFree attribute for function return value. 2150 struct AANoFreeReturned final : AANoFreeFloating { 2151 AANoFreeReturned(const IRPosition &IRP, Attributor &A) 2152 : AANoFreeFloating(IRP, A) { 2153 llvm_unreachable("NoFree is not applicable to function returns!"); 2154 } 2155 2156 /// See AbstractAttribute::initialize(...). 2157 void initialize(Attributor &A) override { 2158 llvm_unreachable("NoFree is not applicable to function returns!"); 2159 } 2160 2161 /// See AbstractAttribute::updateImpl(...). 2162 ChangeStatus updateImpl(Attributor &A) override { 2163 llvm_unreachable("NoFree is not applicable to function returns!"); 2164 } 2165 2166 /// See AbstractAttribute::trackStatistics() 2167 void trackStatistics() const override {} 2168 }; 2169 2170 /// NoFree attribute deduction for a call site return value. 2171 struct AANoFreeCallSiteReturned final : AANoFreeFloating { 2172 AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A) 2173 : AANoFreeFloating(IRP, A) {} 2174 2175 ChangeStatus manifest(Attributor &A) override { 2176 return ChangeStatus::UNCHANGED; 2177 } 2178 /// See AbstractAttribute::trackStatistics() 2179 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) } 2180 }; 2181 } // namespace 2182 2183 /// ------------------------ NonNull Argument Attribute ------------------------ 2184 namespace { 2185 static int64_t getKnownNonNullAndDerefBytesForUse( 2186 Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue, 2187 const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) { 2188 TrackUse = false; 2189 2190 const Value *UseV = U->get(); 2191 if (!UseV->getType()->isPointerTy()) 2192 return 0; 2193 2194 // We need to follow common pointer manipulation uses to the accesses they 2195 // feed into. We can try to be smart to avoid looking through things we do not 2196 // like for now, e.g., non-inbounds GEPs. 2197 if (isa<CastInst>(I)) { 2198 TrackUse = true; 2199 return 0; 2200 } 2201 2202 if (isa<GetElementPtrInst>(I)) { 2203 TrackUse = true; 2204 return 0; 2205 } 2206 2207 Type *PtrTy = UseV->getType(); 2208 const Function *F = I->getFunction(); 2209 bool NullPointerIsDefined = 2210 F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true; 2211 const DataLayout &DL = A.getInfoCache().getDL(); 2212 if (const auto *CB = dyn_cast<CallBase>(I)) { 2213 if (CB->isBundleOperand(U)) { 2214 if (RetainedKnowledge RK = getKnowledgeFromUse( 2215 U, {Attribute::NonNull, Attribute::Dereferenceable})) { 2216 IsNonNull |= 2217 (RK.AttrKind == Attribute::NonNull || !NullPointerIsDefined); 2218 return RK.ArgValue; 2219 } 2220 return 0; 2221 } 2222 2223 if (CB->isCallee(U)) { 2224 IsNonNull |= !NullPointerIsDefined; 2225 return 0; 2226 } 2227 2228 unsigned ArgNo = CB->getArgOperandNo(U); 2229 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo); 2230 // As long as we only use known information there is no need to track 2231 // dependences here. 2232 auto &DerefAA = 2233 A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE); 2234 IsNonNull |= DerefAA.isKnownNonNull(); 2235 return DerefAA.getKnownDereferenceableBytes(); 2236 } 2237 2238 Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I); 2239 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile()) 2240 return 0; 2241 2242 int64_t Offset; 2243 const Value *Base = 2244 getMinimalBaseOfPointer(A, QueryingAA, Loc->Ptr, Offset, DL); 2245 if (Base && Base == &AssociatedValue) { 2246 int64_t DerefBytes = Loc->Size.getValue() + Offset; 2247 IsNonNull |= !NullPointerIsDefined; 2248 return std::max(int64_t(0), DerefBytes); 2249 } 2250 2251 /// Corner case when an offset is 0. 2252 Base = GetPointerBaseWithConstantOffset(Loc->Ptr, Offset, DL, 2253 /*AllowNonInbounds*/ true); 2254 if (Base && Base == &AssociatedValue && Offset == 0) { 2255 int64_t DerefBytes = Loc->Size.getValue(); 2256 IsNonNull |= !NullPointerIsDefined; 2257 return std::max(int64_t(0), DerefBytes); 2258 } 2259 2260 return 0; 2261 } 2262 2263 struct AANonNullImpl : AANonNull { 2264 AANonNullImpl(const IRPosition &IRP, Attributor &A) 2265 : AANonNull(IRP, A), 2266 NullIsDefined(NullPointerIsDefined( 2267 getAnchorScope(), 2268 getAssociatedValue().getType()->getPointerAddressSpace())) {} 2269 2270 /// See AbstractAttribute::initialize(...). 2271 void initialize(Attributor &A) override { 2272 Value &V = *getAssociatedValue().stripPointerCasts(); 2273 if (!NullIsDefined && 2274 hasAttr({Attribute::NonNull, Attribute::Dereferenceable}, 2275 /* IgnoreSubsumingPositions */ false, &A)) { 2276 indicateOptimisticFixpoint(); 2277 return; 2278 } 2279 2280 if (isa<ConstantPointerNull>(V)) { 2281 indicatePessimisticFixpoint(); 2282 return; 2283 } 2284 2285 AANonNull::initialize(A); 2286 2287 bool CanBeNull, CanBeFreed; 2288 if (V.getPointerDereferenceableBytes(A.getDataLayout(), CanBeNull, 2289 CanBeFreed)) { 2290 if (!CanBeNull) { 2291 indicateOptimisticFixpoint(); 2292 return; 2293 } 2294 } 2295 2296 if (isa<GlobalValue>(V)) { 2297 indicatePessimisticFixpoint(); 2298 return; 2299 } 2300 2301 if (Instruction *CtxI = getCtxI()) 2302 followUsesInMBEC(*this, A, getState(), *CtxI); 2303 } 2304 2305 /// See followUsesInMBEC 2306 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 2307 AANonNull::StateType &State) { 2308 bool IsNonNull = false; 2309 bool TrackUse = false; 2310 getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I, 2311 IsNonNull, TrackUse); 2312 State.setKnown(IsNonNull); 2313 return TrackUse; 2314 } 2315 2316 /// See AbstractAttribute::getAsStr(). 2317 const std::string getAsStr() const override { 2318 return getAssumed() ? "nonnull" : "may-null"; 2319 } 2320 2321 /// Flag to determine if the underlying value can be null and still allow 2322 /// valid accesses. 2323 const bool NullIsDefined; 2324 }; 2325 2326 /// NonNull attribute for a floating value. 2327 struct AANonNullFloating : public AANonNullImpl { 2328 AANonNullFloating(const IRPosition &IRP, Attributor &A) 2329 : AANonNullImpl(IRP, A) {} 2330 2331 /// See AbstractAttribute::updateImpl(...). 2332 ChangeStatus updateImpl(Attributor &A) override { 2333 const DataLayout &DL = A.getDataLayout(); 2334 2335 bool Stripped; 2336 bool UsedAssumedInformation = false; 2337 SmallVector<AA::ValueAndContext> Values; 2338 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values, 2339 AA::AnyScope, UsedAssumedInformation)) { 2340 Values.push_back({getAssociatedValue(), getCtxI()}); 2341 Stripped = false; 2342 } else { 2343 Stripped = Values.size() != 1 || 2344 Values.front().getValue() != &getAssociatedValue(); 2345 } 2346 2347 DominatorTree *DT = nullptr; 2348 AssumptionCache *AC = nullptr; 2349 InformationCache &InfoCache = A.getInfoCache(); 2350 if (const Function *Fn = getAnchorScope()) { 2351 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn); 2352 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn); 2353 } 2354 2355 AANonNull::StateType T; 2356 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool { 2357 const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V), 2358 DepClassTy::REQUIRED); 2359 if (!Stripped && this == &AA) { 2360 if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT)) 2361 T.indicatePessimisticFixpoint(); 2362 } else { 2363 // Use abstract attribute information. 2364 const AANonNull::StateType &NS = AA.getState(); 2365 T ^= NS; 2366 } 2367 return T.isValidState(); 2368 }; 2369 2370 for (const auto &VAC : Values) 2371 if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI())) 2372 return indicatePessimisticFixpoint(); 2373 2374 return clampStateAndIndicateChange(getState(), T); 2375 } 2376 2377 /// See AbstractAttribute::trackStatistics() 2378 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 2379 }; 2380 2381 /// NonNull attribute for function return value. 2382 struct AANonNullReturned final 2383 : AAReturnedFromReturnedValues<AANonNull, AANonNull> { 2384 AANonNullReturned(const IRPosition &IRP, Attributor &A) 2385 : AAReturnedFromReturnedValues<AANonNull, AANonNull>(IRP, A) {} 2386 2387 /// See AbstractAttribute::getAsStr(). 2388 const std::string getAsStr() const override { 2389 return getAssumed() ? "nonnull" : "may-null"; 2390 } 2391 2392 /// See AbstractAttribute::trackStatistics() 2393 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 2394 }; 2395 2396 /// NonNull attribute for function argument. 2397 struct AANonNullArgument final 2398 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> { 2399 AANonNullArgument(const IRPosition &IRP, Attributor &A) 2400 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {} 2401 2402 /// See AbstractAttribute::trackStatistics() 2403 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) } 2404 }; 2405 2406 struct AANonNullCallSiteArgument final : AANonNullFloating { 2407 AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A) 2408 : AANonNullFloating(IRP, A) {} 2409 2410 /// See AbstractAttribute::trackStatistics() 2411 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) } 2412 }; 2413 2414 /// NonNull attribute for a call site return position. 2415 struct AANonNullCallSiteReturned final 2416 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> { 2417 AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A) 2418 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP, A) {} 2419 2420 /// See AbstractAttribute::trackStatistics() 2421 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) } 2422 }; 2423 } // namespace 2424 2425 /// ------------------------ No-Recurse Attributes ---------------------------- 2426 2427 namespace { 2428 struct AANoRecurseImpl : public AANoRecurse { 2429 AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {} 2430 2431 /// See AbstractAttribute::getAsStr() 2432 const std::string getAsStr() const override { 2433 return getAssumed() ? "norecurse" : "may-recurse"; 2434 } 2435 }; 2436 2437 struct AANoRecurseFunction final : AANoRecurseImpl { 2438 AANoRecurseFunction(const IRPosition &IRP, Attributor &A) 2439 : AANoRecurseImpl(IRP, A) {} 2440 2441 /// See AbstractAttribute::updateImpl(...). 2442 ChangeStatus updateImpl(Attributor &A) override { 2443 2444 // If all live call sites are known to be no-recurse, we are as well. 2445 auto CallSitePred = [&](AbstractCallSite ACS) { 2446 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 2447 *this, IRPosition::function(*ACS.getInstruction()->getFunction()), 2448 DepClassTy::NONE); 2449 return NoRecurseAA.isKnownNoRecurse(); 2450 }; 2451 bool UsedAssumedInformation = false; 2452 if (A.checkForAllCallSites(CallSitePred, *this, true, 2453 UsedAssumedInformation)) { 2454 // If we know all call sites and all are known no-recurse, we are done. 2455 // If all known call sites, which might not be all that exist, are known 2456 // to be no-recurse, we are not done but we can continue to assume 2457 // no-recurse. If one of the call sites we have not visited will become 2458 // live, another update is triggered. 2459 if (!UsedAssumedInformation) 2460 indicateOptimisticFixpoint(); 2461 return ChangeStatus::UNCHANGED; 2462 } 2463 2464 const AAFunctionReachability &EdgeReachability = 2465 A.getAAFor<AAFunctionReachability>(*this, getIRPosition(), 2466 DepClassTy::REQUIRED); 2467 if (EdgeReachability.canReach(A, *getAnchorScope())) 2468 return indicatePessimisticFixpoint(); 2469 return ChangeStatus::UNCHANGED; 2470 } 2471 2472 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) } 2473 }; 2474 2475 /// NoRecurse attribute deduction for a call sites. 2476 struct AANoRecurseCallSite final : AANoRecurseImpl { 2477 AANoRecurseCallSite(const IRPosition &IRP, Attributor &A) 2478 : AANoRecurseImpl(IRP, A) {} 2479 2480 /// See AbstractAttribute::initialize(...). 2481 void initialize(Attributor &A) override { 2482 AANoRecurseImpl::initialize(A); 2483 Function *F = getAssociatedFunction(); 2484 if (!F || F->isDeclaration()) 2485 indicatePessimisticFixpoint(); 2486 } 2487 2488 /// See AbstractAttribute::updateImpl(...). 2489 ChangeStatus updateImpl(Attributor &A) override { 2490 // TODO: Once we have call site specific value information we can provide 2491 // call site specific liveness information and then it makes 2492 // sense to specialize attributes for call sites arguments instead of 2493 // redirecting requests to the callee argument. 2494 Function *F = getAssociatedFunction(); 2495 const IRPosition &FnPos = IRPosition::function(*F); 2496 auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos, DepClassTy::REQUIRED); 2497 return clampStateAndIndicateChange(getState(), FnAA.getState()); 2498 } 2499 2500 /// See AbstractAttribute::trackStatistics() 2501 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); } 2502 }; 2503 } // namespace 2504 2505 /// -------------------- Undefined-Behavior Attributes ------------------------ 2506 2507 namespace { 2508 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior { 2509 AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A) 2510 : AAUndefinedBehavior(IRP, A) {} 2511 2512 /// See AbstractAttribute::updateImpl(...). 2513 // through a pointer (i.e. also branches etc.) 2514 ChangeStatus updateImpl(Attributor &A) override { 2515 const size_t UBPrevSize = KnownUBInsts.size(); 2516 const size_t NoUBPrevSize = AssumedNoUBInsts.size(); 2517 2518 auto InspectMemAccessInstForUB = [&](Instruction &I) { 2519 // Lang ref now states volatile store is not UB, let's skip them. 2520 if (I.isVolatile() && I.mayWriteToMemory()) 2521 return true; 2522 2523 // Skip instructions that are already saved. 2524 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 2525 return true; 2526 2527 // If we reach here, we know we have an instruction 2528 // that accesses memory through a pointer operand, 2529 // for which getPointerOperand() should give it to us. 2530 Value *PtrOp = 2531 const_cast<Value *>(getPointerOperand(&I, /* AllowVolatile */ true)); 2532 assert(PtrOp && 2533 "Expected pointer operand of memory accessing instruction"); 2534 2535 // Either we stopped and the appropriate action was taken, 2536 // or we got back a simplified value to continue. 2537 Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I); 2538 if (!SimplifiedPtrOp || !SimplifiedPtrOp.value()) 2539 return true; 2540 const Value *PtrOpVal = SimplifiedPtrOp.value(); 2541 2542 // A memory access through a pointer is considered UB 2543 // only if the pointer has constant null value. 2544 // TODO: Expand it to not only check constant values. 2545 if (!isa<ConstantPointerNull>(PtrOpVal)) { 2546 AssumedNoUBInsts.insert(&I); 2547 return true; 2548 } 2549 const Type *PtrTy = PtrOpVal->getType(); 2550 2551 // Because we only consider instructions inside functions, 2552 // assume that a parent function exists. 2553 const Function *F = I.getFunction(); 2554 2555 // A memory access using constant null pointer is only considered UB 2556 // if null pointer is _not_ defined for the target platform. 2557 if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace())) 2558 AssumedNoUBInsts.insert(&I); 2559 else 2560 KnownUBInsts.insert(&I); 2561 return true; 2562 }; 2563 2564 auto InspectBrInstForUB = [&](Instruction &I) { 2565 // A conditional branch instruction is considered UB if it has `undef` 2566 // condition. 2567 2568 // Skip instructions that are already saved. 2569 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 2570 return true; 2571 2572 // We know we have a branch instruction. 2573 auto *BrInst = cast<BranchInst>(&I); 2574 2575 // Unconditional branches are never considered UB. 2576 if (BrInst->isUnconditional()) 2577 return true; 2578 2579 // Either we stopped and the appropriate action was taken, 2580 // or we got back a simplified value to continue. 2581 Optional<Value *> SimplifiedCond = 2582 stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst); 2583 if (!SimplifiedCond || !*SimplifiedCond) 2584 return true; 2585 AssumedNoUBInsts.insert(&I); 2586 return true; 2587 }; 2588 2589 auto InspectCallSiteForUB = [&](Instruction &I) { 2590 // Check whether a callsite always cause UB or not 2591 2592 // Skip instructions that are already saved. 2593 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 2594 return true; 2595 2596 // Check nonnull and noundef argument attribute violation for each 2597 // callsite. 2598 CallBase &CB = cast<CallBase>(I); 2599 Function *Callee = CB.getCalledFunction(); 2600 if (!Callee) 2601 return true; 2602 for (unsigned idx = 0; idx < CB.arg_size(); idx++) { 2603 // If current argument is known to be simplified to null pointer and the 2604 // corresponding argument position is known to have nonnull attribute, 2605 // the argument is poison. Furthermore, if the argument is poison and 2606 // the position is known to have noundef attriubte, this callsite is 2607 // considered UB. 2608 if (idx >= Callee->arg_size()) 2609 break; 2610 Value *ArgVal = CB.getArgOperand(idx); 2611 if (!ArgVal) 2612 continue; 2613 // Here, we handle three cases. 2614 // (1) Not having a value means it is dead. (we can replace the value 2615 // with undef) 2616 // (2) Simplified to undef. The argument violate noundef attriubte. 2617 // (3) Simplified to null pointer where known to be nonnull. 2618 // The argument is a poison value and violate noundef attribute. 2619 IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx); 2620 auto &NoUndefAA = 2621 A.getAAFor<AANoUndef>(*this, CalleeArgumentIRP, DepClassTy::NONE); 2622 if (!NoUndefAA.isKnownNoUndef()) 2623 continue; 2624 bool UsedAssumedInformation = false; 2625 Optional<Value *> SimplifiedVal = 2626 A.getAssumedSimplified(IRPosition::value(*ArgVal), *this, 2627 UsedAssumedInformation, AA::Interprocedural); 2628 if (UsedAssumedInformation) 2629 continue; 2630 if (SimplifiedVal && !SimplifiedVal.value()) 2631 return true; 2632 if (!SimplifiedVal || isa<UndefValue>(*SimplifiedVal.value())) { 2633 KnownUBInsts.insert(&I); 2634 continue; 2635 } 2636 if (!ArgVal->getType()->isPointerTy() || 2637 !isa<ConstantPointerNull>(*SimplifiedVal.value())) 2638 continue; 2639 auto &NonNullAA = 2640 A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE); 2641 if (NonNullAA.isKnownNonNull()) 2642 KnownUBInsts.insert(&I); 2643 } 2644 return true; 2645 }; 2646 2647 auto InspectReturnInstForUB = [&](Instruction &I) { 2648 auto &RI = cast<ReturnInst>(I); 2649 // Either we stopped and the appropriate action was taken, 2650 // or we got back a simplified return value to continue. 2651 Optional<Value *> SimplifiedRetValue = 2652 stopOnUndefOrAssumed(A, RI.getReturnValue(), &I); 2653 if (!SimplifiedRetValue || !*SimplifiedRetValue) 2654 return true; 2655 2656 // Check if a return instruction always cause UB or not 2657 // Note: It is guaranteed that the returned position of the anchor 2658 // scope has noundef attribute when this is called. 2659 // We also ensure the return position is not "assumed dead" 2660 // because the returned value was then potentially simplified to 2661 // `undef` in AAReturnedValues without removing the `noundef` 2662 // attribute yet. 2663 2664 // When the returned position has noundef attriubte, UB occurs in the 2665 // following cases. 2666 // (1) Returned value is known to be undef. 2667 // (2) The value is known to be a null pointer and the returned 2668 // position has nonnull attribute (because the returned value is 2669 // poison). 2670 if (isa<ConstantPointerNull>(*SimplifiedRetValue)) { 2671 auto &NonNullAA = A.getAAFor<AANonNull>( 2672 *this, IRPosition::returned(*getAnchorScope()), DepClassTy::NONE); 2673 if (NonNullAA.isKnownNonNull()) 2674 KnownUBInsts.insert(&I); 2675 } 2676 2677 return true; 2678 }; 2679 2680 bool UsedAssumedInformation = false; 2681 A.checkForAllInstructions(InspectMemAccessInstForUB, *this, 2682 {Instruction::Load, Instruction::Store, 2683 Instruction::AtomicCmpXchg, 2684 Instruction::AtomicRMW}, 2685 UsedAssumedInformation, 2686 /* CheckBBLivenessOnly */ true); 2687 A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br}, 2688 UsedAssumedInformation, 2689 /* CheckBBLivenessOnly */ true); 2690 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this, 2691 UsedAssumedInformation); 2692 2693 // If the returned position of the anchor scope has noundef attriubte, check 2694 // all returned instructions. 2695 if (!getAnchorScope()->getReturnType()->isVoidTy()) { 2696 const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope()); 2697 if (!A.isAssumedDead(ReturnIRP, this, nullptr, UsedAssumedInformation)) { 2698 auto &RetPosNoUndefAA = 2699 A.getAAFor<AANoUndef>(*this, ReturnIRP, DepClassTy::NONE); 2700 if (RetPosNoUndefAA.isKnownNoUndef()) 2701 A.checkForAllInstructions(InspectReturnInstForUB, *this, 2702 {Instruction::Ret}, UsedAssumedInformation, 2703 /* CheckBBLivenessOnly */ true); 2704 } 2705 } 2706 2707 if (NoUBPrevSize != AssumedNoUBInsts.size() || 2708 UBPrevSize != KnownUBInsts.size()) 2709 return ChangeStatus::CHANGED; 2710 return ChangeStatus::UNCHANGED; 2711 } 2712 2713 bool isKnownToCauseUB(Instruction *I) const override { 2714 return KnownUBInsts.count(I); 2715 } 2716 2717 bool isAssumedToCauseUB(Instruction *I) const override { 2718 // In simple words, if an instruction is not in the assumed to _not_ 2719 // cause UB, then it is assumed UB (that includes those 2720 // in the KnownUBInsts set). The rest is boilerplate 2721 // is to ensure that it is one of the instructions we test 2722 // for UB. 2723 2724 switch (I->getOpcode()) { 2725 case Instruction::Load: 2726 case Instruction::Store: 2727 case Instruction::AtomicCmpXchg: 2728 case Instruction::AtomicRMW: 2729 return !AssumedNoUBInsts.count(I); 2730 case Instruction::Br: { 2731 auto *BrInst = cast<BranchInst>(I); 2732 if (BrInst->isUnconditional()) 2733 return false; 2734 return !AssumedNoUBInsts.count(I); 2735 } break; 2736 default: 2737 return false; 2738 } 2739 return false; 2740 } 2741 2742 ChangeStatus manifest(Attributor &A) override { 2743 if (KnownUBInsts.empty()) 2744 return ChangeStatus::UNCHANGED; 2745 for (Instruction *I : KnownUBInsts) 2746 A.changeToUnreachableAfterManifest(I); 2747 return ChangeStatus::CHANGED; 2748 } 2749 2750 /// See AbstractAttribute::getAsStr() 2751 const std::string getAsStr() const override { 2752 return getAssumed() ? "undefined-behavior" : "no-ub"; 2753 } 2754 2755 /// Note: The correctness of this analysis depends on the fact that the 2756 /// following 2 sets will stop changing after some point. 2757 /// "Change" here means that their size changes. 2758 /// The size of each set is monotonically increasing 2759 /// (we only add items to them) and it is upper bounded by the number of 2760 /// instructions in the processed function (we can never save more 2761 /// elements in either set than this number). Hence, at some point, 2762 /// they will stop increasing. 2763 /// Consequently, at some point, both sets will have stopped 2764 /// changing, effectively making the analysis reach a fixpoint. 2765 2766 /// Note: These 2 sets are disjoint and an instruction can be considered 2767 /// one of 3 things: 2768 /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in 2769 /// the KnownUBInsts set. 2770 /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior 2771 /// has a reason to assume it). 2772 /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior 2773 /// could not find a reason to assume or prove that it can cause UB, 2774 /// hence it assumes it doesn't. We have a set for these instructions 2775 /// so that we don't reprocess them in every update. 2776 /// Note however that instructions in this set may cause UB. 2777 2778 protected: 2779 /// A set of all live instructions _known_ to cause UB. 2780 SmallPtrSet<Instruction *, 8> KnownUBInsts; 2781 2782 private: 2783 /// A set of all the (live) instructions that are assumed to _not_ cause UB. 2784 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts; 2785 2786 // Should be called on updates in which if we're processing an instruction 2787 // \p I that depends on a value \p V, one of the following has to happen: 2788 // - If the value is assumed, then stop. 2789 // - If the value is known but undef, then consider it UB. 2790 // - Otherwise, do specific processing with the simplified value. 2791 // We return None in the first 2 cases to signify that an appropriate 2792 // action was taken and the caller should stop. 2793 // Otherwise, we return the simplified value that the caller should 2794 // use for specific processing. 2795 Optional<Value *> stopOnUndefOrAssumed(Attributor &A, Value *V, 2796 Instruction *I) { 2797 bool UsedAssumedInformation = false; 2798 Optional<Value *> SimplifiedV = 2799 A.getAssumedSimplified(IRPosition::value(*V), *this, 2800 UsedAssumedInformation, AA::Interprocedural); 2801 if (!UsedAssumedInformation) { 2802 // Don't depend on assumed values. 2803 if (!SimplifiedV) { 2804 // If it is known (which we tested above) but it doesn't have a value, 2805 // then we can assume `undef` and hence the instruction is UB. 2806 KnownUBInsts.insert(I); 2807 return llvm::None; 2808 } 2809 if (!*SimplifiedV) 2810 return nullptr; 2811 V = *SimplifiedV; 2812 } 2813 if (isa<UndefValue>(V)) { 2814 KnownUBInsts.insert(I); 2815 return llvm::None; 2816 } 2817 return V; 2818 } 2819 }; 2820 2821 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl { 2822 AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A) 2823 : AAUndefinedBehaviorImpl(IRP, A) {} 2824 2825 /// See AbstractAttribute::trackStatistics() 2826 void trackStatistics() const override { 2827 STATS_DECL(UndefinedBehaviorInstruction, Instruction, 2828 "Number of instructions known to have UB"); 2829 BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) += 2830 KnownUBInsts.size(); 2831 } 2832 }; 2833 } // namespace 2834 2835 /// ------------------------ Will-Return Attributes ---------------------------- 2836 2837 namespace { 2838 // Helper function that checks whether a function has any cycle which we don't 2839 // know if it is bounded or not. 2840 // Loops with maximum trip count are considered bounded, any other cycle not. 2841 static bool mayContainUnboundedCycle(Function &F, Attributor &A) { 2842 ScalarEvolution *SE = 2843 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F); 2844 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F); 2845 // If either SCEV or LoopInfo is not available for the function then we assume 2846 // any cycle to be unbounded cycle. 2847 // We use scc_iterator which uses Tarjan algorithm to find all the maximal 2848 // SCCs.To detect if there's a cycle, we only need to find the maximal ones. 2849 if (!SE || !LI) { 2850 for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI) 2851 if (SCCI.hasCycle()) 2852 return true; 2853 return false; 2854 } 2855 2856 // If there's irreducible control, the function may contain non-loop cycles. 2857 if (mayContainIrreducibleControl(F, LI)) 2858 return true; 2859 2860 // Any loop that does not have a max trip count is considered unbounded cycle. 2861 for (auto *L : LI->getLoopsInPreorder()) { 2862 if (!SE->getSmallConstantMaxTripCount(L)) 2863 return true; 2864 } 2865 return false; 2866 } 2867 2868 struct AAWillReturnImpl : public AAWillReturn { 2869 AAWillReturnImpl(const IRPosition &IRP, Attributor &A) 2870 : AAWillReturn(IRP, A) {} 2871 2872 /// See AbstractAttribute::initialize(...). 2873 void initialize(Attributor &A) override { 2874 AAWillReturn::initialize(A); 2875 2876 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ true)) { 2877 indicateOptimisticFixpoint(); 2878 return; 2879 } 2880 } 2881 2882 /// Check for `mustprogress` and `readonly` as they imply `willreturn`. 2883 bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) { 2884 // Check for `mustprogress` in the scope and the associated function which 2885 // might be different if this is a call site. 2886 if ((!getAnchorScope() || !getAnchorScope()->mustProgress()) && 2887 (!getAssociatedFunction() || !getAssociatedFunction()->mustProgress())) 2888 return false; 2889 2890 bool IsKnown; 2891 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown)) 2892 return IsKnown || !KnownOnly; 2893 return false; 2894 } 2895 2896 /// See AbstractAttribute::updateImpl(...). 2897 ChangeStatus updateImpl(Attributor &A) override { 2898 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false)) 2899 return ChangeStatus::UNCHANGED; 2900 2901 auto CheckForWillReturn = [&](Instruction &I) { 2902 IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I)); 2903 const auto &WillReturnAA = 2904 A.getAAFor<AAWillReturn>(*this, IPos, DepClassTy::REQUIRED); 2905 if (WillReturnAA.isKnownWillReturn()) 2906 return true; 2907 if (!WillReturnAA.isAssumedWillReturn()) 2908 return false; 2909 const auto &NoRecurseAA = 2910 A.getAAFor<AANoRecurse>(*this, IPos, DepClassTy::REQUIRED); 2911 return NoRecurseAA.isAssumedNoRecurse(); 2912 }; 2913 2914 bool UsedAssumedInformation = false; 2915 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this, 2916 UsedAssumedInformation)) 2917 return indicatePessimisticFixpoint(); 2918 2919 return ChangeStatus::UNCHANGED; 2920 } 2921 2922 /// See AbstractAttribute::getAsStr() 2923 const std::string getAsStr() const override { 2924 return getAssumed() ? "willreturn" : "may-noreturn"; 2925 } 2926 }; 2927 2928 struct AAWillReturnFunction final : AAWillReturnImpl { 2929 AAWillReturnFunction(const IRPosition &IRP, Attributor &A) 2930 : AAWillReturnImpl(IRP, A) {} 2931 2932 /// See AbstractAttribute::initialize(...). 2933 void initialize(Attributor &A) override { 2934 AAWillReturnImpl::initialize(A); 2935 2936 Function *F = getAnchorScope(); 2937 if (!F || F->isDeclaration() || mayContainUnboundedCycle(*F, A)) 2938 indicatePessimisticFixpoint(); 2939 } 2940 2941 /// See AbstractAttribute::trackStatistics() 2942 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) } 2943 }; 2944 2945 /// WillReturn attribute deduction for a call sites. 2946 struct AAWillReturnCallSite final : AAWillReturnImpl { 2947 AAWillReturnCallSite(const IRPosition &IRP, Attributor &A) 2948 : AAWillReturnImpl(IRP, A) {} 2949 2950 /// See AbstractAttribute::initialize(...). 2951 void initialize(Attributor &A) override { 2952 AAWillReturnImpl::initialize(A); 2953 Function *F = getAssociatedFunction(); 2954 if (!F || !A.isFunctionIPOAmendable(*F)) 2955 indicatePessimisticFixpoint(); 2956 } 2957 2958 /// See AbstractAttribute::updateImpl(...). 2959 ChangeStatus updateImpl(Attributor &A) override { 2960 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false)) 2961 return ChangeStatus::UNCHANGED; 2962 2963 // TODO: Once we have call site specific value information we can provide 2964 // call site specific liveness information and then it makes 2965 // sense to specialize attributes for call sites arguments instead of 2966 // redirecting requests to the callee argument. 2967 Function *F = getAssociatedFunction(); 2968 const IRPosition &FnPos = IRPosition::function(*F); 2969 auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos, DepClassTy::REQUIRED); 2970 return clampStateAndIndicateChange(getState(), FnAA.getState()); 2971 } 2972 2973 /// See AbstractAttribute::trackStatistics() 2974 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); } 2975 }; 2976 } // namespace 2977 2978 /// -------------------AAReachability Attribute-------------------------- 2979 2980 namespace { 2981 struct AAReachabilityImpl : AAReachability { 2982 AAReachabilityImpl(const IRPosition &IRP, Attributor &A) 2983 : AAReachability(IRP, A) {} 2984 2985 const std::string getAsStr() const override { 2986 // TODO: Return the number of reachable queries. 2987 return "reachable"; 2988 } 2989 2990 /// See AbstractAttribute::updateImpl(...). 2991 ChangeStatus updateImpl(Attributor &A) override { 2992 return ChangeStatus::UNCHANGED; 2993 } 2994 }; 2995 2996 struct AAReachabilityFunction final : public AAReachabilityImpl { 2997 AAReachabilityFunction(const IRPosition &IRP, Attributor &A) 2998 : AAReachabilityImpl(IRP, A) {} 2999 3000 /// See AbstractAttribute::trackStatistics() 3001 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); } 3002 }; 3003 } // namespace 3004 3005 /// ------------------------ NoAlias Argument Attribute ------------------------ 3006 3007 namespace { 3008 struct AANoAliasImpl : AANoAlias { 3009 AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) { 3010 assert(getAssociatedType()->isPointerTy() && 3011 "Noalias is a pointer attribute"); 3012 } 3013 3014 const std::string getAsStr() const override { 3015 return getAssumed() ? "noalias" : "may-alias"; 3016 } 3017 }; 3018 3019 /// NoAlias attribute for a floating value. 3020 struct AANoAliasFloating final : AANoAliasImpl { 3021 AANoAliasFloating(const IRPosition &IRP, Attributor &A) 3022 : AANoAliasImpl(IRP, A) {} 3023 3024 /// See AbstractAttribute::initialize(...). 3025 void initialize(Attributor &A) override { 3026 AANoAliasImpl::initialize(A); 3027 Value *Val = &getAssociatedValue(); 3028 do { 3029 CastInst *CI = dyn_cast<CastInst>(Val); 3030 if (!CI) 3031 break; 3032 Value *Base = CI->getOperand(0); 3033 if (!Base->hasOneUse()) 3034 break; 3035 Val = Base; 3036 } while (true); 3037 3038 if (!Val->getType()->isPointerTy()) { 3039 indicatePessimisticFixpoint(); 3040 return; 3041 } 3042 3043 if (isa<AllocaInst>(Val)) 3044 indicateOptimisticFixpoint(); 3045 else if (isa<ConstantPointerNull>(Val) && 3046 !NullPointerIsDefined(getAnchorScope(), 3047 Val->getType()->getPointerAddressSpace())) 3048 indicateOptimisticFixpoint(); 3049 else if (Val != &getAssociatedValue()) { 3050 const auto &ValNoAliasAA = A.getAAFor<AANoAlias>( 3051 *this, IRPosition::value(*Val), DepClassTy::OPTIONAL); 3052 if (ValNoAliasAA.isKnownNoAlias()) 3053 indicateOptimisticFixpoint(); 3054 } 3055 } 3056 3057 /// See AbstractAttribute::updateImpl(...). 3058 ChangeStatus updateImpl(Attributor &A) override { 3059 // TODO: Implement this. 3060 return indicatePessimisticFixpoint(); 3061 } 3062 3063 /// See AbstractAttribute::trackStatistics() 3064 void trackStatistics() const override { 3065 STATS_DECLTRACK_FLOATING_ATTR(noalias) 3066 } 3067 }; 3068 3069 /// NoAlias attribute for an argument. 3070 struct AANoAliasArgument final 3071 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> { 3072 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>; 3073 AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 3074 3075 /// See AbstractAttribute::initialize(...). 3076 void initialize(Attributor &A) override { 3077 Base::initialize(A); 3078 // See callsite argument attribute and callee argument attribute. 3079 if (hasAttr({Attribute::ByVal})) 3080 indicateOptimisticFixpoint(); 3081 } 3082 3083 /// See AbstractAttribute::update(...). 3084 ChangeStatus updateImpl(Attributor &A) override { 3085 // We have to make sure no-alias on the argument does not break 3086 // synchronization when this is a callback argument, see also [1] below. 3087 // If synchronization cannot be affected, we delegate to the base updateImpl 3088 // function, otherwise we give up for now. 3089 3090 // If the function is no-sync, no-alias cannot break synchronization. 3091 const auto &NoSyncAA = 3092 A.getAAFor<AANoSync>(*this, IRPosition::function_scope(getIRPosition()), 3093 DepClassTy::OPTIONAL); 3094 if (NoSyncAA.isAssumedNoSync()) 3095 return Base::updateImpl(A); 3096 3097 // If the argument is read-only, no-alias cannot break synchronization. 3098 bool IsKnown; 3099 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown)) 3100 return Base::updateImpl(A); 3101 3102 // If the argument is never passed through callbacks, no-alias cannot break 3103 // synchronization. 3104 bool UsedAssumedInformation = false; 3105 if (A.checkForAllCallSites( 3106 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this, 3107 true, UsedAssumedInformation)) 3108 return Base::updateImpl(A); 3109 3110 // TODO: add no-alias but make sure it doesn't break synchronization by 3111 // introducing fake uses. See: 3112 // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel, 3113 // International Workshop on OpenMP 2018, 3114 // http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf 3115 3116 return indicatePessimisticFixpoint(); 3117 } 3118 3119 /// See AbstractAttribute::trackStatistics() 3120 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 3121 }; 3122 3123 struct AANoAliasCallSiteArgument final : AANoAliasImpl { 3124 AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A) 3125 : AANoAliasImpl(IRP, A) {} 3126 3127 /// See AbstractAttribute::initialize(...). 3128 void initialize(Attributor &A) override { 3129 // See callsite argument attribute and callee argument attribute. 3130 const auto &CB = cast<CallBase>(getAnchorValue()); 3131 if (CB.paramHasAttr(getCallSiteArgNo(), Attribute::NoAlias)) 3132 indicateOptimisticFixpoint(); 3133 Value &Val = getAssociatedValue(); 3134 if (isa<ConstantPointerNull>(Val) && 3135 !NullPointerIsDefined(getAnchorScope(), 3136 Val.getType()->getPointerAddressSpace())) 3137 indicateOptimisticFixpoint(); 3138 } 3139 3140 /// Determine if the underlying value may alias with the call site argument 3141 /// \p OtherArgNo of \p ICS (= the underlying call site). 3142 bool mayAliasWithArgument(Attributor &A, AAResults *&AAR, 3143 const AAMemoryBehavior &MemBehaviorAA, 3144 const CallBase &CB, unsigned OtherArgNo) { 3145 // We do not need to worry about aliasing with the underlying IRP. 3146 if (this->getCalleeArgNo() == (int)OtherArgNo) 3147 return false; 3148 3149 // If it is not a pointer or pointer vector we do not alias. 3150 const Value *ArgOp = CB.getArgOperand(OtherArgNo); 3151 if (!ArgOp->getType()->isPtrOrPtrVectorTy()) 3152 return false; 3153 3154 auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 3155 *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE); 3156 3157 // If the argument is readnone, there is no read-write aliasing. 3158 if (CBArgMemBehaviorAA.isAssumedReadNone()) { 3159 A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL); 3160 return false; 3161 } 3162 3163 // If the argument is readonly and the underlying value is readonly, there 3164 // is no read-write aliasing. 3165 bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly(); 3166 if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) { 3167 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 3168 A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL); 3169 return false; 3170 } 3171 3172 // We have to utilize actual alias analysis queries so we need the object. 3173 if (!AAR) 3174 AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope()); 3175 3176 // Try to rule it out at the call site. 3177 bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp); 3178 LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between " 3179 "callsite arguments: " 3180 << getAssociatedValue() << " " << *ArgOp << " => " 3181 << (IsAliasing ? "" : "no-") << "alias \n"); 3182 3183 return IsAliasing; 3184 } 3185 3186 bool 3187 isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR, 3188 const AAMemoryBehavior &MemBehaviorAA, 3189 const AANoAlias &NoAliasAA) { 3190 // We can deduce "noalias" if the following conditions hold. 3191 // (i) Associated value is assumed to be noalias in the definition. 3192 // (ii) Associated value is assumed to be no-capture in all the uses 3193 // possibly executed before this callsite. 3194 // (iii) There is no other pointer argument which could alias with the 3195 // value. 3196 3197 bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias(); 3198 if (!AssociatedValueIsNoAliasAtDef) { 3199 LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue() 3200 << " is not no-alias at the definition\n"); 3201 return false; 3202 } 3203 3204 auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) { 3205 const auto &DerefAA = A.getAAFor<AADereferenceable>( 3206 *this, IRPosition::value(*O), DepClassTy::OPTIONAL); 3207 return DerefAA.getAssumedDereferenceableBytes(); 3208 }; 3209 3210 A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL); 3211 3212 const IRPosition &VIRP = IRPosition::value(getAssociatedValue()); 3213 const Function *ScopeFn = VIRP.getAnchorScope(); 3214 auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, VIRP, DepClassTy::NONE); 3215 // Check whether the value is captured in the scope using AANoCapture. 3216 // Look at CFG and check only uses possibly executed before this 3217 // callsite. 3218 auto UsePred = [&](const Use &U, bool &Follow) -> bool { 3219 Instruction *UserI = cast<Instruction>(U.getUser()); 3220 3221 // If UserI is the curr instruction and there is a single potential use of 3222 // the value in UserI we allow the use. 3223 // TODO: We should inspect the operands and allow those that cannot alias 3224 // with the value. 3225 if (UserI == getCtxI() && UserI->getNumOperands() == 1) 3226 return true; 3227 3228 if (ScopeFn) { 3229 if (auto *CB = dyn_cast<CallBase>(UserI)) { 3230 if (CB->isArgOperand(&U)) { 3231 3232 unsigned ArgNo = CB->getArgOperandNo(&U); 3233 3234 const auto &NoCaptureAA = A.getAAFor<AANoCapture>( 3235 *this, IRPosition::callsite_argument(*CB, ArgNo), 3236 DepClassTy::OPTIONAL); 3237 3238 if (NoCaptureAA.isAssumedNoCapture()) 3239 return true; 3240 } 3241 } 3242 3243 if (!AA::isPotentiallyReachable( 3244 A, *UserI, *getCtxI(), *this, 3245 [ScopeFn](const Function &Fn) { return &Fn != ScopeFn; })) 3246 return true; 3247 } 3248 3249 // TODO: We should track the capturing uses in AANoCapture but the problem 3250 // is CGSCC runs. For those we would need to "allow" AANoCapture for 3251 // a value in the module slice. 3252 switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) { 3253 case UseCaptureKind::NO_CAPTURE: 3254 return true; 3255 case UseCaptureKind::MAY_CAPTURE: 3256 LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *UserI 3257 << "\n"); 3258 return false; 3259 case UseCaptureKind::PASSTHROUGH: 3260 Follow = true; 3261 return true; 3262 } 3263 llvm_unreachable("unknown UseCaptureKind"); 3264 }; 3265 3266 if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 3267 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) { 3268 LLVM_DEBUG( 3269 dbgs() << "[AANoAliasCSArg] " << getAssociatedValue() 3270 << " cannot be noalias as it is potentially captured\n"); 3271 return false; 3272 } 3273 } 3274 A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL); 3275 3276 // Check there is no other pointer argument which could alias with the 3277 // value passed at this call site. 3278 // TODO: AbstractCallSite 3279 const auto &CB = cast<CallBase>(getAnchorValue()); 3280 for (unsigned OtherArgNo = 0; OtherArgNo < CB.arg_size(); OtherArgNo++) 3281 if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo)) 3282 return false; 3283 3284 return true; 3285 } 3286 3287 /// See AbstractAttribute::updateImpl(...). 3288 ChangeStatus updateImpl(Attributor &A) override { 3289 // If the argument is readnone we are done as there are no accesses via the 3290 // argument. 3291 auto &MemBehaviorAA = 3292 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 3293 if (MemBehaviorAA.isAssumedReadNone()) { 3294 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 3295 return ChangeStatus::UNCHANGED; 3296 } 3297 3298 const IRPosition &VIRP = IRPosition::value(getAssociatedValue()); 3299 const auto &NoAliasAA = 3300 A.getAAFor<AANoAlias>(*this, VIRP, DepClassTy::NONE); 3301 3302 AAResults *AAR = nullptr; 3303 if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA, 3304 NoAliasAA)) { 3305 LLVM_DEBUG( 3306 dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n"); 3307 return ChangeStatus::UNCHANGED; 3308 } 3309 3310 return indicatePessimisticFixpoint(); 3311 } 3312 3313 /// See AbstractAttribute::trackStatistics() 3314 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) } 3315 }; 3316 3317 /// NoAlias attribute for function return value. 3318 struct AANoAliasReturned final : AANoAliasImpl { 3319 AANoAliasReturned(const IRPosition &IRP, Attributor &A) 3320 : AANoAliasImpl(IRP, A) {} 3321 3322 /// See AbstractAttribute::initialize(...). 3323 void initialize(Attributor &A) override { 3324 AANoAliasImpl::initialize(A); 3325 Function *F = getAssociatedFunction(); 3326 if (!F || F->isDeclaration()) 3327 indicatePessimisticFixpoint(); 3328 } 3329 3330 /// See AbstractAttribute::updateImpl(...). 3331 virtual ChangeStatus updateImpl(Attributor &A) override { 3332 3333 auto CheckReturnValue = [&](Value &RV) -> bool { 3334 if (Constant *C = dyn_cast<Constant>(&RV)) 3335 if (C->isNullValue() || isa<UndefValue>(C)) 3336 return true; 3337 3338 /// For now, we can only deduce noalias if we have call sites. 3339 /// FIXME: add more support. 3340 if (!isa<CallBase>(&RV)) 3341 return false; 3342 3343 const IRPosition &RVPos = IRPosition::value(RV); 3344 const auto &NoAliasAA = 3345 A.getAAFor<AANoAlias>(*this, RVPos, DepClassTy::REQUIRED); 3346 if (!NoAliasAA.isAssumedNoAlias()) 3347 return false; 3348 3349 const auto &NoCaptureAA = 3350 A.getAAFor<AANoCapture>(*this, RVPos, DepClassTy::REQUIRED); 3351 return NoCaptureAA.isAssumedNoCaptureMaybeReturned(); 3352 }; 3353 3354 if (!A.checkForAllReturnedValues(CheckReturnValue, *this)) 3355 return indicatePessimisticFixpoint(); 3356 3357 return ChangeStatus::UNCHANGED; 3358 } 3359 3360 /// See AbstractAttribute::trackStatistics() 3361 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) } 3362 }; 3363 3364 /// NoAlias attribute deduction for a call site return value. 3365 struct AANoAliasCallSiteReturned final : AANoAliasImpl { 3366 AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A) 3367 : AANoAliasImpl(IRP, A) {} 3368 3369 /// See AbstractAttribute::initialize(...). 3370 void initialize(Attributor &A) override { 3371 AANoAliasImpl::initialize(A); 3372 Function *F = getAssociatedFunction(); 3373 if (!F || F->isDeclaration()) 3374 indicatePessimisticFixpoint(); 3375 } 3376 3377 /// See AbstractAttribute::updateImpl(...). 3378 ChangeStatus updateImpl(Attributor &A) override { 3379 // TODO: Once we have call site specific value information we can provide 3380 // call site specific liveness information and then it makes 3381 // sense to specialize attributes for call sites arguments instead of 3382 // redirecting requests to the callee argument. 3383 Function *F = getAssociatedFunction(); 3384 const IRPosition &FnPos = IRPosition::returned(*F); 3385 auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos, DepClassTy::REQUIRED); 3386 return clampStateAndIndicateChange(getState(), FnAA.getState()); 3387 } 3388 3389 /// See AbstractAttribute::trackStatistics() 3390 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); } 3391 }; 3392 } // namespace 3393 3394 /// -------------------AAIsDead Function Attribute----------------------- 3395 3396 namespace { 3397 struct AAIsDeadValueImpl : public AAIsDead { 3398 AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {} 3399 3400 /// See AbstractAttribute::initialize(...). 3401 void initialize(Attributor &A) override { 3402 if (auto *Scope = getAnchorScope()) 3403 if (!A.isRunOn(*Scope)) 3404 indicatePessimisticFixpoint(); 3405 } 3406 3407 /// See AAIsDead::isAssumedDead(). 3408 bool isAssumedDead() const override { return isAssumed(IS_DEAD); } 3409 3410 /// See AAIsDead::isKnownDead(). 3411 bool isKnownDead() const override { return isKnown(IS_DEAD); } 3412 3413 /// See AAIsDead::isAssumedDead(BasicBlock *). 3414 bool isAssumedDead(const BasicBlock *BB) const override { return false; } 3415 3416 /// See AAIsDead::isKnownDead(BasicBlock *). 3417 bool isKnownDead(const BasicBlock *BB) const override { return false; } 3418 3419 /// See AAIsDead::isAssumedDead(Instruction *I). 3420 bool isAssumedDead(const Instruction *I) const override { 3421 return I == getCtxI() && isAssumedDead(); 3422 } 3423 3424 /// See AAIsDead::isKnownDead(Instruction *I). 3425 bool isKnownDead(const Instruction *I) const override { 3426 return isAssumedDead(I) && isKnownDead(); 3427 } 3428 3429 /// See AbstractAttribute::getAsStr(). 3430 virtual const std::string getAsStr() const override { 3431 return isAssumedDead() ? "assumed-dead" : "assumed-live"; 3432 } 3433 3434 /// Check if all uses are assumed dead. 3435 bool areAllUsesAssumedDead(Attributor &A, Value &V) { 3436 // Callers might not check the type, void has no uses. 3437 if (V.getType()->isVoidTy() || V.use_empty()) 3438 return true; 3439 3440 // If we replace a value with a constant there are no uses left afterwards. 3441 if (!isa<Constant>(V)) { 3442 if (auto *I = dyn_cast<Instruction>(&V)) 3443 if (!A.isRunOn(*I->getFunction())) 3444 return false; 3445 bool UsedAssumedInformation = false; 3446 Optional<Constant *> C = 3447 A.getAssumedConstant(V, *this, UsedAssumedInformation); 3448 if (!C || *C) 3449 return true; 3450 } 3451 3452 auto UsePred = [&](const Use &U, bool &Follow) { return false; }; 3453 // Explicitly set the dependence class to required because we want a long 3454 // chain of N dependent instructions to be considered live as soon as one is 3455 // without going through N update cycles. This is not required for 3456 // correctness. 3457 return A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ false, 3458 DepClassTy::REQUIRED, 3459 /* IgnoreDroppableUses */ false); 3460 } 3461 3462 /// Determine if \p I is assumed to be side-effect free. 3463 bool isAssumedSideEffectFree(Attributor &A, Instruction *I) { 3464 if (!I || wouldInstructionBeTriviallyDead(I)) 3465 return true; 3466 3467 auto *CB = dyn_cast<CallBase>(I); 3468 if (!CB || isa<IntrinsicInst>(CB)) 3469 return false; 3470 3471 const IRPosition &CallIRP = IRPosition::callsite_function(*CB); 3472 const auto &NoUnwindAA = 3473 A.getAndUpdateAAFor<AANoUnwind>(*this, CallIRP, DepClassTy::NONE); 3474 if (!NoUnwindAA.isAssumedNoUnwind()) 3475 return false; 3476 if (!NoUnwindAA.isKnownNoUnwind()) 3477 A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL); 3478 3479 bool IsKnown; 3480 return AA::isAssumedReadOnly(A, CallIRP, *this, IsKnown); 3481 } 3482 }; 3483 3484 struct AAIsDeadFloating : public AAIsDeadValueImpl { 3485 AAIsDeadFloating(const IRPosition &IRP, Attributor &A) 3486 : AAIsDeadValueImpl(IRP, A) {} 3487 3488 /// See AbstractAttribute::initialize(...). 3489 void initialize(Attributor &A) override { 3490 AAIsDeadValueImpl::initialize(A); 3491 3492 if (isa<UndefValue>(getAssociatedValue())) { 3493 indicatePessimisticFixpoint(); 3494 return; 3495 } 3496 3497 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 3498 if (!isAssumedSideEffectFree(A, I)) { 3499 if (!isa_and_nonnull<StoreInst>(I)) 3500 indicatePessimisticFixpoint(); 3501 else 3502 removeAssumedBits(HAS_NO_EFFECT); 3503 } 3504 } 3505 3506 bool isDeadStore(Attributor &A, StoreInst &SI) { 3507 // Lang ref now states volatile store is not UB/dead, let's skip them. 3508 if (SI.isVolatile()) 3509 return false; 3510 3511 bool UsedAssumedInformation = false; 3512 SmallSetVector<Value *, 4> PotentialCopies; 3513 if (!AA::getPotentialCopiesOfStoredValue(A, SI, PotentialCopies, *this, 3514 UsedAssumedInformation)) 3515 return false; 3516 return llvm::all_of(PotentialCopies, [&](Value *V) { 3517 return A.isAssumedDead(IRPosition::value(*V), this, nullptr, 3518 UsedAssumedInformation); 3519 }); 3520 } 3521 3522 /// See AbstractAttribute::getAsStr(). 3523 const std::string getAsStr() const override { 3524 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 3525 if (isa_and_nonnull<StoreInst>(I)) 3526 if (isValidState()) 3527 return "assumed-dead-store"; 3528 return AAIsDeadValueImpl::getAsStr(); 3529 } 3530 3531 /// See AbstractAttribute::updateImpl(...). 3532 ChangeStatus updateImpl(Attributor &A) override { 3533 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 3534 if (auto *SI = dyn_cast_or_null<StoreInst>(I)) { 3535 if (!isDeadStore(A, *SI)) 3536 return indicatePessimisticFixpoint(); 3537 } else { 3538 if (!isAssumedSideEffectFree(A, I)) 3539 return indicatePessimisticFixpoint(); 3540 if (!areAllUsesAssumedDead(A, getAssociatedValue())) 3541 return indicatePessimisticFixpoint(); 3542 } 3543 return ChangeStatus::UNCHANGED; 3544 } 3545 3546 bool isRemovableStore() const override { 3547 return isAssumed(IS_REMOVABLE) && isa<StoreInst>(&getAssociatedValue()); 3548 } 3549 3550 /// See AbstractAttribute::manifest(...). 3551 ChangeStatus manifest(Attributor &A) override { 3552 Value &V = getAssociatedValue(); 3553 if (auto *I = dyn_cast<Instruction>(&V)) { 3554 // If we get here we basically know the users are all dead. We check if 3555 // isAssumedSideEffectFree returns true here again because it might not be 3556 // the case and only the users are dead but the instruction (=call) is 3557 // still needed. 3558 if (isa<StoreInst>(I) || 3559 (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I))) { 3560 A.deleteAfterManifest(*I); 3561 return ChangeStatus::CHANGED; 3562 } 3563 } 3564 return ChangeStatus::UNCHANGED; 3565 } 3566 3567 /// See AbstractAttribute::trackStatistics() 3568 void trackStatistics() const override { 3569 STATS_DECLTRACK_FLOATING_ATTR(IsDead) 3570 } 3571 }; 3572 3573 struct AAIsDeadArgument : public AAIsDeadFloating { 3574 AAIsDeadArgument(const IRPosition &IRP, Attributor &A) 3575 : AAIsDeadFloating(IRP, A) {} 3576 3577 /// See AbstractAttribute::initialize(...). 3578 void initialize(Attributor &A) override { 3579 AAIsDeadFloating::initialize(A); 3580 if (!A.isFunctionIPOAmendable(*getAnchorScope())) 3581 indicatePessimisticFixpoint(); 3582 } 3583 3584 /// See AbstractAttribute::manifest(...). 3585 ChangeStatus manifest(Attributor &A) override { 3586 Argument &Arg = *getAssociatedArgument(); 3587 if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {})) 3588 if (A.registerFunctionSignatureRewrite( 3589 Arg, /* ReplacementTypes */ {}, 3590 Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{}, 3591 Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) { 3592 return ChangeStatus::CHANGED; 3593 } 3594 return ChangeStatus::UNCHANGED; 3595 } 3596 3597 /// See AbstractAttribute::trackStatistics() 3598 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) } 3599 }; 3600 3601 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl { 3602 AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A) 3603 : AAIsDeadValueImpl(IRP, A) {} 3604 3605 /// See AbstractAttribute::initialize(...). 3606 void initialize(Attributor &A) override { 3607 AAIsDeadValueImpl::initialize(A); 3608 if (isa<UndefValue>(getAssociatedValue())) 3609 indicatePessimisticFixpoint(); 3610 } 3611 3612 /// See AbstractAttribute::updateImpl(...). 3613 ChangeStatus updateImpl(Attributor &A) override { 3614 // TODO: Once we have call site specific value information we can provide 3615 // call site specific liveness information and then it makes 3616 // sense to specialize attributes for call sites arguments instead of 3617 // redirecting requests to the callee argument. 3618 Argument *Arg = getAssociatedArgument(); 3619 if (!Arg) 3620 return indicatePessimisticFixpoint(); 3621 const IRPosition &ArgPos = IRPosition::argument(*Arg); 3622 auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED); 3623 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 3624 } 3625 3626 /// See AbstractAttribute::manifest(...). 3627 ChangeStatus manifest(Attributor &A) override { 3628 CallBase &CB = cast<CallBase>(getAnchorValue()); 3629 Use &U = CB.getArgOperandUse(getCallSiteArgNo()); 3630 assert(!isa<UndefValue>(U.get()) && 3631 "Expected undef values to be filtered out!"); 3632 UndefValue &UV = *UndefValue::get(U->getType()); 3633 if (A.changeUseAfterManifest(U, UV)) 3634 return ChangeStatus::CHANGED; 3635 return ChangeStatus::UNCHANGED; 3636 } 3637 3638 /// See AbstractAttribute::trackStatistics() 3639 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) } 3640 }; 3641 3642 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating { 3643 AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A) 3644 : AAIsDeadFloating(IRP, A) {} 3645 3646 /// See AAIsDead::isAssumedDead(). 3647 bool isAssumedDead() const override { 3648 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree; 3649 } 3650 3651 /// See AbstractAttribute::initialize(...). 3652 void initialize(Attributor &A) override { 3653 AAIsDeadFloating::initialize(A); 3654 if (isa<UndefValue>(getAssociatedValue())) { 3655 indicatePessimisticFixpoint(); 3656 return; 3657 } 3658 3659 // We track this separately as a secondary state. 3660 IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI()); 3661 } 3662 3663 /// See AbstractAttribute::updateImpl(...). 3664 ChangeStatus updateImpl(Attributor &A) override { 3665 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3666 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) { 3667 IsAssumedSideEffectFree = false; 3668 Changed = ChangeStatus::CHANGED; 3669 } 3670 if (!areAllUsesAssumedDead(A, getAssociatedValue())) 3671 return indicatePessimisticFixpoint(); 3672 return Changed; 3673 } 3674 3675 /// See AbstractAttribute::trackStatistics() 3676 void trackStatistics() const override { 3677 if (IsAssumedSideEffectFree) 3678 STATS_DECLTRACK_CSRET_ATTR(IsDead) 3679 else 3680 STATS_DECLTRACK_CSRET_ATTR(UnusedResult) 3681 } 3682 3683 /// See AbstractAttribute::getAsStr(). 3684 const std::string getAsStr() const override { 3685 return isAssumedDead() 3686 ? "assumed-dead" 3687 : (getAssumed() ? "assumed-dead-users" : "assumed-live"); 3688 } 3689 3690 private: 3691 bool IsAssumedSideEffectFree = true; 3692 }; 3693 3694 struct AAIsDeadReturned : public AAIsDeadValueImpl { 3695 AAIsDeadReturned(const IRPosition &IRP, Attributor &A) 3696 : AAIsDeadValueImpl(IRP, A) {} 3697 3698 /// See AbstractAttribute::updateImpl(...). 3699 ChangeStatus updateImpl(Attributor &A) override { 3700 3701 bool UsedAssumedInformation = false; 3702 A.checkForAllInstructions([](Instruction &) { return true; }, *this, 3703 {Instruction::Ret}, UsedAssumedInformation); 3704 3705 auto PredForCallSite = [&](AbstractCallSite ACS) { 3706 if (ACS.isCallbackCall() || !ACS.getInstruction()) 3707 return false; 3708 return areAllUsesAssumedDead(A, *ACS.getInstruction()); 3709 }; 3710 3711 if (!A.checkForAllCallSites(PredForCallSite, *this, true, 3712 UsedAssumedInformation)) 3713 return indicatePessimisticFixpoint(); 3714 3715 return ChangeStatus::UNCHANGED; 3716 } 3717 3718 /// See AbstractAttribute::manifest(...). 3719 ChangeStatus manifest(Attributor &A) override { 3720 // TODO: Rewrite the signature to return void? 3721 bool AnyChange = false; 3722 UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType()); 3723 auto RetInstPred = [&](Instruction &I) { 3724 ReturnInst &RI = cast<ReturnInst>(I); 3725 if (!isa<UndefValue>(RI.getReturnValue())) 3726 AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV); 3727 return true; 3728 }; 3729 bool UsedAssumedInformation = false; 3730 A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret}, 3731 UsedAssumedInformation); 3732 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 3733 } 3734 3735 /// See AbstractAttribute::trackStatistics() 3736 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) } 3737 }; 3738 3739 struct AAIsDeadFunction : public AAIsDead { 3740 AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {} 3741 3742 /// See AbstractAttribute::initialize(...). 3743 void initialize(Attributor &A) override { 3744 Function *F = getAnchorScope(); 3745 if (!F || F->isDeclaration() || !A.isRunOn(*F)) { 3746 indicatePessimisticFixpoint(); 3747 return; 3748 } 3749 ToBeExploredFrom.insert(&F->getEntryBlock().front()); 3750 assumeLive(A, F->getEntryBlock()); 3751 } 3752 3753 /// See AbstractAttribute::getAsStr(). 3754 const std::string getAsStr() const override { 3755 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" + 3756 std::to_string(getAnchorScope()->size()) + "][#TBEP " + 3757 std::to_string(ToBeExploredFrom.size()) + "][#KDE " + 3758 std::to_string(KnownDeadEnds.size()) + "]"; 3759 } 3760 3761 /// See AbstractAttribute::manifest(...). 3762 ChangeStatus manifest(Attributor &A) override { 3763 assert(getState().isValidState() && 3764 "Attempted to manifest an invalid state!"); 3765 3766 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 3767 Function &F = *getAnchorScope(); 3768 3769 if (AssumedLiveBlocks.empty()) { 3770 A.deleteAfterManifest(F); 3771 return ChangeStatus::CHANGED; 3772 } 3773 3774 // Flag to determine if we can change an invoke to a call assuming the 3775 // callee is nounwind. This is not possible if the personality of the 3776 // function allows to catch asynchronous exceptions. 3777 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 3778 3779 KnownDeadEnds.set_union(ToBeExploredFrom); 3780 for (const Instruction *DeadEndI : KnownDeadEnds) { 3781 auto *CB = dyn_cast<CallBase>(DeadEndI); 3782 if (!CB) 3783 continue; 3784 const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>( 3785 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL); 3786 bool MayReturn = !NoReturnAA.isAssumedNoReturn(); 3787 if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB))) 3788 continue; 3789 3790 if (auto *II = dyn_cast<InvokeInst>(DeadEndI)) 3791 A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II)); 3792 else 3793 A.changeToUnreachableAfterManifest( 3794 const_cast<Instruction *>(DeadEndI->getNextNode())); 3795 HasChanged = ChangeStatus::CHANGED; 3796 } 3797 3798 STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted."); 3799 for (BasicBlock &BB : F) 3800 if (!AssumedLiveBlocks.count(&BB)) { 3801 A.deleteAfterManifest(BB); 3802 ++BUILD_STAT_NAME(AAIsDead, BasicBlock); 3803 HasChanged = ChangeStatus::CHANGED; 3804 } 3805 3806 return HasChanged; 3807 } 3808 3809 /// See AbstractAttribute::updateImpl(...). 3810 ChangeStatus updateImpl(Attributor &A) override; 3811 3812 bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override { 3813 assert(From->getParent() == getAnchorScope() && 3814 To->getParent() == getAnchorScope() && 3815 "Used AAIsDead of the wrong function"); 3816 return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To)); 3817 } 3818 3819 /// See AbstractAttribute::trackStatistics() 3820 void trackStatistics() const override {} 3821 3822 /// Returns true if the function is assumed dead. 3823 bool isAssumedDead() const override { return false; } 3824 3825 /// See AAIsDead::isKnownDead(). 3826 bool isKnownDead() const override { return false; } 3827 3828 /// See AAIsDead::isAssumedDead(BasicBlock *). 3829 bool isAssumedDead(const BasicBlock *BB) const override { 3830 assert(BB->getParent() == getAnchorScope() && 3831 "BB must be in the same anchor scope function."); 3832 3833 if (!getAssumed()) 3834 return false; 3835 return !AssumedLiveBlocks.count(BB); 3836 } 3837 3838 /// See AAIsDead::isKnownDead(BasicBlock *). 3839 bool isKnownDead(const BasicBlock *BB) const override { 3840 return getKnown() && isAssumedDead(BB); 3841 } 3842 3843 /// See AAIsDead::isAssumed(Instruction *I). 3844 bool isAssumedDead(const Instruction *I) const override { 3845 assert(I->getParent()->getParent() == getAnchorScope() && 3846 "Instruction must be in the same anchor scope function."); 3847 3848 if (!getAssumed()) 3849 return false; 3850 3851 // If it is not in AssumedLiveBlocks then it for sure dead. 3852 // Otherwise, it can still be after noreturn call in a live block. 3853 if (!AssumedLiveBlocks.count(I->getParent())) 3854 return true; 3855 3856 // If it is not after a liveness barrier it is live. 3857 const Instruction *PrevI = I->getPrevNode(); 3858 while (PrevI) { 3859 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI)) 3860 return true; 3861 PrevI = PrevI->getPrevNode(); 3862 } 3863 return false; 3864 } 3865 3866 /// See AAIsDead::isKnownDead(Instruction *I). 3867 bool isKnownDead(const Instruction *I) const override { 3868 return getKnown() && isAssumedDead(I); 3869 } 3870 3871 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A 3872 /// that internal function called from \p BB should now be looked at. 3873 bool assumeLive(Attributor &A, const BasicBlock &BB) { 3874 if (!AssumedLiveBlocks.insert(&BB).second) 3875 return false; 3876 3877 // We assume that all of BB is (probably) live now and if there are calls to 3878 // internal functions we will assume that those are now live as well. This 3879 // is a performance optimization for blocks with calls to a lot of internal 3880 // functions. It can however cause dead functions to be treated as live. 3881 for (const Instruction &I : BB) 3882 if (const auto *CB = dyn_cast<CallBase>(&I)) 3883 if (const Function *F = CB->getCalledFunction()) 3884 if (F->hasLocalLinkage()) 3885 A.markLiveInternalFunction(*F); 3886 return true; 3887 } 3888 3889 /// Collection of instructions that need to be explored again, e.g., we 3890 /// did assume they do not transfer control to (one of their) successors. 3891 SmallSetVector<const Instruction *, 8> ToBeExploredFrom; 3892 3893 /// Collection of instructions that are known to not transfer control. 3894 SmallSetVector<const Instruction *, 8> KnownDeadEnds; 3895 3896 /// Collection of all assumed live edges 3897 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges; 3898 3899 /// Collection of all assumed live BasicBlocks. 3900 DenseSet<const BasicBlock *> AssumedLiveBlocks; 3901 }; 3902 3903 static bool 3904 identifyAliveSuccessors(Attributor &A, const CallBase &CB, 3905 AbstractAttribute &AA, 3906 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3907 const IRPosition &IPos = IRPosition::callsite_function(CB); 3908 3909 const auto &NoReturnAA = 3910 A.getAndUpdateAAFor<AANoReturn>(AA, IPos, DepClassTy::OPTIONAL); 3911 if (NoReturnAA.isAssumedNoReturn()) 3912 return !NoReturnAA.isKnownNoReturn(); 3913 if (CB.isTerminator()) 3914 AliveSuccessors.push_back(&CB.getSuccessor(0)->front()); 3915 else 3916 AliveSuccessors.push_back(CB.getNextNode()); 3917 return false; 3918 } 3919 3920 static bool 3921 identifyAliveSuccessors(Attributor &A, const InvokeInst &II, 3922 AbstractAttribute &AA, 3923 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3924 bool UsedAssumedInformation = 3925 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors); 3926 3927 // First, determine if we can change an invoke to a call assuming the 3928 // callee is nounwind. This is not possible if the personality of the 3929 // function allows to catch asynchronous exceptions. 3930 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) { 3931 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 3932 } else { 3933 const IRPosition &IPos = IRPosition::callsite_function(II); 3934 const auto &AANoUnw = 3935 A.getAndUpdateAAFor<AANoUnwind>(AA, IPos, DepClassTy::OPTIONAL); 3936 if (AANoUnw.isAssumedNoUnwind()) { 3937 UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind(); 3938 } else { 3939 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 3940 } 3941 } 3942 return UsedAssumedInformation; 3943 } 3944 3945 static bool 3946 identifyAliveSuccessors(Attributor &A, const BranchInst &BI, 3947 AbstractAttribute &AA, 3948 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3949 bool UsedAssumedInformation = false; 3950 if (BI.getNumSuccessors() == 1) { 3951 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 3952 } else { 3953 Optional<Constant *> C = 3954 A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation); 3955 if (!C || isa_and_nonnull<UndefValue>(*C)) { 3956 // No value yet, assume both edges are dead. 3957 } else if (isa_and_nonnull<ConstantInt>(*C)) { 3958 const BasicBlock *SuccBB = 3959 BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue()); 3960 AliveSuccessors.push_back(&SuccBB->front()); 3961 } else { 3962 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 3963 AliveSuccessors.push_back(&BI.getSuccessor(1)->front()); 3964 UsedAssumedInformation = false; 3965 } 3966 } 3967 return UsedAssumedInformation; 3968 } 3969 3970 static bool 3971 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI, 3972 AbstractAttribute &AA, 3973 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3974 bool UsedAssumedInformation = false; 3975 Optional<Constant *> C = 3976 A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation); 3977 if (!C || isa_and_nonnull<UndefValue>(C.value())) { 3978 // No value yet, assume all edges are dead. 3979 } else if (isa_and_nonnull<ConstantInt>(C.value())) { 3980 for (auto &CaseIt : SI.cases()) { 3981 if (CaseIt.getCaseValue() == C.value()) { 3982 AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front()); 3983 return UsedAssumedInformation; 3984 } 3985 } 3986 AliveSuccessors.push_back(&SI.getDefaultDest()->front()); 3987 return UsedAssumedInformation; 3988 } else { 3989 for (const BasicBlock *SuccBB : successors(SI.getParent())) 3990 AliveSuccessors.push_back(&SuccBB->front()); 3991 } 3992 return UsedAssumedInformation; 3993 } 3994 3995 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) { 3996 ChangeStatus Change = ChangeStatus::UNCHANGED; 3997 3998 LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/" 3999 << getAnchorScope()->size() << "] BBs and " 4000 << ToBeExploredFrom.size() << " exploration points and " 4001 << KnownDeadEnds.size() << " known dead ends\n"); 4002 4003 // Copy and clear the list of instructions we need to explore from. It is 4004 // refilled with instructions the next update has to look at. 4005 SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(), 4006 ToBeExploredFrom.end()); 4007 decltype(ToBeExploredFrom) NewToBeExploredFrom; 4008 4009 SmallVector<const Instruction *, 8> AliveSuccessors; 4010 while (!Worklist.empty()) { 4011 const Instruction *I = Worklist.pop_back_val(); 4012 LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n"); 4013 4014 // Fast forward for uninteresting instructions. We could look for UB here 4015 // though. 4016 while (!I->isTerminator() && !isa<CallBase>(I)) 4017 I = I->getNextNode(); 4018 4019 AliveSuccessors.clear(); 4020 4021 bool UsedAssumedInformation = false; 4022 switch (I->getOpcode()) { 4023 // TODO: look for (assumed) UB to backwards propagate "deadness". 4024 default: 4025 assert(I->isTerminator() && 4026 "Expected non-terminators to be handled already!"); 4027 for (const BasicBlock *SuccBB : successors(I->getParent())) 4028 AliveSuccessors.push_back(&SuccBB->front()); 4029 break; 4030 case Instruction::Call: 4031 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I), 4032 *this, AliveSuccessors); 4033 break; 4034 case Instruction::Invoke: 4035 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I), 4036 *this, AliveSuccessors); 4037 break; 4038 case Instruction::Br: 4039 UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I), 4040 *this, AliveSuccessors); 4041 break; 4042 case Instruction::Switch: 4043 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I), 4044 *this, AliveSuccessors); 4045 break; 4046 } 4047 4048 if (UsedAssumedInformation) { 4049 NewToBeExploredFrom.insert(I); 4050 } else if (AliveSuccessors.empty() || 4051 (I->isTerminator() && 4052 AliveSuccessors.size() < I->getNumSuccessors())) { 4053 if (KnownDeadEnds.insert(I)) 4054 Change = ChangeStatus::CHANGED; 4055 } 4056 4057 LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: " 4058 << AliveSuccessors.size() << " UsedAssumedInformation: " 4059 << UsedAssumedInformation << "\n"); 4060 4061 for (const Instruction *AliveSuccessor : AliveSuccessors) { 4062 if (!I->isTerminator()) { 4063 assert(AliveSuccessors.size() == 1 && 4064 "Non-terminator expected to have a single successor!"); 4065 Worklist.push_back(AliveSuccessor); 4066 } else { 4067 // record the assumed live edge 4068 auto Edge = std::make_pair(I->getParent(), AliveSuccessor->getParent()); 4069 if (AssumedLiveEdges.insert(Edge).second) 4070 Change = ChangeStatus::CHANGED; 4071 if (assumeLive(A, *AliveSuccessor->getParent())) 4072 Worklist.push_back(AliveSuccessor); 4073 } 4074 } 4075 } 4076 4077 // Check if the content of ToBeExploredFrom changed, ignore the order. 4078 if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() || 4079 llvm::any_of(NewToBeExploredFrom, [&](const Instruction *I) { 4080 return !ToBeExploredFrom.count(I); 4081 })) { 4082 Change = ChangeStatus::CHANGED; 4083 ToBeExploredFrom = std::move(NewToBeExploredFrom); 4084 } 4085 4086 // If we know everything is live there is no need to query for liveness. 4087 // Instead, indicating a pessimistic fixpoint will cause the state to be 4088 // "invalid" and all queries to be answered conservatively without lookups. 4089 // To be in this state we have to (1) finished the exploration and (3) not 4090 // discovered any non-trivial dead end and (2) not ruled unreachable code 4091 // dead. 4092 if (ToBeExploredFrom.empty() && 4093 getAnchorScope()->size() == AssumedLiveBlocks.size() && 4094 llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) { 4095 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0; 4096 })) 4097 return indicatePessimisticFixpoint(); 4098 return Change; 4099 } 4100 4101 /// Liveness information for a call sites. 4102 struct AAIsDeadCallSite final : AAIsDeadFunction { 4103 AAIsDeadCallSite(const IRPosition &IRP, Attributor &A) 4104 : AAIsDeadFunction(IRP, A) {} 4105 4106 /// See AbstractAttribute::initialize(...). 4107 void initialize(Attributor &A) override { 4108 // TODO: Once we have call site specific value information we can provide 4109 // call site specific liveness information and then it makes 4110 // sense to specialize attributes for call sites instead of 4111 // redirecting requests to the callee. 4112 llvm_unreachable("Abstract attributes for liveness are not " 4113 "supported for call sites yet!"); 4114 } 4115 4116 /// See AbstractAttribute::updateImpl(...). 4117 ChangeStatus updateImpl(Attributor &A) override { 4118 return indicatePessimisticFixpoint(); 4119 } 4120 4121 /// See AbstractAttribute::trackStatistics() 4122 void trackStatistics() const override {} 4123 }; 4124 } // namespace 4125 4126 /// -------------------- Dereferenceable Argument Attribute -------------------- 4127 4128 namespace { 4129 struct AADereferenceableImpl : AADereferenceable { 4130 AADereferenceableImpl(const IRPosition &IRP, Attributor &A) 4131 : AADereferenceable(IRP, A) {} 4132 using StateType = DerefState; 4133 4134 /// See AbstractAttribute::initialize(...). 4135 void initialize(Attributor &A) override { 4136 Value &V = *getAssociatedValue().stripPointerCasts(); 4137 SmallVector<Attribute, 4> Attrs; 4138 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull}, 4139 Attrs, /* IgnoreSubsumingPositions */ false, &A); 4140 for (const Attribute &Attr : Attrs) 4141 takeKnownDerefBytesMaximum(Attr.getValueAsInt()); 4142 4143 const IRPosition &IRP = this->getIRPosition(); 4144 NonNullAA = &A.getAAFor<AANonNull>(*this, IRP, DepClassTy::NONE); 4145 4146 bool CanBeNull, CanBeFreed; 4147 takeKnownDerefBytesMaximum(V.getPointerDereferenceableBytes( 4148 A.getDataLayout(), CanBeNull, CanBeFreed)); 4149 4150 bool IsFnInterface = IRP.isFnInterfaceKind(); 4151 Function *FnScope = IRP.getAnchorScope(); 4152 if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) { 4153 indicatePessimisticFixpoint(); 4154 return; 4155 } 4156 4157 if (Instruction *CtxI = getCtxI()) 4158 followUsesInMBEC(*this, A, getState(), *CtxI); 4159 } 4160 4161 /// See AbstractAttribute::getState() 4162 /// { 4163 StateType &getState() override { return *this; } 4164 const StateType &getState() const override { return *this; } 4165 /// } 4166 4167 /// Helper function for collecting accessed bytes in must-be-executed-context 4168 void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I, 4169 DerefState &State) { 4170 const Value *UseV = U->get(); 4171 if (!UseV->getType()->isPointerTy()) 4172 return; 4173 4174 Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I); 4175 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile()) 4176 return; 4177 4178 int64_t Offset; 4179 const Value *Base = GetPointerBaseWithConstantOffset( 4180 Loc->Ptr, Offset, A.getDataLayout(), /*AllowNonInbounds*/ true); 4181 if (Base && Base == &getAssociatedValue()) 4182 State.addAccessedBytes(Offset, Loc->Size.getValue()); 4183 } 4184 4185 /// See followUsesInMBEC 4186 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 4187 AADereferenceable::StateType &State) { 4188 bool IsNonNull = false; 4189 bool TrackUse = false; 4190 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse( 4191 A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse); 4192 LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes 4193 << " for instruction " << *I << "\n"); 4194 4195 addAccessedBytesForUse(A, U, I, State); 4196 State.takeKnownDerefBytesMaximum(DerefBytes); 4197 return TrackUse; 4198 } 4199 4200 /// See AbstractAttribute::manifest(...). 4201 ChangeStatus manifest(Attributor &A) override { 4202 ChangeStatus Change = AADereferenceable::manifest(A); 4203 if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) { 4204 removeAttrs({Attribute::DereferenceableOrNull}); 4205 return ChangeStatus::CHANGED; 4206 } 4207 return Change; 4208 } 4209 4210 void getDeducedAttributes(LLVMContext &Ctx, 4211 SmallVectorImpl<Attribute> &Attrs) const override { 4212 // TODO: Add *_globally support 4213 if (isAssumedNonNull()) 4214 Attrs.emplace_back(Attribute::getWithDereferenceableBytes( 4215 Ctx, getAssumedDereferenceableBytes())); 4216 else 4217 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( 4218 Ctx, getAssumedDereferenceableBytes())); 4219 } 4220 4221 /// See AbstractAttribute::getAsStr(). 4222 const std::string getAsStr() const override { 4223 if (!getAssumedDereferenceableBytes()) 4224 return "unknown-dereferenceable"; 4225 return std::string("dereferenceable") + 4226 (isAssumedNonNull() ? "" : "_or_null") + 4227 (isAssumedGlobal() ? "_globally" : "") + "<" + 4228 std::to_string(getKnownDereferenceableBytes()) + "-" + 4229 std::to_string(getAssumedDereferenceableBytes()) + ">"; 4230 } 4231 }; 4232 4233 /// Dereferenceable attribute for a floating value. 4234 struct AADereferenceableFloating : AADereferenceableImpl { 4235 AADereferenceableFloating(const IRPosition &IRP, Attributor &A) 4236 : AADereferenceableImpl(IRP, A) {} 4237 4238 /// See AbstractAttribute::updateImpl(...). 4239 ChangeStatus updateImpl(Attributor &A) override { 4240 4241 bool Stripped; 4242 bool UsedAssumedInformation = false; 4243 SmallVector<AA::ValueAndContext> Values; 4244 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values, 4245 AA::AnyScope, UsedAssumedInformation)) { 4246 Values.push_back({getAssociatedValue(), getCtxI()}); 4247 Stripped = false; 4248 } else { 4249 Stripped = Values.size() != 1 || 4250 Values.front().getValue() != &getAssociatedValue(); 4251 } 4252 4253 const DataLayout &DL = A.getDataLayout(); 4254 DerefState T; 4255 4256 auto VisitValueCB = [&](const Value &V) -> bool { 4257 unsigned IdxWidth = 4258 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); 4259 APInt Offset(IdxWidth, 0); 4260 const Value *Base = stripAndAccumulateOffsets( 4261 A, *this, &V, DL, Offset, /* GetMinOffset */ false, 4262 /* AllowNonInbounds */ true); 4263 4264 const auto &AA = A.getAAFor<AADereferenceable>( 4265 *this, IRPosition::value(*Base), DepClassTy::REQUIRED); 4266 int64_t DerefBytes = 0; 4267 if (!Stripped && this == &AA) { 4268 // Use IR information if we did not strip anything. 4269 // TODO: track globally. 4270 bool CanBeNull, CanBeFreed; 4271 DerefBytes = 4272 Base->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 4273 T.GlobalState.indicatePessimisticFixpoint(); 4274 } else { 4275 const DerefState &DS = AA.getState(); 4276 DerefBytes = DS.DerefBytesState.getAssumed(); 4277 T.GlobalState &= DS.GlobalState; 4278 } 4279 4280 // For now we do not try to "increase" dereferenceability due to negative 4281 // indices as we first have to come up with code to deal with loops and 4282 // for overflows of the dereferenceable bytes. 4283 int64_t OffsetSExt = Offset.getSExtValue(); 4284 if (OffsetSExt < 0) 4285 OffsetSExt = 0; 4286 4287 T.takeAssumedDerefBytesMinimum( 4288 std::max(int64_t(0), DerefBytes - OffsetSExt)); 4289 4290 if (this == &AA) { 4291 if (!Stripped) { 4292 // If nothing was stripped IR information is all we got. 4293 T.takeKnownDerefBytesMaximum( 4294 std::max(int64_t(0), DerefBytes - OffsetSExt)); 4295 T.indicatePessimisticFixpoint(); 4296 } else if (OffsetSExt > 0) { 4297 // If something was stripped but there is circular reasoning we look 4298 // for the offset. If it is positive we basically decrease the 4299 // dereferenceable bytes in a circluar loop now, which will simply 4300 // drive them down to the known value in a very slow way which we 4301 // can accelerate. 4302 T.indicatePessimisticFixpoint(); 4303 } 4304 } 4305 4306 return T.isValidState(); 4307 }; 4308 4309 for (const auto &VAC : Values) 4310 if (!VisitValueCB(*VAC.getValue())) 4311 return indicatePessimisticFixpoint(); 4312 4313 return clampStateAndIndicateChange(getState(), T); 4314 } 4315 4316 /// See AbstractAttribute::trackStatistics() 4317 void trackStatistics() const override { 4318 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable) 4319 } 4320 }; 4321 4322 /// Dereferenceable attribute for a return value. 4323 struct AADereferenceableReturned final 4324 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> { 4325 AADereferenceableReturned(const IRPosition &IRP, Attributor &A) 4326 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>( 4327 IRP, A) {} 4328 4329 /// See AbstractAttribute::trackStatistics() 4330 void trackStatistics() const override { 4331 STATS_DECLTRACK_FNRET_ATTR(dereferenceable) 4332 } 4333 }; 4334 4335 /// Dereferenceable attribute for an argument 4336 struct AADereferenceableArgument final 4337 : AAArgumentFromCallSiteArguments<AADereferenceable, 4338 AADereferenceableImpl> { 4339 using Base = 4340 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>; 4341 AADereferenceableArgument(const IRPosition &IRP, Attributor &A) 4342 : Base(IRP, A) {} 4343 4344 /// See AbstractAttribute::trackStatistics() 4345 void trackStatistics() const override { 4346 STATS_DECLTRACK_ARG_ATTR(dereferenceable) 4347 } 4348 }; 4349 4350 /// Dereferenceable attribute for a call site argument. 4351 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating { 4352 AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A) 4353 : AADereferenceableFloating(IRP, A) {} 4354 4355 /// See AbstractAttribute::trackStatistics() 4356 void trackStatistics() const override { 4357 STATS_DECLTRACK_CSARG_ATTR(dereferenceable) 4358 } 4359 }; 4360 4361 /// Dereferenceable attribute deduction for a call site return value. 4362 struct AADereferenceableCallSiteReturned final 4363 : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> { 4364 using Base = 4365 AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>; 4366 AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A) 4367 : Base(IRP, A) {} 4368 4369 /// See AbstractAttribute::trackStatistics() 4370 void trackStatistics() const override { 4371 STATS_DECLTRACK_CS_ATTR(dereferenceable); 4372 } 4373 }; 4374 } // namespace 4375 4376 // ------------------------ Align Argument Attribute ------------------------ 4377 4378 namespace { 4379 static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA, 4380 Value &AssociatedValue, const Use *U, 4381 const Instruction *I, bool &TrackUse) { 4382 // We need to follow common pointer manipulation uses to the accesses they 4383 // feed into. 4384 if (isa<CastInst>(I)) { 4385 // Follow all but ptr2int casts. 4386 TrackUse = !isa<PtrToIntInst>(I); 4387 return 0; 4388 } 4389 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 4390 if (GEP->hasAllConstantIndices()) 4391 TrackUse = true; 4392 return 0; 4393 } 4394 4395 MaybeAlign MA; 4396 if (const auto *CB = dyn_cast<CallBase>(I)) { 4397 if (CB->isBundleOperand(U) || CB->isCallee(U)) 4398 return 0; 4399 4400 unsigned ArgNo = CB->getArgOperandNo(U); 4401 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo); 4402 // As long as we only use known information there is no need to track 4403 // dependences here. 4404 auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE); 4405 MA = MaybeAlign(AlignAA.getKnownAlign()); 4406 } 4407 4408 const DataLayout &DL = A.getDataLayout(); 4409 const Value *UseV = U->get(); 4410 if (auto *SI = dyn_cast<StoreInst>(I)) { 4411 if (SI->getPointerOperand() == UseV) 4412 MA = SI->getAlign(); 4413 } else if (auto *LI = dyn_cast<LoadInst>(I)) { 4414 if (LI->getPointerOperand() == UseV) 4415 MA = LI->getAlign(); 4416 } 4417 4418 if (!MA || *MA <= QueryingAA.getKnownAlign()) 4419 return 0; 4420 4421 unsigned Alignment = MA->value(); 4422 int64_t Offset; 4423 4424 if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) { 4425 if (Base == &AssociatedValue) { 4426 // BasePointerAddr + Offset = Alignment * Q for some integer Q. 4427 // So we can say that the maximum power of two which is a divisor of 4428 // gcd(Offset, Alignment) is an alignment. 4429 4430 uint32_t gcd = 4431 greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment); 4432 Alignment = llvm::PowerOf2Floor(gcd); 4433 } 4434 } 4435 4436 return Alignment; 4437 } 4438 4439 struct AAAlignImpl : AAAlign { 4440 AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {} 4441 4442 /// See AbstractAttribute::initialize(...). 4443 void initialize(Attributor &A) override { 4444 SmallVector<Attribute, 4> Attrs; 4445 getAttrs({Attribute::Alignment}, Attrs); 4446 for (const Attribute &Attr : Attrs) 4447 takeKnownMaximum(Attr.getValueAsInt()); 4448 4449 Value &V = *getAssociatedValue().stripPointerCasts(); 4450 takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value()); 4451 4452 if (getIRPosition().isFnInterfaceKind() && 4453 (!getAnchorScope() || 4454 !A.isFunctionIPOAmendable(*getAssociatedFunction()))) { 4455 indicatePessimisticFixpoint(); 4456 return; 4457 } 4458 4459 if (Instruction *CtxI = getCtxI()) 4460 followUsesInMBEC(*this, A, getState(), *CtxI); 4461 } 4462 4463 /// See AbstractAttribute::manifest(...). 4464 ChangeStatus manifest(Attributor &A) override { 4465 ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED; 4466 4467 // Check for users that allow alignment annotations. 4468 Value &AssociatedValue = getAssociatedValue(); 4469 for (const Use &U : AssociatedValue.uses()) { 4470 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) { 4471 if (SI->getPointerOperand() == &AssociatedValue) 4472 if (SI->getAlign() < getAssumedAlign()) { 4473 STATS_DECLTRACK(AAAlign, Store, 4474 "Number of times alignment added to a store"); 4475 SI->setAlignment(getAssumedAlign()); 4476 LoadStoreChanged = ChangeStatus::CHANGED; 4477 } 4478 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) { 4479 if (LI->getPointerOperand() == &AssociatedValue) 4480 if (LI->getAlign() < getAssumedAlign()) { 4481 LI->setAlignment(getAssumedAlign()); 4482 STATS_DECLTRACK(AAAlign, Load, 4483 "Number of times alignment added to a load"); 4484 LoadStoreChanged = ChangeStatus::CHANGED; 4485 } 4486 } 4487 } 4488 4489 ChangeStatus Changed = AAAlign::manifest(A); 4490 4491 Align InheritAlign = 4492 getAssociatedValue().getPointerAlignment(A.getDataLayout()); 4493 if (InheritAlign >= getAssumedAlign()) 4494 return LoadStoreChanged; 4495 return Changed | LoadStoreChanged; 4496 } 4497 4498 // TODO: Provide a helper to determine the implied ABI alignment and check in 4499 // the existing manifest method and a new one for AAAlignImpl that value 4500 // to avoid making the alignment explicit if it did not improve. 4501 4502 /// See AbstractAttribute::getDeducedAttributes 4503 virtual void 4504 getDeducedAttributes(LLVMContext &Ctx, 4505 SmallVectorImpl<Attribute> &Attrs) const override { 4506 if (getAssumedAlign() > 1) 4507 Attrs.emplace_back( 4508 Attribute::getWithAlignment(Ctx, Align(getAssumedAlign()))); 4509 } 4510 4511 /// See followUsesInMBEC 4512 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 4513 AAAlign::StateType &State) { 4514 bool TrackUse = false; 4515 4516 unsigned int KnownAlign = 4517 getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse); 4518 State.takeKnownMaximum(KnownAlign); 4519 4520 return TrackUse; 4521 } 4522 4523 /// See AbstractAttribute::getAsStr(). 4524 const std::string getAsStr() const override { 4525 return "align<" + std::to_string(getKnownAlign().value()) + "-" + 4526 std::to_string(getAssumedAlign().value()) + ">"; 4527 } 4528 }; 4529 4530 /// Align attribute for a floating value. 4531 struct AAAlignFloating : AAAlignImpl { 4532 AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {} 4533 4534 /// See AbstractAttribute::updateImpl(...). 4535 ChangeStatus updateImpl(Attributor &A) override { 4536 const DataLayout &DL = A.getDataLayout(); 4537 4538 bool Stripped; 4539 bool UsedAssumedInformation = false; 4540 SmallVector<AA::ValueAndContext> Values; 4541 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values, 4542 AA::AnyScope, UsedAssumedInformation)) { 4543 Values.push_back({getAssociatedValue(), getCtxI()}); 4544 Stripped = false; 4545 } else { 4546 Stripped = Values.size() != 1 || 4547 Values.front().getValue() != &getAssociatedValue(); 4548 } 4549 4550 StateType T; 4551 auto VisitValueCB = [&](Value &V) -> bool { 4552 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V)) 4553 return true; 4554 const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V), 4555 DepClassTy::REQUIRED); 4556 if (!Stripped && this == &AA) { 4557 int64_t Offset; 4558 unsigned Alignment = 1; 4559 if (const Value *Base = 4560 GetPointerBaseWithConstantOffset(&V, Offset, DL)) { 4561 // TODO: Use AAAlign for the base too. 4562 Align PA = Base->getPointerAlignment(DL); 4563 // BasePointerAddr + Offset = Alignment * Q for some integer Q. 4564 // So we can say that the maximum power of two which is a divisor of 4565 // gcd(Offset, Alignment) is an alignment. 4566 4567 uint32_t gcd = greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), 4568 uint32_t(PA.value())); 4569 Alignment = llvm::PowerOf2Floor(gcd); 4570 } else { 4571 Alignment = V.getPointerAlignment(DL).value(); 4572 } 4573 // Use only IR information if we did not strip anything. 4574 T.takeKnownMaximum(Alignment); 4575 T.indicatePessimisticFixpoint(); 4576 } else { 4577 // Use abstract attribute information. 4578 const AAAlign::StateType &DS = AA.getState(); 4579 T ^= DS; 4580 } 4581 return T.isValidState(); 4582 }; 4583 4584 for (const auto &VAC : Values) { 4585 if (!VisitValueCB(*VAC.getValue())) 4586 return indicatePessimisticFixpoint(); 4587 } 4588 4589 // TODO: If we know we visited all incoming values, thus no are assumed 4590 // dead, we can take the known information from the state T. 4591 return clampStateAndIndicateChange(getState(), T); 4592 } 4593 4594 /// See AbstractAttribute::trackStatistics() 4595 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) } 4596 }; 4597 4598 /// Align attribute for function return value. 4599 struct AAAlignReturned final 4600 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> { 4601 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>; 4602 AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 4603 4604 /// See AbstractAttribute::initialize(...). 4605 void initialize(Attributor &A) override { 4606 Base::initialize(A); 4607 Function *F = getAssociatedFunction(); 4608 if (!F || F->isDeclaration()) 4609 indicatePessimisticFixpoint(); 4610 } 4611 4612 /// See AbstractAttribute::trackStatistics() 4613 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) } 4614 }; 4615 4616 /// Align attribute for function argument. 4617 struct AAAlignArgument final 4618 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> { 4619 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>; 4620 AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 4621 4622 /// See AbstractAttribute::manifest(...). 4623 ChangeStatus manifest(Attributor &A) override { 4624 // If the associated argument is involved in a must-tail call we give up 4625 // because we would need to keep the argument alignments of caller and 4626 // callee in-sync. Just does not seem worth the trouble right now. 4627 if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument())) 4628 return ChangeStatus::UNCHANGED; 4629 return Base::manifest(A); 4630 } 4631 4632 /// See AbstractAttribute::trackStatistics() 4633 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) } 4634 }; 4635 4636 struct AAAlignCallSiteArgument final : AAAlignFloating { 4637 AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A) 4638 : AAAlignFloating(IRP, A) {} 4639 4640 /// See AbstractAttribute::manifest(...). 4641 ChangeStatus manifest(Attributor &A) override { 4642 // If the associated argument is involved in a must-tail call we give up 4643 // because we would need to keep the argument alignments of caller and 4644 // callee in-sync. Just does not seem worth the trouble right now. 4645 if (Argument *Arg = getAssociatedArgument()) 4646 if (A.getInfoCache().isInvolvedInMustTailCall(*Arg)) 4647 return ChangeStatus::UNCHANGED; 4648 ChangeStatus Changed = AAAlignImpl::manifest(A); 4649 Align InheritAlign = 4650 getAssociatedValue().getPointerAlignment(A.getDataLayout()); 4651 if (InheritAlign >= getAssumedAlign()) 4652 Changed = ChangeStatus::UNCHANGED; 4653 return Changed; 4654 } 4655 4656 /// See AbstractAttribute::updateImpl(Attributor &A). 4657 ChangeStatus updateImpl(Attributor &A) override { 4658 ChangeStatus Changed = AAAlignFloating::updateImpl(A); 4659 if (Argument *Arg = getAssociatedArgument()) { 4660 // We only take known information from the argument 4661 // so we do not need to track a dependence. 4662 const auto &ArgAlignAA = A.getAAFor<AAAlign>( 4663 *this, IRPosition::argument(*Arg), DepClassTy::NONE); 4664 takeKnownMaximum(ArgAlignAA.getKnownAlign().value()); 4665 } 4666 return Changed; 4667 } 4668 4669 /// See AbstractAttribute::trackStatistics() 4670 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) } 4671 }; 4672 4673 /// Align attribute deduction for a call site return value. 4674 struct AAAlignCallSiteReturned final 4675 : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> { 4676 using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>; 4677 AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A) 4678 : Base(IRP, A) {} 4679 4680 /// See AbstractAttribute::initialize(...). 4681 void initialize(Attributor &A) override { 4682 Base::initialize(A); 4683 Function *F = getAssociatedFunction(); 4684 if (!F || F->isDeclaration()) 4685 indicatePessimisticFixpoint(); 4686 } 4687 4688 /// See AbstractAttribute::trackStatistics() 4689 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); } 4690 }; 4691 } // namespace 4692 4693 /// ------------------ Function No-Return Attribute ---------------------------- 4694 namespace { 4695 struct AANoReturnImpl : public AANoReturn { 4696 AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {} 4697 4698 /// See AbstractAttribute::initialize(...). 4699 void initialize(Attributor &A) override { 4700 AANoReturn::initialize(A); 4701 Function *F = getAssociatedFunction(); 4702 if (!F || F->isDeclaration()) 4703 indicatePessimisticFixpoint(); 4704 } 4705 4706 /// See AbstractAttribute::getAsStr(). 4707 const std::string getAsStr() const override { 4708 return getAssumed() ? "noreturn" : "may-return"; 4709 } 4710 4711 /// See AbstractAttribute::updateImpl(Attributor &A). 4712 virtual ChangeStatus updateImpl(Attributor &A) override { 4713 auto CheckForNoReturn = [](Instruction &) { return false; }; 4714 bool UsedAssumedInformation = false; 4715 if (!A.checkForAllInstructions(CheckForNoReturn, *this, 4716 {(unsigned)Instruction::Ret}, 4717 UsedAssumedInformation)) 4718 return indicatePessimisticFixpoint(); 4719 return ChangeStatus::UNCHANGED; 4720 } 4721 }; 4722 4723 struct AANoReturnFunction final : AANoReturnImpl { 4724 AANoReturnFunction(const IRPosition &IRP, Attributor &A) 4725 : AANoReturnImpl(IRP, A) {} 4726 4727 /// See AbstractAttribute::trackStatistics() 4728 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) } 4729 }; 4730 4731 /// NoReturn attribute deduction for a call sites. 4732 struct AANoReturnCallSite final : AANoReturnImpl { 4733 AANoReturnCallSite(const IRPosition &IRP, Attributor &A) 4734 : AANoReturnImpl(IRP, A) {} 4735 4736 /// See AbstractAttribute::initialize(...). 4737 void initialize(Attributor &A) override { 4738 AANoReturnImpl::initialize(A); 4739 if (Function *F = getAssociatedFunction()) { 4740 const IRPosition &FnPos = IRPosition::function(*F); 4741 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED); 4742 if (!FnAA.isAssumedNoReturn()) 4743 indicatePessimisticFixpoint(); 4744 } 4745 } 4746 4747 /// See AbstractAttribute::updateImpl(...). 4748 ChangeStatus updateImpl(Attributor &A) override { 4749 // TODO: Once we have call site specific value information we can provide 4750 // call site specific liveness information and then it makes 4751 // sense to specialize attributes for call sites arguments instead of 4752 // redirecting requests to the callee argument. 4753 Function *F = getAssociatedFunction(); 4754 const IRPosition &FnPos = IRPosition::function(*F); 4755 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED); 4756 return clampStateAndIndicateChange(getState(), FnAA.getState()); 4757 } 4758 4759 /// See AbstractAttribute::trackStatistics() 4760 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); } 4761 }; 4762 } // namespace 4763 4764 /// ----------------------- Instance Info --------------------------------- 4765 4766 namespace { 4767 /// A class to hold the state of for no-capture attributes. 4768 struct AAInstanceInfoImpl : public AAInstanceInfo { 4769 AAInstanceInfoImpl(const IRPosition &IRP, Attributor &A) 4770 : AAInstanceInfo(IRP, A) {} 4771 4772 /// See AbstractAttribute::initialize(...). 4773 void initialize(Attributor &A) override { 4774 Value &V = getAssociatedValue(); 4775 if (auto *C = dyn_cast<Constant>(&V)) { 4776 if (C->isThreadDependent()) 4777 indicatePessimisticFixpoint(); 4778 else 4779 indicateOptimisticFixpoint(); 4780 return; 4781 } 4782 if (auto *CB = dyn_cast<CallBase>(&V)) 4783 if (CB->arg_size() == 0 && !CB->mayHaveSideEffects() && 4784 !CB->mayReadFromMemory()) { 4785 indicateOptimisticFixpoint(); 4786 return; 4787 } 4788 } 4789 4790 /// See AbstractAttribute::updateImpl(...). 4791 ChangeStatus updateImpl(Attributor &A) override { 4792 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4793 4794 Value &V = getAssociatedValue(); 4795 const Function *Scope = nullptr; 4796 if (auto *I = dyn_cast<Instruction>(&V)) 4797 Scope = I->getFunction(); 4798 if (auto *A = dyn_cast<Argument>(&V)) { 4799 Scope = A->getParent(); 4800 if (!Scope->hasLocalLinkage()) 4801 return Changed; 4802 } 4803 if (!Scope) 4804 return indicateOptimisticFixpoint(); 4805 4806 auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 4807 *this, IRPosition::function(*Scope), DepClassTy::OPTIONAL); 4808 if (NoRecurseAA.isAssumedNoRecurse()) 4809 return Changed; 4810 4811 auto UsePred = [&](const Use &U, bool &Follow) { 4812 const Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 4813 if (!UserI || isa<GetElementPtrInst>(UserI) || isa<CastInst>(UserI) || 4814 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 4815 Follow = true; 4816 return true; 4817 } 4818 if (isa<LoadInst>(UserI) || isa<CmpInst>(UserI) || 4819 (isa<StoreInst>(UserI) && 4820 cast<StoreInst>(UserI)->getValueOperand() != U.get())) 4821 return true; 4822 if (auto *CB = dyn_cast<CallBase>(UserI)) { 4823 // This check is not guaranteeing uniqueness but for now that we cannot 4824 // end up with two versions of \p U thinking it was one. 4825 if (!CB->getCalledFunction() || 4826 !CB->getCalledFunction()->hasLocalLinkage()) 4827 return true; 4828 if (!CB->isArgOperand(&U)) 4829 return false; 4830 const auto &ArgInstanceInfoAA = A.getAAFor<AAInstanceInfo>( 4831 *this, IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)), 4832 DepClassTy::OPTIONAL); 4833 if (!ArgInstanceInfoAA.isAssumedUniqueForAnalysis()) 4834 return false; 4835 // If this call base might reach the scope again we might forward the 4836 // argument back here. This is very conservative. 4837 if (AA::isPotentiallyReachable( 4838 A, *CB, *Scope, *this, 4839 [Scope](const Function &Fn) { return &Fn != Scope; })) 4840 return false; 4841 return true; 4842 } 4843 return false; 4844 }; 4845 4846 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) { 4847 if (auto *SI = dyn_cast<StoreInst>(OldU.getUser())) { 4848 auto *Ptr = SI->getPointerOperand()->stripPointerCasts(); 4849 if (isa<AllocaInst>(Ptr) && AA::isDynamicallyUnique(A, *this, *Ptr)) 4850 return true; 4851 auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction( 4852 *SI->getFunction()); 4853 if (isAllocationFn(Ptr, TLI) && AA::isDynamicallyUnique(A, *this, *Ptr)) 4854 return true; 4855 } 4856 return false; 4857 }; 4858 4859 if (!A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ true, 4860 DepClassTy::OPTIONAL, 4861 /* IgnoreDroppableUses */ true, EquivalentUseCB)) 4862 return indicatePessimisticFixpoint(); 4863 4864 return Changed; 4865 } 4866 4867 /// See AbstractState::getAsStr(). 4868 const std::string getAsStr() const override { 4869 return isAssumedUniqueForAnalysis() ? "<unique [fAa]>" : "<unknown>"; 4870 } 4871 4872 /// See AbstractAttribute::trackStatistics() 4873 void trackStatistics() const override {} 4874 }; 4875 4876 /// InstanceInfo attribute for floating values. 4877 struct AAInstanceInfoFloating : AAInstanceInfoImpl { 4878 AAInstanceInfoFloating(const IRPosition &IRP, Attributor &A) 4879 : AAInstanceInfoImpl(IRP, A) {} 4880 }; 4881 4882 /// NoCapture attribute for function arguments. 4883 struct AAInstanceInfoArgument final : AAInstanceInfoFloating { 4884 AAInstanceInfoArgument(const IRPosition &IRP, Attributor &A) 4885 : AAInstanceInfoFloating(IRP, A) {} 4886 }; 4887 4888 /// InstanceInfo attribute for call site arguments. 4889 struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl { 4890 AAInstanceInfoCallSiteArgument(const IRPosition &IRP, Attributor &A) 4891 : AAInstanceInfoImpl(IRP, A) {} 4892 4893 /// See AbstractAttribute::updateImpl(...). 4894 ChangeStatus updateImpl(Attributor &A) override { 4895 // TODO: Once we have call site specific value information we can provide 4896 // call site specific liveness information and then it makes 4897 // sense to specialize attributes for call sites arguments instead of 4898 // redirecting requests to the callee argument. 4899 Argument *Arg = getAssociatedArgument(); 4900 if (!Arg) 4901 return indicatePessimisticFixpoint(); 4902 const IRPosition &ArgPos = IRPosition::argument(*Arg); 4903 auto &ArgAA = 4904 A.getAAFor<AAInstanceInfo>(*this, ArgPos, DepClassTy::REQUIRED); 4905 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 4906 } 4907 }; 4908 4909 /// InstanceInfo attribute for function return value. 4910 struct AAInstanceInfoReturned final : AAInstanceInfoImpl { 4911 AAInstanceInfoReturned(const IRPosition &IRP, Attributor &A) 4912 : AAInstanceInfoImpl(IRP, A) { 4913 llvm_unreachable("InstanceInfo is not applicable to function returns!"); 4914 } 4915 4916 /// See AbstractAttribute::initialize(...). 4917 void initialize(Attributor &A) override { 4918 llvm_unreachable("InstanceInfo is not applicable to function returns!"); 4919 } 4920 4921 /// See AbstractAttribute::updateImpl(...). 4922 ChangeStatus updateImpl(Attributor &A) override { 4923 llvm_unreachable("InstanceInfo is not applicable to function returns!"); 4924 } 4925 }; 4926 4927 /// InstanceInfo attribute deduction for a call site return value. 4928 struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating { 4929 AAInstanceInfoCallSiteReturned(const IRPosition &IRP, Attributor &A) 4930 : AAInstanceInfoFloating(IRP, A) {} 4931 }; 4932 } // namespace 4933 4934 /// ----------------------- Variable Capturing --------------------------------- 4935 4936 namespace { 4937 /// A class to hold the state of for no-capture attributes. 4938 struct AANoCaptureImpl : public AANoCapture { 4939 AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {} 4940 4941 /// See AbstractAttribute::initialize(...). 4942 void initialize(Attributor &A) override { 4943 if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) { 4944 indicateOptimisticFixpoint(); 4945 return; 4946 } 4947 Function *AnchorScope = getAnchorScope(); 4948 if (isFnInterfaceKind() && 4949 (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) { 4950 indicatePessimisticFixpoint(); 4951 return; 4952 } 4953 4954 // You cannot "capture" null in the default address space. 4955 if (isa<ConstantPointerNull>(getAssociatedValue()) && 4956 getAssociatedValue().getType()->getPointerAddressSpace() == 0) { 4957 indicateOptimisticFixpoint(); 4958 return; 4959 } 4960 4961 const Function *F = 4962 isArgumentPosition() ? getAssociatedFunction() : AnchorScope; 4963 4964 // Check what state the associated function can actually capture. 4965 if (F) 4966 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this); 4967 else 4968 indicatePessimisticFixpoint(); 4969 } 4970 4971 /// See AbstractAttribute::updateImpl(...). 4972 ChangeStatus updateImpl(Attributor &A) override; 4973 4974 /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...). 4975 virtual void 4976 getDeducedAttributes(LLVMContext &Ctx, 4977 SmallVectorImpl<Attribute> &Attrs) const override { 4978 if (!isAssumedNoCaptureMaybeReturned()) 4979 return; 4980 4981 if (isArgumentPosition()) { 4982 if (isAssumedNoCapture()) 4983 Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture)); 4984 else if (ManifestInternal) 4985 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned")); 4986 } 4987 } 4988 4989 /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known 4990 /// depending on the ability of the function associated with \p IRP to capture 4991 /// state in memory and through "returning/throwing", respectively. 4992 static void determineFunctionCaptureCapabilities(const IRPosition &IRP, 4993 const Function &F, 4994 BitIntegerState &State) { 4995 // TODO: Once we have memory behavior attributes we should use them here. 4996 4997 // If we know we cannot communicate or write to memory, we do not care about 4998 // ptr2int anymore. 4999 if (F.onlyReadsMemory() && F.doesNotThrow() && 5000 F.getReturnType()->isVoidTy()) { 5001 State.addKnownBits(NO_CAPTURE); 5002 return; 5003 } 5004 5005 // A function cannot capture state in memory if it only reads memory, it can 5006 // however return/throw state and the state might be influenced by the 5007 // pointer value, e.g., loading from a returned pointer might reveal a bit. 5008 if (F.onlyReadsMemory()) 5009 State.addKnownBits(NOT_CAPTURED_IN_MEM); 5010 5011 // A function cannot communicate state back if it does not through 5012 // exceptions and doesn not return values. 5013 if (F.doesNotThrow() && F.getReturnType()->isVoidTy()) 5014 State.addKnownBits(NOT_CAPTURED_IN_RET); 5015 5016 // Check existing "returned" attributes. 5017 int ArgNo = IRP.getCalleeArgNo(); 5018 if (F.doesNotThrow() && ArgNo >= 0) { 5019 for (unsigned u = 0, e = F.arg_size(); u < e; ++u) 5020 if (F.hasParamAttribute(u, Attribute::Returned)) { 5021 if (u == unsigned(ArgNo)) 5022 State.removeAssumedBits(NOT_CAPTURED_IN_RET); 5023 else if (F.onlyReadsMemory()) 5024 State.addKnownBits(NO_CAPTURE); 5025 else 5026 State.addKnownBits(NOT_CAPTURED_IN_RET); 5027 break; 5028 } 5029 } 5030 } 5031 5032 /// See AbstractState::getAsStr(). 5033 const std::string getAsStr() const override { 5034 if (isKnownNoCapture()) 5035 return "known not-captured"; 5036 if (isAssumedNoCapture()) 5037 return "assumed not-captured"; 5038 if (isKnownNoCaptureMaybeReturned()) 5039 return "known not-captured-maybe-returned"; 5040 if (isAssumedNoCaptureMaybeReturned()) 5041 return "assumed not-captured-maybe-returned"; 5042 return "assumed-captured"; 5043 } 5044 5045 /// Check the use \p U and update \p State accordingly. Return true if we 5046 /// should continue to update the state. 5047 bool checkUse(Attributor &A, AANoCapture::StateType &State, const Use &U, 5048 bool &Follow) { 5049 Instruction *UInst = cast<Instruction>(U.getUser()); 5050 LLVM_DEBUG(dbgs() << "[AANoCapture] Check use: " << *U.get() << " in " 5051 << *UInst << "\n"); 5052 5053 // Deal with ptr2int by following uses. 5054 if (isa<PtrToIntInst>(UInst)) { 5055 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n"); 5056 return isCapturedIn(State, /* Memory */ true, /* Integer */ true, 5057 /* Return */ true); 5058 } 5059 5060 // For stores we already checked if we can follow them, if they make it 5061 // here we give up. 5062 if (isa<StoreInst>(UInst)) 5063 return isCapturedIn(State, /* Memory */ true, /* Integer */ false, 5064 /* Return */ false); 5065 5066 // Explicitly catch return instructions. 5067 if (isa<ReturnInst>(UInst)) { 5068 if (UInst->getFunction() == getAnchorScope()) 5069 return isCapturedIn(State, /* Memory */ false, /* Integer */ false, 5070 /* Return */ true); 5071 return isCapturedIn(State, /* Memory */ true, /* Integer */ true, 5072 /* Return */ true); 5073 } 5074 5075 // For now we only use special logic for call sites. However, the tracker 5076 // itself knows about a lot of other non-capturing cases already. 5077 auto *CB = dyn_cast<CallBase>(UInst); 5078 if (!CB || !CB->isArgOperand(&U)) 5079 return isCapturedIn(State, /* Memory */ true, /* Integer */ true, 5080 /* Return */ true); 5081 5082 unsigned ArgNo = CB->getArgOperandNo(&U); 5083 const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo); 5084 // If we have a abstract no-capture attribute for the argument we can use 5085 // it to justify a non-capture attribute here. This allows recursion! 5086 auto &ArgNoCaptureAA = 5087 A.getAAFor<AANoCapture>(*this, CSArgPos, DepClassTy::REQUIRED); 5088 if (ArgNoCaptureAA.isAssumedNoCapture()) 5089 return isCapturedIn(State, /* Memory */ false, /* Integer */ false, 5090 /* Return */ false); 5091 if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 5092 Follow = true; 5093 return isCapturedIn(State, /* Memory */ false, /* Integer */ false, 5094 /* Return */ false); 5095 } 5096 5097 // Lastly, we could not find a reason no-capture can be assumed so we don't. 5098 return isCapturedIn(State, /* Memory */ true, /* Integer */ true, 5099 /* Return */ true); 5100 } 5101 5102 /// Update \p State according to \p CapturedInMem, \p CapturedInInt, and 5103 /// \p CapturedInRet, then return true if we should continue updating the 5104 /// state. 5105 static bool isCapturedIn(AANoCapture::StateType &State, bool CapturedInMem, 5106 bool CapturedInInt, bool CapturedInRet) { 5107 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int " 5108 << CapturedInInt << "|Ret " << CapturedInRet << "]\n"); 5109 if (CapturedInMem) 5110 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM); 5111 if (CapturedInInt) 5112 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT); 5113 if (CapturedInRet) 5114 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET); 5115 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 5116 } 5117 }; 5118 5119 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) { 5120 const IRPosition &IRP = getIRPosition(); 5121 Value *V = isArgumentPosition() ? IRP.getAssociatedArgument() 5122 : &IRP.getAssociatedValue(); 5123 if (!V) 5124 return indicatePessimisticFixpoint(); 5125 5126 const Function *F = 5127 isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 5128 assert(F && "Expected a function!"); 5129 const IRPosition &FnPos = IRPosition::function(*F); 5130 5131 AANoCapture::StateType T; 5132 5133 // Readonly means we cannot capture through memory. 5134 bool IsKnown; 5135 if (AA::isAssumedReadOnly(A, FnPos, *this, IsKnown)) { 5136 T.addKnownBits(NOT_CAPTURED_IN_MEM); 5137 if (IsKnown) 5138 addKnownBits(NOT_CAPTURED_IN_MEM); 5139 } 5140 5141 // Make sure all returned values are different than the underlying value. 5142 // TODO: we could do this in a more sophisticated way inside 5143 // AAReturnedValues, e.g., track all values that escape through returns 5144 // directly somehow. 5145 auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) { 5146 if (!RVAA.getState().isValidState()) 5147 return false; 5148 bool SeenConstant = false; 5149 for (auto &It : RVAA.returned_values()) { 5150 if (isa<Constant>(It.first)) { 5151 if (SeenConstant) 5152 return false; 5153 SeenConstant = true; 5154 } else if (!isa<Argument>(It.first) || 5155 It.first == getAssociatedArgument()) 5156 return false; 5157 } 5158 return true; 5159 }; 5160 5161 const auto &NoUnwindAA = 5162 A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::OPTIONAL); 5163 if (NoUnwindAA.isAssumedNoUnwind()) { 5164 bool IsVoidTy = F->getReturnType()->isVoidTy(); 5165 const AAReturnedValues *RVAA = 5166 IsVoidTy ? nullptr 5167 : &A.getAAFor<AAReturnedValues>(*this, FnPos, 5168 5169 DepClassTy::OPTIONAL); 5170 if (IsVoidTy || CheckReturnedArgs(*RVAA)) { 5171 T.addKnownBits(NOT_CAPTURED_IN_RET); 5172 if (T.isKnown(NOT_CAPTURED_IN_MEM)) 5173 return ChangeStatus::UNCHANGED; 5174 if (NoUnwindAA.isKnownNoUnwind() && 5175 (IsVoidTy || RVAA->getState().isAtFixpoint())) { 5176 addKnownBits(NOT_CAPTURED_IN_RET); 5177 if (isKnown(NOT_CAPTURED_IN_MEM)) 5178 return indicateOptimisticFixpoint(); 5179 } 5180 } 5181 } 5182 5183 auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) { 5184 const auto &DerefAA = A.getAAFor<AADereferenceable>( 5185 *this, IRPosition::value(*O), DepClassTy::OPTIONAL); 5186 return DerefAA.getAssumedDereferenceableBytes(); 5187 }; 5188 5189 auto UseCheck = [&](const Use &U, bool &Follow) -> bool { 5190 switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) { 5191 case UseCaptureKind::NO_CAPTURE: 5192 return true; 5193 case UseCaptureKind::MAY_CAPTURE: 5194 return checkUse(A, T, U, Follow); 5195 case UseCaptureKind::PASSTHROUGH: 5196 Follow = true; 5197 return true; 5198 } 5199 llvm_unreachable("Unexpected use capture kind!"); 5200 }; 5201 5202 if (!A.checkForAllUses(UseCheck, *this, *V)) 5203 return indicatePessimisticFixpoint(); 5204 5205 AANoCapture::StateType &S = getState(); 5206 auto Assumed = S.getAssumed(); 5207 S.intersectAssumedBits(T.getAssumed()); 5208 if (!isAssumedNoCaptureMaybeReturned()) 5209 return indicatePessimisticFixpoint(); 5210 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 5211 : ChangeStatus::CHANGED; 5212 } 5213 5214 /// NoCapture attribute for function arguments. 5215 struct AANoCaptureArgument final : AANoCaptureImpl { 5216 AANoCaptureArgument(const IRPosition &IRP, Attributor &A) 5217 : AANoCaptureImpl(IRP, A) {} 5218 5219 /// See AbstractAttribute::trackStatistics() 5220 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) } 5221 }; 5222 5223 /// NoCapture attribute for call site arguments. 5224 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl { 5225 AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A) 5226 : AANoCaptureImpl(IRP, A) {} 5227 5228 /// See AbstractAttribute::initialize(...). 5229 void initialize(Attributor &A) override { 5230 if (Argument *Arg = getAssociatedArgument()) 5231 if (Arg->hasByValAttr()) 5232 indicateOptimisticFixpoint(); 5233 AANoCaptureImpl::initialize(A); 5234 } 5235 5236 /// See AbstractAttribute::updateImpl(...). 5237 ChangeStatus updateImpl(Attributor &A) override { 5238 // TODO: Once we have call site specific value information we can provide 5239 // call site specific liveness information and then it makes 5240 // sense to specialize attributes for call sites arguments instead of 5241 // redirecting requests to the callee argument. 5242 Argument *Arg = getAssociatedArgument(); 5243 if (!Arg) 5244 return indicatePessimisticFixpoint(); 5245 const IRPosition &ArgPos = IRPosition::argument(*Arg); 5246 auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos, DepClassTy::REQUIRED); 5247 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 5248 } 5249 5250 /// See AbstractAttribute::trackStatistics() 5251 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)}; 5252 }; 5253 5254 /// NoCapture attribute for floating values. 5255 struct AANoCaptureFloating final : AANoCaptureImpl { 5256 AANoCaptureFloating(const IRPosition &IRP, Attributor &A) 5257 : AANoCaptureImpl(IRP, A) {} 5258 5259 /// See AbstractAttribute::trackStatistics() 5260 void trackStatistics() const override { 5261 STATS_DECLTRACK_FLOATING_ATTR(nocapture) 5262 } 5263 }; 5264 5265 /// NoCapture attribute for function return value. 5266 struct AANoCaptureReturned final : AANoCaptureImpl { 5267 AANoCaptureReturned(const IRPosition &IRP, Attributor &A) 5268 : AANoCaptureImpl(IRP, A) { 5269 llvm_unreachable("NoCapture is not applicable to function returns!"); 5270 } 5271 5272 /// See AbstractAttribute::initialize(...). 5273 void initialize(Attributor &A) override { 5274 llvm_unreachable("NoCapture is not applicable to function returns!"); 5275 } 5276 5277 /// See AbstractAttribute::updateImpl(...). 5278 ChangeStatus updateImpl(Attributor &A) override { 5279 llvm_unreachable("NoCapture is not applicable to function returns!"); 5280 } 5281 5282 /// See AbstractAttribute::trackStatistics() 5283 void trackStatistics() const override {} 5284 }; 5285 5286 /// NoCapture attribute deduction for a call site return value. 5287 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl { 5288 AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A) 5289 : AANoCaptureImpl(IRP, A) {} 5290 5291 /// See AbstractAttribute::initialize(...). 5292 void initialize(Attributor &A) override { 5293 const Function *F = getAnchorScope(); 5294 // Check what state the associated function can actually capture. 5295 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this); 5296 } 5297 5298 /// See AbstractAttribute::trackStatistics() 5299 void trackStatistics() const override { 5300 STATS_DECLTRACK_CSRET_ATTR(nocapture) 5301 } 5302 }; 5303 } // namespace 5304 5305 /// ------------------ Value Simplify Attribute ---------------------------- 5306 5307 bool ValueSimplifyStateType::unionAssumed(Optional<Value *> Other) { 5308 // FIXME: Add a typecast support. 5309 SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice( 5310 SimplifiedAssociatedValue, Other, Ty); 5311 if (SimplifiedAssociatedValue == Optional<Value *>(nullptr)) 5312 return false; 5313 5314 LLVM_DEBUG({ 5315 if (SimplifiedAssociatedValue) 5316 dbgs() << "[ValueSimplify] is assumed to be " 5317 << **SimplifiedAssociatedValue << "\n"; 5318 else 5319 dbgs() << "[ValueSimplify] is assumed to be <none>\n"; 5320 }); 5321 return true; 5322 } 5323 5324 namespace { 5325 struct AAValueSimplifyImpl : AAValueSimplify { 5326 AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A) 5327 : AAValueSimplify(IRP, A) {} 5328 5329 /// See AbstractAttribute::initialize(...). 5330 void initialize(Attributor &A) override { 5331 if (getAssociatedValue().getType()->isVoidTy()) 5332 indicatePessimisticFixpoint(); 5333 if (A.hasSimplificationCallback(getIRPosition())) 5334 indicatePessimisticFixpoint(); 5335 } 5336 5337 /// See AbstractAttribute::getAsStr(). 5338 const std::string getAsStr() const override { 5339 LLVM_DEBUG({ 5340 dbgs() << "SAV: " << (bool)SimplifiedAssociatedValue << " "; 5341 if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue) 5342 dbgs() << "SAV: " << **SimplifiedAssociatedValue << " "; 5343 }); 5344 return isValidState() ? (isAtFixpoint() ? "simplified" : "maybe-simple") 5345 : "not-simple"; 5346 } 5347 5348 /// See AbstractAttribute::trackStatistics() 5349 void trackStatistics() const override {} 5350 5351 /// See AAValueSimplify::getAssumedSimplifiedValue() 5352 Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override { 5353 return SimplifiedAssociatedValue; 5354 } 5355 5356 /// Ensure the return value is \p V with type \p Ty, if not possible return 5357 /// nullptr. If \p Check is true we will only verify such an operation would 5358 /// suceed and return a non-nullptr value if that is the case. No IR is 5359 /// generated or modified. 5360 static Value *ensureType(Attributor &A, Value &V, Type &Ty, Instruction *CtxI, 5361 bool Check) { 5362 if (auto *TypedV = AA::getWithType(V, Ty)) 5363 return TypedV; 5364 if (CtxI && V.getType()->canLosslesslyBitCastTo(&Ty)) 5365 return Check ? &V 5366 : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(&V, &Ty, 5367 "", CtxI); 5368 return nullptr; 5369 } 5370 5371 /// Reproduce \p I with type \p Ty or return nullptr if that is not posisble. 5372 /// If \p Check is true we will only verify such an operation would suceed and 5373 /// return a non-nullptr value if that is the case. No IR is generated or 5374 /// modified. 5375 static Value *reproduceInst(Attributor &A, 5376 const AbstractAttribute &QueryingAA, 5377 Instruction &I, Type &Ty, Instruction *CtxI, 5378 bool Check, ValueToValueMapTy &VMap) { 5379 assert(CtxI && "Cannot reproduce an instruction without context!"); 5380 if (Check && (I.mayReadFromMemory() || 5381 !isSafeToSpeculativelyExecute(&I, CtxI, /* DT */ nullptr, 5382 /* TLI */ nullptr))) 5383 return nullptr; 5384 for (Value *Op : I.operands()) { 5385 Value *NewOp = reproduceValue(A, QueryingAA, *Op, Ty, CtxI, Check, VMap); 5386 if (!NewOp) { 5387 assert(Check && "Manifest of new value unexpectedly failed!"); 5388 return nullptr; 5389 } 5390 if (!Check) 5391 VMap[Op] = NewOp; 5392 } 5393 if (Check) 5394 return &I; 5395 5396 Instruction *CloneI = I.clone(); 5397 // TODO: Try to salvage debug information here. 5398 CloneI->setDebugLoc(DebugLoc()); 5399 VMap[&I] = CloneI; 5400 CloneI->insertBefore(CtxI); 5401 RemapInstruction(CloneI, VMap); 5402 return CloneI; 5403 } 5404 5405 /// Reproduce \p V with type \p Ty or return nullptr if that is not posisble. 5406 /// If \p Check is true we will only verify such an operation would suceed and 5407 /// return a non-nullptr value if that is the case. No IR is generated or 5408 /// modified. 5409 static Value *reproduceValue(Attributor &A, 5410 const AbstractAttribute &QueryingAA, Value &V, 5411 Type &Ty, Instruction *CtxI, bool Check, 5412 ValueToValueMapTy &VMap) { 5413 if (const auto &NewV = VMap.lookup(&V)) 5414 return NewV; 5415 bool UsedAssumedInformation = false; 5416 Optional<Value *> SimpleV = A.getAssumedSimplified( 5417 V, QueryingAA, UsedAssumedInformation, AA::Interprocedural); 5418 if (!SimpleV.has_value()) 5419 return PoisonValue::get(&Ty); 5420 Value *EffectiveV = &V; 5421 if (SimpleV.value()) 5422 EffectiveV = SimpleV.value(); 5423 if (auto *C = dyn_cast<Constant>(EffectiveV)) 5424 return C; 5425 if (CtxI && AA::isValidAtPosition(AA::ValueAndContext(*EffectiveV, *CtxI), 5426 A.getInfoCache())) 5427 return ensureType(A, *EffectiveV, Ty, CtxI, Check); 5428 if (auto *I = dyn_cast<Instruction>(EffectiveV)) 5429 if (Value *NewV = reproduceInst(A, QueryingAA, *I, Ty, CtxI, Check, VMap)) 5430 return ensureType(A, *NewV, Ty, CtxI, Check); 5431 return nullptr; 5432 } 5433 5434 /// Return a value we can use as replacement for the associated one, or 5435 /// nullptr if we don't have one that makes sense. 5436 Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const { 5437 Value *NewV = SimplifiedAssociatedValue 5438 ? SimplifiedAssociatedValue.value() 5439 : UndefValue::get(getAssociatedType()); 5440 if (NewV && NewV != &getAssociatedValue()) { 5441 ValueToValueMapTy VMap; 5442 // First verify we can reprduce the value with the required type at the 5443 // context location before we actually start modifying the IR. 5444 if (reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI, 5445 /* CheckOnly */ true, VMap)) 5446 return reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI, 5447 /* CheckOnly */ false, VMap); 5448 } 5449 return nullptr; 5450 } 5451 5452 /// Helper function for querying AAValueSimplify and updating candicate. 5453 /// \param IRP The value position we are trying to unify with SimplifiedValue 5454 bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA, 5455 const IRPosition &IRP, bool Simplify = true) { 5456 bool UsedAssumedInformation = false; 5457 Optional<Value *> QueryingValueSimplified = &IRP.getAssociatedValue(); 5458 if (Simplify) 5459 QueryingValueSimplified = A.getAssumedSimplified( 5460 IRP, QueryingAA, UsedAssumedInformation, AA::Interprocedural); 5461 return unionAssumed(QueryingValueSimplified); 5462 } 5463 5464 /// Returns a candidate is found or not 5465 template <typename AAType> bool askSimplifiedValueFor(Attributor &A) { 5466 if (!getAssociatedValue().getType()->isIntegerTy()) 5467 return false; 5468 5469 // This will also pass the call base context. 5470 const auto &AA = 5471 A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE); 5472 5473 Optional<Constant *> COpt = AA.getAssumedConstant(A); 5474 5475 if (!COpt) { 5476 SimplifiedAssociatedValue = llvm::None; 5477 A.recordDependence(AA, *this, DepClassTy::OPTIONAL); 5478 return true; 5479 } 5480 if (auto *C = *COpt) { 5481 SimplifiedAssociatedValue = C; 5482 A.recordDependence(AA, *this, DepClassTy::OPTIONAL); 5483 return true; 5484 } 5485 return false; 5486 } 5487 5488 bool askSimplifiedValueForOtherAAs(Attributor &A) { 5489 if (askSimplifiedValueFor<AAValueConstantRange>(A)) 5490 return true; 5491 if (askSimplifiedValueFor<AAPotentialConstantValues>(A)) 5492 return true; 5493 return false; 5494 } 5495 5496 /// See AbstractAttribute::manifest(...). 5497 ChangeStatus manifest(Attributor &A) override { 5498 ChangeStatus Changed = ChangeStatus::UNCHANGED; 5499 for (auto &U : getAssociatedValue().uses()) { 5500 // Check if we need to adjust the insertion point to make sure the IR is 5501 // valid. 5502 Instruction *IP = dyn_cast<Instruction>(U.getUser()); 5503 if (auto *PHI = dyn_cast_or_null<PHINode>(IP)) 5504 IP = PHI->getIncomingBlock(U)->getTerminator(); 5505 if (auto *NewV = manifestReplacementValue(A, IP)) { 5506 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue() 5507 << " -> " << *NewV << " :: " << *this << "\n"); 5508 if (A.changeUseAfterManifest(U, *NewV)) 5509 Changed = ChangeStatus::CHANGED; 5510 } 5511 } 5512 5513 return Changed | AAValueSimplify::manifest(A); 5514 } 5515 5516 /// See AbstractState::indicatePessimisticFixpoint(...). 5517 ChangeStatus indicatePessimisticFixpoint() override { 5518 SimplifiedAssociatedValue = &getAssociatedValue(); 5519 return AAValueSimplify::indicatePessimisticFixpoint(); 5520 } 5521 }; 5522 5523 struct AAValueSimplifyArgument final : AAValueSimplifyImpl { 5524 AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A) 5525 : AAValueSimplifyImpl(IRP, A) {} 5526 5527 void initialize(Attributor &A) override { 5528 AAValueSimplifyImpl::initialize(A); 5529 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) 5530 indicatePessimisticFixpoint(); 5531 if (hasAttr({Attribute::InAlloca, Attribute::Preallocated, 5532 Attribute::StructRet, Attribute::Nest, Attribute::ByVal}, 5533 /* IgnoreSubsumingPositions */ true)) 5534 indicatePessimisticFixpoint(); 5535 } 5536 5537 /// See AbstractAttribute::updateImpl(...). 5538 ChangeStatus updateImpl(Attributor &A) override { 5539 // Byval is only replacable if it is readonly otherwise we would write into 5540 // the replaced value and not the copy that byval creates implicitly. 5541 Argument *Arg = getAssociatedArgument(); 5542 if (Arg->hasByValAttr()) { 5543 // TODO: We probably need to verify synchronization is not an issue, e.g., 5544 // there is no race by not copying a constant byval. 5545 bool IsKnown; 5546 if (!AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown)) 5547 return indicatePessimisticFixpoint(); 5548 } 5549 5550 auto Before = SimplifiedAssociatedValue; 5551 5552 auto PredForCallSite = [&](AbstractCallSite ACS) { 5553 const IRPosition &ACSArgPos = 5554 IRPosition::callsite_argument(ACS, getCallSiteArgNo()); 5555 // Check if a coresponding argument was found or if it is on not 5556 // associated (which can happen for callback calls). 5557 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 5558 return false; 5559 5560 // Simplify the argument operand explicitly and check if the result is 5561 // valid in the current scope. This avoids refering to simplified values 5562 // in other functions, e.g., we don't want to say a an argument in a 5563 // static function is actually an argument in a different function. 5564 bool UsedAssumedInformation = false; 5565 Optional<Constant *> SimpleArgOp = 5566 A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation); 5567 if (!SimpleArgOp) 5568 return true; 5569 if (!SimpleArgOp.value()) 5570 return false; 5571 if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp)) 5572 return false; 5573 return unionAssumed(*SimpleArgOp); 5574 }; 5575 5576 // Generate a answer specific to a call site context. 5577 bool Success; 5578 bool UsedAssumedInformation = false; 5579 if (hasCallBaseContext() && 5580 getCallBaseContext()->getCalledFunction() == Arg->getParent()) 5581 Success = PredForCallSite( 5582 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse())); 5583 else 5584 Success = A.checkForAllCallSites(PredForCallSite, *this, true, 5585 UsedAssumedInformation); 5586 5587 if (!Success) 5588 if (!askSimplifiedValueForOtherAAs(A)) 5589 return indicatePessimisticFixpoint(); 5590 5591 // If a candicate was found in this update, return CHANGED. 5592 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 5593 : ChangeStatus ::CHANGED; 5594 } 5595 5596 /// See AbstractAttribute::trackStatistics() 5597 void trackStatistics() const override { 5598 STATS_DECLTRACK_ARG_ATTR(value_simplify) 5599 } 5600 }; 5601 5602 struct AAValueSimplifyReturned : AAValueSimplifyImpl { 5603 AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A) 5604 : AAValueSimplifyImpl(IRP, A) {} 5605 5606 /// See AAValueSimplify::getAssumedSimplifiedValue() 5607 Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override { 5608 if (!isValidState()) 5609 return nullptr; 5610 return SimplifiedAssociatedValue; 5611 } 5612 5613 /// See AbstractAttribute::updateImpl(...). 5614 ChangeStatus updateImpl(Attributor &A) override { 5615 auto Before = SimplifiedAssociatedValue; 5616 5617 auto ReturnInstCB = [&](Instruction &I) { 5618 auto &RI = cast<ReturnInst>(I); 5619 return checkAndUpdate( 5620 A, *this, 5621 IRPosition::value(*RI.getReturnValue(), getCallBaseContext())); 5622 }; 5623 5624 bool UsedAssumedInformation = false; 5625 if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret}, 5626 UsedAssumedInformation)) 5627 if (!askSimplifiedValueForOtherAAs(A)) 5628 return indicatePessimisticFixpoint(); 5629 5630 // If a candicate was found in this update, return CHANGED. 5631 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 5632 : ChangeStatus ::CHANGED; 5633 } 5634 5635 ChangeStatus manifest(Attributor &A) override { 5636 // We queried AAValueSimplify for the returned values so they will be 5637 // replaced if a simplified form was found. Nothing to do here. 5638 return ChangeStatus::UNCHANGED; 5639 } 5640 5641 /// See AbstractAttribute::trackStatistics() 5642 void trackStatistics() const override { 5643 STATS_DECLTRACK_FNRET_ATTR(value_simplify) 5644 } 5645 }; 5646 5647 struct AAValueSimplifyFloating : AAValueSimplifyImpl { 5648 AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A) 5649 : AAValueSimplifyImpl(IRP, A) {} 5650 5651 /// See AbstractAttribute::initialize(...). 5652 void initialize(Attributor &A) override { 5653 AAValueSimplifyImpl::initialize(A); 5654 Value &V = getAnchorValue(); 5655 5656 // TODO: add other stuffs 5657 if (isa<Constant>(V)) 5658 indicatePessimisticFixpoint(); 5659 } 5660 5661 /// See AbstractAttribute::updateImpl(...). 5662 ChangeStatus updateImpl(Attributor &A) override { 5663 auto Before = SimplifiedAssociatedValue; 5664 if (!askSimplifiedValueForOtherAAs(A)) 5665 return indicatePessimisticFixpoint(); 5666 5667 // If a candicate was found in this update, return CHANGED. 5668 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 5669 : ChangeStatus ::CHANGED; 5670 } 5671 5672 /// See AbstractAttribute::trackStatistics() 5673 void trackStatistics() const override { 5674 STATS_DECLTRACK_FLOATING_ATTR(value_simplify) 5675 } 5676 }; 5677 5678 struct AAValueSimplifyFunction : AAValueSimplifyImpl { 5679 AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A) 5680 : AAValueSimplifyImpl(IRP, A) {} 5681 5682 /// See AbstractAttribute::initialize(...). 5683 void initialize(Attributor &A) override { 5684 SimplifiedAssociatedValue = nullptr; 5685 indicateOptimisticFixpoint(); 5686 } 5687 /// See AbstractAttribute::initialize(...). 5688 ChangeStatus updateImpl(Attributor &A) override { 5689 llvm_unreachable( 5690 "AAValueSimplify(Function|CallSite)::updateImpl will not be called"); 5691 } 5692 /// See AbstractAttribute::trackStatistics() 5693 void trackStatistics() const override { 5694 STATS_DECLTRACK_FN_ATTR(value_simplify) 5695 } 5696 }; 5697 5698 struct AAValueSimplifyCallSite : AAValueSimplifyFunction { 5699 AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A) 5700 : AAValueSimplifyFunction(IRP, A) {} 5701 /// See AbstractAttribute::trackStatistics() 5702 void trackStatistics() const override { 5703 STATS_DECLTRACK_CS_ATTR(value_simplify) 5704 } 5705 }; 5706 5707 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl { 5708 AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A) 5709 : AAValueSimplifyImpl(IRP, A) {} 5710 5711 void initialize(Attributor &A) override { 5712 AAValueSimplifyImpl::initialize(A); 5713 Function *Fn = getAssociatedFunction(); 5714 if (!Fn) { 5715 indicatePessimisticFixpoint(); 5716 return; 5717 } 5718 for (Argument &Arg : Fn->args()) { 5719 if (Arg.hasReturnedAttr()) { 5720 auto IRP = IRPosition::callsite_argument(*cast<CallBase>(getCtxI()), 5721 Arg.getArgNo()); 5722 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_ARGUMENT && 5723 checkAndUpdate(A, *this, IRP)) 5724 indicateOptimisticFixpoint(); 5725 else 5726 indicatePessimisticFixpoint(); 5727 return; 5728 } 5729 } 5730 } 5731 5732 /// See AbstractAttribute::updateImpl(...). 5733 ChangeStatus updateImpl(Attributor &A) override { 5734 auto Before = SimplifiedAssociatedValue; 5735 auto &RetAA = A.getAAFor<AAReturnedValues>( 5736 *this, IRPosition::function(*getAssociatedFunction()), 5737 DepClassTy::REQUIRED); 5738 auto PredForReturned = 5739 [&](Value &RetVal, const SmallSetVector<ReturnInst *, 4> &RetInsts) { 5740 bool UsedAssumedInformation = false; 5741 Optional<Value *> CSRetVal = A.translateArgumentToCallSiteContent( 5742 &RetVal, *cast<CallBase>(getCtxI()), *this, 5743 UsedAssumedInformation); 5744 SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice( 5745 SimplifiedAssociatedValue, CSRetVal, getAssociatedType()); 5746 return SimplifiedAssociatedValue != Optional<Value *>(nullptr); 5747 }; 5748 if (!RetAA.checkForAllReturnedValuesAndReturnInsts(PredForReturned)) 5749 if (!askSimplifiedValueForOtherAAs(A)) 5750 return indicatePessimisticFixpoint(); 5751 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 5752 : ChangeStatus ::CHANGED; 5753 } 5754 5755 void trackStatistics() const override { 5756 STATS_DECLTRACK_CSRET_ATTR(value_simplify) 5757 } 5758 }; 5759 5760 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating { 5761 AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A) 5762 : AAValueSimplifyFloating(IRP, A) {} 5763 5764 /// See AbstractAttribute::manifest(...). 5765 ChangeStatus manifest(Attributor &A) override { 5766 ChangeStatus Changed = ChangeStatus::UNCHANGED; 5767 // TODO: We should avoid simplification duplication to begin with. 5768 auto *FloatAA = A.lookupAAFor<AAValueSimplify>( 5769 IRPosition::value(getAssociatedValue()), this, DepClassTy::NONE); 5770 if (FloatAA && FloatAA->getState().isValidState()) 5771 return Changed; 5772 5773 if (auto *NewV = manifestReplacementValue(A, getCtxI())) { 5774 Use &U = cast<CallBase>(&getAnchorValue()) 5775 ->getArgOperandUse(getCallSiteArgNo()); 5776 if (A.changeUseAfterManifest(U, *NewV)) 5777 Changed = ChangeStatus::CHANGED; 5778 } 5779 5780 return Changed | AAValueSimplify::manifest(A); 5781 } 5782 5783 void trackStatistics() const override { 5784 STATS_DECLTRACK_CSARG_ATTR(value_simplify) 5785 } 5786 }; 5787 } // namespace 5788 5789 /// ----------------------- Heap-To-Stack Conversion --------------------------- 5790 namespace { 5791 struct AAHeapToStackFunction final : public AAHeapToStack { 5792 5793 struct AllocationInfo { 5794 /// The call that allocates the memory. 5795 CallBase *const CB; 5796 5797 /// The library function id for the allocation. 5798 LibFunc LibraryFunctionId = NotLibFunc; 5799 5800 /// The status wrt. a rewrite. 5801 enum { 5802 STACK_DUE_TO_USE, 5803 STACK_DUE_TO_FREE, 5804 INVALID, 5805 } Status = STACK_DUE_TO_USE; 5806 5807 /// Flag to indicate if we encountered a use that might free this allocation 5808 /// but which is not in the deallocation infos. 5809 bool HasPotentiallyFreeingUnknownUses = false; 5810 5811 /// Flag to indicate that we should place the new alloca in the function 5812 /// entry block rather than where the call site (CB) is. 5813 bool MoveAllocaIntoEntry = true; 5814 5815 /// The set of free calls that use this allocation. 5816 SmallSetVector<CallBase *, 1> PotentialFreeCalls{}; 5817 }; 5818 5819 struct DeallocationInfo { 5820 /// The call that deallocates the memory. 5821 CallBase *const CB; 5822 /// The value freed by the call. 5823 Value *FreedOp; 5824 5825 /// Flag to indicate if we don't know all objects this deallocation might 5826 /// free. 5827 bool MightFreeUnknownObjects = false; 5828 5829 /// The set of allocation calls that are potentially freed. 5830 SmallSetVector<CallBase *, 1> PotentialAllocationCalls{}; 5831 }; 5832 5833 AAHeapToStackFunction(const IRPosition &IRP, Attributor &A) 5834 : AAHeapToStack(IRP, A) {} 5835 5836 ~AAHeapToStackFunction() { 5837 // Ensure we call the destructor so we release any memory allocated in the 5838 // sets. 5839 for (auto &It : AllocationInfos) 5840 It.second->~AllocationInfo(); 5841 for (auto &It : DeallocationInfos) 5842 It.second->~DeallocationInfo(); 5843 } 5844 5845 void initialize(Attributor &A) override { 5846 AAHeapToStack::initialize(A); 5847 5848 const Function *F = getAnchorScope(); 5849 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 5850 5851 auto AllocationIdentifierCB = [&](Instruction &I) { 5852 CallBase *CB = dyn_cast<CallBase>(&I); 5853 if (!CB) 5854 return true; 5855 if (Value *FreedOp = getFreedOperand(CB, TLI)) { 5856 DeallocationInfos[CB] = new (A.Allocator) DeallocationInfo{CB, FreedOp}; 5857 return true; 5858 } 5859 // To do heap to stack, we need to know that the allocation itself is 5860 // removable once uses are rewritten, and that we can initialize the 5861 // alloca to the same pattern as the original allocation result. 5862 if (isRemovableAlloc(CB, TLI)) { 5863 auto *I8Ty = Type::getInt8Ty(CB->getParent()->getContext()); 5864 if (nullptr != getInitialValueOfAllocation(CB, TLI, I8Ty)) { 5865 AllocationInfo *AI = new (A.Allocator) AllocationInfo{CB}; 5866 AllocationInfos[CB] = AI; 5867 if (TLI) 5868 TLI->getLibFunc(*CB, AI->LibraryFunctionId); 5869 } 5870 } 5871 return true; 5872 }; 5873 5874 bool UsedAssumedInformation = false; 5875 bool Success = A.checkForAllCallLikeInstructions( 5876 AllocationIdentifierCB, *this, UsedAssumedInformation, 5877 /* CheckBBLivenessOnly */ false, 5878 /* CheckPotentiallyDead */ true); 5879 (void)Success; 5880 assert(Success && "Did not expect the call base visit callback to fail!"); 5881 5882 Attributor::SimplifictionCallbackTy SCB = 5883 [](const IRPosition &, const AbstractAttribute *, 5884 bool &) -> Optional<Value *> { return nullptr; }; 5885 for (const auto &It : AllocationInfos) 5886 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first), 5887 SCB); 5888 for (const auto &It : DeallocationInfos) 5889 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first), 5890 SCB); 5891 } 5892 5893 const std::string getAsStr() const override { 5894 unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0; 5895 for (const auto &It : AllocationInfos) { 5896 if (It.second->Status == AllocationInfo::INVALID) 5897 ++NumInvalidMallocs; 5898 else 5899 ++NumH2SMallocs; 5900 } 5901 return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) + "/" + 5902 std::to_string(NumInvalidMallocs); 5903 } 5904 5905 /// See AbstractAttribute::trackStatistics(). 5906 void trackStatistics() const override { 5907 STATS_DECL( 5908 MallocCalls, Function, 5909 "Number of malloc/calloc/aligned_alloc calls converted to allocas"); 5910 for (auto &It : AllocationInfos) 5911 if (It.second->Status != AllocationInfo::INVALID) 5912 ++BUILD_STAT_NAME(MallocCalls, Function); 5913 } 5914 5915 bool isAssumedHeapToStack(const CallBase &CB) const override { 5916 if (isValidState()) 5917 if (AllocationInfo *AI = 5918 AllocationInfos.lookup(const_cast<CallBase *>(&CB))) 5919 return AI->Status != AllocationInfo::INVALID; 5920 return false; 5921 } 5922 5923 bool isAssumedHeapToStackRemovedFree(CallBase &CB) const override { 5924 if (!isValidState()) 5925 return false; 5926 5927 for (auto &It : AllocationInfos) { 5928 AllocationInfo &AI = *It.second; 5929 if (AI.Status == AllocationInfo::INVALID) 5930 continue; 5931 5932 if (AI.PotentialFreeCalls.count(&CB)) 5933 return true; 5934 } 5935 5936 return false; 5937 } 5938 5939 ChangeStatus manifest(Attributor &A) override { 5940 assert(getState().isValidState() && 5941 "Attempted to manifest an invalid state!"); 5942 5943 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 5944 Function *F = getAnchorScope(); 5945 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 5946 5947 for (auto &It : AllocationInfos) { 5948 AllocationInfo &AI = *It.second; 5949 if (AI.Status == AllocationInfo::INVALID) 5950 continue; 5951 5952 for (CallBase *FreeCall : AI.PotentialFreeCalls) { 5953 LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n"); 5954 A.deleteAfterManifest(*FreeCall); 5955 HasChanged = ChangeStatus::CHANGED; 5956 } 5957 5958 LLVM_DEBUG(dbgs() << "H2S: Removing malloc-like call: " << *AI.CB 5959 << "\n"); 5960 5961 auto Remark = [&](OptimizationRemark OR) { 5962 LibFunc IsAllocShared; 5963 if (TLI->getLibFunc(*AI.CB, IsAllocShared)) 5964 if (IsAllocShared == LibFunc___kmpc_alloc_shared) 5965 return OR << "Moving globalized variable to the stack."; 5966 return OR << "Moving memory allocation from the heap to the stack."; 5967 }; 5968 if (AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared) 5969 A.emitRemark<OptimizationRemark>(AI.CB, "OMP110", Remark); 5970 else 5971 A.emitRemark<OptimizationRemark>(AI.CB, "HeapToStack", Remark); 5972 5973 const DataLayout &DL = A.getInfoCache().getDL(); 5974 Value *Size; 5975 Optional<APInt> SizeAPI = getSize(A, *this, AI); 5976 if (SizeAPI) { 5977 Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI); 5978 } else { 5979 LLVMContext &Ctx = AI.CB->getContext(); 5980 ObjectSizeOpts Opts; 5981 ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, Opts); 5982 SizeOffsetEvalType SizeOffsetPair = Eval.compute(AI.CB); 5983 assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() && 5984 cast<ConstantInt>(SizeOffsetPair.second)->isZero()); 5985 Size = SizeOffsetPair.first; 5986 } 5987 5988 Instruction *IP = 5989 AI.MoveAllocaIntoEntry ? &F->getEntryBlock().front() : AI.CB; 5990 5991 Align Alignment(1); 5992 if (MaybeAlign RetAlign = AI.CB->getRetAlign()) 5993 Alignment = std::max(Alignment, *RetAlign); 5994 if (Value *Align = getAllocAlignment(AI.CB, TLI)) { 5995 Optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align); 5996 assert(AlignmentAPI && AlignmentAPI.value().getZExtValue() > 0 && 5997 "Expected an alignment during manifest!"); 5998 Alignment = std::max( 5999 Alignment, assumeAligned(AlignmentAPI.value().getZExtValue())); 6000 } 6001 6002 // TODO: Hoist the alloca towards the function entry. 6003 unsigned AS = DL.getAllocaAddrSpace(); 6004 Instruction *Alloca = 6005 new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment, 6006 AI.CB->getName() + ".h2s", IP); 6007 6008 if (Alloca->getType() != AI.CB->getType()) 6009 Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast( 6010 Alloca, AI.CB->getType(), "malloc_cast", AI.CB); 6011 6012 auto *I8Ty = Type::getInt8Ty(F->getContext()); 6013 auto *InitVal = getInitialValueOfAllocation(AI.CB, TLI, I8Ty); 6014 assert(InitVal && 6015 "Must be able to materialize initial memory state of allocation"); 6016 6017 A.changeAfterManifest(IRPosition::inst(*AI.CB), *Alloca); 6018 6019 if (auto *II = dyn_cast<InvokeInst>(AI.CB)) { 6020 auto *NBB = II->getNormalDest(); 6021 BranchInst::Create(NBB, AI.CB->getParent()); 6022 A.deleteAfterManifest(*AI.CB); 6023 } else { 6024 A.deleteAfterManifest(*AI.CB); 6025 } 6026 6027 // Initialize the alloca with the same value as used by the allocation 6028 // function. We can skip undef as the initial value of an alloc is 6029 // undef, and the memset would simply end up being DSEd. 6030 if (!isa<UndefValue>(InitVal)) { 6031 IRBuilder<> Builder(Alloca->getNextNode()); 6032 // TODO: Use alignment above if align!=1 6033 Builder.CreateMemSet(Alloca, InitVal, Size, None); 6034 } 6035 HasChanged = ChangeStatus::CHANGED; 6036 } 6037 6038 return HasChanged; 6039 } 6040 6041 Optional<APInt> getAPInt(Attributor &A, const AbstractAttribute &AA, 6042 Value &V) { 6043 bool UsedAssumedInformation = false; 6044 Optional<Constant *> SimpleV = 6045 A.getAssumedConstant(V, AA, UsedAssumedInformation); 6046 if (!SimpleV) 6047 return APInt(64, 0); 6048 if (auto *CI = dyn_cast_or_null<ConstantInt>(SimpleV.value())) 6049 return CI->getValue(); 6050 return llvm::None; 6051 } 6052 6053 Optional<APInt> getSize(Attributor &A, const AbstractAttribute &AA, 6054 AllocationInfo &AI) { 6055 auto Mapper = [&](const Value *V) -> const Value * { 6056 bool UsedAssumedInformation = false; 6057 if (Optional<Constant *> SimpleV = 6058 A.getAssumedConstant(*V, AA, UsedAssumedInformation)) 6059 if (*SimpleV) 6060 return *SimpleV; 6061 return V; 6062 }; 6063 6064 const Function *F = getAnchorScope(); 6065 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 6066 return getAllocSize(AI.CB, TLI, Mapper); 6067 } 6068 6069 /// Collection of all malloc-like calls in a function with associated 6070 /// information. 6071 MapVector<CallBase *, AllocationInfo *> AllocationInfos; 6072 6073 /// Collection of all free-like calls in a function with associated 6074 /// information. 6075 MapVector<CallBase *, DeallocationInfo *> DeallocationInfos; 6076 6077 ChangeStatus updateImpl(Attributor &A) override; 6078 }; 6079 6080 ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) { 6081 ChangeStatus Changed = ChangeStatus::UNCHANGED; 6082 const Function *F = getAnchorScope(); 6083 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 6084 6085 const auto &LivenessAA = 6086 A.getAAFor<AAIsDead>(*this, IRPosition::function(*F), DepClassTy::NONE); 6087 6088 MustBeExecutedContextExplorer &Explorer = 6089 A.getInfoCache().getMustBeExecutedContextExplorer(); 6090 6091 bool StackIsAccessibleByOtherThreads = 6092 A.getInfoCache().stackIsAccessibleByOtherThreads(); 6093 6094 LoopInfo *LI = 6095 A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F); 6096 Optional<bool> MayContainIrreducibleControl; 6097 auto IsInLoop = [&](BasicBlock &BB) { 6098 if (&F->getEntryBlock() == &BB) 6099 return false; 6100 if (!MayContainIrreducibleControl.has_value()) 6101 MayContainIrreducibleControl = mayContainIrreducibleControl(*F, LI); 6102 if (MayContainIrreducibleControl.value()) 6103 return true; 6104 if (!LI) 6105 return true; 6106 return LI->getLoopFor(&BB) != nullptr; 6107 }; 6108 6109 // Flag to ensure we update our deallocation information at most once per 6110 // updateImpl call and only if we use the free check reasoning. 6111 bool HasUpdatedFrees = false; 6112 6113 auto UpdateFrees = [&]() { 6114 HasUpdatedFrees = true; 6115 6116 for (auto &It : DeallocationInfos) { 6117 DeallocationInfo &DI = *It.second; 6118 // For now we cannot use deallocations that have unknown inputs, skip 6119 // them. 6120 if (DI.MightFreeUnknownObjects) 6121 continue; 6122 6123 // No need to analyze dead calls, ignore them instead. 6124 bool UsedAssumedInformation = false; 6125 if (A.isAssumedDead(*DI.CB, this, &LivenessAA, UsedAssumedInformation, 6126 /* CheckBBLivenessOnly */ true)) 6127 continue; 6128 6129 // Use the non-optimistic version to get the freed object. 6130 Value *Obj = getUnderlyingObject(DI.FreedOp); 6131 if (!Obj) { 6132 LLVM_DEBUG(dbgs() << "[H2S] Unknown underlying object for free!\n"); 6133 DI.MightFreeUnknownObjects = true; 6134 continue; 6135 } 6136 6137 // Free of null and undef can be ignored as no-ops (or UB in the latter 6138 // case). 6139 if (isa<ConstantPointerNull>(Obj) || isa<UndefValue>(Obj)) 6140 continue; 6141 6142 CallBase *ObjCB = dyn_cast<CallBase>(Obj); 6143 if (!ObjCB) { 6144 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-call object: " << *Obj 6145 << "\n"); 6146 DI.MightFreeUnknownObjects = true; 6147 continue; 6148 } 6149 6150 AllocationInfo *AI = AllocationInfos.lookup(ObjCB); 6151 if (!AI) { 6152 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-allocation object: " << *Obj 6153 << "\n"); 6154 DI.MightFreeUnknownObjects = true; 6155 continue; 6156 } 6157 6158 DI.PotentialAllocationCalls.insert(ObjCB); 6159 } 6160 }; 6161 6162 auto FreeCheck = [&](AllocationInfo &AI) { 6163 // If the stack is not accessible by other threads, the "must-free" logic 6164 // doesn't apply as the pointer could be shared and needs to be places in 6165 // "shareable" memory. 6166 if (!StackIsAccessibleByOtherThreads) { 6167 auto &NoSyncAA = 6168 A.getAAFor<AANoSync>(*this, getIRPosition(), DepClassTy::OPTIONAL); 6169 if (!NoSyncAA.isAssumedNoSync()) { 6170 LLVM_DEBUG( 6171 dbgs() << "[H2S] found an escaping use, stack is not accessible by " 6172 "other threads and function is not nosync:\n"); 6173 return false; 6174 } 6175 } 6176 if (!HasUpdatedFrees) 6177 UpdateFrees(); 6178 6179 // TODO: Allow multi exit functions that have different free calls. 6180 if (AI.PotentialFreeCalls.size() != 1) { 6181 LLVM_DEBUG(dbgs() << "[H2S] did not find one free call but " 6182 << AI.PotentialFreeCalls.size() << "\n"); 6183 return false; 6184 } 6185 CallBase *UniqueFree = *AI.PotentialFreeCalls.begin(); 6186 DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree); 6187 if (!DI) { 6188 LLVM_DEBUG( 6189 dbgs() << "[H2S] unique free call was not known as deallocation call " 6190 << *UniqueFree << "\n"); 6191 return false; 6192 } 6193 if (DI->MightFreeUnknownObjects) { 6194 LLVM_DEBUG( 6195 dbgs() << "[H2S] unique free call might free unknown allocations\n"); 6196 return false; 6197 } 6198 if (DI->PotentialAllocationCalls.empty()) 6199 return true; 6200 if (DI->PotentialAllocationCalls.size() > 1) { 6201 LLVM_DEBUG(dbgs() << "[H2S] unique free call might free " 6202 << DI->PotentialAllocationCalls.size() 6203 << " different allocations\n"); 6204 return false; 6205 } 6206 if (*DI->PotentialAllocationCalls.begin() != AI.CB) { 6207 LLVM_DEBUG( 6208 dbgs() 6209 << "[H2S] unique free call not known to free this allocation but " 6210 << **DI->PotentialAllocationCalls.begin() << "\n"); 6211 return false; 6212 } 6213 Instruction *CtxI = isa<InvokeInst>(AI.CB) ? AI.CB : AI.CB->getNextNode(); 6214 if (!Explorer.findInContextOf(UniqueFree, CtxI)) { 6215 LLVM_DEBUG( 6216 dbgs() 6217 << "[H2S] unique free call might not be executed with the allocation " 6218 << *UniqueFree << "\n"); 6219 return false; 6220 } 6221 return true; 6222 }; 6223 6224 auto UsesCheck = [&](AllocationInfo &AI) { 6225 bool ValidUsesOnly = true; 6226 6227 auto Pred = [&](const Use &U, bool &Follow) -> bool { 6228 Instruction *UserI = cast<Instruction>(U.getUser()); 6229 if (isa<LoadInst>(UserI)) 6230 return true; 6231 if (auto *SI = dyn_cast<StoreInst>(UserI)) { 6232 if (SI->getValueOperand() == U.get()) { 6233 LLVM_DEBUG(dbgs() 6234 << "[H2S] escaping store to memory: " << *UserI << "\n"); 6235 ValidUsesOnly = false; 6236 } else { 6237 // A store into the malloc'ed memory is fine. 6238 } 6239 return true; 6240 } 6241 if (auto *CB = dyn_cast<CallBase>(UserI)) { 6242 if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd()) 6243 return true; 6244 if (DeallocationInfos.count(CB)) { 6245 AI.PotentialFreeCalls.insert(CB); 6246 return true; 6247 } 6248 6249 unsigned ArgNo = CB->getArgOperandNo(&U); 6250 6251 const auto &NoCaptureAA = A.getAAFor<AANoCapture>( 6252 *this, IRPosition::callsite_argument(*CB, ArgNo), 6253 DepClassTy::OPTIONAL); 6254 6255 // If a call site argument use is nofree, we are fine. 6256 const auto &ArgNoFreeAA = A.getAAFor<AANoFree>( 6257 *this, IRPosition::callsite_argument(*CB, ArgNo), 6258 DepClassTy::OPTIONAL); 6259 6260 bool MaybeCaptured = !NoCaptureAA.isAssumedNoCapture(); 6261 bool MaybeFreed = !ArgNoFreeAA.isAssumedNoFree(); 6262 if (MaybeCaptured || 6263 (AI.LibraryFunctionId != LibFunc___kmpc_alloc_shared && 6264 MaybeFreed)) { 6265 AI.HasPotentiallyFreeingUnknownUses |= MaybeFreed; 6266 6267 // Emit a missed remark if this is missed OpenMP globalization. 6268 auto Remark = [&](OptimizationRemarkMissed ORM) { 6269 return ORM 6270 << "Could not move globalized variable to the stack. " 6271 "Variable is potentially captured in call. Mark " 6272 "parameter as `__attribute__((noescape))` to override."; 6273 }; 6274 6275 if (ValidUsesOnly && 6276 AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared) 6277 A.emitRemark<OptimizationRemarkMissed>(CB, "OMP113", Remark); 6278 6279 LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n"); 6280 ValidUsesOnly = false; 6281 } 6282 return true; 6283 } 6284 6285 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) || 6286 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 6287 Follow = true; 6288 return true; 6289 } 6290 // Unknown user for which we can not track uses further (in a way that 6291 // makes sense). 6292 LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n"); 6293 ValidUsesOnly = false; 6294 return true; 6295 }; 6296 if (!A.checkForAllUses(Pred, *this, *AI.CB)) 6297 return false; 6298 return ValidUsesOnly; 6299 }; 6300 6301 // The actual update starts here. We look at all allocations and depending on 6302 // their status perform the appropriate check(s). 6303 for (auto &It : AllocationInfos) { 6304 AllocationInfo &AI = *It.second; 6305 if (AI.Status == AllocationInfo::INVALID) 6306 continue; 6307 6308 if (Value *Align = getAllocAlignment(AI.CB, TLI)) { 6309 Optional<APInt> APAlign = getAPInt(A, *this, *Align); 6310 if (!APAlign) { 6311 // Can't generate an alloca which respects the required alignment 6312 // on the allocation. 6313 LLVM_DEBUG(dbgs() << "[H2S] Unknown allocation alignment: " << *AI.CB 6314 << "\n"); 6315 AI.Status = AllocationInfo::INVALID; 6316 Changed = ChangeStatus::CHANGED; 6317 continue; 6318 } 6319 if (APAlign->ugt(llvm::Value::MaximumAlignment) || 6320 !APAlign->isPowerOf2()) { 6321 LLVM_DEBUG(dbgs() << "[H2S] Invalid allocation alignment: " << APAlign 6322 << "\n"); 6323 AI.Status = AllocationInfo::INVALID; 6324 Changed = ChangeStatus::CHANGED; 6325 continue; 6326 } 6327 } 6328 6329 Optional<APInt> Size = getSize(A, *this, AI); 6330 if (MaxHeapToStackSize != -1) { 6331 if (!Size || Size.value().ugt(MaxHeapToStackSize)) { 6332 LLVM_DEBUG({ 6333 if (!Size) 6334 dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n"; 6335 else 6336 dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. " 6337 << MaxHeapToStackSize << "\n"; 6338 }); 6339 6340 AI.Status = AllocationInfo::INVALID; 6341 Changed = ChangeStatus::CHANGED; 6342 continue; 6343 } 6344 } 6345 6346 switch (AI.Status) { 6347 case AllocationInfo::STACK_DUE_TO_USE: 6348 if (UsesCheck(AI)) 6349 break; 6350 AI.Status = AllocationInfo::STACK_DUE_TO_FREE; 6351 LLVM_FALLTHROUGH; 6352 case AllocationInfo::STACK_DUE_TO_FREE: 6353 if (FreeCheck(AI)) 6354 break; 6355 AI.Status = AllocationInfo::INVALID; 6356 Changed = ChangeStatus::CHANGED; 6357 break; 6358 case AllocationInfo::INVALID: 6359 llvm_unreachable("Invalid allocations should never reach this point!"); 6360 }; 6361 6362 // Check if we still think we can move it into the entry block. 6363 if (AI.MoveAllocaIntoEntry && 6364 (!Size.has_value() || IsInLoop(*AI.CB->getParent()))) 6365 AI.MoveAllocaIntoEntry = false; 6366 } 6367 6368 return Changed; 6369 } 6370 } // namespace 6371 6372 /// ----------------------- Privatizable Pointers ------------------------------ 6373 namespace { 6374 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr { 6375 AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A) 6376 : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {} 6377 6378 ChangeStatus indicatePessimisticFixpoint() override { 6379 AAPrivatizablePtr::indicatePessimisticFixpoint(); 6380 PrivatizableType = nullptr; 6381 return ChangeStatus::CHANGED; 6382 } 6383 6384 /// Identify the type we can chose for a private copy of the underlying 6385 /// argument. None means it is not clear yet, nullptr means there is none. 6386 virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0; 6387 6388 /// Return a privatizable type that encloses both T0 and T1. 6389 /// TODO: This is merely a stub for now as we should manage a mapping as well. 6390 Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) { 6391 if (!T0) 6392 return T1; 6393 if (!T1) 6394 return T0; 6395 if (T0 == T1) 6396 return T0; 6397 return nullptr; 6398 } 6399 6400 Optional<Type *> getPrivatizableType() const override { 6401 return PrivatizableType; 6402 } 6403 6404 const std::string getAsStr() const override { 6405 return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]"; 6406 } 6407 6408 protected: 6409 Optional<Type *> PrivatizableType; 6410 }; 6411 6412 // TODO: Do this for call site arguments (probably also other values) as well. 6413 6414 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { 6415 AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A) 6416 : AAPrivatizablePtrImpl(IRP, A) {} 6417 6418 /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...) 6419 Optional<Type *> identifyPrivatizableType(Attributor &A) override { 6420 // If this is a byval argument and we know all the call sites (so we can 6421 // rewrite them), there is no need to check them explicitly. 6422 bool UsedAssumedInformation = false; 6423 SmallVector<Attribute, 1> Attrs; 6424 getAttrs({Attribute::ByVal}, Attrs, /* IgnoreSubsumingPositions */ true); 6425 if (!Attrs.empty() && 6426 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this, 6427 true, UsedAssumedInformation)) 6428 return Attrs[0].getValueAsType(); 6429 6430 Optional<Type *> Ty; 6431 unsigned ArgNo = getIRPosition().getCallSiteArgNo(); 6432 6433 // Make sure the associated call site argument has the same type at all call 6434 // sites and it is an allocation we know is safe to privatize, for now that 6435 // means we only allow alloca instructions. 6436 // TODO: We can additionally analyze the accesses in the callee to create 6437 // the type from that information instead. That is a little more 6438 // involved and will be done in a follow up patch. 6439 auto CallSiteCheck = [&](AbstractCallSite ACS) { 6440 IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo); 6441 // Check if a coresponding argument was found or if it is one not 6442 // associated (which can happen for callback calls). 6443 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 6444 return false; 6445 6446 // Check that all call sites agree on a type. 6447 auto &PrivCSArgAA = 6448 A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED); 6449 Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType(); 6450 6451 LLVM_DEBUG({ 6452 dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: "; 6453 if (CSTy && CSTy.value()) 6454 CSTy.value()->print(dbgs()); 6455 else if (CSTy) 6456 dbgs() << "<nullptr>"; 6457 else 6458 dbgs() << "<none>"; 6459 }); 6460 6461 Ty = combineTypes(Ty, CSTy); 6462 6463 LLVM_DEBUG({ 6464 dbgs() << " : New Type: "; 6465 if (Ty && Ty.value()) 6466 Ty.value()->print(dbgs()); 6467 else if (Ty) 6468 dbgs() << "<nullptr>"; 6469 else 6470 dbgs() << "<none>"; 6471 dbgs() << "\n"; 6472 }); 6473 6474 return !Ty || Ty.value(); 6475 }; 6476 6477 if (!A.checkForAllCallSites(CallSiteCheck, *this, true, 6478 UsedAssumedInformation)) 6479 return nullptr; 6480 return Ty; 6481 } 6482 6483 /// See AbstractAttribute::updateImpl(...). 6484 ChangeStatus updateImpl(Attributor &A) override { 6485 PrivatizableType = identifyPrivatizableType(A); 6486 if (!PrivatizableType) 6487 return ChangeStatus::UNCHANGED; 6488 if (!PrivatizableType.value()) 6489 return indicatePessimisticFixpoint(); 6490 6491 // The dependence is optional so we don't give up once we give up on the 6492 // alignment. 6493 A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()), 6494 DepClassTy::OPTIONAL); 6495 6496 // Avoid arguments with padding for now. 6497 if (!getIRPosition().hasAttr(Attribute::ByVal) && 6498 !isDenselyPacked(*PrivatizableType, A.getInfoCache().getDL())) { 6499 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n"); 6500 return indicatePessimisticFixpoint(); 6501 } 6502 6503 // Collect the types that will replace the privatizable type in the function 6504 // signature. 6505 SmallVector<Type *, 16> ReplacementTypes; 6506 identifyReplacementTypes(*PrivatizableType, ReplacementTypes); 6507 6508 // Verify callee and caller agree on how the promoted argument would be 6509 // passed. 6510 Function &Fn = *getIRPosition().getAnchorScope(); 6511 const auto *TTI = 6512 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn); 6513 if (!TTI) { 6514 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Missing TTI for function " 6515 << Fn.getName() << "\n"); 6516 return indicatePessimisticFixpoint(); 6517 } 6518 6519 auto CallSiteCheck = [&](AbstractCallSite ACS) { 6520 CallBase *CB = ACS.getInstruction(); 6521 return TTI->areTypesABICompatible( 6522 CB->getCaller(), CB->getCalledFunction(), ReplacementTypes); 6523 }; 6524 bool UsedAssumedInformation = false; 6525 if (!A.checkForAllCallSites(CallSiteCheck, *this, true, 6526 UsedAssumedInformation)) { 6527 LLVM_DEBUG( 6528 dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for " 6529 << Fn.getName() << "\n"); 6530 return indicatePessimisticFixpoint(); 6531 } 6532 6533 // Register a rewrite of the argument. 6534 Argument *Arg = getAssociatedArgument(); 6535 if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) { 6536 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n"); 6537 return indicatePessimisticFixpoint(); 6538 } 6539 6540 unsigned ArgNo = Arg->getArgNo(); 6541 6542 // Helper to check if for the given call site the associated argument is 6543 // passed to a callback where the privatization would be different. 6544 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) { 6545 SmallVector<const Use *, 4> CallbackUses; 6546 AbstractCallSite::getCallbackUses(CB, CallbackUses); 6547 for (const Use *U : CallbackUses) { 6548 AbstractCallSite CBACS(U); 6549 assert(CBACS && CBACS.isCallbackCall()); 6550 for (Argument &CBArg : CBACS.getCalledFunction()->args()) { 6551 int CBArgNo = CBACS.getCallArgOperandNo(CBArg); 6552 6553 LLVM_DEBUG({ 6554 dbgs() 6555 << "[AAPrivatizablePtr] Argument " << *Arg 6556 << "check if can be privatized in the context of its parent (" 6557 << Arg->getParent()->getName() 6558 << ")\n[AAPrivatizablePtr] because it is an argument in a " 6559 "callback (" 6560 << CBArgNo << "@" << CBACS.getCalledFunction()->getName() 6561 << ")\n[AAPrivatizablePtr] " << CBArg << " : " 6562 << CBACS.getCallArgOperand(CBArg) << " vs " 6563 << CB.getArgOperand(ArgNo) << "\n" 6564 << "[AAPrivatizablePtr] " << CBArg << " : " 6565 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n"; 6566 }); 6567 6568 if (CBArgNo != int(ArgNo)) 6569 continue; 6570 const auto &CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>( 6571 *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED); 6572 if (CBArgPrivAA.isValidState()) { 6573 auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType(); 6574 if (!CBArgPrivTy) 6575 continue; 6576 if (CBArgPrivTy.value() == PrivatizableType) 6577 continue; 6578 } 6579 6580 LLVM_DEBUG({ 6581 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 6582 << " cannot be privatized in the context of its parent (" 6583 << Arg->getParent()->getName() 6584 << ")\n[AAPrivatizablePtr] because it is an argument in a " 6585 "callback (" 6586 << CBArgNo << "@" << CBACS.getCalledFunction()->getName() 6587 << ").\n[AAPrivatizablePtr] for which the argument " 6588 "privatization is not compatible.\n"; 6589 }); 6590 return false; 6591 } 6592 } 6593 return true; 6594 }; 6595 6596 // Helper to check if for the given call site the associated argument is 6597 // passed to a direct call where the privatization would be different. 6598 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) { 6599 CallBase *DC = cast<CallBase>(ACS.getInstruction()); 6600 int DCArgNo = ACS.getCallArgOperandNo(ArgNo); 6601 assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->arg_size() && 6602 "Expected a direct call operand for callback call operand"); 6603 6604 LLVM_DEBUG({ 6605 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 6606 << " check if be privatized in the context of its parent (" 6607 << Arg->getParent()->getName() 6608 << ")\n[AAPrivatizablePtr] because it is an argument in a " 6609 "direct call of (" 6610 << DCArgNo << "@" << DC->getCalledFunction()->getName() 6611 << ").\n"; 6612 }); 6613 6614 Function *DCCallee = DC->getCalledFunction(); 6615 if (unsigned(DCArgNo) < DCCallee->arg_size()) { 6616 const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>( 6617 *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)), 6618 DepClassTy::REQUIRED); 6619 if (DCArgPrivAA.isValidState()) { 6620 auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType(); 6621 if (!DCArgPrivTy) 6622 return true; 6623 if (DCArgPrivTy.value() == PrivatizableType) 6624 return true; 6625 } 6626 } 6627 6628 LLVM_DEBUG({ 6629 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 6630 << " cannot be privatized in the context of its parent (" 6631 << Arg->getParent()->getName() 6632 << ")\n[AAPrivatizablePtr] because it is an argument in a " 6633 "direct call of (" 6634 << ACS.getInstruction()->getCalledFunction()->getName() 6635 << ").\n[AAPrivatizablePtr] for which the argument " 6636 "privatization is not compatible.\n"; 6637 }); 6638 return false; 6639 }; 6640 6641 // Helper to check if the associated argument is used at the given abstract 6642 // call site in a way that is incompatible with the privatization assumed 6643 // here. 6644 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) { 6645 if (ACS.isDirectCall()) 6646 return IsCompatiblePrivArgOfCallback(*ACS.getInstruction()); 6647 if (ACS.isCallbackCall()) 6648 return IsCompatiblePrivArgOfDirectCS(ACS); 6649 return false; 6650 }; 6651 6652 if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true, 6653 UsedAssumedInformation)) 6654 return indicatePessimisticFixpoint(); 6655 6656 return ChangeStatus::UNCHANGED; 6657 } 6658 6659 /// Given a type to private \p PrivType, collect the constituates (which are 6660 /// used) in \p ReplacementTypes. 6661 static void 6662 identifyReplacementTypes(Type *PrivType, 6663 SmallVectorImpl<Type *> &ReplacementTypes) { 6664 // TODO: For now we expand the privatization type to the fullest which can 6665 // lead to dead arguments that need to be removed later. 6666 assert(PrivType && "Expected privatizable type!"); 6667 6668 // Traverse the type, extract constituate types on the outermost level. 6669 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 6670 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) 6671 ReplacementTypes.push_back(PrivStructType->getElementType(u)); 6672 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 6673 ReplacementTypes.append(PrivArrayType->getNumElements(), 6674 PrivArrayType->getElementType()); 6675 } else { 6676 ReplacementTypes.push_back(PrivType); 6677 } 6678 } 6679 6680 /// Initialize \p Base according to the type \p PrivType at position \p IP. 6681 /// The values needed are taken from the arguments of \p F starting at 6682 /// position \p ArgNo. 6683 static void createInitialization(Type *PrivType, Value &Base, Function &F, 6684 unsigned ArgNo, Instruction &IP) { 6685 assert(PrivType && "Expected privatizable type!"); 6686 6687 IRBuilder<NoFolder> IRB(&IP); 6688 const DataLayout &DL = F.getParent()->getDataLayout(); 6689 6690 // Traverse the type, build GEPs and stores. 6691 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 6692 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType); 6693 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) { 6694 Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo(); 6695 Value *Ptr = 6696 constructPointer(PointeeTy, PrivType, &Base, 6697 PrivStructLayout->getElementOffset(u), IRB, DL); 6698 new StoreInst(F.getArg(ArgNo + u), Ptr, &IP); 6699 } 6700 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 6701 Type *PointeeTy = PrivArrayType->getElementType(); 6702 Type *PointeePtrTy = PointeeTy->getPointerTo(); 6703 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy); 6704 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) { 6705 Value *Ptr = constructPointer(PointeePtrTy, PrivType, &Base, 6706 u * PointeeTySize, IRB, DL); 6707 new StoreInst(F.getArg(ArgNo + u), Ptr, &IP); 6708 } 6709 } else { 6710 new StoreInst(F.getArg(ArgNo), &Base, &IP); 6711 } 6712 } 6713 6714 /// Extract values from \p Base according to the type \p PrivType at the 6715 /// call position \p ACS. The values are appended to \p ReplacementValues. 6716 void createReplacementValues(Align Alignment, Type *PrivType, 6717 AbstractCallSite ACS, Value *Base, 6718 SmallVectorImpl<Value *> &ReplacementValues) { 6719 assert(Base && "Expected base value!"); 6720 assert(PrivType && "Expected privatizable type!"); 6721 Instruction *IP = ACS.getInstruction(); 6722 6723 IRBuilder<NoFolder> IRB(IP); 6724 const DataLayout &DL = IP->getModule()->getDataLayout(); 6725 6726 Type *PrivPtrType = PrivType->getPointerTo(); 6727 if (Base->getType() != PrivPtrType) 6728 Base = BitCastInst::CreatePointerBitCastOrAddrSpaceCast( 6729 Base, PrivPtrType, "", ACS.getInstruction()); 6730 6731 // Traverse the type, build GEPs and loads. 6732 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 6733 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType); 6734 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) { 6735 Type *PointeeTy = PrivStructType->getElementType(u); 6736 Value *Ptr = 6737 constructPointer(PointeeTy->getPointerTo(), PrivType, Base, 6738 PrivStructLayout->getElementOffset(u), IRB, DL); 6739 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP); 6740 L->setAlignment(Alignment); 6741 ReplacementValues.push_back(L); 6742 } 6743 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 6744 Type *PointeeTy = PrivArrayType->getElementType(); 6745 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy); 6746 Type *PointeePtrTy = PointeeTy->getPointerTo(); 6747 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) { 6748 Value *Ptr = constructPointer(PointeePtrTy, PrivType, Base, 6749 u * PointeeTySize, IRB, DL); 6750 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP); 6751 L->setAlignment(Alignment); 6752 ReplacementValues.push_back(L); 6753 } 6754 } else { 6755 LoadInst *L = new LoadInst(PrivType, Base, "", IP); 6756 L->setAlignment(Alignment); 6757 ReplacementValues.push_back(L); 6758 } 6759 } 6760 6761 /// See AbstractAttribute::manifest(...) 6762 ChangeStatus manifest(Attributor &A) override { 6763 if (!PrivatizableType) 6764 return ChangeStatus::UNCHANGED; 6765 assert(PrivatizableType.value() && "Expected privatizable type!"); 6766 6767 // Collect all tail calls in the function as we cannot allow new allocas to 6768 // escape into tail recursion. 6769 // TODO: Be smarter about new allocas escaping into tail calls. 6770 SmallVector<CallInst *, 16> TailCalls; 6771 bool UsedAssumedInformation = false; 6772 if (!A.checkForAllInstructions( 6773 [&](Instruction &I) { 6774 CallInst &CI = cast<CallInst>(I); 6775 if (CI.isTailCall()) 6776 TailCalls.push_back(&CI); 6777 return true; 6778 }, 6779 *this, {Instruction::Call}, UsedAssumedInformation)) 6780 return ChangeStatus::UNCHANGED; 6781 6782 Argument *Arg = getAssociatedArgument(); 6783 // Query AAAlign attribute for alignment of associated argument to 6784 // determine the best alignment of loads. 6785 const auto &AlignAA = 6786 A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE); 6787 6788 // Callback to repair the associated function. A new alloca is placed at the 6789 // beginning and initialized with the values passed through arguments. The 6790 // new alloca replaces the use of the old pointer argument. 6791 Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB = 6792 [=](const Attributor::ArgumentReplacementInfo &ARI, 6793 Function &ReplacementFn, Function::arg_iterator ArgIt) { 6794 BasicBlock &EntryBB = ReplacementFn.getEntryBlock(); 6795 Instruction *IP = &*EntryBB.getFirstInsertionPt(); 6796 const DataLayout &DL = IP->getModule()->getDataLayout(); 6797 unsigned AS = DL.getAllocaAddrSpace(); 6798 Instruction *AI = new AllocaInst(PrivatizableType.value(), AS, 6799 Arg->getName() + ".priv", IP); 6800 createInitialization(PrivatizableType.value(), *AI, ReplacementFn, 6801 ArgIt->getArgNo(), *IP); 6802 6803 if (AI->getType() != Arg->getType()) 6804 AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast( 6805 AI, Arg->getType(), "", IP); 6806 Arg->replaceAllUsesWith(AI); 6807 6808 for (CallInst *CI : TailCalls) 6809 CI->setTailCall(false); 6810 }; 6811 6812 // Callback to repair a call site of the associated function. The elements 6813 // of the privatizable type are loaded prior to the call and passed to the 6814 // new function version. 6815 Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB = 6816 [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI, 6817 AbstractCallSite ACS, 6818 SmallVectorImpl<Value *> &NewArgOperands) { 6819 // When no alignment is specified for the load instruction, 6820 // natural alignment is assumed. 6821 createReplacementValues( 6822 AlignAA.getAssumedAlign(), *PrivatizableType, ACS, 6823 ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()), 6824 NewArgOperands); 6825 }; 6826 6827 // Collect the types that will replace the privatizable type in the function 6828 // signature. 6829 SmallVector<Type *, 16> ReplacementTypes; 6830 identifyReplacementTypes(*PrivatizableType, ReplacementTypes); 6831 6832 // Register a rewrite of the argument. 6833 if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes, 6834 std::move(FnRepairCB), 6835 std::move(ACSRepairCB))) 6836 return ChangeStatus::CHANGED; 6837 return ChangeStatus::UNCHANGED; 6838 } 6839 6840 /// See AbstractAttribute::trackStatistics() 6841 void trackStatistics() const override { 6842 STATS_DECLTRACK_ARG_ATTR(privatizable_ptr); 6843 } 6844 }; 6845 6846 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl { 6847 AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A) 6848 : AAPrivatizablePtrImpl(IRP, A) {} 6849 6850 /// See AbstractAttribute::initialize(...). 6851 virtual void initialize(Attributor &A) override { 6852 // TODO: We can privatize more than arguments. 6853 indicatePessimisticFixpoint(); 6854 } 6855 6856 ChangeStatus updateImpl(Attributor &A) override { 6857 llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::" 6858 "updateImpl will not be called"); 6859 } 6860 6861 /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...) 6862 Optional<Type *> identifyPrivatizableType(Attributor &A) override { 6863 Value *Obj = getUnderlyingObject(&getAssociatedValue()); 6864 if (!Obj) { 6865 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n"); 6866 return nullptr; 6867 } 6868 6869 if (auto *AI = dyn_cast<AllocaInst>(Obj)) 6870 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) 6871 if (CI->isOne()) 6872 return AI->getAllocatedType(); 6873 if (auto *Arg = dyn_cast<Argument>(Obj)) { 6874 auto &PrivArgAA = A.getAAFor<AAPrivatizablePtr>( 6875 *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED); 6876 if (PrivArgAA.isAssumedPrivatizablePtr()) 6877 return PrivArgAA.getPrivatizableType(); 6878 } 6879 6880 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid " 6881 "alloca nor privatizable argument: " 6882 << *Obj << "!\n"); 6883 return nullptr; 6884 } 6885 6886 /// See AbstractAttribute::trackStatistics() 6887 void trackStatistics() const override { 6888 STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr); 6889 } 6890 }; 6891 6892 struct AAPrivatizablePtrCallSiteArgument final 6893 : public AAPrivatizablePtrFloating { 6894 AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A) 6895 : AAPrivatizablePtrFloating(IRP, A) {} 6896 6897 /// See AbstractAttribute::initialize(...). 6898 void initialize(Attributor &A) override { 6899 if (getIRPosition().hasAttr(Attribute::ByVal)) 6900 indicateOptimisticFixpoint(); 6901 } 6902 6903 /// See AbstractAttribute::updateImpl(...). 6904 ChangeStatus updateImpl(Attributor &A) override { 6905 PrivatizableType = identifyPrivatizableType(A); 6906 if (!PrivatizableType) 6907 return ChangeStatus::UNCHANGED; 6908 if (!PrivatizableType.value()) 6909 return indicatePessimisticFixpoint(); 6910 6911 const IRPosition &IRP = getIRPosition(); 6912 auto &NoCaptureAA = 6913 A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::REQUIRED); 6914 if (!NoCaptureAA.isAssumedNoCapture()) { 6915 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n"); 6916 return indicatePessimisticFixpoint(); 6917 } 6918 6919 auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP, DepClassTy::REQUIRED); 6920 if (!NoAliasAA.isAssumedNoAlias()) { 6921 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n"); 6922 return indicatePessimisticFixpoint(); 6923 } 6924 6925 bool IsKnown; 6926 if (!AA::isAssumedReadOnly(A, IRP, *this, IsKnown)) { 6927 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n"); 6928 return indicatePessimisticFixpoint(); 6929 } 6930 6931 return ChangeStatus::UNCHANGED; 6932 } 6933 6934 /// See AbstractAttribute::trackStatistics() 6935 void trackStatistics() const override { 6936 STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr); 6937 } 6938 }; 6939 6940 struct AAPrivatizablePtrCallSiteReturned final 6941 : public AAPrivatizablePtrFloating { 6942 AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A) 6943 : AAPrivatizablePtrFloating(IRP, A) {} 6944 6945 /// See AbstractAttribute::initialize(...). 6946 void initialize(Attributor &A) override { 6947 // TODO: We can privatize more than arguments. 6948 indicatePessimisticFixpoint(); 6949 } 6950 6951 /// See AbstractAttribute::trackStatistics() 6952 void trackStatistics() const override { 6953 STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr); 6954 } 6955 }; 6956 6957 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating { 6958 AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A) 6959 : AAPrivatizablePtrFloating(IRP, A) {} 6960 6961 /// See AbstractAttribute::initialize(...). 6962 void initialize(Attributor &A) override { 6963 // TODO: We can privatize more than arguments. 6964 indicatePessimisticFixpoint(); 6965 } 6966 6967 /// See AbstractAttribute::trackStatistics() 6968 void trackStatistics() const override { 6969 STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr); 6970 } 6971 }; 6972 } // namespace 6973 6974 /// -------------------- Memory Behavior Attributes ---------------------------- 6975 /// Includes read-none, read-only, and write-only. 6976 /// ---------------------------------------------------------------------------- 6977 namespace { 6978 struct AAMemoryBehaviorImpl : public AAMemoryBehavior { 6979 AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A) 6980 : AAMemoryBehavior(IRP, A) {} 6981 6982 /// See AbstractAttribute::initialize(...). 6983 void initialize(Attributor &A) override { 6984 intersectAssumedBits(BEST_STATE); 6985 getKnownStateFromValue(getIRPosition(), getState()); 6986 AAMemoryBehavior::initialize(A); 6987 } 6988 6989 /// Return the memory behavior information encoded in the IR for \p IRP. 6990 static void getKnownStateFromValue(const IRPosition &IRP, 6991 BitIntegerState &State, 6992 bool IgnoreSubsumingPositions = false) { 6993 SmallVector<Attribute, 2> Attrs; 6994 IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions); 6995 for (const Attribute &Attr : Attrs) { 6996 switch (Attr.getKindAsEnum()) { 6997 case Attribute::ReadNone: 6998 State.addKnownBits(NO_ACCESSES); 6999 break; 7000 case Attribute::ReadOnly: 7001 State.addKnownBits(NO_WRITES); 7002 break; 7003 case Attribute::WriteOnly: 7004 State.addKnownBits(NO_READS); 7005 break; 7006 default: 7007 llvm_unreachable("Unexpected attribute!"); 7008 } 7009 } 7010 7011 if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) { 7012 if (!I->mayReadFromMemory()) 7013 State.addKnownBits(NO_READS); 7014 if (!I->mayWriteToMemory()) 7015 State.addKnownBits(NO_WRITES); 7016 } 7017 } 7018 7019 /// See AbstractAttribute::getDeducedAttributes(...). 7020 void getDeducedAttributes(LLVMContext &Ctx, 7021 SmallVectorImpl<Attribute> &Attrs) const override { 7022 assert(Attrs.size() == 0); 7023 if (isAssumedReadNone()) 7024 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 7025 else if (isAssumedReadOnly()) 7026 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly)); 7027 else if (isAssumedWriteOnly()) 7028 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly)); 7029 assert(Attrs.size() <= 1); 7030 } 7031 7032 /// See AbstractAttribute::manifest(...). 7033 ChangeStatus manifest(Attributor &A) override { 7034 if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true)) 7035 return ChangeStatus::UNCHANGED; 7036 7037 const IRPosition &IRP = getIRPosition(); 7038 7039 // Check if we would improve the existing attributes first. 7040 SmallVector<Attribute, 4> DeducedAttrs; 7041 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 7042 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 7043 return IRP.hasAttr(Attr.getKindAsEnum(), 7044 /* IgnoreSubsumingPositions */ true); 7045 })) 7046 return ChangeStatus::UNCHANGED; 7047 7048 // Clear existing attributes. 7049 IRP.removeAttrs(AttrKinds); 7050 7051 // Use the generic manifest method. 7052 return IRAttribute::manifest(A); 7053 } 7054 7055 /// See AbstractState::getAsStr(). 7056 const std::string getAsStr() const override { 7057 if (isAssumedReadNone()) 7058 return "readnone"; 7059 if (isAssumedReadOnly()) 7060 return "readonly"; 7061 if (isAssumedWriteOnly()) 7062 return "writeonly"; 7063 return "may-read/write"; 7064 } 7065 7066 /// The set of IR attributes AAMemoryBehavior deals with. 7067 static const Attribute::AttrKind AttrKinds[3]; 7068 }; 7069 7070 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = { 7071 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly}; 7072 7073 /// Memory behavior attribute for a floating value. 7074 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl { 7075 AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A) 7076 : AAMemoryBehaviorImpl(IRP, A) {} 7077 7078 /// See AbstractAttribute::updateImpl(...). 7079 ChangeStatus updateImpl(Attributor &A) override; 7080 7081 /// See AbstractAttribute::trackStatistics() 7082 void trackStatistics() const override { 7083 if (isAssumedReadNone()) 7084 STATS_DECLTRACK_FLOATING_ATTR(readnone) 7085 else if (isAssumedReadOnly()) 7086 STATS_DECLTRACK_FLOATING_ATTR(readonly) 7087 else if (isAssumedWriteOnly()) 7088 STATS_DECLTRACK_FLOATING_ATTR(writeonly) 7089 } 7090 7091 private: 7092 /// Return true if users of \p UserI might access the underlying 7093 /// variable/location described by \p U and should therefore be analyzed. 7094 bool followUsersOfUseIn(Attributor &A, const Use &U, 7095 const Instruction *UserI); 7096 7097 /// Update the state according to the effect of use \p U in \p UserI. 7098 void analyzeUseIn(Attributor &A, const Use &U, const Instruction *UserI); 7099 }; 7100 7101 /// Memory behavior attribute for function argument. 7102 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating { 7103 AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A) 7104 : AAMemoryBehaviorFloating(IRP, A) {} 7105 7106 /// See AbstractAttribute::initialize(...). 7107 void initialize(Attributor &A) override { 7108 intersectAssumedBits(BEST_STATE); 7109 const IRPosition &IRP = getIRPosition(); 7110 // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we 7111 // can query it when we use has/getAttr. That would allow us to reuse the 7112 // initialize of the base class here. 7113 bool HasByVal = 7114 IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true); 7115 getKnownStateFromValue(IRP, getState(), 7116 /* IgnoreSubsumingPositions */ HasByVal); 7117 7118 // Initialize the use vector with all direct uses of the associated value. 7119 Argument *Arg = getAssociatedArgument(); 7120 if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) 7121 indicatePessimisticFixpoint(); 7122 } 7123 7124 ChangeStatus manifest(Attributor &A) override { 7125 // TODO: Pointer arguments are not supported on vectors of pointers yet. 7126 if (!getAssociatedValue().getType()->isPointerTy()) 7127 return ChangeStatus::UNCHANGED; 7128 7129 // TODO: From readattrs.ll: "inalloca parameters are always 7130 // considered written" 7131 if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) { 7132 removeKnownBits(NO_WRITES); 7133 removeAssumedBits(NO_WRITES); 7134 } 7135 return AAMemoryBehaviorFloating::manifest(A); 7136 } 7137 7138 /// See AbstractAttribute::trackStatistics() 7139 void trackStatistics() const override { 7140 if (isAssumedReadNone()) 7141 STATS_DECLTRACK_ARG_ATTR(readnone) 7142 else if (isAssumedReadOnly()) 7143 STATS_DECLTRACK_ARG_ATTR(readonly) 7144 else if (isAssumedWriteOnly()) 7145 STATS_DECLTRACK_ARG_ATTR(writeonly) 7146 } 7147 }; 7148 7149 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument { 7150 AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A) 7151 : AAMemoryBehaviorArgument(IRP, A) {} 7152 7153 /// See AbstractAttribute::initialize(...). 7154 void initialize(Attributor &A) override { 7155 // If we don't have an associated attribute this is either a variadic call 7156 // or an indirect call, either way, nothing to do here. 7157 Argument *Arg = getAssociatedArgument(); 7158 if (!Arg) { 7159 indicatePessimisticFixpoint(); 7160 return; 7161 } 7162 if (Arg->hasByValAttr()) { 7163 addKnownBits(NO_WRITES); 7164 removeKnownBits(NO_READS); 7165 removeAssumedBits(NO_READS); 7166 } 7167 AAMemoryBehaviorArgument::initialize(A); 7168 if (getAssociatedFunction()->isDeclaration()) 7169 indicatePessimisticFixpoint(); 7170 } 7171 7172 /// See AbstractAttribute::updateImpl(...). 7173 ChangeStatus updateImpl(Attributor &A) override { 7174 // TODO: Once we have call site specific value information we can provide 7175 // call site specific liveness liveness information and then it makes 7176 // sense to specialize attributes for call sites arguments instead of 7177 // redirecting requests to the callee argument. 7178 Argument *Arg = getAssociatedArgument(); 7179 const IRPosition &ArgPos = IRPosition::argument(*Arg); 7180 auto &ArgAA = 7181 A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED); 7182 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 7183 } 7184 7185 /// See AbstractAttribute::trackStatistics() 7186 void trackStatistics() const override { 7187 if (isAssumedReadNone()) 7188 STATS_DECLTRACK_CSARG_ATTR(readnone) 7189 else if (isAssumedReadOnly()) 7190 STATS_DECLTRACK_CSARG_ATTR(readonly) 7191 else if (isAssumedWriteOnly()) 7192 STATS_DECLTRACK_CSARG_ATTR(writeonly) 7193 } 7194 }; 7195 7196 /// Memory behavior attribute for a call site return position. 7197 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating { 7198 AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A) 7199 : AAMemoryBehaviorFloating(IRP, A) {} 7200 7201 /// See AbstractAttribute::initialize(...). 7202 void initialize(Attributor &A) override { 7203 AAMemoryBehaviorImpl::initialize(A); 7204 Function *F = getAssociatedFunction(); 7205 if (!F || F->isDeclaration()) 7206 indicatePessimisticFixpoint(); 7207 } 7208 7209 /// See AbstractAttribute::manifest(...). 7210 ChangeStatus manifest(Attributor &A) override { 7211 // We do not annotate returned values. 7212 return ChangeStatus::UNCHANGED; 7213 } 7214 7215 /// See AbstractAttribute::trackStatistics() 7216 void trackStatistics() const override {} 7217 }; 7218 7219 /// An AA to represent the memory behavior function attributes. 7220 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl { 7221 AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A) 7222 : AAMemoryBehaviorImpl(IRP, A) {} 7223 7224 /// See AbstractAttribute::updateImpl(Attributor &A). 7225 virtual ChangeStatus updateImpl(Attributor &A) override; 7226 7227 /// See AbstractAttribute::manifest(...). 7228 ChangeStatus manifest(Attributor &A) override { 7229 Function &F = cast<Function>(getAnchorValue()); 7230 if (isAssumedReadNone()) { 7231 F.removeFnAttr(Attribute::ArgMemOnly); 7232 F.removeFnAttr(Attribute::InaccessibleMemOnly); 7233 F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly); 7234 } 7235 return AAMemoryBehaviorImpl::manifest(A); 7236 } 7237 7238 /// See AbstractAttribute::trackStatistics() 7239 void trackStatistics() const override { 7240 if (isAssumedReadNone()) 7241 STATS_DECLTRACK_FN_ATTR(readnone) 7242 else if (isAssumedReadOnly()) 7243 STATS_DECLTRACK_FN_ATTR(readonly) 7244 else if (isAssumedWriteOnly()) 7245 STATS_DECLTRACK_FN_ATTR(writeonly) 7246 } 7247 }; 7248 7249 /// AAMemoryBehavior attribute for call sites. 7250 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl { 7251 AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A) 7252 : AAMemoryBehaviorImpl(IRP, A) {} 7253 7254 /// See AbstractAttribute::initialize(...). 7255 void initialize(Attributor &A) override { 7256 AAMemoryBehaviorImpl::initialize(A); 7257 Function *F = getAssociatedFunction(); 7258 if (!F || F->isDeclaration()) 7259 indicatePessimisticFixpoint(); 7260 } 7261 7262 /// See AbstractAttribute::updateImpl(...). 7263 ChangeStatus updateImpl(Attributor &A) override { 7264 // TODO: Once we have call site specific value information we can provide 7265 // call site specific liveness liveness information and then it makes 7266 // sense to specialize attributes for call sites arguments instead of 7267 // redirecting requests to the callee argument. 7268 Function *F = getAssociatedFunction(); 7269 const IRPosition &FnPos = IRPosition::function(*F); 7270 auto &FnAA = 7271 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::REQUIRED); 7272 return clampStateAndIndicateChange(getState(), FnAA.getState()); 7273 } 7274 7275 /// See AbstractAttribute::trackStatistics() 7276 void trackStatistics() const override { 7277 if (isAssumedReadNone()) 7278 STATS_DECLTRACK_CS_ATTR(readnone) 7279 else if (isAssumedReadOnly()) 7280 STATS_DECLTRACK_CS_ATTR(readonly) 7281 else if (isAssumedWriteOnly()) 7282 STATS_DECLTRACK_CS_ATTR(writeonly) 7283 } 7284 }; 7285 7286 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) { 7287 7288 // The current assumed state used to determine a change. 7289 auto AssumedState = getAssumed(); 7290 7291 auto CheckRWInst = [&](Instruction &I) { 7292 // If the instruction has an own memory behavior state, use it to restrict 7293 // the local state. No further analysis is required as the other memory 7294 // state is as optimistic as it gets. 7295 if (const auto *CB = dyn_cast<CallBase>(&I)) { 7296 const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 7297 *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED); 7298 intersectAssumedBits(MemBehaviorAA.getAssumed()); 7299 return !isAtFixpoint(); 7300 } 7301 7302 // Remove access kind modifiers if necessary. 7303 if (I.mayReadFromMemory()) 7304 removeAssumedBits(NO_READS); 7305 if (I.mayWriteToMemory()) 7306 removeAssumedBits(NO_WRITES); 7307 return !isAtFixpoint(); 7308 }; 7309 7310 bool UsedAssumedInformation = false; 7311 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this, 7312 UsedAssumedInformation)) 7313 return indicatePessimisticFixpoint(); 7314 7315 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 7316 : ChangeStatus::UNCHANGED; 7317 } 7318 7319 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) { 7320 7321 const IRPosition &IRP = getIRPosition(); 7322 const IRPosition &FnPos = IRPosition::function_scope(IRP); 7323 AAMemoryBehavior::StateType &S = getState(); 7324 7325 // First, check the function scope. We take the known information and we avoid 7326 // work if the assumed information implies the current assumed information for 7327 // this attribute. This is a valid for all but byval arguments. 7328 Argument *Arg = IRP.getAssociatedArgument(); 7329 AAMemoryBehavior::base_t FnMemAssumedState = 7330 AAMemoryBehavior::StateType::getWorstState(); 7331 if (!Arg || !Arg->hasByValAttr()) { 7332 const auto &FnMemAA = 7333 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL); 7334 FnMemAssumedState = FnMemAA.getAssumed(); 7335 S.addKnownBits(FnMemAA.getKnown()); 7336 if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed()) 7337 return ChangeStatus::UNCHANGED; 7338 } 7339 7340 // The current assumed state used to determine a change. 7341 auto AssumedState = S.getAssumed(); 7342 7343 // Make sure the value is not captured (except through "return"), if 7344 // it is, any information derived would be irrelevant anyway as we cannot 7345 // check the potential aliases introduced by the capture. However, no need 7346 // to fall back to anythign less optimistic than the function state. 7347 const auto &ArgNoCaptureAA = 7348 A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::OPTIONAL); 7349 if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 7350 S.intersectAssumedBits(FnMemAssumedState); 7351 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 7352 : ChangeStatus::UNCHANGED; 7353 } 7354 7355 // Visit and expand uses until all are analyzed or a fixpoint is reached. 7356 auto UsePred = [&](const Use &U, bool &Follow) -> bool { 7357 Instruction *UserI = cast<Instruction>(U.getUser()); 7358 LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << *U << " in " << *UserI 7359 << " \n"); 7360 7361 // Droppable users, e.g., llvm::assume does not actually perform any action. 7362 if (UserI->isDroppable()) 7363 return true; 7364 7365 // Check if the users of UserI should also be visited. 7366 Follow = followUsersOfUseIn(A, U, UserI); 7367 7368 // If UserI might touch memory we analyze the use in detail. 7369 if (UserI->mayReadOrWriteMemory()) 7370 analyzeUseIn(A, U, UserI); 7371 7372 return !isAtFixpoint(); 7373 }; 7374 7375 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) 7376 return indicatePessimisticFixpoint(); 7377 7378 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 7379 : ChangeStatus::UNCHANGED; 7380 } 7381 7382 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use &U, 7383 const Instruction *UserI) { 7384 // The loaded value is unrelated to the pointer argument, no need to 7385 // follow the users of the load. 7386 if (isa<LoadInst>(UserI) || isa<ReturnInst>(UserI)) 7387 return false; 7388 7389 // By default we follow all uses assuming UserI might leak information on U, 7390 // we have special handling for call sites operands though. 7391 const auto *CB = dyn_cast<CallBase>(UserI); 7392 if (!CB || !CB->isArgOperand(&U)) 7393 return true; 7394 7395 // If the use is a call argument known not to be captured, the users of 7396 // the call do not need to be visited because they have to be unrelated to 7397 // the input. Note that this check is not trivial even though we disallow 7398 // general capturing of the underlying argument. The reason is that the 7399 // call might the argument "through return", which we allow and for which we 7400 // need to check call users. 7401 if (U.get()->getType()->isPointerTy()) { 7402 unsigned ArgNo = CB->getArgOperandNo(&U); 7403 const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>( 7404 *this, IRPosition::callsite_argument(*CB, ArgNo), DepClassTy::OPTIONAL); 7405 return !ArgNoCaptureAA.isAssumedNoCapture(); 7406 } 7407 7408 return true; 7409 } 7410 7411 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use &U, 7412 const Instruction *UserI) { 7413 assert(UserI->mayReadOrWriteMemory()); 7414 7415 switch (UserI->getOpcode()) { 7416 default: 7417 // TODO: Handle all atomics and other side-effect operations we know of. 7418 break; 7419 case Instruction::Load: 7420 // Loads cause the NO_READS property to disappear. 7421 removeAssumedBits(NO_READS); 7422 return; 7423 7424 case Instruction::Store: 7425 // Stores cause the NO_WRITES property to disappear if the use is the 7426 // pointer operand. Note that while capturing was taken care of somewhere 7427 // else we need to deal with stores of the value that is not looked through. 7428 if (cast<StoreInst>(UserI)->getPointerOperand() == U.get()) 7429 removeAssumedBits(NO_WRITES); 7430 else 7431 indicatePessimisticFixpoint(); 7432 return; 7433 7434 case Instruction::Call: 7435 case Instruction::CallBr: 7436 case Instruction::Invoke: { 7437 // For call sites we look at the argument memory behavior attribute (this 7438 // could be recursive!) in order to restrict our own state. 7439 const auto *CB = cast<CallBase>(UserI); 7440 7441 // Give up on operand bundles. 7442 if (CB->isBundleOperand(&U)) { 7443 indicatePessimisticFixpoint(); 7444 return; 7445 } 7446 7447 // Calling a function does read the function pointer, maybe write it if the 7448 // function is self-modifying. 7449 if (CB->isCallee(&U)) { 7450 removeAssumedBits(NO_READS); 7451 break; 7452 } 7453 7454 // Adjust the possible access behavior based on the information on the 7455 // argument. 7456 IRPosition Pos; 7457 if (U.get()->getType()->isPointerTy()) 7458 Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 7459 else 7460 Pos = IRPosition::callsite_function(*CB); 7461 const auto &MemBehaviorAA = 7462 A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL); 7463 // "assumed" has at most the same bits as the MemBehaviorAA assumed 7464 // and at least "known". 7465 intersectAssumedBits(MemBehaviorAA.getAssumed()); 7466 return; 7467 } 7468 }; 7469 7470 // Generally, look at the "may-properties" and adjust the assumed state if we 7471 // did not trigger special handling before. 7472 if (UserI->mayReadFromMemory()) 7473 removeAssumedBits(NO_READS); 7474 if (UserI->mayWriteToMemory()) 7475 removeAssumedBits(NO_WRITES); 7476 } 7477 } // namespace 7478 7479 /// -------------------- Memory Locations Attributes --------------------------- 7480 /// Includes read-none, argmemonly, inaccessiblememonly, 7481 /// inaccessiblememorargmemonly 7482 /// ---------------------------------------------------------------------------- 7483 7484 std::string AAMemoryLocation::getMemoryLocationsAsStr( 7485 AAMemoryLocation::MemoryLocationsKind MLK) { 7486 if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS)) 7487 return "all memory"; 7488 if (MLK == AAMemoryLocation::NO_LOCATIONS) 7489 return "no memory"; 7490 std::string S = "memory:"; 7491 if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM)) 7492 S += "stack,"; 7493 if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM)) 7494 S += "constant,"; 7495 if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM)) 7496 S += "internal global,"; 7497 if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM)) 7498 S += "external global,"; 7499 if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM)) 7500 S += "argument,"; 7501 if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM)) 7502 S += "inaccessible,"; 7503 if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM)) 7504 S += "malloced,"; 7505 if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM)) 7506 S += "unknown,"; 7507 S.pop_back(); 7508 return S; 7509 } 7510 7511 namespace { 7512 struct AAMemoryLocationImpl : public AAMemoryLocation { 7513 7514 AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A) 7515 : AAMemoryLocation(IRP, A), Allocator(A.Allocator) { 7516 for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u) 7517 AccessKind2Accesses[u] = nullptr; 7518 } 7519 7520 ~AAMemoryLocationImpl() { 7521 // The AccessSets are allocated via a BumpPtrAllocator, we call 7522 // the destructor manually. 7523 for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u) 7524 if (AccessKind2Accesses[u]) 7525 AccessKind2Accesses[u]->~AccessSet(); 7526 } 7527 7528 /// See AbstractAttribute::initialize(...). 7529 void initialize(Attributor &A) override { 7530 intersectAssumedBits(BEST_STATE); 7531 getKnownStateFromValue(A, getIRPosition(), getState()); 7532 AAMemoryLocation::initialize(A); 7533 } 7534 7535 /// Return the memory behavior information encoded in the IR for \p IRP. 7536 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP, 7537 BitIntegerState &State, 7538 bool IgnoreSubsumingPositions = false) { 7539 // For internal functions we ignore `argmemonly` and 7540 // `inaccessiblememorargmemonly` as we might break it via interprocedural 7541 // constant propagation. It is unclear if this is the best way but it is 7542 // unlikely this will cause real performance problems. If we are deriving 7543 // attributes for the anchor function we even remove the attribute in 7544 // addition to ignoring it. 7545 bool UseArgMemOnly = true; 7546 Function *AnchorFn = IRP.getAnchorScope(); 7547 if (AnchorFn && A.isRunOn(*AnchorFn)) 7548 UseArgMemOnly = !AnchorFn->hasLocalLinkage(); 7549 7550 SmallVector<Attribute, 2> Attrs; 7551 IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions); 7552 for (const Attribute &Attr : Attrs) { 7553 switch (Attr.getKindAsEnum()) { 7554 case Attribute::ReadNone: 7555 State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM); 7556 break; 7557 case Attribute::InaccessibleMemOnly: 7558 State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true)); 7559 break; 7560 case Attribute::ArgMemOnly: 7561 if (UseArgMemOnly) 7562 State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true)); 7563 else 7564 IRP.removeAttrs({Attribute::ArgMemOnly}); 7565 break; 7566 case Attribute::InaccessibleMemOrArgMemOnly: 7567 if (UseArgMemOnly) 7568 State.addKnownBits(inverseLocation( 7569 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true)); 7570 else 7571 IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly}); 7572 break; 7573 default: 7574 llvm_unreachable("Unexpected attribute!"); 7575 } 7576 } 7577 } 7578 7579 /// See AbstractAttribute::getDeducedAttributes(...). 7580 void getDeducedAttributes(LLVMContext &Ctx, 7581 SmallVectorImpl<Attribute> &Attrs) const override { 7582 assert(Attrs.size() == 0); 7583 if (isAssumedReadNone()) { 7584 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 7585 } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) { 7586 if (isAssumedInaccessibleMemOnly()) 7587 Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly)); 7588 else if (isAssumedArgMemOnly()) 7589 Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly)); 7590 else if (isAssumedInaccessibleOrArgMemOnly()) 7591 Attrs.push_back( 7592 Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly)); 7593 } 7594 assert(Attrs.size() <= 1); 7595 } 7596 7597 /// See AbstractAttribute::manifest(...). 7598 ChangeStatus manifest(Attributor &A) override { 7599 const IRPosition &IRP = getIRPosition(); 7600 7601 // Check if we would improve the existing attributes first. 7602 SmallVector<Attribute, 4> DeducedAttrs; 7603 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 7604 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 7605 return IRP.hasAttr(Attr.getKindAsEnum(), 7606 /* IgnoreSubsumingPositions */ true); 7607 })) 7608 return ChangeStatus::UNCHANGED; 7609 7610 // Clear existing attributes. 7611 IRP.removeAttrs(AttrKinds); 7612 if (isAssumedReadNone()) 7613 IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds); 7614 7615 // Use the generic manifest method. 7616 return IRAttribute::manifest(A); 7617 } 7618 7619 /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...). 7620 bool checkForAllAccessesToMemoryKind( 7621 function_ref<bool(const Instruction *, const Value *, AccessKind, 7622 MemoryLocationsKind)> 7623 Pred, 7624 MemoryLocationsKind RequestedMLK) const override { 7625 if (!isValidState()) 7626 return false; 7627 7628 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation(); 7629 if (AssumedMLK == NO_LOCATIONS) 7630 return true; 7631 7632 unsigned Idx = 0; 7633 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; 7634 CurMLK *= 2, ++Idx) { 7635 if (CurMLK & RequestedMLK) 7636 continue; 7637 7638 if (const AccessSet *Accesses = AccessKind2Accesses[Idx]) 7639 for (const AccessInfo &AI : *Accesses) 7640 if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK)) 7641 return false; 7642 } 7643 7644 return true; 7645 } 7646 7647 ChangeStatus indicatePessimisticFixpoint() override { 7648 // If we give up and indicate a pessimistic fixpoint this instruction will 7649 // become an access for all potential access kinds: 7650 // TODO: Add pointers for argmemonly and globals to improve the results of 7651 // checkForAllAccessesToMemoryKind. 7652 bool Changed = false; 7653 MemoryLocationsKind KnownMLK = getKnown(); 7654 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 7655 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) 7656 if (!(CurMLK & KnownMLK)) 7657 updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed, 7658 getAccessKindFromInst(I)); 7659 return AAMemoryLocation::indicatePessimisticFixpoint(); 7660 } 7661 7662 protected: 7663 /// Helper struct to tie together an instruction that has a read or write 7664 /// effect with the pointer it accesses (if any). 7665 struct AccessInfo { 7666 7667 /// The instruction that caused the access. 7668 const Instruction *I; 7669 7670 /// The base pointer that is accessed, or null if unknown. 7671 const Value *Ptr; 7672 7673 /// The kind of access (read/write/read+write). 7674 AccessKind Kind; 7675 7676 bool operator==(const AccessInfo &RHS) const { 7677 return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind; 7678 } 7679 bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const { 7680 if (LHS.I != RHS.I) 7681 return LHS.I < RHS.I; 7682 if (LHS.Ptr != RHS.Ptr) 7683 return LHS.Ptr < RHS.Ptr; 7684 if (LHS.Kind != RHS.Kind) 7685 return LHS.Kind < RHS.Kind; 7686 return false; 7687 } 7688 }; 7689 7690 /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the 7691 /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind. 7692 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>; 7693 AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()]; 7694 7695 /// Categorize the pointer arguments of CB that might access memory in 7696 /// AccessedLoc and update the state and access map accordingly. 7697 void 7698 categorizeArgumentPointerLocations(Attributor &A, CallBase &CB, 7699 AAMemoryLocation::StateType &AccessedLocs, 7700 bool &Changed); 7701 7702 /// Return the kind(s) of location that may be accessed by \p V. 7703 AAMemoryLocation::MemoryLocationsKind 7704 categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed); 7705 7706 /// Return the access kind as determined by \p I. 7707 AccessKind getAccessKindFromInst(const Instruction *I) { 7708 AccessKind AK = READ_WRITE; 7709 if (I) { 7710 AK = I->mayReadFromMemory() ? READ : NONE; 7711 AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE)); 7712 } 7713 return AK; 7714 } 7715 7716 /// Update the state \p State and the AccessKind2Accesses given that \p I is 7717 /// an access of kind \p AK to a \p MLK memory location with the access 7718 /// pointer \p Ptr. 7719 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State, 7720 MemoryLocationsKind MLK, const Instruction *I, 7721 const Value *Ptr, bool &Changed, 7722 AccessKind AK = READ_WRITE) { 7723 7724 assert(isPowerOf2_32(MLK) && "Expected a single location set!"); 7725 auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)]; 7726 if (!Accesses) 7727 Accesses = new (Allocator) AccessSet(); 7728 Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second; 7729 State.removeAssumedBits(MLK); 7730 } 7731 7732 /// Determine the underlying locations kinds for \p Ptr, e.g., globals or 7733 /// arguments, and update the state and access map accordingly. 7734 void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr, 7735 AAMemoryLocation::StateType &State, bool &Changed); 7736 7737 /// Used to allocate access sets. 7738 BumpPtrAllocator &Allocator; 7739 7740 /// The set of IR attributes AAMemoryLocation deals with. 7741 static const Attribute::AttrKind AttrKinds[4]; 7742 }; 7743 7744 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = { 7745 Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly, 7746 Attribute::InaccessibleMemOrArgMemOnly}; 7747 7748 void AAMemoryLocationImpl::categorizePtrValue( 7749 Attributor &A, const Instruction &I, const Value &Ptr, 7750 AAMemoryLocation::StateType &State, bool &Changed) { 7751 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for " 7752 << Ptr << " [" 7753 << getMemoryLocationsAsStr(State.getAssumed()) << "]\n"); 7754 7755 SmallSetVector<Value *, 8> Objects; 7756 bool UsedAssumedInformation = false; 7757 if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, *this, &I, 7758 UsedAssumedInformation, 7759 AA::Intraprocedural)) { 7760 LLVM_DEBUG( 7761 dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n"); 7762 updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed, 7763 getAccessKindFromInst(&I)); 7764 return; 7765 } 7766 7767 for (Value *Obj : Objects) { 7768 // TODO: recognize the TBAA used for constant accesses. 7769 MemoryLocationsKind MLK = NO_LOCATIONS; 7770 if (isa<UndefValue>(Obj)) 7771 continue; 7772 if (isa<Argument>(Obj)) { 7773 // TODO: For now we do not treat byval arguments as local copies performed 7774 // on the call edge, though, we should. To make that happen we need to 7775 // teach various passes, e.g., DSE, about the copy effect of a byval. That 7776 // would also allow us to mark functions only accessing byval arguments as 7777 // readnone again, atguably their acceses have no effect outside of the 7778 // function, like accesses to allocas. 7779 MLK = NO_ARGUMENT_MEM; 7780 } else if (auto *GV = dyn_cast<GlobalValue>(Obj)) { 7781 // Reading constant memory is not treated as a read "effect" by the 7782 // function attr pass so we won't neither. Constants defined by TBAA are 7783 // similar. (We know we do not write it because it is constant.) 7784 if (auto *GVar = dyn_cast<GlobalVariable>(GV)) 7785 if (GVar->isConstant()) 7786 continue; 7787 7788 if (GV->hasLocalLinkage()) 7789 MLK = NO_GLOBAL_INTERNAL_MEM; 7790 else 7791 MLK = NO_GLOBAL_EXTERNAL_MEM; 7792 } else if (isa<ConstantPointerNull>(Obj) && 7793 !NullPointerIsDefined(getAssociatedFunction(), 7794 Ptr.getType()->getPointerAddressSpace())) { 7795 continue; 7796 } else if (isa<AllocaInst>(Obj)) { 7797 MLK = NO_LOCAL_MEM; 7798 } else if (const auto *CB = dyn_cast<CallBase>(Obj)) { 7799 const auto &NoAliasAA = A.getAAFor<AANoAlias>( 7800 *this, IRPosition::callsite_returned(*CB), DepClassTy::OPTIONAL); 7801 if (NoAliasAA.isAssumedNoAlias()) 7802 MLK = NO_MALLOCED_MEM; 7803 else 7804 MLK = NO_UNKOWN_MEM; 7805 } else { 7806 MLK = NO_UNKOWN_MEM; 7807 } 7808 7809 assert(MLK != NO_LOCATIONS && "No location specified!"); 7810 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: " 7811 << *Obj << " -> " << getMemoryLocationsAsStr(MLK) 7812 << "\n"); 7813 updateStateAndAccessesMap(getState(), MLK, &I, Obj, Changed, 7814 getAccessKindFromInst(&I)); 7815 } 7816 7817 LLVM_DEBUG( 7818 dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: " 7819 << getMemoryLocationsAsStr(State.getAssumed()) << "\n"); 7820 } 7821 7822 void AAMemoryLocationImpl::categorizeArgumentPointerLocations( 7823 Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs, 7824 bool &Changed) { 7825 for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) { 7826 7827 // Skip non-pointer arguments. 7828 const Value *ArgOp = CB.getArgOperand(ArgNo); 7829 if (!ArgOp->getType()->isPtrOrPtrVectorTy()) 7830 continue; 7831 7832 // Skip readnone arguments. 7833 const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo); 7834 const auto &ArgOpMemLocationAA = 7835 A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL); 7836 7837 if (ArgOpMemLocationAA.isAssumedReadNone()) 7838 continue; 7839 7840 // Categorize potentially accessed pointer arguments as if there was an 7841 // access instruction with them as pointer. 7842 categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed); 7843 } 7844 } 7845 7846 AAMemoryLocation::MemoryLocationsKind 7847 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I, 7848 bool &Changed) { 7849 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for " 7850 << I << "\n"); 7851 7852 AAMemoryLocation::StateType AccessedLocs; 7853 AccessedLocs.intersectAssumedBits(NO_LOCATIONS); 7854 7855 if (auto *CB = dyn_cast<CallBase>(&I)) { 7856 7857 // First check if we assume any memory is access is visible. 7858 const auto &CBMemLocationAA = A.getAAFor<AAMemoryLocation>( 7859 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL); 7860 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I 7861 << " [" << CBMemLocationAA << "]\n"); 7862 7863 if (CBMemLocationAA.isAssumedReadNone()) 7864 return NO_LOCATIONS; 7865 7866 if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) { 7867 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr, 7868 Changed, getAccessKindFromInst(&I)); 7869 return AccessedLocs.getAssumed(); 7870 } 7871 7872 uint32_t CBAssumedNotAccessedLocs = 7873 CBMemLocationAA.getAssumedNotAccessedLocation(); 7874 7875 // Set the argmemonly and global bit as we handle them separately below. 7876 uint32_t CBAssumedNotAccessedLocsNoArgMem = 7877 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM; 7878 7879 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) { 7880 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK) 7881 continue; 7882 updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed, 7883 getAccessKindFromInst(&I)); 7884 } 7885 7886 // Now handle global memory if it might be accessed. This is slightly tricky 7887 // as NO_GLOBAL_MEM has multiple bits set. 7888 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM); 7889 if (HasGlobalAccesses) { 7890 auto AccessPred = [&](const Instruction *, const Value *Ptr, 7891 AccessKind Kind, MemoryLocationsKind MLK) { 7892 updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed, 7893 getAccessKindFromInst(&I)); 7894 return true; 7895 }; 7896 if (!CBMemLocationAA.checkForAllAccessesToMemoryKind( 7897 AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false))) 7898 return AccessedLocs.getWorstState(); 7899 } 7900 7901 LLVM_DEBUG( 7902 dbgs() << "[AAMemoryLocation] Accessed state before argument handling: " 7903 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 7904 7905 // Now handle argument memory if it might be accessed. 7906 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM); 7907 if (HasArgAccesses) 7908 categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed); 7909 7910 LLVM_DEBUG( 7911 dbgs() << "[AAMemoryLocation] Accessed state after argument handling: " 7912 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 7913 7914 return AccessedLocs.getAssumed(); 7915 } 7916 7917 if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) { 7918 LLVM_DEBUG( 7919 dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: " 7920 << I << " [" << *Ptr << "]\n"); 7921 categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed); 7922 return AccessedLocs.getAssumed(); 7923 } 7924 7925 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: " 7926 << I << "\n"); 7927 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed, 7928 getAccessKindFromInst(&I)); 7929 return AccessedLocs.getAssumed(); 7930 } 7931 7932 /// An AA to represent the memory behavior function attributes. 7933 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl { 7934 AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A) 7935 : AAMemoryLocationImpl(IRP, A) {} 7936 7937 /// See AbstractAttribute::updateImpl(Attributor &A). 7938 virtual ChangeStatus updateImpl(Attributor &A) override { 7939 7940 const auto &MemBehaviorAA = 7941 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 7942 if (MemBehaviorAA.isAssumedReadNone()) { 7943 if (MemBehaviorAA.isKnownReadNone()) 7944 return indicateOptimisticFixpoint(); 7945 assert(isAssumedReadNone() && 7946 "AAMemoryLocation was not read-none but AAMemoryBehavior was!"); 7947 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 7948 return ChangeStatus::UNCHANGED; 7949 } 7950 7951 // The current assumed state used to determine a change. 7952 auto AssumedState = getAssumed(); 7953 bool Changed = false; 7954 7955 auto CheckRWInst = [&](Instruction &I) { 7956 MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed); 7957 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I 7958 << ": " << getMemoryLocationsAsStr(MLK) << "\n"); 7959 removeAssumedBits(inverseLocation(MLK, false, false)); 7960 // Stop once only the valid bit set in the *not assumed location*, thus 7961 // once we don't actually exclude any memory locations in the state. 7962 return getAssumedNotAccessedLocation() != VALID_STATE; 7963 }; 7964 7965 bool UsedAssumedInformation = false; 7966 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this, 7967 UsedAssumedInformation)) 7968 return indicatePessimisticFixpoint(); 7969 7970 Changed |= AssumedState != getAssumed(); 7971 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 7972 } 7973 7974 /// See AbstractAttribute::trackStatistics() 7975 void trackStatistics() const override { 7976 if (isAssumedReadNone()) 7977 STATS_DECLTRACK_FN_ATTR(readnone) 7978 else if (isAssumedArgMemOnly()) 7979 STATS_DECLTRACK_FN_ATTR(argmemonly) 7980 else if (isAssumedInaccessibleMemOnly()) 7981 STATS_DECLTRACK_FN_ATTR(inaccessiblememonly) 7982 else if (isAssumedInaccessibleOrArgMemOnly()) 7983 STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly) 7984 } 7985 }; 7986 7987 /// AAMemoryLocation attribute for call sites. 7988 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl { 7989 AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A) 7990 : AAMemoryLocationImpl(IRP, A) {} 7991 7992 /// See AbstractAttribute::initialize(...). 7993 void initialize(Attributor &A) override { 7994 AAMemoryLocationImpl::initialize(A); 7995 Function *F = getAssociatedFunction(); 7996 if (!F || F->isDeclaration()) 7997 indicatePessimisticFixpoint(); 7998 } 7999 8000 /// See AbstractAttribute::updateImpl(...). 8001 ChangeStatus updateImpl(Attributor &A) override { 8002 // TODO: Once we have call site specific value information we can provide 8003 // call site specific liveness liveness information and then it makes 8004 // sense to specialize attributes for call sites arguments instead of 8005 // redirecting requests to the callee argument. 8006 Function *F = getAssociatedFunction(); 8007 const IRPosition &FnPos = IRPosition::function(*F); 8008 auto &FnAA = 8009 A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED); 8010 bool Changed = false; 8011 auto AccessPred = [&](const Instruction *I, const Value *Ptr, 8012 AccessKind Kind, MemoryLocationsKind MLK) { 8013 updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed, 8014 getAccessKindFromInst(I)); 8015 return true; 8016 }; 8017 if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS)) 8018 return indicatePessimisticFixpoint(); 8019 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 8020 } 8021 8022 /// See AbstractAttribute::trackStatistics() 8023 void trackStatistics() const override { 8024 if (isAssumedReadNone()) 8025 STATS_DECLTRACK_CS_ATTR(readnone) 8026 } 8027 }; 8028 } // namespace 8029 8030 /// ------------------ Value Constant Range Attribute ------------------------- 8031 8032 namespace { 8033 struct AAValueConstantRangeImpl : AAValueConstantRange { 8034 using StateType = IntegerRangeState; 8035 AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A) 8036 : AAValueConstantRange(IRP, A) {} 8037 8038 /// See AbstractAttribute::initialize(..). 8039 void initialize(Attributor &A) override { 8040 if (A.hasSimplificationCallback(getIRPosition())) { 8041 indicatePessimisticFixpoint(); 8042 return; 8043 } 8044 8045 // Intersect a range given by SCEV. 8046 intersectKnown(getConstantRangeFromSCEV(A, getCtxI())); 8047 8048 // Intersect a range given by LVI. 8049 intersectKnown(getConstantRangeFromLVI(A, getCtxI())); 8050 } 8051 8052 /// See AbstractAttribute::getAsStr(). 8053 const std::string getAsStr() const override { 8054 std::string Str; 8055 llvm::raw_string_ostream OS(Str); 8056 OS << "range(" << getBitWidth() << ")<"; 8057 getKnown().print(OS); 8058 OS << " / "; 8059 getAssumed().print(OS); 8060 OS << ">"; 8061 return OS.str(); 8062 } 8063 8064 /// Helper function to get a SCEV expr for the associated value at program 8065 /// point \p I. 8066 const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const { 8067 if (!getAnchorScope()) 8068 return nullptr; 8069 8070 ScalarEvolution *SE = 8071 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 8072 *getAnchorScope()); 8073 8074 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>( 8075 *getAnchorScope()); 8076 8077 if (!SE || !LI) 8078 return nullptr; 8079 8080 const SCEV *S = SE->getSCEV(&getAssociatedValue()); 8081 if (!I) 8082 return S; 8083 8084 return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent())); 8085 } 8086 8087 /// Helper function to get a range from SCEV for the associated value at 8088 /// program point \p I. 8089 ConstantRange getConstantRangeFromSCEV(Attributor &A, 8090 const Instruction *I = nullptr) const { 8091 if (!getAnchorScope()) 8092 return getWorstState(getBitWidth()); 8093 8094 ScalarEvolution *SE = 8095 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 8096 *getAnchorScope()); 8097 8098 const SCEV *S = getSCEV(A, I); 8099 if (!SE || !S) 8100 return getWorstState(getBitWidth()); 8101 8102 return SE->getUnsignedRange(S); 8103 } 8104 8105 /// Helper function to get a range from LVI for the associated value at 8106 /// program point \p I. 8107 ConstantRange 8108 getConstantRangeFromLVI(Attributor &A, 8109 const Instruction *CtxI = nullptr) const { 8110 if (!getAnchorScope()) 8111 return getWorstState(getBitWidth()); 8112 8113 LazyValueInfo *LVI = 8114 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>( 8115 *getAnchorScope()); 8116 8117 if (!LVI || !CtxI) 8118 return getWorstState(getBitWidth()); 8119 return LVI->getConstantRange(&getAssociatedValue(), 8120 const_cast<Instruction *>(CtxI)); 8121 } 8122 8123 /// Return true if \p CtxI is valid for querying outside analyses. 8124 /// This basically makes sure we do not ask intra-procedural analysis 8125 /// about a context in the wrong function or a context that violates 8126 /// dominance assumptions they might have. The \p AllowAACtxI flag indicates 8127 /// if the original context of this AA is OK or should be considered invalid. 8128 bool isValidCtxInstructionForOutsideAnalysis(Attributor &A, 8129 const Instruction *CtxI, 8130 bool AllowAACtxI) const { 8131 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI())) 8132 return false; 8133 8134 // Our context might be in a different function, neither intra-procedural 8135 // analysis (ScalarEvolution nor LazyValueInfo) can handle that. 8136 if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction())) 8137 return false; 8138 8139 // If the context is not dominated by the value there are paths to the 8140 // context that do not define the value. This cannot be handled by 8141 // LazyValueInfo so we need to bail. 8142 if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) { 8143 InformationCache &InfoCache = A.getInfoCache(); 8144 const DominatorTree *DT = 8145 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>( 8146 *I->getFunction()); 8147 return DT && DT->dominates(I, CtxI); 8148 } 8149 8150 return true; 8151 } 8152 8153 /// See AAValueConstantRange::getKnownConstantRange(..). 8154 ConstantRange 8155 getKnownConstantRange(Attributor &A, 8156 const Instruction *CtxI = nullptr) const override { 8157 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI, 8158 /* AllowAACtxI */ false)) 8159 return getKnown(); 8160 8161 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 8162 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 8163 return getKnown().intersectWith(SCEVR).intersectWith(LVIR); 8164 } 8165 8166 /// See AAValueConstantRange::getAssumedConstantRange(..). 8167 ConstantRange 8168 getAssumedConstantRange(Attributor &A, 8169 const Instruction *CtxI = nullptr) const override { 8170 // TODO: Make SCEV use Attributor assumption. 8171 // We may be able to bound a variable range via assumptions in 8172 // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to 8173 // evolve to x^2 + x, then we can say that y is in [2, 12]. 8174 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI, 8175 /* AllowAACtxI */ false)) 8176 return getAssumed(); 8177 8178 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 8179 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 8180 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR); 8181 } 8182 8183 /// Helper function to create MDNode for range metadata. 8184 static MDNode * 8185 getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx, 8186 const ConstantRange &AssumedConstantRange) { 8187 Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get( 8188 Ty, AssumedConstantRange.getLower())), 8189 ConstantAsMetadata::get(ConstantInt::get( 8190 Ty, AssumedConstantRange.getUpper()))}; 8191 return MDNode::get(Ctx, LowAndHigh); 8192 } 8193 8194 /// Return true if \p Assumed is included in \p KnownRanges. 8195 static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) { 8196 8197 if (Assumed.isFullSet()) 8198 return false; 8199 8200 if (!KnownRanges) 8201 return true; 8202 8203 // If multiple ranges are annotated in IR, we give up to annotate assumed 8204 // range for now. 8205 8206 // TODO: If there exists a known range which containts assumed range, we 8207 // can say assumed range is better. 8208 if (KnownRanges->getNumOperands() > 2) 8209 return false; 8210 8211 ConstantInt *Lower = 8212 mdconst::extract<ConstantInt>(KnownRanges->getOperand(0)); 8213 ConstantInt *Upper = 8214 mdconst::extract<ConstantInt>(KnownRanges->getOperand(1)); 8215 8216 ConstantRange Known(Lower->getValue(), Upper->getValue()); 8217 return Known.contains(Assumed) && Known != Assumed; 8218 } 8219 8220 /// Helper function to set range metadata. 8221 static bool 8222 setRangeMetadataIfisBetterRange(Instruction *I, 8223 const ConstantRange &AssumedConstantRange) { 8224 auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range); 8225 if (isBetterRange(AssumedConstantRange, OldRangeMD)) { 8226 if (!AssumedConstantRange.isEmptySet()) { 8227 I->setMetadata(LLVMContext::MD_range, 8228 getMDNodeForConstantRange(I->getType(), I->getContext(), 8229 AssumedConstantRange)); 8230 return true; 8231 } 8232 } 8233 return false; 8234 } 8235 8236 /// See AbstractAttribute::manifest() 8237 ChangeStatus manifest(Attributor &A) override { 8238 ChangeStatus Changed = ChangeStatus::UNCHANGED; 8239 ConstantRange AssumedConstantRange = getAssumedConstantRange(A); 8240 assert(!AssumedConstantRange.isFullSet() && "Invalid state"); 8241 8242 auto &V = getAssociatedValue(); 8243 if (!AssumedConstantRange.isEmptySet() && 8244 !AssumedConstantRange.isSingleElement()) { 8245 if (Instruction *I = dyn_cast<Instruction>(&V)) { 8246 assert(I == getCtxI() && "Should not annotate an instruction which is " 8247 "not the context instruction"); 8248 if (isa<CallInst>(I) || isa<LoadInst>(I)) 8249 if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange)) 8250 Changed = ChangeStatus::CHANGED; 8251 } 8252 } 8253 8254 return Changed; 8255 } 8256 }; 8257 8258 struct AAValueConstantRangeArgument final 8259 : AAArgumentFromCallSiteArguments< 8260 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 8261 true /* BridgeCallBaseContext */> { 8262 using Base = AAArgumentFromCallSiteArguments< 8263 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 8264 true /* BridgeCallBaseContext */>; 8265 AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A) 8266 : Base(IRP, A) {} 8267 8268 /// See AbstractAttribute::initialize(..). 8269 void initialize(Attributor &A) override { 8270 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 8271 indicatePessimisticFixpoint(); 8272 } else { 8273 Base::initialize(A); 8274 } 8275 } 8276 8277 /// See AbstractAttribute::trackStatistics() 8278 void trackStatistics() const override { 8279 STATS_DECLTRACK_ARG_ATTR(value_range) 8280 } 8281 }; 8282 8283 struct AAValueConstantRangeReturned 8284 : AAReturnedFromReturnedValues<AAValueConstantRange, 8285 AAValueConstantRangeImpl, 8286 AAValueConstantRangeImpl::StateType, 8287 /* PropogateCallBaseContext */ true> { 8288 using Base = 8289 AAReturnedFromReturnedValues<AAValueConstantRange, 8290 AAValueConstantRangeImpl, 8291 AAValueConstantRangeImpl::StateType, 8292 /* PropogateCallBaseContext */ true>; 8293 AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A) 8294 : Base(IRP, A) {} 8295 8296 /// See AbstractAttribute::initialize(...). 8297 void initialize(Attributor &A) override {} 8298 8299 /// See AbstractAttribute::trackStatistics() 8300 void trackStatistics() const override { 8301 STATS_DECLTRACK_FNRET_ATTR(value_range) 8302 } 8303 }; 8304 8305 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { 8306 AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A) 8307 : AAValueConstantRangeImpl(IRP, A) {} 8308 8309 /// See AbstractAttribute::initialize(...). 8310 void initialize(Attributor &A) override { 8311 AAValueConstantRangeImpl::initialize(A); 8312 if (isAtFixpoint()) 8313 return; 8314 8315 Value &V = getAssociatedValue(); 8316 8317 if (auto *C = dyn_cast<ConstantInt>(&V)) { 8318 unionAssumed(ConstantRange(C->getValue())); 8319 indicateOptimisticFixpoint(); 8320 return; 8321 } 8322 8323 if (isa<UndefValue>(&V)) { 8324 // Collapse the undef state to 0. 8325 unionAssumed(ConstantRange(APInt(getBitWidth(), 0))); 8326 indicateOptimisticFixpoint(); 8327 return; 8328 } 8329 8330 if (isa<CallBase>(&V)) 8331 return; 8332 8333 if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V)) 8334 return; 8335 8336 // If it is a load instruction with range metadata, use it. 8337 if (LoadInst *LI = dyn_cast<LoadInst>(&V)) 8338 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) { 8339 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 8340 return; 8341 } 8342 8343 // We can work with PHI and select instruction as we traverse their operands 8344 // during update. 8345 if (isa<SelectInst>(V) || isa<PHINode>(V)) 8346 return; 8347 8348 // Otherwise we give up. 8349 indicatePessimisticFixpoint(); 8350 8351 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: " 8352 << getAssociatedValue() << "\n"); 8353 } 8354 8355 bool calculateBinaryOperator( 8356 Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T, 8357 const Instruction *CtxI, 8358 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8359 Value *LHS = BinOp->getOperand(0); 8360 Value *RHS = BinOp->getOperand(1); 8361 8362 // Simplify the operands first. 8363 bool UsedAssumedInformation = false; 8364 const auto &SimplifiedLHS = A.getAssumedSimplified( 8365 IRPosition::value(*LHS, getCallBaseContext()), *this, 8366 UsedAssumedInformation, AA::Interprocedural); 8367 if (!SimplifiedLHS.has_value()) 8368 return true; 8369 if (!SimplifiedLHS.value()) 8370 return false; 8371 LHS = *SimplifiedLHS; 8372 8373 const auto &SimplifiedRHS = A.getAssumedSimplified( 8374 IRPosition::value(*RHS, getCallBaseContext()), *this, 8375 UsedAssumedInformation, AA::Interprocedural); 8376 if (!SimplifiedRHS.has_value()) 8377 return true; 8378 if (!SimplifiedRHS.value()) 8379 return false; 8380 RHS = *SimplifiedRHS; 8381 8382 // TODO: Allow non integers as well. 8383 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 8384 return false; 8385 8386 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 8387 *this, IRPosition::value(*LHS, getCallBaseContext()), 8388 DepClassTy::REQUIRED); 8389 QuerriedAAs.push_back(&LHSAA); 8390 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 8391 8392 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 8393 *this, IRPosition::value(*RHS, getCallBaseContext()), 8394 DepClassTy::REQUIRED); 8395 QuerriedAAs.push_back(&RHSAA); 8396 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 8397 8398 auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange); 8399 8400 T.unionAssumed(AssumedRange); 8401 8402 // TODO: Track a known state too. 8403 8404 return T.isValidState(); 8405 } 8406 8407 bool calculateCastInst( 8408 Attributor &A, CastInst *CastI, IntegerRangeState &T, 8409 const Instruction *CtxI, 8410 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8411 assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!"); 8412 // TODO: Allow non integers as well. 8413 Value *OpV = CastI->getOperand(0); 8414 8415 // Simplify the operand first. 8416 bool UsedAssumedInformation = false; 8417 const auto &SimplifiedOpV = A.getAssumedSimplified( 8418 IRPosition::value(*OpV, getCallBaseContext()), *this, 8419 UsedAssumedInformation, AA::Interprocedural); 8420 if (!SimplifiedOpV.has_value()) 8421 return true; 8422 if (!SimplifiedOpV.value()) 8423 return false; 8424 OpV = *SimplifiedOpV; 8425 8426 if (!OpV->getType()->isIntegerTy()) 8427 return false; 8428 8429 auto &OpAA = A.getAAFor<AAValueConstantRange>( 8430 *this, IRPosition::value(*OpV, getCallBaseContext()), 8431 DepClassTy::REQUIRED); 8432 QuerriedAAs.push_back(&OpAA); 8433 T.unionAssumed( 8434 OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth())); 8435 return T.isValidState(); 8436 } 8437 8438 bool 8439 calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T, 8440 const Instruction *CtxI, 8441 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8442 Value *LHS = CmpI->getOperand(0); 8443 Value *RHS = CmpI->getOperand(1); 8444 8445 // Simplify the operands first. 8446 bool UsedAssumedInformation = false; 8447 const auto &SimplifiedLHS = A.getAssumedSimplified( 8448 IRPosition::value(*LHS, getCallBaseContext()), *this, 8449 UsedAssumedInformation, AA::Interprocedural); 8450 if (!SimplifiedLHS.has_value()) 8451 return true; 8452 if (!SimplifiedLHS.value()) 8453 return false; 8454 LHS = *SimplifiedLHS; 8455 8456 const auto &SimplifiedRHS = A.getAssumedSimplified( 8457 IRPosition::value(*RHS, getCallBaseContext()), *this, 8458 UsedAssumedInformation, AA::Interprocedural); 8459 if (!SimplifiedRHS.has_value()) 8460 return true; 8461 if (!SimplifiedRHS.value()) 8462 return false; 8463 RHS = *SimplifiedRHS; 8464 8465 // TODO: Allow non integers as well. 8466 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 8467 return false; 8468 8469 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 8470 *this, IRPosition::value(*LHS, getCallBaseContext()), 8471 DepClassTy::REQUIRED); 8472 QuerriedAAs.push_back(&LHSAA); 8473 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 8474 *this, IRPosition::value(*RHS, getCallBaseContext()), 8475 DepClassTy::REQUIRED); 8476 QuerriedAAs.push_back(&RHSAA); 8477 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 8478 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 8479 8480 // If one of them is empty set, we can't decide. 8481 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet()) 8482 return true; 8483 8484 bool MustTrue = false, MustFalse = false; 8485 8486 auto AllowedRegion = 8487 ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange); 8488 8489 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet()) 8490 MustFalse = true; 8491 8492 if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange)) 8493 MustTrue = true; 8494 8495 assert((!MustTrue || !MustFalse) && 8496 "Either MustTrue or MustFalse should be false!"); 8497 8498 if (MustTrue) 8499 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1))); 8500 else if (MustFalse) 8501 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0))); 8502 else 8503 T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true)); 8504 8505 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA 8506 << " " << RHSAA << "\n"); 8507 8508 // TODO: Track a known state too. 8509 return T.isValidState(); 8510 } 8511 8512 /// See AbstractAttribute::updateImpl(...). 8513 ChangeStatus updateImpl(Attributor &A) override { 8514 8515 IntegerRangeState T(getBitWidth()); 8516 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool { 8517 Instruction *I = dyn_cast<Instruction>(&V); 8518 if (!I || isa<CallBase>(I)) { 8519 8520 // Simplify the operand first. 8521 bool UsedAssumedInformation = false; 8522 const auto &SimplifiedOpV = A.getAssumedSimplified( 8523 IRPosition::value(V, getCallBaseContext()), *this, 8524 UsedAssumedInformation, AA::Interprocedural); 8525 if (!SimplifiedOpV.has_value()) 8526 return true; 8527 if (!SimplifiedOpV.value()) 8528 return false; 8529 Value *VPtr = *SimplifiedOpV; 8530 8531 // If the value is not instruction, we query AA to Attributor. 8532 const auto &AA = A.getAAFor<AAValueConstantRange>( 8533 *this, IRPosition::value(*VPtr, getCallBaseContext()), 8534 DepClassTy::REQUIRED); 8535 8536 // Clamp operator is not used to utilize a program point CtxI. 8537 T.unionAssumed(AA.getAssumedConstantRange(A, CtxI)); 8538 8539 return T.isValidState(); 8540 } 8541 8542 SmallVector<const AAValueConstantRange *, 4> QuerriedAAs; 8543 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) { 8544 if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs)) 8545 return false; 8546 } else if (auto *CmpI = dyn_cast<CmpInst>(I)) { 8547 if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs)) 8548 return false; 8549 } else if (auto *CastI = dyn_cast<CastInst>(I)) { 8550 if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs)) 8551 return false; 8552 } else { 8553 // Give up with other instructions. 8554 // TODO: Add other instructions 8555 8556 T.indicatePessimisticFixpoint(); 8557 return false; 8558 } 8559 8560 // Catch circular reasoning in a pessimistic way for now. 8561 // TODO: Check how the range evolves and if we stripped anything, see also 8562 // AADereferenceable or AAAlign for similar situations. 8563 for (const AAValueConstantRange *QueriedAA : QuerriedAAs) { 8564 if (QueriedAA != this) 8565 continue; 8566 // If we are in a stady state we do not need to worry. 8567 if (T.getAssumed() == getState().getAssumed()) 8568 continue; 8569 T.indicatePessimisticFixpoint(); 8570 } 8571 8572 return T.isValidState(); 8573 }; 8574 8575 if (!VisitValueCB(getAssociatedValue(), getCtxI())) 8576 return indicatePessimisticFixpoint(); 8577 8578 // Ensure that long def-use chains can't cause circular reasoning either by 8579 // introducing a cutoff below. 8580 if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED) 8581 return ChangeStatus::UNCHANGED; 8582 if (++NumChanges > MaxNumChanges) { 8583 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges 8584 << " but only " << MaxNumChanges 8585 << " are allowed to avoid cyclic reasoning."); 8586 return indicatePessimisticFixpoint(); 8587 } 8588 return ChangeStatus::CHANGED; 8589 } 8590 8591 /// See AbstractAttribute::trackStatistics() 8592 void trackStatistics() const override { 8593 STATS_DECLTRACK_FLOATING_ATTR(value_range) 8594 } 8595 8596 /// Tracker to bail after too many widening steps of the constant range. 8597 int NumChanges = 0; 8598 8599 /// Upper bound for the number of allowed changes (=widening steps) for the 8600 /// constant range before we give up. 8601 static constexpr int MaxNumChanges = 5; 8602 }; 8603 8604 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl { 8605 AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A) 8606 : AAValueConstantRangeImpl(IRP, A) {} 8607 8608 /// See AbstractAttribute::initialize(...). 8609 ChangeStatus updateImpl(Attributor &A) override { 8610 llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will " 8611 "not be called"); 8612 } 8613 8614 /// See AbstractAttribute::trackStatistics() 8615 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) } 8616 }; 8617 8618 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction { 8619 AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A) 8620 : AAValueConstantRangeFunction(IRP, A) {} 8621 8622 /// See AbstractAttribute::trackStatistics() 8623 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) } 8624 }; 8625 8626 struct AAValueConstantRangeCallSiteReturned 8627 : AACallSiteReturnedFromReturned<AAValueConstantRange, 8628 AAValueConstantRangeImpl, 8629 AAValueConstantRangeImpl::StateType, 8630 /* IntroduceCallBaseContext */ true> { 8631 AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A) 8632 : AACallSiteReturnedFromReturned<AAValueConstantRange, 8633 AAValueConstantRangeImpl, 8634 AAValueConstantRangeImpl::StateType, 8635 /* IntroduceCallBaseContext */ true>(IRP, 8636 A) { 8637 } 8638 8639 /// See AbstractAttribute::initialize(...). 8640 void initialize(Attributor &A) override { 8641 // If it is a load instruction with range metadata, use the metadata. 8642 if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue())) 8643 if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range)) 8644 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 8645 8646 AAValueConstantRangeImpl::initialize(A); 8647 } 8648 8649 /// See AbstractAttribute::trackStatistics() 8650 void trackStatistics() const override { 8651 STATS_DECLTRACK_CSRET_ATTR(value_range) 8652 } 8653 }; 8654 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating { 8655 AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A) 8656 : AAValueConstantRangeFloating(IRP, A) {} 8657 8658 /// See AbstractAttribute::manifest() 8659 ChangeStatus manifest(Attributor &A) override { 8660 return ChangeStatus::UNCHANGED; 8661 } 8662 8663 /// See AbstractAttribute::trackStatistics() 8664 void trackStatistics() const override { 8665 STATS_DECLTRACK_CSARG_ATTR(value_range) 8666 } 8667 }; 8668 } // namespace 8669 8670 /// ------------------ Potential Values Attribute ------------------------- 8671 8672 namespace { 8673 struct AAPotentialConstantValuesImpl : AAPotentialConstantValues { 8674 using StateType = PotentialConstantIntValuesState; 8675 8676 AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A) 8677 : AAPotentialConstantValues(IRP, A) {} 8678 8679 /// See AbstractAttribute::initialize(..). 8680 void initialize(Attributor &A) override { 8681 if (A.hasSimplificationCallback(getIRPosition())) 8682 indicatePessimisticFixpoint(); 8683 else 8684 AAPotentialConstantValues::initialize(A); 8685 } 8686 8687 bool fillSetWithConstantValues(Attributor &A, const IRPosition &IRP, SetTy &S, 8688 bool &ContainsUndef) { 8689 SmallVector<AA::ValueAndContext> Values; 8690 bool UsedAssumedInformation = false; 8691 if (!A.getAssumedSimplifiedValues(IRP, *this, Values, AA::Interprocedural, 8692 UsedAssumedInformation)) { 8693 if (!IRP.getAssociatedType()->isIntegerTy()) 8694 return false; 8695 auto &PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>( 8696 *this, IRP, DepClassTy::REQUIRED); 8697 if (!PotentialValuesAA.getState().isValidState()) 8698 return false; 8699 ContainsUndef = PotentialValuesAA.getState().undefIsContained(); 8700 S = PotentialValuesAA.getState().getAssumedSet(); 8701 return true; 8702 } 8703 8704 for (auto &It : Values) { 8705 if (isa<UndefValue>(It.getValue())) 8706 continue; 8707 auto *CI = dyn_cast<ConstantInt>(It.getValue()); 8708 if (!CI) 8709 return false; 8710 S.insert(CI->getValue()); 8711 } 8712 ContainsUndef = S.empty(); 8713 8714 return true; 8715 } 8716 8717 /// See AbstractAttribute::getAsStr(). 8718 const std::string getAsStr() const override { 8719 std::string Str; 8720 llvm::raw_string_ostream OS(Str); 8721 OS << getState(); 8722 return OS.str(); 8723 } 8724 8725 /// See AbstractAttribute::updateImpl(...). 8726 ChangeStatus updateImpl(Attributor &A) override { 8727 return indicatePessimisticFixpoint(); 8728 } 8729 }; 8730 8731 struct AAPotentialConstantValuesArgument final 8732 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues, 8733 AAPotentialConstantValuesImpl, 8734 PotentialConstantIntValuesState> { 8735 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues, 8736 AAPotentialConstantValuesImpl, 8737 PotentialConstantIntValuesState>; 8738 AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A) 8739 : Base(IRP, A) {} 8740 8741 /// See AbstractAttribute::initialize(..). 8742 void initialize(Attributor &A) override { 8743 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 8744 indicatePessimisticFixpoint(); 8745 } else { 8746 Base::initialize(A); 8747 } 8748 } 8749 8750 /// See AbstractAttribute::trackStatistics() 8751 void trackStatistics() const override { 8752 STATS_DECLTRACK_ARG_ATTR(potential_values) 8753 } 8754 }; 8755 8756 struct AAPotentialConstantValuesReturned 8757 : AAReturnedFromReturnedValues<AAPotentialConstantValues, 8758 AAPotentialConstantValuesImpl> { 8759 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues, 8760 AAPotentialConstantValuesImpl>; 8761 AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A) 8762 : Base(IRP, A) {} 8763 8764 /// See AbstractAttribute::trackStatistics() 8765 void trackStatistics() const override { 8766 STATS_DECLTRACK_FNRET_ATTR(potential_values) 8767 } 8768 }; 8769 8770 struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { 8771 AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A) 8772 : AAPotentialConstantValuesImpl(IRP, A) {} 8773 8774 /// See AbstractAttribute::initialize(..). 8775 void initialize(Attributor &A) override { 8776 AAPotentialConstantValuesImpl::initialize(A); 8777 if (isAtFixpoint()) 8778 return; 8779 8780 Value &V = getAssociatedValue(); 8781 8782 if (auto *C = dyn_cast<ConstantInt>(&V)) { 8783 unionAssumed(C->getValue()); 8784 indicateOptimisticFixpoint(); 8785 return; 8786 } 8787 8788 if (isa<UndefValue>(&V)) { 8789 unionAssumedWithUndef(); 8790 indicateOptimisticFixpoint(); 8791 return; 8792 } 8793 8794 if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V)) 8795 return; 8796 8797 if (isa<SelectInst>(V) || isa<PHINode>(V) || isa<LoadInst>(V)) 8798 return; 8799 8800 indicatePessimisticFixpoint(); 8801 8802 LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: " 8803 << getAssociatedValue() << "\n"); 8804 } 8805 8806 static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS, 8807 const APInt &RHS) { 8808 return ICmpInst::compare(LHS, RHS, ICI->getPredicate()); 8809 } 8810 8811 static APInt calculateCastInst(const CastInst *CI, const APInt &Src, 8812 uint32_t ResultBitWidth) { 8813 Instruction::CastOps CastOp = CI->getOpcode(); 8814 switch (CastOp) { 8815 default: 8816 llvm_unreachable("unsupported or not integer cast"); 8817 case Instruction::Trunc: 8818 return Src.trunc(ResultBitWidth); 8819 case Instruction::SExt: 8820 return Src.sext(ResultBitWidth); 8821 case Instruction::ZExt: 8822 return Src.zext(ResultBitWidth); 8823 case Instruction::BitCast: 8824 return Src; 8825 } 8826 } 8827 8828 static APInt calculateBinaryOperator(const BinaryOperator *BinOp, 8829 const APInt &LHS, const APInt &RHS, 8830 bool &SkipOperation, bool &Unsupported) { 8831 Instruction::BinaryOps BinOpcode = BinOp->getOpcode(); 8832 // Unsupported is set to true when the binary operator is not supported. 8833 // SkipOperation is set to true when UB occur with the given operand pair 8834 // (LHS, RHS). 8835 // TODO: we should look at nsw and nuw keywords to handle operations 8836 // that create poison or undef value. 8837 switch (BinOpcode) { 8838 default: 8839 Unsupported = true; 8840 return LHS; 8841 case Instruction::Add: 8842 return LHS + RHS; 8843 case Instruction::Sub: 8844 return LHS - RHS; 8845 case Instruction::Mul: 8846 return LHS * RHS; 8847 case Instruction::UDiv: 8848 if (RHS.isZero()) { 8849 SkipOperation = true; 8850 return LHS; 8851 } 8852 return LHS.udiv(RHS); 8853 case Instruction::SDiv: 8854 if (RHS.isZero()) { 8855 SkipOperation = true; 8856 return LHS; 8857 } 8858 return LHS.sdiv(RHS); 8859 case Instruction::URem: 8860 if (RHS.isZero()) { 8861 SkipOperation = true; 8862 return LHS; 8863 } 8864 return LHS.urem(RHS); 8865 case Instruction::SRem: 8866 if (RHS.isZero()) { 8867 SkipOperation = true; 8868 return LHS; 8869 } 8870 return LHS.srem(RHS); 8871 case Instruction::Shl: 8872 return LHS.shl(RHS); 8873 case Instruction::LShr: 8874 return LHS.lshr(RHS); 8875 case Instruction::AShr: 8876 return LHS.ashr(RHS); 8877 case Instruction::And: 8878 return LHS & RHS; 8879 case Instruction::Or: 8880 return LHS | RHS; 8881 case Instruction::Xor: 8882 return LHS ^ RHS; 8883 } 8884 } 8885 8886 bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp, 8887 const APInt &LHS, const APInt &RHS) { 8888 bool SkipOperation = false; 8889 bool Unsupported = false; 8890 APInt Result = 8891 calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported); 8892 if (Unsupported) 8893 return false; 8894 // If SkipOperation is true, we can ignore this operand pair (L, R). 8895 if (!SkipOperation) 8896 unionAssumed(Result); 8897 return isValidState(); 8898 } 8899 8900 ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) { 8901 auto AssumedBefore = getAssumed(); 8902 Value *LHS = ICI->getOperand(0); 8903 Value *RHS = ICI->getOperand(1); 8904 8905 bool LHSContainsUndef = false, RHSContainsUndef = false; 8906 SetTy LHSAAPVS, RHSAAPVS; 8907 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS, 8908 LHSContainsUndef) || 8909 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS, 8910 RHSContainsUndef)) 8911 return indicatePessimisticFixpoint(); 8912 8913 // TODO: make use of undef flag to limit potential values aggressively. 8914 bool MaybeTrue = false, MaybeFalse = false; 8915 const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0); 8916 if (LHSContainsUndef && RHSContainsUndef) { 8917 // The result of any comparison between undefs can be soundly replaced 8918 // with undef. 8919 unionAssumedWithUndef(); 8920 } else if (LHSContainsUndef) { 8921 for (const APInt &R : RHSAAPVS) { 8922 bool CmpResult = calculateICmpInst(ICI, Zero, R); 8923 MaybeTrue |= CmpResult; 8924 MaybeFalse |= !CmpResult; 8925 if (MaybeTrue & MaybeFalse) 8926 return indicatePessimisticFixpoint(); 8927 } 8928 } else if (RHSContainsUndef) { 8929 for (const APInt &L : LHSAAPVS) { 8930 bool CmpResult = calculateICmpInst(ICI, L, Zero); 8931 MaybeTrue |= CmpResult; 8932 MaybeFalse |= !CmpResult; 8933 if (MaybeTrue & MaybeFalse) 8934 return indicatePessimisticFixpoint(); 8935 } 8936 } else { 8937 for (const APInt &L : LHSAAPVS) { 8938 for (const APInt &R : RHSAAPVS) { 8939 bool CmpResult = calculateICmpInst(ICI, L, R); 8940 MaybeTrue |= CmpResult; 8941 MaybeFalse |= !CmpResult; 8942 if (MaybeTrue & MaybeFalse) 8943 return indicatePessimisticFixpoint(); 8944 } 8945 } 8946 } 8947 if (MaybeTrue) 8948 unionAssumed(APInt(/* numBits */ 1, /* val */ 1)); 8949 if (MaybeFalse) 8950 unionAssumed(APInt(/* numBits */ 1, /* val */ 0)); 8951 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 8952 : ChangeStatus::CHANGED; 8953 } 8954 8955 ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) { 8956 auto AssumedBefore = getAssumed(); 8957 Value *LHS = SI->getTrueValue(); 8958 Value *RHS = SI->getFalseValue(); 8959 8960 bool UsedAssumedInformation = false; 8961 Optional<Constant *> C = A.getAssumedConstant(*SI->getCondition(), *this, 8962 UsedAssumedInformation); 8963 8964 // Check if we only need one operand. 8965 bool OnlyLeft = false, OnlyRight = false; 8966 if (C && *C && (*C)->isOneValue()) 8967 OnlyLeft = true; 8968 else if (C && *C && (*C)->isZeroValue()) 8969 OnlyRight = true; 8970 8971 bool LHSContainsUndef = false, RHSContainsUndef = false; 8972 SetTy LHSAAPVS, RHSAAPVS; 8973 if (!OnlyRight && !fillSetWithConstantValues(A, IRPosition::value(*LHS), 8974 LHSAAPVS, LHSContainsUndef)) 8975 return indicatePessimisticFixpoint(); 8976 8977 if (!OnlyLeft && !fillSetWithConstantValues(A, IRPosition::value(*RHS), 8978 RHSAAPVS, RHSContainsUndef)) 8979 return indicatePessimisticFixpoint(); 8980 8981 if (OnlyLeft || OnlyRight) { 8982 // select (true/false), lhs, rhs 8983 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS; 8984 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef; 8985 8986 if (Undef) 8987 unionAssumedWithUndef(); 8988 else { 8989 for (auto &It : *OpAA) 8990 unionAssumed(It); 8991 } 8992 8993 } else if (LHSContainsUndef && RHSContainsUndef) { 8994 // select i1 *, undef , undef => undef 8995 unionAssumedWithUndef(); 8996 } else { 8997 for (auto &It : LHSAAPVS) 8998 unionAssumed(It); 8999 for (auto &It : RHSAAPVS) 9000 unionAssumed(It); 9001 } 9002 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9003 : ChangeStatus::CHANGED; 9004 } 9005 9006 ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) { 9007 auto AssumedBefore = getAssumed(); 9008 if (!CI->isIntegerCast()) 9009 return indicatePessimisticFixpoint(); 9010 assert(CI->getNumOperands() == 1 && "Expected cast to be unary!"); 9011 uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth(); 9012 Value *Src = CI->getOperand(0); 9013 9014 bool SrcContainsUndef = false; 9015 SetTy SrcPVS; 9016 if (!fillSetWithConstantValues(A, IRPosition::value(*Src), SrcPVS, 9017 SrcContainsUndef)) 9018 return indicatePessimisticFixpoint(); 9019 9020 if (SrcContainsUndef) 9021 unionAssumedWithUndef(); 9022 else { 9023 for (const APInt &S : SrcPVS) { 9024 APInt T = calculateCastInst(CI, S, ResultBitWidth); 9025 unionAssumed(T); 9026 } 9027 } 9028 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9029 : ChangeStatus::CHANGED; 9030 } 9031 9032 ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) { 9033 auto AssumedBefore = getAssumed(); 9034 Value *LHS = BinOp->getOperand(0); 9035 Value *RHS = BinOp->getOperand(1); 9036 9037 bool LHSContainsUndef = false, RHSContainsUndef = false; 9038 SetTy LHSAAPVS, RHSAAPVS; 9039 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS, 9040 LHSContainsUndef) || 9041 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS, 9042 RHSContainsUndef)) 9043 return indicatePessimisticFixpoint(); 9044 9045 const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0); 9046 9047 // TODO: make use of undef flag to limit potential values aggressively. 9048 if (LHSContainsUndef && RHSContainsUndef) { 9049 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero)) 9050 return indicatePessimisticFixpoint(); 9051 } else if (LHSContainsUndef) { 9052 for (const APInt &R : RHSAAPVS) { 9053 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R)) 9054 return indicatePessimisticFixpoint(); 9055 } 9056 } else if (RHSContainsUndef) { 9057 for (const APInt &L : LHSAAPVS) { 9058 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero)) 9059 return indicatePessimisticFixpoint(); 9060 } 9061 } else { 9062 for (const APInt &L : LHSAAPVS) { 9063 for (const APInt &R : RHSAAPVS) { 9064 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R)) 9065 return indicatePessimisticFixpoint(); 9066 } 9067 } 9068 } 9069 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9070 : ChangeStatus::CHANGED; 9071 } 9072 9073 /// See AbstractAttribute::updateImpl(...). 9074 ChangeStatus updateImpl(Attributor &A) override { 9075 Value &V = getAssociatedValue(); 9076 Instruction *I = dyn_cast<Instruction>(&V); 9077 9078 if (auto *ICI = dyn_cast<ICmpInst>(I)) 9079 return updateWithICmpInst(A, ICI); 9080 9081 if (auto *SI = dyn_cast<SelectInst>(I)) 9082 return updateWithSelectInst(A, SI); 9083 9084 if (auto *CI = dyn_cast<CastInst>(I)) 9085 return updateWithCastInst(A, CI); 9086 9087 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) 9088 return updateWithBinaryOperator(A, BinOp); 9089 9090 return indicatePessimisticFixpoint(); 9091 } 9092 9093 /// See AbstractAttribute::trackStatistics() 9094 void trackStatistics() const override { 9095 STATS_DECLTRACK_FLOATING_ATTR(potential_values) 9096 } 9097 }; 9098 9099 struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl { 9100 AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A) 9101 : AAPotentialConstantValuesImpl(IRP, A) {} 9102 9103 /// See AbstractAttribute::initialize(...). 9104 ChangeStatus updateImpl(Attributor &A) override { 9105 llvm_unreachable( 9106 "AAPotentialConstantValues(Function|CallSite)::updateImpl will " 9107 "not be called"); 9108 } 9109 9110 /// See AbstractAttribute::trackStatistics() 9111 void trackStatistics() const override { 9112 STATS_DECLTRACK_FN_ATTR(potential_values) 9113 } 9114 }; 9115 9116 struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction { 9117 AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A) 9118 : AAPotentialConstantValuesFunction(IRP, A) {} 9119 9120 /// See AbstractAttribute::trackStatistics() 9121 void trackStatistics() const override { 9122 STATS_DECLTRACK_CS_ATTR(potential_values) 9123 } 9124 }; 9125 9126 struct AAPotentialConstantValuesCallSiteReturned 9127 : AACallSiteReturnedFromReturned<AAPotentialConstantValues, 9128 AAPotentialConstantValuesImpl> { 9129 AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP, 9130 Attributor &A) 9131 : AACallSiteReturnedFromReturned<AAPotentialConstantValues, 9132 AAPotentialConstantValuesImpl>(IRP, A) {} 9133 9134 /// See AbstractAttribute::trackStatistics() 9135 void trackStatistics() const override { 9136 STATS_DECLTRACK_CSRET_ATTR(potential_values) 9137 } 9138 }; 9139 9140 struct AAPotentialConstantValuesCallSiteArgument 9141 : AAPotentialConstantValuesFloating { 9142 AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP, 9143 Attributor &A) 9144 : AAPotentialConstantValuesFloating(IRP, A) {} 9145 9146 /// See AbstractAttribute::initialize(..). 9147 void initialize(Attributor &A) override { 9148 AAPotentialConstantValuesImpl::initialize(A); 9149 if (isAtFixpoint()) 9150 return; 9151 9152 Value &V = getAssociatedValue(); 9153 9154 if (auto *C = dyn_cast<ConstantInt>(&V)) { 9155 unionAssumed(C->getValue()); 9156 indicateOptimisticFixpoint(); 9157 return; 9158 } 9159 9160 if (isa<UndefValue>(&V)) { 9161 unionAssumedWithUndef(); 9162 indicateOptimisticFixpoint(); 9163 return; 9164 } 9165 } 9166 9167 /// See AbstractAttribute::updateImpl(...). 9168 ChangeStatus updateImpl(Attributor &A) override { 9169 Value &V = getAssociatedValue(); 9170 auto AssumedBefore = getAssumed(); 9171 auto &AA = A.getAAFor<AAPotentialConstantValues>( 9172 *this, IRPosition::value(V), DepClassTy::REQUIRED); 9173 const auto &S = AA.getAssumed(); 9174 unionAssumed(S); 9175 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9176 : ChangeStatus::CHANGED; 9177 } 9178 9179 /// See AbstractAttribute::trackStatistics() 9180 void trackStatistics() const override { 9181 STATS_DECLTRACK_CSARG_ATTR(potential_values) 9182 } 9183 }; 9184 9185 /// ------------------------ NoUndef Attribute --------------------------------- 9186 struct AANoUndefImpl : AANoUndef { 9187 AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {} 9188 9189 /// See AbstractAttribute::initialize(...). 9190 void initialize(Attributor &A) override { 9191 if (getIRPosition().hasAttr({Attribute::NoUndef})) { 9192 indicateOptimisticFixpoint(); 9193 return; 9194 } 9195 Value &V = getAssociatedValue(); 9196 if (isa<UndefValue>(V)) 9197 indicatePessimisticFixpoint(); 9198 else if (isa<FreezeInst>(V)) 9199 indicateOptimisticFixpoint(); 9200 else if (getPositionKind() != IRPosition::IRP_RETURNED && 9201 isGuaranteedNotToBeUndefOrPoison(&V)) 9202 indicateOptimisticFixpoint(); 9203 else 9204 AANoUndef::initialize(A); 9205 } 9206 9207 /// See followUsesInMBEC 9208 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 9209 AANoUndef::StateType &State) { 9210 const Value *UseV = U->get(); 9211 const DominatorTree *DT = nullptr; 9212 AssumptionCache *AC = nullptr; 9213 InformationCache &InfoCache = A.getInfoCache(); 9214 if (Function *F = getAnchorScope()) { 9215 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F); 9216 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F); 9217 } 9218 State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT)); 9219 bool TrackUse = false; 9220 // Track use for instructions which must produce undef or poison bits when 9221 // at least one operand contains such bits. 9222 if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I)) 9223 TrackUse = true; 9224 return TrackUse; 9225 } 9226 9227 /// See AbstractAttribute::getAsStr(). 9228 const std::string getAsStr() const override { 9229 return getAssumed() ? "noundef" : "may-undef-or-poison"; 9230 } 9231 9232 ChangeStatus manifest(Attributor &A) override { 9233 // We don't manifest noundef attribute for dead positions because the 9234 // associated values with dead positions would be replaced with undef 9235 // values. 9236 bool UsedAssumedInformation = false; 9237 if (A.isAssumedDead(getIRPosition(), nullptr, nullptr, 9238 UsedAssumedInformation)) 9239 return ChangeStatus::UNCHANGED; 9240 // A position whose simplified value does not have any value is 9241 // considered to be dead. We don't manifest noundef in such positions for 9242 // the same reason above. 9243 if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation, 9244 AA::Interprocedural) 9245 .has_value()) 9246 return ChangeStatus::UNCHANGED; 9247 return AANoUndef::manifest(A); 9248 } 9249 }; 9250 9251 struct AANoUndefFloating : public AANoUndefImpl { 9252 AANoUndefFloating(const IRPosition &IRP, Attributor &A) 9253 : AANoUndefImpl(IRP, A) {} 9254 9255 /// See AbstractAttribute::initialize(...). 9256 void initialize(Attributor &A) override { 9257 AANoUndefImpl::initialize(A); 9258 if (!getState().isAtFixpoint()) 9259 if (Instruction *CtxI = getCtxI()) 9260 followUsesInMBEC(*this, A, getState(), *CtxI); 9261 } 9262 9263 /// See AbstractAttribute::updateImpl(...). 9264 ChangeStatus updateImpl(Attributor &A) override { 9265 9266 SmallVector<AA::ValueAndContext> Values; 9267 bool UsedAssumedInformation = false; 9268 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values, 9269 AA::AnyScope, UsedAssumedInformation)) { 9270 Values.push_back({getAssociatedValue(), getCtxI()}); 9271 } 9272 9273 StateType T; 9274 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool { 9275 const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V), 9276 DepClassTy::REQUIRED); 9277 if (this == &AA) { 9278 T.indicatePessimisticFixpoint(); 9279 } else { 9280 const AANoUndef::StateType &S = 9281 static_cast<const AANoUndef::StateType &>(AA.getState()); 9282 T ^= S; 9283 } 9284 return T.isValidState(); 9285 }; 9286 9287 for (const auto &VAC : Values) 9288 if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI())) 9289 return indicatePessimisticFixpoint(); 9290 9291 return clampStateAndIndicateChange(getState(), T); 9292 } 9293 9294 /// See AbstractAttribute::trackStatistics() 9295 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 9296 }; 9297 9298 struct AANoUndefReturned final 9299 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> { 9300 AANoUndefReturned(const IRPosition &IRP, Attributor &A) 9301 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {} 9302 9303 /// See AbstractAttribute::trackStatistics() 9304 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 9305 }; 9306 9307 struct AANoUndefArgument final 9308 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> { 9309 AANoUndefArgument(const IRPosition &IRP, Attributor &A) 9310 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {} 9311 9312 /// See AbstractAttribute::trackStatistics() 9313 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) } 9314 }; 9315 9316 struct AANoUndefCallSiteArgument final : AANoUndefFloating { 9317 AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A) 9318 : AANoUndefFloating(IRP, A) {} 9319 9320 /// See AbstractAttribute::trackStatistics() 9321 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) } 9322 }; 9323 9324 struct AANoUndefCallSiteReturned final 9325 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> { 9326 AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A) 9327 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {} 9328 9329 /// See AbstractAttribute::trackStatistics() 9330 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) } 9331 }; 9332 9333 struct AACallEdgesImpl : public AACallEdges { 9334 AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {} 9335 9336 virtual const SetVector<Function *> &getOptimisticEdges() const override { 9337 return CalledFunctions; 9338 } 9339 9340 virtual bool hasUnknownCallee() const override { return HasUnknownCallee; } 9341 9342 virtual bool hasNonAsmUnknownCallee() const override { 9343 return HasUnknownCalleeNonAsm; 9344 } 9345 9346 const std::string getAsStr() const override { 9347 return "CallEdges[" + std::to_string(HasUnknownCallee) + "," + 9348 std::to_string(CalledFunctions.size()) + "]"; 9349 } 9350 9351 void trackStatistics() const override {} 9352 9353 protected: 9354 void addCalledFunction(Function *Fn, ChangeStatus &Change) { 9355 if (CalledFunctions.insert(Fn)) { 9356 Change = ChangeStatus::CHANGED; 9357 LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName() 9358 << "\n"); 9359 } 9360 } 9361 9362 void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) { 9363 if (!HasUnknownCallee) 9364 Change = ChangeStatus::CHANGED; 9365 if (NonAsm && !HasUnknownCalleeNonAsm) 9366 Change = ChangeStatus::CHANGED; 9367 HasUnknownCalleeNonAsm |= NonAsm; 9368 HasUnknownCallee = true; 9369 } 9370 9371 private: 9372 /// Optimistic set of functions that might be called by this position. 9373 SetVector<Function *> CalledFunctions; 9374 9375 /// Is there any call with a unknown callee. 9376 bool HasUnknownCallee = false; 9377 9378 /// Is there any call with a unknown callee, excluding any inline asm. 9379 bool HasUnknownCalleeNonAsm = false; 9380 }; 9381 9382 struct AACallEdgesCallSite : public AACallEdgesImpl { 9383 AACallEdgesCallSite(const IRPosition &IRP, Attributor &A) 9384 : AACallEdgesImpl(IRP, A) {} 9385 /// See AbstractAttribute::updateImpl(...). 9386 ChangeStatus updateImpl(Attributor &A) override { 9387 ChangeStatus Change = ChangeStatus::UNCHANGED; 9388 9389 auto VisitValue = [&](Value &V, const Instruction *CtxI) -> bool { 9390 if (Function *Fn = dyn_cast<Function>(&V)) { 9391 addCalledFunction(Fn, Change); 9392 } else { 9393 LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n"); 9394 setHasUnknownCallee(true, Change); 9395 } 9396 9397 // Explore all values. 9398 return true; 9399 }; 9400 9401 SmallVector<AA::ValueAndContext> Values; 9402 // Process any value that we might call. 9403 auto ProcessCalledOperand = [&](Value *V, Instruction *CtxI) { 9404 bool UsedAssumedInformation = false; 9405 Values.clear(); 9406 if (!A.getAssumedSimplifiedValues(IRPosition::value(*V), *this, Values, 9407 AA::AnyScope, UsedAssumedInformation)) { 9408 Values.push_back({*V, CtxI}); 9409 } 9410 for (auto &VAC : Values) 9411 VisitValue(*VAC.getValue(), VAC.getCtxI()); 9412 }; 9413 9414 CallBase *CB = cast<CallBase>(getCtxI()); 9415 9416 if (CB->isInlineAsm()) { 9417 if (!hasAssumption(*CB->getCaller(), "ompx_no_call_asm") && 9418 !hasAssumption(*CB, "ompx_no_call_asm")) 9419 setHasUnknownCallee(false, Change); 9420 return Change; 9421 } 9422 9423 // Process callee metadata if available. 9424 if (auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees)) { 9425 for (auto &Op : MD->operands()) { 9426 Function *Callee = mdconst::dyn_extract_or_null<Function>(Op); 9427 if (Callee) 9428 addCalledFunction(Callee, Change); 9429 } 9430 return Change; 9431 } 9432 9433 // The most simple case. 9434 ProcessCalledOperand(CB->getCalledOperand(), CB); 9435 9436 // Process callback functions. 9437 SmallVector<const Use *, 4u> CallbackUses; 9438 AbstractCallSite::getCallbackUses(*CB, CallbackUses); 9439 for (const Use *U : CallbackUses) 9440 ProcessCalledOperand(U->get(), CB); 9441 9442 return Change; 9443 } 9444 }; 9445 9446 struct AACallEdgesFunction : public AACallEdgesImpl { 9447 AACallEdgesFunction(const IRPosition &IRP, Attributor &A) 9448 : AACallEdgesImpl(IRP, A) {} 9449 9450 /// See AbstractAttribute::updateImpl(...). 9451 ChangeStatus updateImpl(Attributor &A) override { 9452 ChangeStatus Change = ChangeStatus::UNCHANGED; 9453 9454 auto ProcessCallInst = [&](Instruction &Inst) { 9455 CallBase &CB = cast<CallBase>(Inst); 9456 9457 auto &CBEdges = A.getAAFor<AACallEdges>( 9458 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9459 if (CBEdges.hasNonAsmUnknownCallee()) 9460 setHasUnknownCallee(true, Change); 9461 if (CBEdges.hasUnknownCallee()) 9462 setHasUnknownCallee(false, Change); 9463 9464 for (Function *F : CBEdges.getOptimisticEdges()) 9465 addCalledFunction(F, Change); 9466 9467 return true; 9468 }; 9469 9470 // Visit all callable instructions. 9471 bool UsedAssumedInformation = false; 9472 if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this, 9473 UsedAssumedInformation, 9474 /* CheckBBLivenessOnly */ true)) { 9475 // If we haven't looked at all call like instructions, assume that there 9476 // are unknown callees. 9477 setHasUnknownCallee(true, Change); 9478 } 9479 9480 return Change; 9481 } 9482 }; 9483 9484 struct AAFunctionReachabilityFunction : public AAFunctionReachability { 9485 private: 9486 struct QuerySet { 9487 void markReachable(const Function &Fn) { 9488 Reachable.insert(&Fn); 9489 Unreachable.erase(&Fn); 9490 } 9491 9492 /// If there is no information about the function None is returned. 9493 Optional<bool> isCachedReachable(const Function &Fn) { 9494 // Assume that we can reach the function. 9495 // TODO: Be more specific with the unknown callee. 9496 if (CanReachUnknownCallee) 9497 return true; 9498 9499 if (Reachable.count(&Fn)) 9500 return true; 9501 9502 if (Unreachable.count(&Fn)) 9503 return false; 9504 9505 return llvm::None; 9506 } 9507 9508 /// Set of functions that we know for sure is reachable. 9509 DenseSet<const Function *> Reachable; 9510 9511 /// Set of functions that are unreachable, but might become reachable. 9512 DenseSet<const Function *> Unreachable; 9513 9514 /// If we can reach a function with a call to a unknown function we assume 9515 /// that we can reach any function. 9516 bool CanReachUnknownCallee = false; 9517 }; 9518 9519 struct QueryResolver : public QuerySet { 9520 ChangeStatus update(Attributor &A, const AAFunctionReachability &AA, 9521 ArrayRef<const AACallEdges *> AAEdgesList) { 9522 ChangeStatus Change = ChangeStatus::UNCHANGED; 9523 9524 for (auto *AAEdges : AAEdgesList) { 9525 if (AAEdges->hasUnknownCallee()) { 9526 if (!CanReachUnknownCallee) { 9527 LLVM_DEBUG(dbgs() 9528 << "[QueryResolver] Edges include unknown callee!\n"); 9529 Change = ChangeStatus::CHANGED; 9530 } 9531 CanReachUnknownCallee = true; 9532 return Change; 9533 } 9534 } 9535 9536 for (const Function *Fn : make_early_inc_range(Unreachable)) { 9537 if (checkIfReachable(A, AA, AAEdgesList, *Fn)) { 9538 Change = ChangeStatus::CHANGED; 9539 markReachable(*Fn); 9540 } 9541 } 9542 return Change; 9543 } 9544 9545 bool isReachable(Attributor &A, AAFunctionReachability &AA, 9546 ArrayRef<const AACallEdges *> AAEdgesList, 9547 const Function &Fn) { 9548 Optional<bool> Cached = isCachedReachable(Fn); 9549 if (Cached) 9550 return Cached.value(); 9551 9552 // The query was not cached, thus it is new. We need to request an update 9553 // explicitly to make sure this the information is properly run to a 9554 // fixpoint. 9555 A.registerForUpdate(AA); 9556 9557 // We need to assume that this function can't reach Fn to prevent 9558 // an infinite loop if this function is recursive. 9559 Unreachable.insert(&Fn); 9560 9561 bool Result = checkIfReachable(A, AA, AAEdgesList, Fn); 9562 if (Result) 9563 markReachable(Fn); 9564 return Result; 9565 } 9566 9567 bool checkIfReachable(Attributor &A, const AAFunctionReachability &AA, 9568 ArrayRef<const AACallEdges *> AAEdgesList, 9569 const Function &Fn) const { 9570 9571 // Handle the most trivial case first. 9572 for (auto *AAEdges : AAEdgesList) { 9573 const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges(); 9574 9575 if (Edges.count(const_cast<Function *>(&Fn))) 9576 return true; 9577 } 9578 9579 SmallVector<const AAFunctionReachability *, 8> Deps; 9580 for (auto &AAEdges : AAEdgesList) { 9581 const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges(); 9582 9583 for (Function *Edge : Edges) { 9584 // Functions that do not call back into the module can be ignored. 9585 if (Edge->hasFnAttribute(Attribute::NoCallback)) 9586 continue; 9587 9588 // We don't need a dependency if the result is reachable. 9589 const AAFunctionReachability &EdgeReachability = 9590 A.getAAFor<AAFunctionReachability>( 9591 AA, IRPosition::function(*Edge), DepClassTy::NONE); 9592 Deps.push_back(&EdgeReachability); 9593 9594 if (EdgeReachability.canReach(A, Fn)) 9595 return true; 9596 } 9597 } 9598 9599 // The result is false for now, set dependencies and leave. 9600 for (auto *Dep : Deps) 9601 A.recordDependence(*Dep, AA, DepClassTy::REQUIRED); 9602 9603 return false; 9604 } 9605 }; 9606 9607 /// Get call edges that can be reached by this instruction. 9608 bool getReachableCallEdges(Attributor &A, const AAReachability &Reachability, 9609 const Instruction &Inst, 9610 SmallVector<const AACallEdges *> &Result) const { 9611 // Determine call like instructions that we can reach from the inst. 9612 auto CheckCallBase = [&](Instruction &CBInst) { 9613 if (!Reachability.isAssumedReachable(A, Inst, CBInst)) 9614 return true; 9615 9616 auto &CB = cast<CallBase>(CBInst); 9617 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9618 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9619 9620 Result.push_back(&AAEdges); 9621 return true; 9622 }; 9623 9624 bool UsedAssumedInformation = false; 9625 return A.checkForAllCallLikeInstructions(CheckCallBase, *this, 9626 UsedAssumedInformation, 9627 /* CheckBBLivenessOnly */ true); 9628 } 9629 9630 public: 9631 AAFunctionReachabilityFunction(const IRPosition &IRP, Attributor &A) 9632 : AAFunctionReachability(IRP, A) {} 9633 9634 bool canReach(Attributor &A, const Function &Fn) const override { 9635 if (!isValidState()) 9636 return true; 9637 9638 const AACallEdges &AAEdges = 9639 A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED); 9640 9641 // Attributor returns attributes as const, so this function has to be 9642 // const for users of this attribute to use it without having to do 9643 // a const_cast. 9644 // This is a hack for us to be able to cache queries. 9645 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9646 bool Result = NonConstThis->WholeFunction.isReachable(A, *NonConstThis, 9647 {&AAEdges}, Fn); 9648 9649 return Result; 9650 } 9651 9652 /// Can \p CB reach \p Fn 9653 bool canReach(Attributor &A, CallBase &CB, 9654 const Function &Fn) const override { 9655 if (!isValidState()) 9656 return true; 9657 9658 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9659 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9660 9661 // Attributor returns attributes as const, so this function has to be 9662 // const for users of this attribute to use it without having to do 9663 // a const_cast. 9664 // This is a hack for us to be able to cache queries. 9665 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9666 QueryResolver &CBQuery = NonConstThis->CBQueries[&CB]; 9667 9668 bool Result = CBQuery.isReachable(A, *NonConstThis, {&AAEdges}, Fn); 9669 9670 return Result; 9671 } 9672 9673 bool instructionCanReach(Attributor &A, const Instruction &Inst, 9674 const Function &Fn) const override { 9675 if (!isValidState()) 9676 return true; 9677 9678 const auto &Reachability = A.getAAFor<AAReachability>( 9679 *this, IRPosition::function(*getAssociatedFunction()), 9680 DepClassTy::REQUIRED); 9681 9682 SmallVector<const AACallEdges *> CallEdges; 9683 bool AllKnown = getReachableCallEdges(A, Reachability, Inst, CallEdges); 9684 // Attributor returns attributes as const, so this function has to be 9685 // const for users of this attribute to use it without having to do 9686 // a const_cast. 9687 // This is a hack for us to be able to cache queries. 9688 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9689 QueryResolver &InstQSet = NonConstThis->InstQueries[&Inst]; 9690 if (!AllKnown) { 9691 LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges known, " 9692 "may reach unknown callee!\n"); 9693 InstQSet.CanReachUnknownCallee = true; 9694 } 9695 9696 return InstQSet.isReachable(A, *NonConstThis, CallEdges, Fn); 9697 } 9698 9699 /// See AbstractAttribute::updateImpl(...). 9700 ChangeStatus updateImpl(Attributor &A) override { 9701 const AACallEdges &AAEdges = 9702 A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED); 9703 ChangeStatus Change = ChangeStatus::UNCHANGED; 9704 9705 Change |= WholeFunction.update(A, *this, {&AAEdges}); 9706 9707 for (auto &CBPair : CBQueries) { 9708 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9709 *this, IRPosition::callsite_function(*CBPair.first), 9710 DepClassTy::REQUIRED); 9711 9712 Change |= CBPair.second.update(A, *this, {&AAEdges}); 9713 } 9714 9715 // Update the Instruction queries. 9716 if (!InstQueries.empty()) { 9717 const AAReachability *Reachability = &A.getAAFor<AAReachability>( 9718 *this, IRPosition::function(*getAssociatedFunction()), 9719 DepClassTy::REQUIRED); 9720 9721 // Check for local callbases first. 9722 for (auto &InstPair : InstQueries) { 9723 SmallVector<const AACallEdges *> CallEdges; 9724 bool AllKnown = 9725 getReachableCallEdges(A, *Reachability, *InstPair.first, CallEdges); 9726 // Update will return change if we this effects any queries. 9727 if (!AllKnown) { 9728 LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges " 9729 "known, may reach unknown callee!\n"); 9730 InstPair.second.CanReachUnknownCallee = true; 9731 } 9732 Change |= InstPair.second.update(A, *this, CallEdges); 9733 } 9734 } 9735 9736 return Change; 9737 } 9738 9739 const std::string getAsStr() const override { 9740 size_t QueryCount = 9741 WholeFunction.Reachable.size() + WholeFunction.Unreachable.size(); 9742 9743 return "FunctionReachability [" + 9744 (canReachUnknownCallee() 9745 ? "unknown" 9746 : (std::to_string(WholeFunction.Reachable.size()) + "," + 9747 std::to_string(QueryCount))) + 9748 "]"; 9749 } 9750 9751 void trackStatistics() const override {} 9752 9753 private: 9754 bool canReachUnknownCallee() const override { 9755 return WholeFunction.CanReachUnknownCallee; 9756 } 9757 9758 /// Used to answer if a the whole function can reacha a specific function. 9759 QueryResolver WholeFunction; 9760 9761 /// Used to answer if a call base inside this function can reach a specific 9762 /// function. 9763 MapVector<const CallBase *, QueryResolver> CBQueries; 9764 9765 /// This is for instruction queries than scan "forward". 9766 MapVector<const Instruction *, QueryResolver> InstQueries; 9767 }; 9768 } // namespace 9769 9770 template <typename AAType> 9771 static Optional<Constant *> 9772 askForAssumedConstant(Attributor &A, const AbstractAttribute &QueryingAA, 9773 const IRPosition &IRP, Type &Ty) { 9774 if (!Ty.isIntegerTy()) 9775 return nullptr; 9776 9777 // This will also pass the call base context. 9778 const auto &AA = A.getAAFor<AAType>(QueryingAA, IRP, DepClassTy::NONE); 9779 9780 Optional<Constant *> COpt = AA.getAssumedConstant(A); 9781 9782 if (!COpt.has_value()) { 9783 A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL); 9784 return llvm::None; 9785 } 9786 if (auto *C = COpt.value()) { 9787 A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL); 9788 return C; 9789 } 9790 return nullptr; 9791 } 9792 9793 Value *AAPotentialValues::getSingleValue( 9794 Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP, 9795 SmallVectorImpl<AA::ValueAndContext> &Values) { 9796 Type &Ty = *IRP.getAssociatedType(); 9797 Optional<Value *> V; 9798 for (auto &It : Values) { 9799 V = AA::combineOptionalValuesInAAValueLatice(V, It.getValue(), &Ty); 9800 if (V.has_value() && !V.value()) 9801 break; 9802 } 9803 if (!V.has_value()) 9804 return UndefValue::get(&Ty); 9805 return V.value(); 9806 } 9807 9808 namespace { 9809 struct AAPotentialValuesImpl : AAPotentialValues { 9810 using StateType = PotentialLLVMValuesState; 9811 9812 AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A) 9813 : AAPotentialValues(IRP, A) {} 9814 9815 /// See AbstractAttribute::initialize(..). 9816 void initialize(Attributor &A) override { 9817 if (A.hasSimplificationCallback(getIRPosition())) { 9818 indicatePessimisticFixpoint(); 9819 return; 9820 } 9821 Value *Stripped = getAssociatedValue().stripPointerCasts(); 9822 if (isa<Constant>(Stripped)) { 9823 addValue(A, getState(), *Stripped, getCtxI(), AA::AnyScope, 9824 getAnchorScope()); 9825 indicateOptimisticFixpoint(); 9826 return; 9827 } 9828 AAPotentialValues::initialize(A); 9829 } 9830 9831 /// See AbstractAttribute::getAsStr(). 9832 const std::string getAsStr() const override { 9833 std::string Str; 9834 llvm::raw_string_ostream OS(Str); 9835 OS << getState(); 9836 return OS.str(); 9837 } 9838 9839 template <typename AAType> 9840 static Optional<Value *> askOtherAA(Attributor &A, 9841 const AbstractAttribute &AA, 9842 const IRPosition &IRP, Type &Ty) { 9843 if (isa<Constant>(IRP.getAssociatedValue())) 9844 return &IRP.getAssociatedValue(); 9845 Optional<Constant *> C = askForAssumedConstant<AAType>(A, AA, IRP, Ty); 9846 if (!C) 9847 return llvm::None; 9848 if (C.value()) 9849 if (auto *CC = AA::getWithType(**C, Ty)) 9850 return CC; 9851 return nullptr; 9852 } 9853 9854 void addValue(Attributor &A, StateType &State, Value &V, 9855 const Instruction *CtxI, AA::ValueScope S, 9856 Function *AnchorScope) const { 9857 9858 IRPosition ValIRP = IRPosition::value(V); 9859 if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) { 9860 for (auto &U : CB->args()) { 9861 if (U.get() != &V) 9862 continue; 9863 ValIRP = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 9864 break; 9865 } 9866 } 9867 9868 Value *VPtr = &V; 9869 if (ValIRP.getAssociatedType()->isIntegerTy()) { 9870 Type &Ty = *getAssociatedType(); 9871 Optional<Value *> SimpleV = 9872 askOtherAA<AAValueConstantRange>(A, *this, ValIRP, Ty); 9873 if (SimpleV.has_value() && !SimpleV.value()) { 9874 auto &PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>( 9875 *this, ValIRP, DepClassTy::OPTIONAL); 9876 if (PotentialConstantsAA.isValidState()) { 9877 for (auto &It : PotentialConstantsAA.getAssumedSet()) { 9878 State.unionAssumed({{*ConstantInt::get(&Ty, It), nullptr}, S}); 9879 } 9880 assert(!PotentialConstantsAA.undefIsContained() && 9881 "Undef should be an explicit value!"); 9882 return; 9883 } 9884 } 9885 if (!SimpleV.has_value()) 9886 return; 9887 9888 if (SimpleV.value()) 9889 VPtr = SimpleV.value(); 9890 } 9891 9892 if (isa<ConstantInt>(VPtr)) 9893 CtxI = nullptr; 9894 if (!AA::isValidInScope(*VPtr, AnchorScope)) 9895 S = AA::ValueScope(S | AA::Interprocedural); 9896 9897 State.unionAssumed({{*VPtr, CtxI}, S}); 9898 } 9899 9900 /// Helper struct to tie a value+context pair together with the scope for 9901 /// which this is the simplified version. 9902 struct ItemInfo { 9903 AA::ValueAndContext I; 9904 AA::ValueScope S; 9905 }; 9906 9907 bool recurseForValue(Attributor &A, const IRPosition &IRP, AA::ValueScope S) { 9908 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap; 9909 for (auto CS : {AA::Intraprocedural, AA::Interprocedural}) { 9910 if (!(CS & S)) 9911 continue; 9912 9913 bool UsedAssumedInformation = false; 9914 SmallVector<AA::ValueAndContext> Values; 9915 if (!A.getAssumedSimplifiedValues(IRP, this, Values, CS, 9916 UsedAssumedInformation)) 9917 return false; 9918 9919 for (auto &It : Values) 9920 ValueScopeMap[It] += CS; 9921 } 9922 for (auto &It : ValueScopeMap) 9923 addValue(A, getState(), *It.first.getValue(), It.first.getCtxI(), 9924 AA::ValueScope(It.second), getAnchorScope()); 9925 9926 return true; 9927 } 9928 9929 void giveUpOnIntraprocedural(Attributor &A) { 9930 auto NewS = StateType::getBestState(getState()); 9931 for (auto &It : getAssumedSet()) { 9932 if (It.second == AA::Intraprocedural) 9933 continue; 9934 addValue(A, NewS, *It.first.getValue(), It.first.getCtxI(), 9935 AA::Interprocedural, getAnchorScope()); 9936 } 9937 assert(!undefIsContained() && "Undef should be an explicit value!"); 9938 addValue(A, NewS, getAssociatedValue(), getCtxI(), AA::Intraprocedural, 9939 getAnchorScope()); 9940 getState() = NewS; 9941 } 9942 9943 /// See AbstractState::indicatePessimisticFixpoint(...). 9944 ChangeStatus indicatePessimisticFixpoint() override { 9945 getState() = StateType::getBestState(getState()); 9946 getState().unionAssumed({{getAssociatedValue(), getCtxI()}, AA::AnyScope}); 9947 AAPotentialValues::indicateOptimisticFixpoint(); 9948 return ChangeStatus::CHANGED; 9949 } 9950 9951 /// See AbstractAttribute::updateImpl(...). 9952 ChangeStatus updateImpl(Attributor &A) override { 9953 return indicatePessimisticFixpoint(); 9954 } 9955 9956 /// See AbstractAttribute::manifest(...). 9957 ChangeStatus manifest(Attributor &A) override { 9958 SmallVector<AA::ValueAndContext> Values; 9959 for (AA::ValueScope S : {AA::Interprocedural, AA::Intraprocedural}) { 9960 Values.clear(); 9961 if (!getAssumedSimplifiedValues(A, Values, S)) 9962 continue; 9963 Value &OldV = getAssociatedValue(); 9964 if (isa<UndefValue>(OldV)) 9965 continue; 9966 Value *NewV = getSingleValue(A, *this, getIRPosition(), Values); 9967 if (!NewV || NewV == &OldV) 9968 continue; 9969 if (getCtxI() && 9970 !AA::isValidAtPosition({*NewV, *getCtxI()}, A.getInfoCache())) 9971 continue; 9972 if (A.changeAfterManifest(getIRPosition(), *NewV)) 9973 return ChangeStatus::CHANGED; 9974 } 9975 return ChangeStatus::UNCHANGED; 9976 } 9977 9978 bool getAssumedSimplifiedValues(Attributor &A, 9979 SmallVectorImpl<AA::ValueAndContext> &Values, 9980 AA::ValueScope S) const override { 9981 if (!isValidState()) 9982 return false; 9983 for (auto &It : getAssumedSet()) 9984 if (It.second & S) 9985 Values.push_back(It.first); 9986 assert(!undefIsContained() && "Undef should be an explicit value!"); 9987 return true; 9988 } 9989 }; 9990 9991 struct AAPotentialValuesFloating : AAPotentialValuesImpl { 9992 AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A) 9993 : AAPotentialValuesImpl(IRP, A) {} 9994 9995 /// See AbstractAttribute::updateImpl(...). 9996 ChangeStatus updateImpl(Attributor &A) override { 9997 auto AssumedBefore = getAssumed(); 9998 9999 genericValueTraversal(A); 10000 10001 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10002 : ChangeStatus::CHANGED; 10003 } 10004 10005 /// Helper struct to remember which AAIsDead instances we actually used. 10006 struct LivenessInfo { 10007 const AAIsDead *LivenessAA = nullptr; 10008 bool AnyDead = false; 10009 }; 10010 10011 /// Check if \p Cmp is a comparison we can simplify. 10012 /// 10013 /// We handle multiple cases, one in which at least one operand is an 10014 /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other 10015 /// operand. Return true if successful, in that case Worklist will be updated. 10016 bool handleCmp(Attributor &A, CmpInst &Cmp, ItemInfo II, 10017 SmallVectorImpl<ItemInfo> &Worklist) { 10018 Value *LHS = Cmp.getOperand(0); 10019 Value *RHS = Cmp.getOperand(1); 10020 10021 // Simplify the operands first. 10022 bool UsedAssumedInformation = false; 10023 const auto &SimplifiedLHS = A.getAssumedSimplified( 10024 IRPosition::value(*LHS, getCallBaseContext()), *this, 10025 UsedAssumedInformation, AA::Intraprocedural); 10026 if (!SimplifiedLHS.has_value()) 10027 return true; 10028 if (!SimplifiedLHS.value()) 10029 return false; 10030 LHS = *SimplifiedLHS; 10031 10032 const auto &SimplifiedRHS = A.getAssumedSimplified( 10033 IRPosition::value(*RHS, getCallBaseContext()), *this, 10034 UsedAssumedInformation, AA::Intraprocedural); 10035 if (!SimplifiedRHS.has_value()) 10036 return true; 10037 if (!SimplifiedRHS.value()) 10038 return false; 10039 RHS = *SimplifiedRHS; 10040 10041 LLVMContext &Ctx = Cmp.getContext(); 10042 // Handle the trivial case first in which we don't even need to think about 10043 // null or non-null. 10044 if (LHS == RHS && (Cmp.isTrueWhenEqual() || Cmp.isFalseWhenEqual())) { 10045 Constant *NewV = 10046 ConstantInt::get(Type::getInt1Ty(Ctx), Cmp.isTrueWhenEqual()); 10047 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S, 10048 getAnchorScope()); 10049 return true; 10050 } 10051 10052 // From now on we only handle equalities (==, !=). 10053 ICmpInst *ICmp = dyn_cast<ICmpInst>(&Cmp); 10054 if (!ICmp || !ICmp->isEquality()) 10055 return false; 10056 10057 bool LHSIsNull = isa<ConstantPointerNull>(LHS); 10058 bool RHSIsNull = isa<ConstantPointerNull>(RHS); 10059 if (!LHSIsNull && !RHSIsNull) 10060 return false; 10061 10062 // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the 10063 // non-nullptr operand and if we assume it's non-null we can conclude the 10064 // result of the comparison. 10065 assert((LHSIsNull || RHSIsNull) && 10066 "Expected nullptr versus non-nullptr comparison at this point"); 10067 10068 // The index is the operand that we assume is not null. 10069 unsigned PtrIdx = LHSIsNull; 10070 auto &PtrNonNullAA = A.getAAFor<AANonNull>( 10071 *this, IRPosition::value(*ICmp->getOperand(PtrIdx)), 10072 DepClassTy::REQUIRED); 10073 if (!PtrNonNullAA.isAssumedNonNull()) 10074 return false; 10075 10076 // The new value depends on the predicate, true for != and false for ==. 10077 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx), 10078 ICmp->getPredicate() == CmpInst::ICMP_NE); 10079 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S, getAnchorScope()); 10080 return true; 10081 } 10082 10083 bool handleSelectInst(Attributor &A, SelectInst &SI, ItemInfo II, 10084 SmallVectorImpl<ItemInfo> &Worklist) { 10085 const Instruction *CtxI = II.I.getCtxI(); 10086 bool UsedAssumedInformation = false; 10087 10088 Optional<Constant *> C = 10089 A.getAssumedConstant(*SI.getCondition(), *this, UsedAssumedInformation); 10090 bool NoValueYet = !C.has_value(); 10091 if (NoValueYet || isa_and_nonnull<UndefValue>(*C)) 10092 return true; 10093 if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) { 10094 if (CI->isZero()) 10095 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S}); 10096 else 10097 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S}); 10098 } else { 10099 // We could not simplify the condition, assume both values. 10100 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S}); 10101 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S}); 10102 } 10103 return true; 10104 } 10105 10106 bool handleLoadInst(Attributor &A, LoadInst &LI, ItemInfo II, 10107 SmallVectorImpl<ItemInfo> &Worklist) { 10108 SmallSetVector<Value *, 4> PotentialCopies; 10109 SmallSetVector<Instruction *, 4> PotentialValueOrigins; 10110 bool UsedAssumedInformation = false; 10111 if (!AA::getPotentiallyLoadedValues(A, LI, PotentialCopies, 10112 PotentialValueOrigins, *this, 10113 UsedAssumedInformation, 10114 /* OnlyExact */ true)) { 10115 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Failed to get potentially " 10116 "loaded values for load instruction " 10117 << LI << "\n"); 10118 return false; 10119 } 10120 10121 // Do not simplify loads that are only used in llvm.assume if we cannot also 10122 // remove all stores that may feed into the load. The reason is that the 10123 // assume is probably worth something as long as the stores are around. 10124 InformationCache &InfoCache = A.getInfoCache(); 10125 if (InfoCache.isOnlyUsedByAssume(LI)) { 10126 if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) { 10127 if (!I) 10128 return true; 10129 if (auto *SI = dyn_cast<StoreInst>(I)) 10130 return A.isAssumedDead(SI->getOperandUse(0), this, 10131 /* LivenessAA */ nullptr, 10132 UsedAssumedInformation, 10133 /* CheckBBLivenessOnly */ false); 10134 return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr, 10135 UsedAssumedInformation, 10136 /* CheckBBLivenessOnly */ false); 10137 })) { 10138 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Load is onl used by assumes " 10139 "and we cannot delete all the stores: " 10140 << LI << "\n"); 10141 return false; 10142 } 10143 } 10144 10145 // Values have to be dynamically unique or we loose the fact that a 10146 // single llvm::Value might represent two runtime values (e.g., 10147 // stack locations in different recursive calls). 10148 const Instruction *CtxI = II.I.getCtxI(); 10149 bool ScopeIsLocal = (II.S & AA::Intraprocedural); 10150 bool AllLocal = ScopeIsLocal; 10151 bool DynamicallyUnique = llvm::all_of(PotentialCopies, [&](Value *PC) { 10152 AllLocal &= AA::isValidInScope(*PC, getAnchorScope()); 10153 return AA::isDynamicallyUnique(A, *this, *PC); 10154 }); 10155 if (!DynamicallyUnique) { 10156 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Not all potentially loaded " 10157 "values are dynamically unique: " 10158 << LI << "\n"); 10159 return false; 10160 } 10161 10162 for (auto *PotentialCopy : PotentialCopies) { 10163 if (AllLocal) { 10164 Worklist.push_back({{*PotentialCopy, CtxI}, II.S}); 10165 } else { 10166 Worklist.push_back({{*PotentialCopy, CtxI}, AA::Interprocedural}); 10167 } 10168 } 10169 if (!AllLocal && ScopeIsLocal) 10170 addValue(A, getState(), LI, CtxI, AA::Intraprocedural, getAnchorScope()); 10171 return true; 10172 } 10173 10174 bool handlePHINode( 10175 Attributor &A, PHINode &PHI, ItemInfo II, 10176 SmallVectorImpl<ItemInfo> &Worklist, 10177 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) { 10178 auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & { 10179 LivenessInfo &LI = LivenessAAs[&F]; 10180 if (!LI.LivenessAA) 10181 LI.LivenessAA = &A.getAAFor<AAIsDead>(*this, IRPosition::function(F), 10182 DepClassTy::NONE); 10183 return LI; 10184 }; 10185 10186 LivenessInfo &LI = GetLivenessInfo(*PHI.getFunction()); 10187 for (unsigned u = 0, e = PHI.getNumIncomingValues(); u < e; u++) { 10188 BasicBlock *IncomingBB = PHI.getIncomingBlock(u); 10189 if (LI.LivenessAA->isEdgeDead(IncomingBB, PHI.getParent())) { 10190 LI.AnyDead = true; 10191 continue; 10192 } 10193 Worklist.push_back( 10194 {{*PHI.getIncomingValue(u), IncomingBB->getTerminator()}, II.S}); 10195 } 10196 return true; 10197 } 10198 10199 /// Use the generic, non-optimistic InstSimplfy functionality if we managed to 10200 /// simplify any operand of the instruction \p I. Return true if successful, 10201 /// in that case Worklist will be updated. 10202 bool handleGenericInst(Attributor &A, Instruction &I, ItemInfo II, 10203 SmallVectorImpl<ItemInfo> &Worklist) { 10204 bool SomeSimplified = false; 10205 bool UsedAssumedInformation = false; 10206 10207 SmallVector<Value *, 8> NewOps(I.getNumOperands()); 10208 int Idx = 0; 10209 for (Value *Op : I.operands()) { 10210 const auto &SimplifiedOp = A.getAssumedSimplified( 10211 IRPosition::value(*Op, getCallBaseContext()), *this, 10212 UsedAssumedInformation, AA::Intraprocedural); 10213 // If we are not sure about any operand we are not sure about the entire 10214 // instruction, we'll wait. 10215 if (!SimplifiedOp.has_value()) 10216 return true; 10217 10218 if (SimplifiedOp.value()) 10219 NewOps[Idx] = SimplifiedOp.value(); 10220 else 10221 NewOps[Idx] = Op; 10222 10223 SomeSimplified |= (NewOps[Idx] != Op); 10224 ++Idx; 10225 } 10226 10227 // We won't bother with the InstSimplify interface if we didn't simplify any 10228 // operand ourselves. 10229 if (!SomeSimplified) 10230 return false; 10231 10232 InformationCache &InfoCache = A.getInfoCache(); 10233 Function *F = I.getFunction(); 10234 const auto *DT = 10235 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F); 10236 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 10237 auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F); 10238 OptimizationRemarkEmitter *ORE = nullptr; 10239 10240 const DataLayout &DL = I.getModule()->getDataLayout(); 10241 SimplifyQuery Q(DL, TLI, DT, AC, &I); 10242 Value *NewV = simplifyInstructionWithOperands(&I, NewOps, Q, ORE); 10243 if (!NewV || NewV == &I) 10244 return false; 10245 10246 LLVM_DEBUG(dbgs() << "Generic inst " << I << " assumed simplified to " 10247 << *NewV << "\n"); 10248 Worklist.push_back({{*NewV, II.I.getCtxI()}, II.S}); 10249 return true; 10250 } 10251 10252 bool simplifyInstruction( 10253 Attributor &A, Instruction &I, ItemInfo II, 10254 SmallVectorImpl<ItemInfo> &Worklist, 10255 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) { 10256 if (auto *CI = dyn_cast<CmpInst>(&I)) 10257 if (handleCmp(A, *CI, II, Worklist)) 10258 return true; 10259 10260 switch (I.getOpcode()) { 10261 case Instruction::Select: 10262 return handleSelectInst(A, cast<SelectInst>(I), II, Worklist); 10263 case Instruction::PHI: 10264 return handlePHINode(A, cast<PHINode>(I), II, Worklist, LivenessAAs); 10265 case Instruction::Load: 10266 return handleLoadInst(A, cast<LoadInst>(I), II, Worklist); 10267 default: 10268 return handleGenericInst(A, I, II, Worklist); 10269 }; 10270 return false; 10271 } 10272 10273 void genericValueTraversal(Attributor &A) { 10274 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs; 10275 10276 Value *InitialV = &getAssociatedValue(); 10277 SmallSet<AA::ValueAndContext, 16> Visited; 10278 SmallVector<ItemInfo, 16> Worklist; 10279 Worklist.push_back({{*InitialV, getCtxI()}, AA::AnyScope}); 10280 10281 int Iteration = 0; 10282 do { 10283 ItemInfo II = Worklist.pop_back_val(); 10284 Value *V = II.I.getValue(); 10285 assert(V); 10286 const Instruction *CtxI = II.I.getCtxI(); 10287 AA::ValueScope S = II.S; 10288 10289 // Check if we should process the current value. To prevent endless 10290 // recursion keep a record of the values we followed! 10291 if (!Visited.insert(II.I).second) 10292 continue; 10293 10294 // Make sure we limit the compile time for complex expressions. 10295 if (Iteration++ >= MaxPotentialValuesIterations) { 10296 LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: " 10297 << Iteration << "!\n"); 10298 addValue(A, getState(), *V, CtxI, S, getAnchorScope()); 10299 continue; 10300 } 10301 10302 // Explicitly look through calls with a "returned" attribute if we do 10303 // not have a pointer as stripPointerCasts only works on them. 10304 Value *NewV = nullptr; 10305 if (V->getType()->isPointerTy()) { 10306 NewV = AA::getWithType(*V->stripPointerCasts(), *V->getType()); 10307 } else { 10308 auto *CB = dyn_cast<CallBase>(V); 10309 if (CB && CB->getCalledFunction()) { 10310 for (Argument &Arg : CB->getCalledFunction()->args()) 10311 if (Arg.hasReturnedAttr()) { 10312 NewV = CB->getArgOperand(Arg.getArgNo()); 10313 break; 10314 } 10315 } 10316 } 10317 if (NewV && NewV != V) { 10318 Worklist.push_back({{*NewV, CtxI}, S}); 10319 continue; 10320 } 10321 10322 if (auto *I = dyn_cast<Instruction>(V)) { 10323 if (simplifyInstruction(A, *I, II, Worklist, LivenessAAs)) 10324 continue; 10325 } 10326 10327 if (V != InitialV || isa<Argument>(V)) 10328 if (recurseForValue(A, IRPosition::value(*V), II.S)) 10329 continue; 10330 10331 // If we haven't stripped anything we give up. 10332 if (V == InitialV && CtxI == getCtxI()) { 10333 indicatePessimisticFixpoint(); 10334 return; 10335 } 10336 10337 addValue(A, getState(), *V, CtxI, S, getAnchorScope()); 10338 } while (!Worklist.empty()); 10339 10340 // If we actually used liveness information so we have to record a 10341 // dependence. 10342 for (auto &It : LivenessAAs) 10343 if (It.second.AnyDead) 10344 A.recordDependence(*It.second.LivenessAA, *this, DepClassTy::OPTIONAL); 10345 } 10346 10347 /// See AbstractAttribute::trackStatistics() 10348 void trackStatistics() const override { 10349 STATS_DECLTRACK_FLOATING_ATTR(potential_values) 10350 } 10351 }; 10352 10353 struct AAPotentialValuesArgument final : AAPotentialValuesImpl { 10354 using Base = AAPotentialValuesImpl; 10355 AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A) 10356 : Base(IRP, A) {} 10357 10358 /// See AbstractAttribute::initialize(..). 10359 void initialize(Attributor &A) override { 10360 auto &Arg = cast<Argument>(getAssociatedValue()); 10361 if (Arg.hasPointeeInMemoryValueAttr()) 10362 indicatePessimisticFixpoint(); 10363 } 10364 10365 /// See AbstractAttribute::updateImpl(...). 10366 ChangeStatus updateImpl(Attributor &A) override { 10367 auto AssumedBefore = getAssumed(); 10368 10369 unsigned CSArgNo = getCallSiteArgNo(); 10370 10371 bool UsedAssumedInformation = false; 10372 SmallVector<AA::ValueAndContext> Values; 10373 auto CallSitePred = [&](AbstractCallSite ACS) { 10374 const auto CSArgIRP = IRPosition::callsite_argument(ACS, CSArgNo); 10375 if (CSArgIRP.getPositionKind() == IRP_INVALID) 10376 return false; 10377 10378 if (!A.getAssumedSimplifiedValues(CSArgIRP, this, Values, 10379 AA::Interprocedural, 10380 UsedAssumedInformation)) 10381 return false; 10382 10383 return isValidState(); 10384 }; 10385 10386 if (!A.checkForAllCallSites(CallSitePred, *this, 10387 /* RequireAllCallSites */ true, 10388 UsedAssumedInformation)) 10389 return indicatePessimisticFixpoint(); 10390 10391 Function *Fn = getAssociatedFunction(); 10392 bool AnyNonLocal = false; 10393 for (auto &It : Values) { 10394 if (isa<Constant>(It.getValue())) { 10395 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope, 10396 getAnchorScope()); 10397 continue; 10398 } 10399 if (!AA::isDynamicallyUnique(A, *this, *It.getValue())) 10400 return indicatePessimisticFixpoint(); 10401 10402 if (auto *Arg = dyn_cast<Argument>(It.getValue())) 10403 if (Arg->getParent() == Fn) { 10404 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope, 10405 getAnchorScope()); 10406 continue; 10407 } 10408 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::Interprocedural, 10409 getAnchorScope()); 10410 AnyNonLocal = true; 10411 } 10412 if (undefIsContained()) 10413 unionAssumedWithUndef(); 10414 if (AnyNonLocal) 10415 giveUpOnIntraprocedural(A); 10416 10417 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10418 : ChangeStatus::CHANGED; 10419 } 10420 10421 /// See AbstractAttribute::trackStatistics() 10422 void trackStatistics() const override { 10423 STATS_DECLTRACK_ARG_ATTR(potential_values) 10424 } 10425 }; 10426 10427 struct AAPotentialValuesReturned 10428 : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> { 10429 using Base = 10430 AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>; 10431 AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A) 10432 : Base(IRP, A) {} 10433 10434 /// See AbstractAttribute::initialize(..). 10435 void initialize(Attributor &A) override { 10436 if (A.hasSimplificationCallback(getIRPosition())) 10437 indicatePessimisticFixpoint(); 10438 else 10439 AAPotentialValues::initialize(A); 10440 } 10441 10442 ChangeStatus manifest(Attributor &A) override { 10443 // We queried AAValueSimplify for the returned values so they will be 10444 // replaced if a simplified form was found. Nothing to do here. 10445 return ChangeStatus::UNCHANGED; 10446 } 10447 10448 ChangeStatus indicatePessimisticFixpoint() override { 10449 return AAPotentialValues::indicatePessimisticFixpoint(); 10450 } 10451 10452 /// See AbstractAttribute::trackStatistics() 10453 void trackStatistics() const override { 10454 STATS_DECLTRACK_FNRET_ATTR(potential_values) 10455 } 10456 }; 10457 10458 struct AAPotentialValuesFunction : AAPotentialValuesImpl { 10459 AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A) 10460 : AAPotentialValuesImpl(IRP, A) {} 10461 10462 /// See AbstractAttribute::updateImpl(...). 10463 ChangeStatus updateImpl(Attributor &A) override { 10464 llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will " 10465 "not be called"); 10466 } 10467 10468 /// See AbstractAttribute::trackStatistics() 10469 void trackStatistics() const override { 10470 STATS_DECLTRACK_FN_ATTR(potential_values) 10471 } 10472 }; 10473 10474 struct AAPotentialValuesCallSite : AAPotentialValuesFunction { 10475 AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A) 10476 : AAPotentialValuesFunction(IRP, A) {} 10477 10478 /// See AbstractAttribute::trackStatistics() 10479 void trackStatistics() const override { 10480 STATS_DECLTRACK_CS_ATTR(potential_values) 10481 } 10482 }; 10483 10484 struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl { 10485 AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A) 10486 : AAPotentialValuesImpl(IRP, A) {} 10487 10488 /// See AbstractAttribute::updateImpl(...). 10489 ChangeStatus updateImpl(Attributor &A) override { 10490 auto AssumedBefore = getAssumed(); 10491 10492 Function *Callee = getAssociatedFunction(); 10493 if (!Callee) 10494 return indicatePessimisticFixpoint(); 10495 10496 bool UsedAssumedInformation = false; 10497 auto *CB = cast<CallBase>(getCtxI()); 10498 if (CB->isMustTailCall() && 10499 !A.isAssumedDead(IRPosition::inst(*CB), this, nullptr, 10500 UsedAssumedInformation)) 10501 return indicatePessimisticFixpoint(); 10502 10503 SmallVector<AA::ValueAndContext> Values; 10504 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this, 10505 Values, AA::Intraprocedural, 10506 UsedAssumedInformation)) 10507 return indicatePessimisticFixpoint(); 10508 10509 Function *Caller = CB->getCaller(); 10510 10511 bool AnyNonLocal = false; 10512 for (auto &It : Values) { 10513 Value *V = It.getValue(); 10514 Optional<Value *> CallerV = A.translateArgumentToCallSiteContent( 10515 V, *CB, *this, UsedAssumedInformation); 10516 if (!CallerV.has_value()) { 10517 // Nothing to do as long as no value was determined. 10518 continue; 10519 } 10520 V = CallerV.value() ? CallerV.value() : V; 10521 if (AA::isDynamicallyUnique(A, *this, *V) && 10522 AA::isValidInScope(*V, Caller)) { 10523 if (CallerV.value()) { 10524 SmallVector<AA::ValueAndContext> ArgValues; 10525 IRPosition IRP = IRPosition::value(*V); 10526 if (auto *Arg = dyn_cast<Argument>(V)) 10527 if (Arg->getParent() == CB->getCalledFunction()) 10528 IRP = IRPosition::callsite_argument(*CB, Arg->getArgNo()); 10529 if (recurseForValue(A, IRP, AA::AnyScope)) 10530 continue; 10531 } 10532 addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope()); 10533 } else { 10534 AnyNonLocal = true; 10535 break; 10536 } 10537 } 10538 if (AnyNonLocal) { 10539 Values.clear(); 10540 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this, 10541 Values, AA::Interprocedural, 10542 UsedAssumedInformation)) 10543 return indicatePessimisticFixpoint(); 10544 AnyNonLocal = false; 10545 getState() = PotentialLLVMValuesState::getBestState(); 10546 for (auto &It : Values) { 10547 Value *V = It.getValue(); 10548 if (!AA::isDynamicallyUnique(A, *this, *V)) 10549 return indicatePessimisticFixpoint(); 10550 if (AA::isValidInScope(*V, Caller)) { 10551 addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope()); 10552 } else { 10553 AnyNonLocal = true; 10554 addValue(A, getState(), *V, CB, AA::Interprocedural, 10555 getAnchorScope()); 10556 } 10557 } 10558 if (AnyNonLocal) 10559 giveUpOnIntraprocedural(A); 10560 } 10561 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10562 : ChangeStatus::CHANGED; 10563 } 10564 10565 ChangeStatus indicatePessimisticFixpoint() override { 10566 return AAPotentialValues::indicatePessimisticFixpoint(); 10567 } 10568 10569 /// See AbstractAttribute::trackStatistics() 10570 void trackStatistics() const override { 10571 STATS_DECLTRACK_CSRET_ATTR(potential_values) 10572 } 10573 }; 10574 10575 struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating { 10576 AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A) 10577 : AAPotentialValuesFloating(IRP, A) {} 10578 10579 /// See AbstractAttribute::trackStatistics() 10580 void trackStatistics() const override { 10581 STATS_DECLTRACK_CSARG_ATTR(potential_values) 10582 } 10583 }; 10584 } // namespace 10585 10586 /// ---------------------- Assumption Propagation ------------------------------ 10587 namespace { 10588 struct AAAssumptionInfoImpl : public AAAssumptionInfo { 10589 AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A, 10590 const DenseSet<StringRef> &Known) 10591 : AAAssumptionInfo(IRP, A, Known) {} 10592 10593 bool hasAssumption(const StringRef Assumption) const override { 10594 return isValidState() && setContains(Assumption); 10595 } 10596 10597 /// See AbstractAttribute::getAsStr() 10598 const std::string getAsStr() const override { 10599 const SetContents &Known = getKnown(); 10600 const SetContents &Assumed = getAssumed(); 10601 10602 const std::string KnownStr = 10603 llvm::join(Known.getSet().begin(), Known.getSet().end(), ","); 10604 const std::string AssumedStr = 10605 (Assumed.isUniversal()) 10606 ? "Universal" 10607 : llvm::join(Assumed.getSet().begin(), Assumed.getSet().end(), ","); 10608 10609 return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]"; 10610 } 10611 }; 10612 10613 /// Propagates assumption information from parent functions to all of their 10614 /// successors. An assumption can be propagated if the containing function 10615 /// dominates the called function. 10616 /// 10617 /// We start with a "known" set of assumptions already valid for the associated 10618 /// function and an "assumed" set that initially contains all possible 10619 /// assumptions. The assumed set is inter-procedurally updated by narrowing its 10620 /// contents as concrete values are known. The concrete values are seeded by the 10621 /// first nodes that are either entries into the call graph, or contains no 10622 /// assumptions. Each node is updated as the intersection of the assumed state 10623 /// with all of its predecessors. 10624 struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl { 10625 AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A) 10626 : AAAssumptionInfoImpl(IRP, A, 10627 getAssumptions(*IRP.getAssociatedFunction())) {} 10628 10629 /// See AbstractAttribute::manifest(...). 10630 ChangeStatus manifest(Attributor &A) override { 10631 const auto &Assumptions = getKnown(); 10632 10633 // Don't manifest a universal set if it somehow made it here. 10634 if (Assumptions.isUniversal()) 10635 return ChangeStatus::UNCHANGED; 10636 10637 Function *AssociatedFunction = getAssociatedFunction(); 10638 10639 bool Changed = addAssumptions(*AssociatedFunction, Assumptions.getSet()); 10640 10641 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10642 } 10643 10644 /// See AbstractAttribute::updateImpl(...). 10645 ChangeStatus updateImpl(Attributor &A) override { 10646 bool Changed = false; 10647 10648 auto CallSitePred = [&](AbstractCallSite ACS) { 10649 const auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>( 10650 *this, IRPosition::callsite_function(*ACS.getInstruction()), 10651 DepClassTy::REQUIRED); 10652 // Get the set of assumptions shared by all of this function's callers. 10653 Changed |= getIntersection(AssumptionAA.getAssumed()); 10654 return !getAssumed().empty() || !getKnown().empty(); 10655 }; 10656 10657 bool UsedAssumedInformation = false; 10658 // Get the intersection of all assumptions held by this node's predecessors. 10659 // If we don't know all the call sites then this is either an entry into the 10660 // call graph or an empty node. This node is known to only contain its own 10661 // assumptions and can be propagated to its successors. 10662 if (!A.checkForAllCallSites(CallSitePred, *this, true, 10663 UsedAssumedInformation)) 10664 return indicatePessimisticFixpoint(); 10665 10666 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10667 } 10668 10669 void trackStatistics() const override {} 10670 }; 10671 10672 /// Assumption Info defined for call sites. 10673 struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl { 10674 10675 AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A) 10676 : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {} 10677 10678 /// See AbstractAttribute::initialize(...). 10679 void initialize(Attributor &A) override { 10680 const IRPosition &FnPos = IRPosition::function(*getAnchorScope()); 10681 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED); 10682 } 10683 10684 /// See AbstractAttribute::manifest(...). 10685 ChangeStatus manifest(Attributor &A) override { 10686 // Don't manifest a universal set if it somehow made it here. 10687 if (getKnown().isUniversal()) 10688 return ChangeStatus::UNCHANGED; 10689 10690 CallBase &AssociatedCall = cast<CallBase>(getAssociatedValue()); 10691 bool Changed = addAssumptions(AssociatedCall, getAssumed().getSet()); 10692 10693 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10694 } 10695 10696 /// See AbstractAttribute::updateImpl(...). 10697 ChangeStatus updateImpl(Attributor &A) override { 10698 const IRPosition &FnPos = IRPosition::function(*getAnchorScope()); 10699 auto &AssumptionAA = 10700 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED); 10701 bool Changed = getIntersection(AssumptionAA.getAssumed()); 10702 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10703 } 10704 10705 /// See AbstractAttribute::trackStatistics() 10706 void trackStatistics() const override {} 10707 10708 private: 10709 /// Helper to initialized the known set as all the assumptions this call and 10710 /// the callee contain. 10711 DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) { 10712 const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue()); 10713 auto Assumptions = getAssumptions(CB); 10714 if (Function *F = IRP.getAssociatedFunction()) 10715 set_union(Assumptions, getAssumptions(*F)); 10716 if (Function *F = IRP.getAssociatedFunction()) 10717 set_union(Assumptions, getAssumptions(*F)); 10718 return Assumptions; 10719 } 10720 }; 10721 } // namespace 10722 10723 AACallGraphNode *AACallEdgeIterator::operator*() const { 10724 return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>( 10725 &A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I)))); 10726 } 10727 10728 void AttributorCallGraph::print() { llvm::WriteGraph(outs(), this); } 10729 10730 const char AAReturnedValues::ID = 0; 10731 const char AANoUnwind::ID = 0; 10732 const char AANoSync::ID = 0; 10733 const char AANoFree::ID = 0; 10734 const char AANonNull::ID = 0; 10735 const char AANoRecurse::ID = 0; 10736 const char AAWillReturn::ID = 0; 10737 const char AAUndefinedBehavior::ID = 0; 10738 const char AANoAlias::ID = 0; 10739 const char AAReachability::ID = 0; 10740 const char AANoReturn::ID = 0; 10741 const char AAIsDead::ID = 0; 10742 const char AADereferenceable::ID = 0; 10743 const char AAAlign::ID = 0; 10744 const char AAInstanceInfo::ID = 0; 10745 const char AANoCapture::ID = 0; 10746 const char AAValueSimplify::ID = 0; 10747 const char AAHeapToStack::ID = 0; 10748 const char AAPrivatizablePtr::ID = 0; 10749 const char AAMemoryBehavior::ID = 0; 10750 const char AAMemoryLocation::ID = 0; 10751 const char AAValueConstantRange::ID = 0; 10752 const char AAPotentialConstantValues::ID = 0; 10753 const char AAPotentialValues::ID = 0; 10754 const char AANoUndef::ID = 0; 10755 const char AACallEdges::ID = 0; 10756 const char AAFunctionReachability::ID = 0; 10757 const char AAPointerInfo::ID = 0; 10758 const char AAAssumptionInfo::ID = 0; 10759 10760 // Macro magic to create the static generator function for attributes that 10761 // follow the naming scheme. 10762 10763 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 10764 case IRPosition::PK: \ 10765 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 10766 10767 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 10768 case IRPosition::PK: \ 10769 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \ 10770 ++NumAAs; \ 10771 break; 10772 10773 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10774 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10775 CLASS *AA = nullptr; \ 10776 switch (IRP.getPositionKind()) { \ 10777 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10778 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 10779 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 10780 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10781 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 10782 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 10783 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10784 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10785 } \ 10786 return *AA; \ 10787 } 10788 10789 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10790 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10791 CLASS *AA = nullptr; \ 10792 switch (IRP.getPositionKind()) { \ 10793 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10794 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 10795 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 10796 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10797 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10798 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 10799 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10800 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10801 } \ 10802 return *AA; \ 10803 } 10804 10805 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10806 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10807 CLASS *AA = nullptr; \ 10808 switch (IRP.getPositionKind()) { \ 10809 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10810 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10811 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10812 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10813 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10814 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 10815 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10816 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10817 } \ 10818 return *AA; \ 10819 } 10820 10821 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10822 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10823 CLASS *AA = nullptr; \ 10824 switch (IRP.getPositionKind()) { \ 10825 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10826 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 10827 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 10828 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10829 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 10830 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 10831 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 10832 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10833 } \ 10834 return *AA; \ 10835 } 10836 10837 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10838 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10839 CLASS *AA = nullptr; \ 10840 switch (IRP.getPositionKind()) { \ 10841 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10842 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10843 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10844 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10845 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10846 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10847 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10848 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10849 } \ 10850 return *AA; \ 10851 } 10852 10853 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 10854 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 10855 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 10856 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 10857 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 10858 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 10859 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation) 10860 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AACallEdges) 10861 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAssumptionInfo) 10862 10863 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 10864 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 10865 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr) 10866 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 10867 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 10868 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAInstanceInfo) 10869 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture) 10870 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange) 10871 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialConstantValues) 10872 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues) 10873 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef) 10874 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPointerInfo) 10875 10876 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify) 10877 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 10878 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 10879 10880 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack) 10881 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability) 10882 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior) 10883 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAFunctionReachability) 10884 10885 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior) 10886 10887 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION 10888 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 10889 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION 10890 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 10891 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 10892 #undef SWITCH_PK_CREATE 10893 #undef SWITCH_PK_INV 10894