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 (FindInterferingWrites && 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 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 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 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 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 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 AccessKind2Accesses.fill(nullptr); 7517 } 7518 7519 ~AAMemoryLocationImpl() { 7520 // The AccessSets are allocated via a BumpPtrAllocator, we call 7521 // the destructor manually. 7522 for (AccessSet *AS : AccessKind2Accesses) 7523 if (AS) 7524 AS->~AccessSet(); 7525 } 7526 7527 /// See AbstractAttribute::initialize(...). 7528 void initialize(Attributor &A) override { 7529 intersectAssumedBits(BEST_STATE); 7530 getKnownStateFromValue(A, getIRPosition(), getState()); 7531 AAMemoryLocation::initialize(A); 7532 } 7533 7534 /// Return the memory behavior information encoded in the IR for \p IRP. 7535 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP, 7536 BitIntegerState &State, 7537 bool IgnoreSubsumingPositions = false) { 7538 // For internal functions we ignore `argmemonly` and 7539 // `inaccessiblememorargmemonly` as we might break it via interprocedural 7540 // constant propagation. It is unclear if this is the best way but it is 7541 // unlikely this will cause real performance problems. If we are deriving 7542 // attributes for the anchor function we even remove the attribute in 7543 // addition to ignoring it. 7544 bool UseArgMemOnly = true; 7545 Function *AnchorFn = IRP.getAnchorScope(); 7546 if (AnchorFn && A.isRunOn(*AnchorFn)) 7547 UseArgMemOnly = !AnchorFn->hasLocalLinkage(); 7548 7549 SmallVector<Attribute, 2> Attrs; 7550 IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions); 7551 for (const Attribute &Attr : Attrs) { 7552 switch (Attr.getKindAsEnum()) { 7553 case Attribute::ReadNone: 7554 State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM); 7555 break; 7556 case Attribute::InaccessibleMemOnly: 7557 State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true)); 7558 break; 7559 case Attribute::ArgMemOnly: 7560 if (UseArgMemOnly) 7561 State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true)); 7562 else 7563 IRP.removeAttrs({Attribute::ArgMemOnly}); 7564 break; 7565 case Attribute::InaccessibleMemOrArgMemOnly: 7566 if (UseArgMemOnly) 7567 State.addKnownBits(inverseLocation( 7568 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true)); 7569 else 7570 IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly}); 7571 break; 7572 default: 7573 llvm_unreachable("Unexpected attribute!"); 7574 } 7575 } 7576 } 7577 7578 /// See AbstractAttribute::getDeducedAttributes(...). 7579 void getDeducedAttributes(LLVMContext &Ctx, 7580 SmallVectorImpl<Attribute> &Attrs) const override { 7581 assert(Attrs.size() == 0); 7582 if (isAssumedReadNone()) { 7583 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 7584 } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) { 7585 if (isAssumedInaccessibleMemOnly()) 7586 Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly)); 7587 else if (isAssumedArgMemOnly()) 7588 Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly)); 7589 else if (isAssumedInaccessibleOrArgMemOnly()) 7590 Attrs.push_back( 7591 Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly)); 7592 } 7593 assert(Attrs.size() <= 1); 7594 } 7595 7596 /// See AbstractAttribute::manifest(...). 7597 ChangeStatus manifest(Attributor &A) override { 7598 const IRPosition &IRP = getIRPosition(); 7599 7600 // Check if we would improve the existing attributes first. 7601 SmallVector<Attribute, 4> DeducedAttrs; 7602 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 7603 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 7604 return IRP.hasAttr(Attr.getKindAsEnum(), 7605 /* IgnoreSubsumingPositions */ true); 7606 })) 7607 return ChangeStatus::UNCHANGED; 7608 7609 // Clear existing attributes. 7610 IRP.removeAttrs(AttrKinds); 7611 if (isAssumedReadNone()) 7612 IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds); 7613 7614 // Use the generic manifest method. 7615 return IRAttribute::manifest(A); 7616 } 7617 7618 /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...). 7619 bool checkForAllAccessesToMemoryKind( 7620 function_ref<bool(const Instruction *, const Value *, AccessKind, 7621 MemoryLocationsKind)> 7622 Pred, 7623 MemoryLocationsKind RequestedMLK) const override { 7624 if (!isValidState()) 7625 return false; 7626 7627 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation(); 7628 if (AssumedMLK == NO_LOCATIONS) 7629 return true; 7630 7631 unsigned Idx = 0; 7632 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; 7633 CurMLK *= 2, ++Idx) { 7634 if (CurMLK & RequestedMLK) 7635 continue; 7636 7637 if (const AccessSet *Accesses = AccessKind2Accesses[Idx]) 7638 for (const AccessInfo &AI : *Accesses) 7639 if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK)) 7640 return false; 7641 } 7642 7643 return true; 7644 } 7645 7646 ChangeStatus indicatePessimisticFixpoint() override { 7647 // If we give up and indicate a pessimistic fixpoint this instruction will 7648 // become an access for all potential access kinds: 7649 // TODO: Add pointers for argmemonly and globals to improve the results of 7650 // checkForAllAccessesToMemoryKind. 7651 bool Changed = false; 7652 MemoryLocationsKind KnownMLK = getKnown(); 7653 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 7654 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) 7655 if (!(CurMLK & KnownMLK)) 7656 updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed, 7657 getAccessKindFromInst(I)); 7658 return AAMemoryLocation::indicatePessimisticFixpoint(); 7659 } 7660 7661 protected: 7662 /// Helper struct to tie together an instruction that has a read or write 7663 /// effect with the pointer it accesses (if any). 7664 struct AccessInfo { 7665 7666 /// The instruction that caused the access. 7667 const Instruction *I; 7668 7669 /// The base pointer that is accessed, or null if unknown. 7670 const Value *Ptr; 7671 7672 /// The kind of access (read/write/read+write). 7673 AccessKind Kind; 7674 7675 bool operator==(const AccessInfo &RHS) const { 7676 return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind; 7677 } 7678 bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const { 7679 if (LHS.I != RHS.I) 7680 return LHS.I < RHS.I; 7681 if (LHS.Ptr != RHS.Ptr) 7682 return LHS.Ptr < RHS.Ptr; 7683 if (LHS.Kind != RHS.Kind) 7684 return LHS.Kind < RHS.Kind; 7685 return false; 7686 } 7687 }; 7688 7689 /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the 7690 /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind. 7691 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>; 7692 std::array<AccessSet *, llvm::CTLog2<VALID_STATE>()> AccessKind2Accesses; 7693 7694 /// Categorize the pointer arguments of CB that might access memory in 7695 /// AccessedLoc and update the state and access map accordingly. 7696 void 7697 categorizeArgumentPointerLocations(Attributor &A, CallBase &CB, 7698 AAMemoryLocation::StateType &AccessedLocs, 7699 bool &Changed); 7700 7701 /// Return the kind(s) of location that may be accessed by \p V. 7702 AAMemoryLocation::MemoryLocationsKind 7703 categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed); 7704 7705 /// Return the access kind as determined by \p I. 7706 AccessKind getAccessKindFromInst(const Instruction *I) { 7707 AccessKind AK = READ_WRITE; 7708 if (I) { 7709 AK = I->mayReadFromMemory() ? READ : NONE; 7710 AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE)); 7711 } 7712 return AK; 7713 } 7714 7715 /// Update the state \p State and the AccessKind2Accesses given that \p I is 7716 /// an access of kind \p AK to a \p MLK memory location with the access 7717 /// pointer \p Ptr. 7718 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State, 7719 MemoryLocationsKind MLK, const Instruction *I, 7720 const Value *Ptr, bool &Changed, 7721 AccessKind AK = READ_WRITE) { 7722 7723 assert(isPowerOf2_32(MLK) && "Expected a single location set!"); 7724 auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)]; 7725 if (!Accesses) 7726 Accesses = new (Allocator) AccessSet(); 7727 Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second; 7728 State.removeAssumedBits(MLK); 7729 } 7730 7731 /// Determine the underlying locations kinds for \p Ptr, e.g., globals or 7732 /// arguments, and update the state and access map accordingly. 7733 void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr, 7734 AAMemoryLocation::StateType &State, bool &Changed); 7735 7736 /// Used to allocate access sets. 7737 BumpPtrAllocator &Allocator; 7738 7739 /// The set of IR attributes AAMemoryLocation deals with. 7740 static const Attribute::AttrKind AttrKinds[4]; 7741 }; 7742 7743 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = { 7744 Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly, 7745 Attribute::InaccessibleMemOrArgMemOnly}; 7746 7747 void AAMemoryLocationImpl::categorizePtrValue( 7748 Attributor &A, const Instruction &I, const Value &Ptr, 7749 AAMemoryLocation::StateType &State, bool &Changed) { 7750 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for " 7751 << Ptr << " [" 7752 << getMemoryLocationsAsStr(State.getAssumed()) << "]\n"); 7753 7754 SmallSetVector<Value *, 8> Objects; 7755 bool UsedAssumedInformation = false; 7756 if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, *this, &I, 7757 UsedAssumedInformation, 7758 AA::Intraprocedural)) { 7759 LLVM_DEBUG( 7760 dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n"); 7761 updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed, 7762 getAccessKindFromInst(&I)); 7763 return; 7764 } 7765 7766 for (Value *Obj : Objects) { 7767 // TODO: recognize the TBAA used for constant accesses. 7768 MemoryLocationsKind MLK = NO_LOCATIONS; 7769 if (isa<UndefValue>(Obj)) 7770 continue; 7771 if (isa<Argument>(Obj)) { 7772 // TODO: For now we do not treat byval arguments as local copies performed 7773 // on the call edge, though, we should. To make that happen we need to 7774 // teach various passes, e.g., DSE, about the copy effect of a byval. That 7775 // would also allow us to mark functions only accessing byval arguments as 7776 // readnone again, atguably their acceses have no effect outside of the 7777 // function, like accesses to allocas. 7778 MLK = NO_ARGUMENT_MEM; 7779 } else if (auto *GV = dyn_cast<GlobalValue>(Obj)) { 7780 // Reading constant memory is not treated as a read "effect" by the 7781 // function attr pass so we won't neither. Constants defined by TBAA are 7782 // similar. (We know we do not write it because it is constant.) 7783 if (auto *GVar = dyn_cast<GlobalVariable>(GV)) 7784 if (GVar->isConstant()) 7785 continue; 7786 7787 if (GV->hasLocalLinkage()) 7788 MLK = NO_GLOBAL_INTERNAL_MEM; 7789 else 7790 MLK = NO_GLOBAL_EXTERNAL_MEM; 7791 } else if (isa<ConstantPointerNull>(Obj) && 7792 !NullPointerIsDefined(getAssociatedFunction(), 7793 Ptr.getType()->getPointerAddressSpace())) { 7794 continue; 7795 } else if (isa<AllocaInst>(Obj)) { 7796 MLK = NO_LOCAL_MEM; 7797 } else if (const auto *CB = dyn_cast<CallBase>(Obj)) { 7798 const auto &NoAliasAA = A.getAAFor<AANoAlias>( 7799 *this, IRPosition::callsite_returned(*CB), DepClassTy::OPTIONAL); 7800 if (NoAliasAA.isAssumedNoAlias()) 7801 MLK = NO_MALLOCED_MEM; 7802 else 7803 MLK = NO_UNKOWN_MEM; 7804 } else { 7805 MLK = NO_UNKOWN_MEM; 7806 } 7807 7808 assert(MLK != NO_LOCATIONS && "No location specified!"); 7809 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: " 7810 << *Obj << " -> " << getMemoryLocationsAsStr(MLK) 7811 << "\n"); 7812 updateStateAndAccessesMap(getState(), MLK, &I, Obj, Changed, 7813 getAccessKindFromInst(&I)); 7814 } 7815 7816 LLVM_DEBUG( 7817 dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: " 7818 << getMemoryLocationsAsStr(State.getAssumed()) << "\n"); 7819 } 7820 7821 void AAMemoryLocationImpl::categorizeArgumentPointerLocations( 7822 Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs, 7823 bool &Changed) { 7824 for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) { 7825 7826 // Skip non-pointer arguments. 7827 const Value *ArgOp = CB.getArgOperand(ArgNo); 7828 if (!ArgOp->getType()->isPtrOrPtrVectorTy()) 7829 continue; 7830 7831 // Skip readnone arguments. 7832 const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo); 7833 const auto &ArgOpMemLocationAA = 7834 A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL); 7835 7836 if (ArgOpMemLocationAA.isAssumedReadNone()) 7837 continue; 7838 7839 // Categorize potentially accessed pointer arguments as if there was an 7840 // access instruction with them as pointer. 7841 categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed); 7842 } 7843 } 7844 7845 AAMemoryLocation::MemoryLocationsKind 7846 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I, 7847 bool &Changed) { 7848 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for " 7849 << I << "\n"); 7850 7851 AAMemoryLocation::StateType AccessedLocs; 7852 AccessedLocs.intersectAssumedBits(NO_LOCATIONS); 7853 7854 if (auto *CB = dyn_cast<CallBase>(&I)) { 7855 7856 // First check if we assume any memory is access is visible. 7857 const auto &CBMemLocationAA = A.getAAFor<AAMemoryLocation>( 7858 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL); 7859 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I 7860 << " [" << CBMemLocationAA << "]\n"); 7861 7862 if (CBMemLocationAA.isAssumedReadNone()) 7863 return NO_LOCATIONS; 7864 7865 if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) { 7866 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr, 7867 Changed, getAccessKindFromInst(&I)); 7868 return AccessedLocs.getAssumed(); 7869 } 7870 7871 uint32_t CBAssumedNotAccessedLocs = 7872 CBMemLocationAA.getAssumedNotAccessedLocation(); 7873 7874 // Set the argmemonly and global bit as we handle them separately below. 7875 uint32_t CBAssumedNotAccessedLocsNoArgMem = 7876 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM; 7877 7878 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) { 7879 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK) 7880 continue; 7881 updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed, 7882 getAccessKindFromInst(&I)); 7883 } 7884 7885 // Now handle global memory if it might be accessed. This is slightly tricky 7886 // as NO_GLOBAL_MEM has multiple bits set. 7887 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM); 7888 if (HasGlobalAccesses) { 7889 auto AccessPred = [&](const Instruction *, const Value *Ptr, 7890 AccessKind Kind, MemoryLocationsKind MLK) { 7891 updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed, 7892 getAccessKindFromInst(&I)); 7893 return true; 7894 }; 7895 if (!CBMemLocationAA.checkForAllAccessesToMemoryKind( 7896 AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false))) 7897 return AccessedLocs.getWorstState(); 7898 } 7899 7900 LLVM_DEBUG( 7901 dbgs() << "[AAMemoryLocation] Accessed state before argument handling: " 7902 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 7903 7904 // Now handle argument memory if it might be accessed. 7905 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM); 7906 if (HasArgAccesses) 7907 categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed); 7908 7909 LLVM_DEBUG( 7910 dbgs() << "[AAMemoryLocation] Accessed state after argument handling: " 7911 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 7912 7913 return AccessedLocs.getAssumed(); 7914 } 7915 7916 if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) { 7917 LLVM_DEBUG( 7918 dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: " 7919 << I << " [" << *Ptr << "]\n"); 7920 categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed); 7921 return AccessedLocs.getAssumed(); 7922 } 7923 7924 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: " 7925 << I << "\n"); 7926 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed, 7927 getAccessKindFromInst(&I)); 7928 return AccessedLocs.getAssumed(); 7929 } 7930 7931 /// An AA to represent the memory behavior function attributes. 7932 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl { 7933 AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A) 7934 : AAMemoryLocationImpl(IRP, A) {} 7935 7936 /// See AbstractAttribute::updateImpl(Attributor &A). 7937 ChangeStatus updateImpl(Attributor &A) override { 7938 7939 const auto &MemBehaviorAA = 7940 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 7941 if (MemBehaviorAA.isAssumedReadNone()) { 7942 if (MemBehaviorAA.isKnownReadNone()) 7943 return indicateOptimisticFixpoint(); 7944 assert(isAssumedReadNone() && 7945 "AAMemoryLocation was not read-none but AAMemoryBehavior was!"); 7946 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 7947 return ChangeStatus::UNCHANGED; 7948 } 7949 7950 // The current assumed state used to determine a change. 7951 auto AssumedState = getAssumed(); 7952 bool Changed = false; 7953 7954 auto CheckRWInst = [&](Instruction &I) { 7955 MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed); 7956 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I 7957 << ": " << getMemoryLocationsAsStr(MLK) << "\n"); 7958 removeAssumedBits(inverseLocation(MLK, false, false)); 7959 // Stop once only the valid bit set in the *not assumed location*, thus 7960 // once we don't actually exclude any memory locations in the state. 7961 return getAssumedNotAccessedLocation() != VALID_STATE; 7962 }; 7963 7964 bool UsedAssumedInformation = false; 7965 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this, 7966 UsedAssumedInformation)) 7967 return indicatePessimisticFixpoint(); 7968 7969 Changed |= AssumedState != getAssumed(); 7970 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 7971 } 7972 7973 /// See AbstractAttribute::trackStatistics() 7974 void trackStatistics() const override { 7975 if (isAssumedReadNone()) 7976 STATS_DECLTRACK_FN_ATTR(readnone) 7977 else if (isAssumedArgMemOnly()) 7978 STATS_DECLTRACK_FN_ATTR(argmemonly) 7979 else if (isAssumedInaccessibleMemOnly()) 7980 STATS_DECLTRACK_FN_ATTR(inaccessiblememonly) 7981 else if (isAssumedInaccessibleOrArgMemOnly()) 7982 STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly) 7983 } 7984 }; 7985 7986 /// AAMemoryLocation attribute for call sites. 7987 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl { 7988 AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A) 7989 : AAMemoryLocationImpl(IRP, A) {} 7990 7991 /// See AbstractAttribute::initialize(...). 7992 void initialize(Attributor &A) override { 7993 AAMemoryLocationImpl::initialize(A); 7994 Function *F = getAssociatedFunction(); 7995 if (!F || F->isDeclaration()) 7996 indicatePessimisticFixpoint(); 7997 } 7998 7999 /// See AbstractAttribute::updateImpl(...). 8000 ChangeStatus updateImpl(Attributor &A) override { 8001 // TODO: Once we have call site specific value information we can provide 8002 // call site specific liveness liveness information and then it makes 8003 // sense to specialize attributes for call sites arguments instead of 8004 // redirecting requests to the callee argument. 8005 Function *F = getAssociatedFunction(); 8006 const IRPosition &FnPos = IRPosition::function(*F); 8007 auto &FnAA = 8008 A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED); 8009 bool Changed = false; 8010 auto AccessPred = [&](const Instruction *I, const Value *Ptr, 8011 AccessKind Kind, MemoryLocationsKind MLK) { 8012 updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed, 8013 getAccessKindFromInst(I)); 8014 return true; 8015 }; 8016 if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS)) 8017 return indicatePessimisticFixpoint(); 8018 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 8019 } 8020 8021 /// See AbstractAttribute::trackStatistics() 8022 void trackStatistics() const override { 8023 if (isAssumedReadNone()) 8024 STATS_DECLTRACK_CS_ATTR(readnone) 8025 } 8026 }; 8027 } // namespace 8028 8029 /// ------------------ Value Constant Range Attribute ------------------------- 8030 8031 namespace { 8032 struct AAValueConstantRangeImpl : AAValueConstantRange { 8033 using StateType = IntegerRangeState; 8034 AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A) 8035 : AAValueConstantRange(IRP, A) {} 8036 8037 /// See AbstractAttribute::initialize(..). 8038 void initialize(Attributor &A) override { 8039 if (A.hasSimplificationCallback(getIRPosition())) { 8040 indicatePessimisticFixpoint(); 8041 return; 8042 } 8043 8044 // Intersect a range given by SCEV. 8045 intersectKnown(getConstantRangeFromSCEV(A, getCtxI())); 8046 8047 // Intersect a range given by LVI. 8048 intersectKnown(getConstantRangeFromLVI(A, getCtxI())); 8049 } 8050 8051 /// See AbstractAttribute::getAsStr(). 8052 const std::string getAsStr() const override { 8053 std::string Str; 8054 llvm::raw_string_ostream OS(Str); 8055 OS << "range(" << getBitWidth() << ")<"; 8056 getKnown().print(OS); 8057 OS << " / "; 8058 getAssumed().print(OS); 8059 OS << ">"; 8060 return OS.str(); 8061 } 8062 8063 /// Helper function to get a SCEV expr for the associated value at program 8064 /// point \p I. 8065 const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const { 8066 if (!getAnchorScope()) 8067 return nullptr; 8068 8069 ScalarEvolution *SE = 8070 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 8071 *getAnchorScope()); 8072 8073 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>( 8074 *getAnchorScope()); 8075 8076 if (!SE || !LI) 8077 return nullptr; 8078 8079 const SCEV *S = SE->getSCEV(&getAssociatedValue()); 8080 if (!I) 8081 return S; 8082 8083 return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent())); 8084 } 8085 8086 /// Helper function to get a range from SCEV for the associated value at 8087 /// program point \p I. 8088 ConstantRange getConstantRangeFromSCEV(Attributor &A, 8089 const Instruction *I = nullptr) const { 8090 if (!getAnchorScope()) 8091 return getWorstState(getBitWidth()); 8092 8093 ScalarEvolution *SE = 8094 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 8095 *getAnchorScope()); 8096 8097 const SCEV *S = getSCEV(A, I); 8098 if (!SE || !S) 8099 return getWorstState(getBitWidth()); 8100 8101 return SE->getUnsignedRange(S); 8102 } 8103 8104 /// Helper function to get a range from LVI for the associated value at 8105 /// program point \p I. 8106 ConstantRange 8107 getConstantRangeFromLVI(Attributor &A, 8108 const Instruction *CtxI = nullptr) const { 8109 if (!getAnchorScope()) 8110 return getWorstState(getBitWidth()); 8111 8112 LazyValueInfo *LVI = 8113 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>( 8114 *getAnchorScope()); 8115 8116 if (!LVI || !CtxI) 8117 return getWorstState(getBitWidth()); 8118 return LVI->getConstantRange(&getAssociatedValue(), 8119 const_cast<Instruction *>(CtxI)); 8120 } 8121 8122 /// Return true if \p CtxI is valid for querying outside analyses. 8123 /// This basically makes sure we do not ask intra-procedural analysis 8124 /// about a context in the wrong function or a context that violates 8125 /// dominance assumptions they might have. The \p AllowAACtxI flag indicates 8126 /// if the original context of this AA is OK or should be considered invalid. 8127 bool isValidCtxInstructionForOutsideAnalysis(Attributor &A, 8128 const Instruction *CtxI, 8129 bool AllowAACtxI) const { 8130 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI())) 8131 return false; 8132 8133 // Our context might be in a different function, neither intra-procedural 8134 // analysis (ScalarEvolution nor LazyValueInfo) can handle that. 8135 if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction())) 8136 return false; 8137 8138 // If the context is not dominated by the value there are paths to the 8139 // context that do not define the value. This cannot be handled by 8140 // LazyValueInfo so we need to bail. 8141 if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) { 8142 InformationCache &InfoCache = A.getInfoCache(); 8143 const DominatorTree *DT = 8144 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>( 8145 *I->getFunction()); 8146 return DT && DT->dominates(I, CtxI); 8147 } 8148 8149 return true; 8150 } 8151 8152 /// See AAValueConstantRange::getKnownConstantRange(..). 8153 ConstantRange 8154 getKnownConstantRange(Attributor &A, 8155 const Instruction *CtxI = nullptr) const override { 8156 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI, 8157 /* AllowAACtxI */ false)) 8158 return getKnown(); 8159 8160 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 8161 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 8162 return getKnown().intersectWith(SCEVR).intersectWith(LVIR); 8163 } 8164 8165 /// See AAValueConstantRange::getAssumedConstantRange(..). 8166 ConstantRange 8167 getAssumedConstantRange(Attributor &A, 8168 const Instruction *CtxI = nullptr) const override { 8169 // TODO: Make SCEV use Attributor assumption. 8170 // We may be able to bound a variable range via assumptions in 8171 // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to 8172 // evolve to x^2 + x, then we can say that y is in [2, 12]. 8173 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI, 8174 /* AllowAACtxI */ false)) 8175 return getAssumed(); 8176 8177 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 8178 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 8179 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR); 8180 } 8181 8182 /// Helper function to create MDNode for range metadata. 8183 static MDNode * 8184 getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx, 8185 const ConstantRange &AssumedConstantRange) { 8186 Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get( 8187 Ty, AssumedConstantRange.getLower())), 8188 ConstantAsMetadata::get(ConstantInt::get( 8189 Ty, AssumedConstantRange.getUpper()))}; 8190 return MDNode::get(Ctx, LowAndHigh); 8191 } 8192 8193 /// Return true if \p Assumed is included in \p KnownRanges. 8194 static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) { 8195 8196 if (Assumed.isFullSet()) 8197 return false; 8198 8199 if (!KnownRanges) 8200 return true; 8201 8202 // If multiple ranges are annotated in IR, we give up to annotate assumed 8203 // range for now. 8204 8205 // TODO: If there exists a known range which containts assumed range, we 8206 // can say assumed range is better. 8207 if (KnownRanges->getNumOperands() > 2) 8208 return false; 8209 8210 ConstantInt *Lower = 8211 mdconst::extract<ConstantInt>(KnownRanges->getOperand(0)); 8212 ConstantInt *Upper = 8213 mdconst::extract<ConstantInt>(KnownRanges->getOperand(1)); 8214 8215 ConstantRange Known(Lower->getValue(), Upper->getValue()); 8216 return Known.contains(Assumed) && Known != Assumed; 8217 } 8218 8219 /// Helper function to set range metadata. 8220 static bool 8221 setRangeMetadataIfisBetterRange(Instruction *I, 8222 const ConstantRange &AssumedConstantRange) { 8223 auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range); 8224 if (isBetterRange(AssumedConstantRange, OldRangeMD)) { 8225 if (!AssumedConstantRange.isEmptySet()) { 8226 I->setMetadata(LLVMContext::MD_range, 8227 getMDNodeForConstantRange(I->getType(), I->getContext(), 8228 AssumedConstantRange)); 8229 return true; 8230 } 8231 } 8232 return false; 8233 } 8234 8235 /// See AbstractAttribute::manifest() 8236 ChangeStatus manifest(Attributor &A) override { 8237 ChangeStatus Changed = ChangeStatus::UNCHANGED; 8238 ConstantRange AssumedConstantRange = getAssumedConstantRange(A); 8239 assert(!AssumedConstantRange.isFullSet() && "Invalid state"); 8240 8241 auto &V = getAssociatedValue(); 8242 if (!AssumedConstantRange.isEmptySet() && 8243 !AssumedConstantRange.isSingleElement()) { 8244 if (Instruction *I = dyn_cast<Instruction>(&V)) { 8245 assert(I == getCtxI() && "Should not annotate an instruction which is " 8246 "not the context instruction"); 8247 if (isa<CallInst>(I) || isa<LoadInst>(I)) 8248 if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange)) 8249 Changed = ChangeStatus::CHANGED; 8250 } 8251 } 8252 8253 return Changed; 8254 } 8255 }; 8256 8257 struct AAValueConstantRangeArgument final 8258 : AAArgumentFromCallSiteArguments< 8259 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 8260 true /* BridgeCallBaseContext */> { 8261 using Base = AAArgumentFromCallSiteArguments< 8262 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 8263 true /* BridgeCallBaseContext */>; 8264 AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A) 8265 : Base(IRP, A) {} 8266 8267 /// See AbstractAttribute::initialize(..). 8268 void initialize(Attributor &A) override { 8269 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 8270 indicatePessimisticFixpoint(); 8271 } else { 8272 Base::initialize(A); 8273 } 8274 } 8275 8276 /// See AbstractAttribute::trackStatistics() 8277 void trackStatistics() const override { 8278 STATS_DECLTRACK_ARG_ATTR(value_range) 8279 } 8280 }; 8281 8282 struct AAValueConstantRangeReturned 8283 : AAReturnedFromReturnedValues<AAValueConstantRange, 8284 AAValueConstantRangeImpl, 8285 AAValueConstantRangeImpl::StateType, 8286 /* PropogateCallBaseContext */ true> { 8287 using Base = 8288 AAReturnedFromReturnedValues<AAValueConstantRange, 8289 AAValueConstantRangeImpl, 8290 AAValueConstantRangeImpl::StateType, 8291 /* PropogateCallBaseContext */ true>; 8292 AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A) 8293 : Base(IRP, A) {} 8294 8295 /// See AbstractAttribute::initialize(...). 8296 void initialize(Attributor &A) override {} 8297 8298 /// See AbstractAttribute::trackStatistics() 8299 void trackStatistics() const override { 8300 STATS_DECLTRACK_FNRET_ATTR(value_range) 8301 } 8302 }; 8303 8304 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { 8305 AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A) 8306 : AAValueConstantRangeImpl(IRP, A) {} 8307 8308 /// See AbstractAttribute::initialize(...). 8309 void initialize(Attributor &A) override { 8310 AAValueConstantRangeImpl::initialize(A); 8311 if (isAtFixpoint()) 8312 return; 8313 8314 Value &V = getAssociatedValue(); 8315 8316 if (auto *C = dyn_cast<ConstantInt>(&V)) { 8317 unionAssumed(ConstantRange(C->getValue())); 8318 indicateOptimisticFixpoint(); 8319 return; 8320 } 8321 8322 if (isa<UndefValue>(&V)) { 8323 // Collapse the undef state to 0. 8324 unionAssumed(ConstantRange(APInt(getBitWidth(), 0))); 8325 indicateOptimisticFixpoint(); 8326 return; 8327 } 8328 8329 if (isa<CallBase>(&V)) 8330 return; 8331 8332 if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V)) 8333 return; 8334 8335 // If it is a load instruction with range metadata, use it. 8336 if (LoadInst *LI = dyn_cast<LoadInst>(&V)) 8337 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) { 8338 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 8339 return; 8340 } 8341 8342 // We can work with PHI and select instruction as we traverse their operands 8343 // during update. 8344 if (isa<SelectInst>(V) || isa<PHINode>(V)) 8345 return; 8346 8347 // Otherwise we give up. 8348 indicatePessimisticFixpoint(); 8349 8350 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: " 8351 << getAssociatedValue() << "\n"); 8352 } 8353 8354 bool calculateBinaryOperator( 8355 Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T, 8356 const Instruction *CtxI, 8357 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8358 Value *LHS = BinOp->getOperand(0); 8359 Value *RHS = BinOp->getOperand(1); 8360 8361 // Simplify the operands first. 8362 bool UsedAssumedInformation = false; 8363 const auto &SimplifiedLHS = A.getAssumedSimplified( 8364 IRPosition::value(*LHS, getCallBaseContext()), *this, 8365 UsedAssumedInformation, AA::Interprocedural); 8366 if (!SimplifiedLHS.has_value()) 8367 return true; 8368 if (!SimplifiedLHS.value()) 8369 return false; 8370 LHS = *SimplifiedLHS; 8371 8372 const auto &SimplifiedRHS = A.getAssumedSimplified( 8373 IRPosition::value(*RHS, getCallBaseContext()), *this, 8374 UsedAssumedInformation, AA::Interprocedural); 8375 if (!SimplifiedRHS.has_value()) 8376 return true; 8377 if (!SimplifiedRHS.value()) 8378 return false; 8379 RHS = *SimplifiedRHS; 8380 8381 // TODO: Allow non integers as well. 8382 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 8383 return false; 8384 8385 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 8386 *this, IRPosition::value(*LHS, getCallBaseContext()), 8387 DepClassTy::REQUIRED); 8388 QuerriedAAs.push_back(&LHSAA); 8389 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 8390 8391 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 8392 *this, IRPosition::value(*RHS, getCallBaseContext()), 8393 DepClassTy::REQUIRED); 8394 QuerriedAAs.push_back(&RHSAA); 8395 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 8396 8397 auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange); 8398 8399 T.unionAssumed(AssumedRange); 8400 8401 // TODO: Track a known state too. 8402 8403 return T.isValidState(); 8404 } 8405 8406 bool calculateCastInst( 8407 Attributor &A, CastInst *CastI, IntegerRangeState &T, 8408 const Instruction *CtxI, 8409 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8410 assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!"); 8411 // TODO: Allow non integers as well. 8412 Value *OpV = CastI->getOperand(0); 8413 8414 // Simplify the operand first. 8415 bool UsedAssumedInformation = false; 8416 const auto &SimplifiedOpV = A.getAssumedSimplified( 8417 IRPosition::value(*OpV, getCallBaseContext()), *this, 8418 UsedAssumedInformation, AA::Interprocedural); 8419 if (!SimplifiedOpV.has_value()) 8420 return true; 8421 if (!SimplifiedOpV.value()) 8422 return false; 8423 OpV = *SimplifiedOpV; 8424 8425 if (!OpV->getType()->isIntegerTy()) 8426 return false; 8427 8428 auto &OpAA = A.getAAFor<AAValueConstantRange>( 8429 *this, IRPosition::value(*OpV, getCallBaseContext()), 8430 DepClassTy::REQUIRED); 8431 QuerriedAAs.push_back(&OpAA); 8432 T.unionAssumed( 8433 OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth())); 8434 return T.isValidState(); 8435 } 8436 8437 bool 8438 calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T, 8439 const Instruction *CtxI, 8440 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 8441 Value *LHS = CmpI->getOperand(0); 8442 Value *RHS = CmpI->getOperand(1); 8443 8444 // Simplify the operands first. 8445 bool UsedAssumedInformation = false; 8446 const auto &SimplifiedLHS = A.getAssumedSimplified( 8447 IRPosition::value(*LHS, getCallBaseContext()), *this, 8448 UsedAssumedInformation, AA::Interprocedural); 8449 if (!SimplifiedLHS.has_value()) 8450 return true; 8451 if (!SimplifiedLHS.value()) 8452 return false; 8453 LHS = *SimplifiedLHS; 8454 8455 const auto &SimplifiedRHS = A.getAssumedSimplified( 8456 IRPosition::value(*RHS, getCallBaseContext()), *this, 8457 UsedAssumedInformation, AA::Interprocedural); 8458 if (!SimplifiedRHS.has_value()) 8459 return true; 8460 if (!SimplifiedRHS.value()) 8461 return false; 8462 RHS = *SimplifiedRHS; 8463 8464 // TODO: Allow non integers as well. 8465 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 8466 return false; 8467 8468 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 8469 *this, IRPosition::value(*LHS, getCallBaseContext()), 8470 DepClassTy::REQUIRED); 8471 QuerriedAAs.push_back(&LHSAA); 8472 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 8473 *this, IRPosition::value(*RHS, getCallBaseContext()), 8474 DepClassTy::REQUIRED); 8475 QuerriedAAs.push_back(&RHSAA); 8476 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 8477 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 8478 8479 // If one of them is empty set, we can't decide. 8480 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet()) 8481 return true; 8482 8483 bool MustTrue = false, MustFalse = false; 8484 8485 auto AllowedRegion = 8486 ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange); 8487 8488 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet()) 8489 MustFalse = true; 8490 8491 if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange)) 8492 MustTrue = true; 8493 8494 assert((!MustTrue || !MustFalse) && 8495 "Either MustTrue or MustFalse should be false!"); 8496 8497 if (MustTrue) 8498 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1))); 8499 else if (MustFalse) 8500 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0))); 8501 else 8502 T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true)); 8503 8504 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA 8505 << " " << RHSAA << "\n"); 8506 8507 // TODO: Track a known state too. 8508 return T.isValidState(); 8509 } 8510 8511 /// See AbstractAttribute::updateImpl(...). 8512 ChangeStatus updateImpl(Attributor &A) override { 8513 8514 IntegerRangeState T(getBitWidth()); 8515 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool { 8516 Instruction *I = dyn_cast<Instruction>(&V); 8517 if (!I || isa<CallBase>(I)) { 8518 8519 // Simplify the operand first. 8520 bool UsedAssumedInformation = false; 8521 const auto &SimplifiedOpV = A.getAssumedSimplified( 8522 IRPosition::value(V, getCallBaseContext()), *this, 8523 UsedAssumedInformation, AA::Interprocedural); 8524 if (!SimplifiedOpV.has_value()) 8525 return true; 8526 if (!SimplifiedOpV.value()) 8527 return false; 8528 Value *VPtr = *SimplifiedOpV; 8529 8530 // If the value is not instruction, we query AA to Attributor. 8531 const auto &AA = A.getAAFor<AAValueConstantRange>( 8532 *this, IRPosition::value(*VPtr, getCallBaseContext()), 8533 DepClassTy::REQUIRED); 8534 8535 // Clamp operator is not used to utilize a program point CtxI. 8536 T.unionAssumed(AA.getAssumedConstantRange(A, CtxI)); 8537 8538 return T.isValidState(); 8539 } 8540 8541 SmallVector<const AAValueConstantRange *, 4> QuerriedAAs; 8542 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) { 8543 if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs)) 8544 return false; 8545 } else if (auto *CmpI = dyn_cast<CmpInst>(I)) { 8546 if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs)) 8547 return false; 8548 } else if (auto *CastI = dyn_cast<CastInst>(I)) { 8549 if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs)) 8550 return false; 8551 } else { 8552 // Give up with other instructions. 8553 // TODO: Add other instructions 8554 8555 T.indicatePessimisticFixpoint(); 8556 return false; 8557 } 8558 8559 // Catch circular reasoning in a pessimistic way for now. 8560 // TODO: Check how the range evolves and if we stripped anything, see also 8561 // AADereferenceable or AAAlign for similar situations. 8562 for (const AAValueConstantRange *QueriedAA : QuerriedAAs) { 8563 if (QueriedAA != this) 8564 continue; 8565 // If we are in a stady state we do not need to worry. 8566 if (T.getAssumed() == getState().getAssumed()) 8567 continue; 8568 T.indicatePessimisticFixpoint(); 8569 } 8570 8571 return T.isValidState(); 8572 }; 8573 8574 if (!VisitValueCB(getAssociatedValue(), getCtxI())) 8575 return indicatePessimisticFixpoint(); 8576 8577 // Ensure that long def-use chains can't cause circular reasoning either by 8578 // introducing a cutoff below. 8579 if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED) 8580 return ChangeStatus::UNCHANGED; 8581 if (++NumChanges > MaxNumChanges) { 8582 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges 8583 << " but only " << MaxNumChanges 8584 << " are allowed to avoid cyclic reasoning."); 8585 return indicatePessimisticFixpoint(); 8586 } 8587 return ChangeStatus::CHANGED; 8588 } 8589 8590 /// See AbstractAttribute::trackStatistics() 8591 void trackStatistics() const override { 8592 STATS_DECLTRACK_FLOATING_ATTR(value_range) 8593 } 8594 8595 /// Tracker to bail after too many widening steps of the constant range. 8596 int NumChanges = 0; 8597 8598 /// Upper bound for the number of allowed changes (=widening steps) for the 8599 /// constant range before we give up. 8600 static constexpr int MaxNumChanges = 5; 8601 }; 8602 8603 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl { 8604 AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A) 8605 : AAValueConstantRangeImpl(IRP, A) {} 8606 8607 /// See AbstractAttribute::initialize(...). 8608 ChangeStatus updateImpl(Attributor &A) override { 8609 llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will " 8610 "not be called"); 8611 } 8612 8613 /// See AbstractAttribute::trackStatistics() 8614 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) } 8615 }; 8616 8617 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction { 8618 AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A) 8619 : AAValueConstantRangeFunction(IRP, A) {} 8620 8621 /// See AbstractAttribute::trackStatistics() 8622 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) } 8623 }; 8624 8625 struct AAValueConstantRangeCallSiteReturned 8626 : AACallSiteReturnedFromReturned<AAValueConstantRange, 8627 AAValueConstantRangeImpl, 8628 AAValueConstantRangeImpl::StateType, 8629 /* IntroduceCallBaseContext */ true> { 8630 AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A) 8631 : AACallSiteReturnedFromReturned<AAValueConstantRange, 8632 AAValueConstantRangeImpl, 8633 AAValueConstantRangeImpl::StateType, 8634 /* IntroduceCallBaseContext */ true>(IRP, 8635 A) { 8636 } 8637 8638 /// See AbstractAttribute::initialize(...). 8639 void initialize(Attributor &A) override { 8640 // If it is a load instruction with range metadata, use the metadata. 8641 if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue())) 8642 if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range)) 8643 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 8644 8645 AAValueConstantRangeImpl::initialize(A); 8646 } 8647 8648 /// See AbstractAttribute::trackStatistics() 8649 void trackStatistics() const override { 8650 STATS_DECLTRACK_CSRET_ATTR(value_range) 8651 } 8652 }; 8653 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating { 8654 AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A) 8655 : AAValueConstantRangeFloating(IRP, A) {} 8656 8657 /// See AbstractAttribute::manifest() 8658 ChangeStatus manifest(Attributor &A) override { 8659 return ChangeStatus::UNCHANGED; 8660 } 8661 8662 /// See AbstractAttribute::trackStatistics() 8663 void trackStatistics() const override { 8664 STATS_DECLTRACK_CSARG_ATTR(value_range) 8665 } 8666 }; 8667 } // namespace 8668 8669 /// ------------------ Potential Values Attribute ------------------------- 8670 8671 namespace { 8672 struct AAPotentialConstantValuesImpl : AAPotentialConstantValues { 8673 using StateType = PotentialConstantIntValuesState; 8674 8675 AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A) 8676 : AAPotentialConstantValues(IRP, A) {} 8677 8678 /// See AbstractAttribute::initialize(..). 8679 void initialize(Attributor &A) override { 8680 if (A.hasSimplificationCallback(getIRPosition())) 8681 indicatePessimisticFixpoint(); 8682 else 8683 AAPotentialConstantValues::initialize(A); 8684 } 8685 8686 bool fillSetWithConstantValues(Attributor &A, const IRPosition &IRP, SetTy &S, 8687 bool &ContainsUndef) { 8688 SmallVector<AA::ValueAndContext> Values; 8689 bool UsedAssumedInformation = false; 8690 if (!A.getAssumedSimplifiedValues(IRP, *this, Values, AA::Interprocedural, 8691 UsedAssumedInformation)) { 8692 if (!IRP.getAssociatedType()->isIntegerTy()) 8693 return false; 8694 auto &PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>( 8695 *this, IRP, DepClassTy::REQUIRED); 8696 if (!PotentialValuesAA.getState().isValidState()) 8697 return false; 8698 ContainsUndef = PotentialValuesAA.getState().undefIsContained(); 8699 S = PotentialValuesAA.getState().getAssumedSet(); 8700 return true; 8701 } 8702 8703 for (auto &It : Values) { 8704 if (isa<UndefValue>(It.getValue())) 8705 continue; 8706 auto *CI = dyn_cast<ConstantInt>(It.getValue()); 8707 if (!CI) 8708 return false; 8709 S.insert(CI->getValue()); 8710 } 8711 ContainsUndef = S.empty(); 8712 8713 return true; 8714 } 8715 8716 /// See AbstractAttribute::getAsStr(). 8717 const std::string getAsStr() const override { 8718 std::string Str; 8719 llvm::raw_string_ostream OS(Str); 8720 OS << getState(); 8721 return OS.str(); 8722 } 8723 8724 /// See AbstractAttribute::updateImpl(...). 8725 ChangeStatus updateImpl(Attributor &A) override { 8726 return indicatePessimisticFixpoint(); 8727 } 8728 }; 8729 8730 struct AAPotentialConstantValuesArgument final 8731 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues, 8732 AAPotentialConstantValuesImpl, 8733 PotentialConstantIntValuesState> { 8734 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues, 8735 AAPotentialConstantValuesImpl, 8736 PotentialConstantIntValuesState>; 8737 AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A) 8738 : Base(IRP, A) {} 8739 8740 /// See AbstractAttribute::initialize(..). 8741 void initialize(Attributor &A) override { 8742 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 8743 indicatePessimisticFixpoint(); 8744 } else { 8745 Base::initialize(A); 8746 } 8747 } 8748 8749 /// See AbstractAttribute::trackStatistics() 8750 void trackStatistics() const override { 8751 STATS_DECLTRACK_ARG_ATTR(potential_values) 8752 } 8753 }; 8754 8755 struct AAPotentialConstantValuesReturned 8756 : AAReturnedFromReturnedValues<AAPotentialConstantValues, 8757 AAPotentialConstantValuesImpl> { 8758 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues, 8759 AAPotentialConstantValuesImpl>; 8760 AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A) 8761 : Base(IRP, A) {} 8762 8763 /// See AbstractAttribute::trackStatistics() 8764 void trackStatistics() const override { 8765 STATS_DECLTRACK_FNRET_ATTR(potential_values) 8766 } 8767 }; 8768 8769 struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { 8770 AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A) 8771 : AAPotentialConstantValuesImpl(IRP, A) {} 8772 8773 /// See AbstractAttribute::initialize(..). 8774 void initialize(Attributor &A) override { 8775 AAPotentialConstantValuesImpl::initialize(A); 8776 if (isAtFixpoint()) 8777 return; 8778 8779 Value &V = getAssociatedValue(); 8780 8781 if (auto *C = dyn_cast<ConstantInt>(&V)) { 8782 unionAssumed(C->getValue()); 8783 indicateOptimisticFixpoint(); 8784 return; 8785 } 8786 8787 if (isa<UndefValue>(&V)) { 8788 unionAssumedWithUndef(); 8789 indicateOptimisticFixpoint(); 8790 return; 8791 } 8792 8793 if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V)) 8794 return; 8795 8796 if (isa<SelectInst>(V) || isa<PHINode>(V) || isa<LoadInst>(V)) 8797 return; 8798 8799 indicatePessimisticFixpoint(); 8800 8801 LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: " 8802 << getAssociatedValue() << "\n"); 8803 } 8804 8805 static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS, 8806 const APInt &RHS) { 8807 return ICmpInst::compare(LHS, RHS, ICI->getPredicate()); 8808 } 8809 8810 static APInt calculateCastInst(const CastInst *CI, const APInt &Src, 8811 uint32_t ResultBitWidth) { 8812 Instruction::CastOps CastOp = CI->getOpcode(); 8813 switch (CastOp) { 8814 default: 8815 llvm_unreachable("unsupported or not integer cast"); 8816 case Instruction::Trunc: 8817 return Src.trunc(ResultBitWidth); 8818 case Instruction::SExt: 8819 return Src.sext(ResultBitWidth); 8820 case Instruction::ZExt: 8821 return Src.zext(ResultBitWidth); 8822 case Instruction::BitCast: 8823 return Src; 8824 } 8825 } 8826 8827 static APInt calculateBinaryOperator(const BinaryOperator *BinOp, 8828 const APInt &LHS, const APInt &RHS, 8829 bool &SkipOperation, bool &Unsupported) { 8830 Instruction::BinaryOps BinOpcode = BinOp->getOpcode(); 8831 // Unsupported is set to true when the binary operator is not supported. 8832 // SkipOperation is set to true when UB occur with the given operand pair 8833 // (LHS, RHS). 8834 // TODO: we should look at nsw and nuw keywords to handle operations 8835 // that create poison or undef value. 8836 switch (BinOpcode) { 8837 default: 8838 Unsupported = true; 8839 return LHS; 8840 case Instruction::Add: 8841 return LHS + RHS; 8842 case Instruction::Sub: 8843 return LHS - RHS; 8844 case Instruction::Mul: 8845 return LHS * RHS; 8846 case Instruction::UDiv: 8847 if (RHS.isZero()) { 8848 SkipOperation = true; 8849 return LHS; 8850 } 8851 return LHS.udiv(RHS); 8852 case Instruction::SDiv: 8853 if (RHS.isZero()) { 8854 SkipOperation = true; 8855 return LHS; 8856 } 8857 return LHS.sdiv(RHS); 8858 case Instruction::URem: 8859 if (RHS.isZero()) { 8860 SkipOperation = true; 8861 return LHS; 8862 } 8863 return LHS.urem(RHS); 8864 case Instruction::SRem: 8865 if (RHS.isZero()) { 8866 SkipOperation = true; 8867 return LHS; 8868 } 8869 return LHS.srem(RHS); 8870 case Instruction::Shl: 8871 return LHS.shl(RHS); 8872 case Instruction::LShr: 8873 return LHS.lshr(RHS); 8874 case Instruction::AShr: 8875 return LHS.ashr(RHS); 8876 case Instruction::And: 8877 return LHS & RHS; 8878 case Instruction::Or: 8879 return LHS | RHS; 8880 case Instruction::Xor: 8881 return LHS ^ RHS; 8882 } 8883 } 8884 8885 bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp, 8886 const APInt &LHS, const APInt &RHS) { 8887 bool SkipOperation = false; 8888 bool Unsupported = false; 8889 APInt Result = 8890 calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported); 8891 if (Unsupported) 8892 return false; 8893 // If SkipOperation is true, we can ignore this operand pair (L, R). 8894 if (!SkipOperation) 8895 unionAssumed(Result); 8896 return isValidState(); 8897 } 8898 8899 ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) { 8900 auto AssumedBefore = getAssumed(); 8901 Value *LHS = ICI->getOperand(0); 8902 Value *RHS = ICI->getOperand(1); 8903 8904 bool LHSContainsUndef = false, RHSContainsUndef = false; 8905 SetTy LHSAAPVS, RHSAAPVS; 8906 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS, 8907 LHSContainsUndef) || 8908 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS, 8909 RHSContainsUndef)) 8910 return indicatePessimisticFixpoint(); 8911 8912 // TODO: make use of undef flag to limit potential values aggressively. 8913 bool MaybeTrue = false, MaybeFalse = false; 8914 const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0); 8915 if (LHSContainsUndef && RHSContainsUndef) { 8916 // The result of any comparison between undefs can be soundly replaced 8917 // with undef. 8918 unionAssumedWithUndef(); 8919 } else if (LHSContainsUndef) { 8920 for (const APInt &R : RHSAAPVS) { 8921 bool CmpResult = calculateICmpInst(ICI, Zero, R); 8922 MaybeTrue |= CmpResult; 8923 MaybeFalse |= !CmpResult; 8924 if (MaybeTrue & MaybeFalse) 8925 return indicatePessimisticFixpoint(); 8926 } 8927 } else if (RHSContainsUndef) { 8928 for (const APInt &L : LHSAAPVS) { 8929 bool CmpResult = calculateICmpInst(ICI, L, Zero); 8930 MaybeTrue |= CmpResult; 8931 MaybeFalse |= !CmpResult; 8932 if (MaybeTrue & MaybeFalse) 8933 return indicatePessimisticFixpoint(); 8934 } 8935 } else { 8936 for (const APInt &L : LHSAAPVS) { 8937 for (const APInt &R : RHSAAPVS) { 8938 bool CmpResult = calculateICmpInst(ICI, L, R); 8939 MaybeTrue |= CmpResult; 8940 MaybeFalse |= !CmpResult; 8941 if (MaybeTrue & MaybeFalse) 8942 return indicatePessimisticFixpoint(); 8943 } 8944 } 8945 } 8946 if (MaybeTrue) 8947 unionAssumed(APInt(/* numBits */ 1, /* val */ 1)); 8948 if (MaybeFalse) 8949 unionAssumed(APInt(/* numBits */ 1, /* val */ 0)); 8950 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 8951 : ChangeStatus::CHANGED; 8952 } 8953 8954 ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) { 8955 auto AssumedBefore = getAssumed(); 8956 Value *LHS = SI->getTrueValue(); 8957 Value *RHS = SI->getFalseValue(); 8958 8959 bool UsedAssumedInformation = false; 8960 Optional<Constant *> C = A.getAssumedConstant(*SI->getCondition(), *this, 8961 UsedAssumedInformation); 8962 8963 // Check if we only need one operand. 8964 bool OnlyLeft = false, OnlyRight = false; 8965 if (C && *C && (*C)->isOneValue()) 8966 OnlyLeft = true; 8967 else if (C && *C && (*C)->isZeroValue()) 8968 OnlyRight = true; 8969 8970 bool LHSContainsUndef = false, RHSContainsUndef = false; 8971 SetTy LHSAAPVS, RHSAAPVS; 8972 if (!OnlyRight && !fillSetWithConstantValues(A, IRPosition::value(*LHS), 8973 LHSAAPVS, LHSContainsUndef)) 8974 return indicatePessimisticFixpoint(); 8975 8976 if (!OnlyLeft && !fillSetWithConstantValues(A, IRPosition::value(*RHS), 8977 RHSAAPVS, RHSContainsUndef)) 8978 return indicatePessimisticFixpoint(); 8979 8980 if (OnlyLeft || OnlyRight) { 8981 // select (true/false), lhs, rhs 8982 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS; 8983 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef; 8984 8985 if (Undef) 8986 unionAssumedWithUndef(); 8987 else { 8988 for (auto &It : *OpAA) 8989 unionAssumed(It); 8990 } 8991 8992 } else if (LHSContainsUndef && RHSContainsUndef) { 8993 // select i1 *, undef , undef => undef 8994 unionAssumedWithUndef(); 8995 } else { 8996 for (auto &It : LHSAAPVS) 8997 unionAssumed(It); 8998 for (auto &It : RHSAAPVS) 8999 unionAssumed(It); 9000 } 9001 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9002 : ChangeStatus::CHANGED; 9003 } 9004 9005 ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) { 9006 auto AssumedBefore = getAssumed(); 9007 if (!CI->isIntegerCast()) 9008 return indicatePessimisticFixpoint(); 9009 assert(CI->getNumOperands() == 1 && "Expected cast to be unary!"); 9010 uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth(); 9011 Value *Src = CI->getOperand(0); 9012 9013 bool SrcContainsUndef = false; 9014 SetTy SrcPVS; 9015 if (!fillSetWithConstantValues(A, IRPosition::value(*Src), SrcPVS, 9016 SrcContainsUndef)) 9017 return indicatePessimisticFixpoint(); 9018 9019 if (SrcContainsUndef) 9020 unionAssumedWithUndef(); 9021 else { 9022 for (const APInt &S : SrcPVS) { 9023 APInt T = calculateCastInst(CI, S, ResultBitWidth); 9024 unionAssumed(T); 9025 } 9026 } 9027 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9028 : ChangeStatus::CHANGED; 9029 } 9030 9031 ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) { 9032 auto AssumedBefore = getAssumed(); 9033 Value *LHS = BinOp->getOperand(0); 9034 Value *RHS = BinOp->getOperand(1); 9035 9036 bool LHSContainsUndef = false, RHSContainsUndef = false; 9037 SetTy LHSAAPVS, RHSAAPVS; 9038 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS, 9039 LHSContainsUndef) || 9040 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS, 9041 RHSContainsUndef)) 9042 return indicatePessimisticFixpoint(); 9043 9044 const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0); 9045 9046 // TODO: make use of undef flag to limit potential values aggressively. 9047 if (LHSContainsUndef && RHSContainsUndef) { 9048 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero)) 9049 return indicatePessimisticFixpoint(); 9050 } else if (LHSContainsUndef) { 9051 for (const APInt &R : RHSAAPVS) { 9052 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R)) 9053 return indicatePessimisticFixpoint(); 9054 } 9055 } else if (RHSContainsUndef) { 9056 for (const APInt &L : LHSAAPVS) { 9057 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero)) 9058 return indicatePessimisticFixpoint(); 9059 } 9060 } else { 9061 for (const APInt &L : LHSAAPVS) { 9062 for (const APInt &R : RHSAAPVS) { 9063 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R)) 9064 return indicatePessimisticFixpoint(); 9065 } 9066 } 9067 } 9068 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9069 : ChangeStatus::CHANGED; 9070 } 9071 9072 /// See AbstractAttribute::updateImpl(...). 9073 ChangeStatus updateImpl(Attributor &A) override { 9074 Value &V = getAssociatedValue(); 9075 Instruction *I = dyn_cast<Instruction>(&V); 9076 9077 if (auto *ICI = dyn_cast<ICmpInst>(I)) 9078 return updateWithICmpInst(A, ICI); 9079 9080 if (auto *SI = dyn_cast<SelectInst>(I)) 9081 return updateWithSelectInst(A, SI); 9082 9083 if (auto *CI = dyn_cast<CastInst>(I)) 9084 return updateWithCastInst(A, CI); 9085 9086 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) 9087 return updateWithBinaryOperator(A, BinOp); 9088 9089 return indicatePessimisticFixpoint(); 9090 } 9091 9092 /// See AbstractAttribute::trackStatistics() 9093 void trackStatistics() const override { 9094 STATS_DECLTRACK_FLOATING_ATTR(potential_values) 9095 } 9096 }; 9097 9098 struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl { 9099 AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A) 9100 : AAPotentialConstantValuesImpl(IRP, A) {} 9101 9102 /// See AbstractAttribute::initialize(...). 9103 ChangeStatus updateImpl(Attributor &A) override { 9104 llvm_unreachable( 9105 "AAPotentialConstantValues(Function|CallSite)::updateImpl will " 9106 "not be called"); 9107 } 9108 9109 /// See AbstractAttribute::trackStatistics() 9110 void trackStatistics() const override { 9111 STATS_DECLTRACK_FN_ATTR(potential_values) 9112 } 9113 }; 9114 9115 struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction { 9116 AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A) 9117 : AAPotentialConstantValuesFunction(IRP, A) {} 9118 9119 /// See AbstractAttribute::trackStatistics() 9120 void trackStatistics() const override { 9121 STATS_DECLTRACK_CS_ATTR(potential_values) 9122 } 9123 }; 9124 9125 struct AAPotentialConstantValuesCallSiteReturned 9126 : AACallSiteReturnedFromReturned<AAPotentialConstantValues, 9127 AAPotentialConstantValuesImpl> { 9128 AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP, 9129 Attributor &A) 9130 : AACallSiteReturnedFromReturned<AAPotentialConstantValues, 9131 AAPotentialConstantValuesImpl>(IRP, A) {} 9132 9133 /// See AbstractAttribute::trackStatistics() 9134 void trackStatistics() const override { 9135 STATS_DECLTRACK_CSRET_ATTR(potential_values) 9136 } 9137 }; 9138 9139 struct AAPotentialConstantValuesCallSiteArgument 9140 : AAPotentialConstantValuesFloating { 9141 AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP, 9142 Attributor &A) 9143 : AAPotentialConstantValuesFloating(IRP, A) {} 9144 9145 /// See AbstractAttribute::initialize(..). 9146 void initialize(Attributor &A) override { 9147 AAPotentialConstantValuesImpl::initialize(A); 9148 if (isAtFixpoint()) 9149 return; 9150 9151 Value &V = getAssociatedValue(); 9152 9153 if (auto *C = dyn_cast<ConstantInt>(&V)) { 9154 unionAssumed(C->getValue()); 9155 indicateOptimisticFixpoint(); 9156 return; 9157 } 9158 9159 if (isa<UndefValue>(&V)) { 9160 unionAssumedWithUndef(); 9161 indicateOptimisticFixpoint(); 9162 return; 9163 } 9164 } 9165 9166 /// See AbstractAttribute::updateImpl(...). 9167 ChangeStatus updateImpl(Attributor &A) override { 9168 Value &V = getAssociatedValue(); 9169 auto AssumedBefore = getAssumed(); 9170 auto &AA = A.getAAFor<AAPotentialConstantValues>( 9171 *this, IRPosition::value(V), DepClassTy::REQUIRED); 9172 const auto &S = AA.getAssumed(); 9173 unionAssumed(S); 9174 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 9175 : ChangeStatus::CHANGED; 9176 } 9177 9178 /// See AbstractAttribute::trackStatistics() 9179 void trackStatistics() const override { 9180 STATS_DECLTRACK_CSARG_ATTR(potential_values) 9181 } 9182 }; 9183 9184 /// ------------------------ NoUndef Attribute --------------------------------- 9185 struct AANoUndefImpl : AANoUndef { 9186 AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {} 9187 9188 /// See AbstractAttribute::initialize(...). 9189 void initialize(Attributor &A) override { 9190 if (getIRPosition().hasAttr({Attribute::NoUndef})) { 9191 indicateOptimisticFixpoint(); 9192 return; 9193 } 9194 Value &V = getAssociatedValue(); 9195 if (isa<UndefValue>(V)) 9196 indicatePessimisticFixpoint(); 9197 else if (isa<FreezeInst>(V)) 9198 indicateOptimisticFixpoint(); 9199 else if (getPositionKind() != IRPosition::IRP_RETURNED && 9200 isGuaranteedNotToBeUndefOrPoison(&V)) 9201 indicateOptimisticFixpoint(); 9202 else 9203 AANoUndef::initialize(A); 9204 } 9205 9206 /// See followUsesInMBEC 9207 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 9208 AANoUndef::StateType &State) { 9209 const Value *UseV = U->get(); 9210 const DominatorTree *DT = nullptr; 9211 AssumptionCache *AC = nullptr; 9212 InformationCache &InfoCache = A.getInfoCache(); 9213 if (Function *F = getAnchorScope()) { 9214 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F); 9215 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F); 9216 } 9217 State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT)); 9218 bool TrackUse = false; 9219 // Track use for instructions which must produce undef or poison bits when 9220 // at least one operand contains such bits. 9221 if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I)) 9222 TrackUse = true; 9223 return TrackUse; 9224 } 9225 9226 /// See AbstractAttribute::getAsStr(). 9227 const std::string getAsStr() const override { 9228 return getAssumed() ? "noundef" : "may-undef-or-poison"; 9229 } 9230 9231 ChangeStatus manifest(Attributor &A) override { 9232 // We don't manifest noundef attribute for dead positions because the 9233 // associated values with dead positions would be replaced with undef 9234 // values. 9235 bool UsedAssumedInformation = false; 9236 if (A.isAssumedDead(getIRPosition(), nullptr, nullptr, 9237 UsedAssumedInformation)) 9238 return ChangeStatus::UNCHANGED; 9239 // A position whose simplified value does not have any value is 9240 // considered to be dead. We don't manifest noundef in such positions for 9241 // the same reason above. 9242 if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation, 9243 AA::Interprocedural) 9244 .has_value()) 9245 return ChangeStatus::UNCHANGED; 9246 return AANoUndef::manifest(A); 9247 } 9248 }; 9249 9250 struct AANoUndefFloating : public AANoUndefImpl { 9251 AANoUndefFloating(const IRPosition &IRP, Attributor &A) 9252 : AANoUndefImpl(IRP, A) {} 9253 9254 /// See AbstractAttribute::initialize(...). 9255 void initialize(Attributor &A) override { 9256 AANoUndefImpl::initialize(A); 9257 if (!getState().isAtFixpoint()) 9258 if (Instruction *CtxI = getCtxI()) 9259 followUsesInMBEC(*this, A, getState(), *CtxI); 9260 } 9261 9262 /// See AbstractAttribute::updateImpl(...). 9263 ChangeStatus updateImpl(Attributor &A) override { 9264 9265 SmallVector<AA::ValueAndContext> Values; 9266 bool UsedAssumedInformation = false; 9267 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values, 9268 AA::AnyScope, UsedAssumedInformation)) { 9269 Values.push_back({getAssociatedValue(), getCtxI()}); 9270 } 9271 9272 StateType T; 9273 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool { 9274 const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V), 9275 DepClassTy::REQUIRED); 9276 if (this == &AA) { 9277 T.indicatePessimisticFixpoint(); 9278 } else { 9279 const AANoUndef::StateType &S = 9280 static_cast<const AANoUndef::StateType &>(AA.getState()); 9281 T ^= S; 9282 } 9283 return T.isValidState(); 9284 }; 9285 9286 for (const auto &VAC : Values) 9287 if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI())) 9288 return indicatePessimisticFixpoint(); 9289 9290 return clampStateAndIndicateChange(getState(), T); 9291 } 9292 9293 /// See AbstractAttribute::trackStatistics() 9294 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 9295 }; 9296 9297 struct AANoUndefReturned final 9298 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> { 9299 AANoUndefReturned(const IRPosition &IRP, Attributor &A) 9300 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {} 9301 9302 /// See AbstractAttribute::trackStatistics() 9303 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 9304 }; 9305 9306 struct AANoUndefArgument final 9307 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> { 9308 AANoUndefArgument(const IRPosition &IRP, Attributor &A) 9309 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {} 9310 9311 /// See AbstractAttribute::trackStatistics() 9312 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) } 9313 }; 9314 9315 struct AANoUndefCallSiteArgument final : AANoUndefFloating { 9316 AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A) 9317 : AANoUndefFloating(IRP, A) {} 9318 9319 /// See AbstractAttribute::trackStatistics() 9320 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) } 9321 }; 9322 9323 struct AANoUndefCallSiteReturned final 9324 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> { 9325 AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A) 9326 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {} 9327 9328 /// See AbstractAttribute::trackStatistics() 9329 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) } 9330 }; 9331 9332 struct AACallEdgesImpl : public AACallEdges { 9333 AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {} 9334 9335 const SetVector<Function *> &getOptimisticEdges() const override { 9336 return CalledFunctions; 9337 } 9338 9339 bool hasUnknownCallee() const override { return HasUnknownCallee; } 9340 9341 bool hasNonAsmUnknownCallee() const override { 9342 return HasUnknownCalleeNonAsm; 9343 } 9344 9345 const std::string getAsStr() const override { 9346 return "CallEdges[" + std::to_string(HasUnknownCallee) + "," + 9347 std::to_string(CalledFunctions.size()) + "]"; 9348 } 9349 9350 void trackStatistics() const override {} 9351 9352 protected: 9353 void addCalledFunction(Function *Fn, ChangeStatus &Change) { 9354 if (CalledFunctions.insert(Fn)) { 9355 Change = ChangeStatus::CHANGED; 9356 LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName() 9357 << "\n"); 9358 } 9359 } 9360 9361 void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) { 9362 if (!HasUnknownCallee) 9363 Change = ChangeStatus::CHANGED; 9364 if (NonAsm && !HasUnknownCalleeNonAsm) 9365 Change = ChangeStatus::CHANGED; 9366 HasUnknownCalleeNonAsm |= NonAsm; 9367 HasUnknownCallee = true; 9368 } 9369 9370 private: 9371 /// Optimistic set of functions that might be called by this position. 9372 SetVector<Function *> CalledFunctions; 9373 9374 /// Is there any call with a unknown callee. 9375 bool HasUnknownCallee = false; 9376 9377 /// Is there any call with a unknown callee, excluding any inline asm. 9378 bool HasUnknownCalleeNonAsm = false; 9379 }; 9380 9381 struct AACallEdgesCallSite : public AACallEdgesImpl { 9382 AACallEdgesCallSite(const IRPosition &IRP, Attributor &A) 9383 : AACallEdgesImpl(IRP, A) {} 9384 /// See AbstractAttribute::updateImpl(...). 9385 ChangeStatus updateImpl(Attributor &A) override { 9386 ChangeStatus Change = ChangeStatus::UNCHANGED; 9387 9388 auto VisitValue = [&](Value &V, const Instruction *CtxI) -> bool { 9389 if (Function *Fn = dyn_cast<Function>(&V)) { 9390 addCalledFunction(Fn, Change); 9391 } else { 9392 LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n"); 9393 setHasUnknownCallee(true, Change); 9394 } 9395 9396 // Explore all values. 9397 return true; 9398 }; 9399 9400 SmallVector<AA::ValueAndContext> Values; 9401 // Process any value that we might call. 9402 auto ProcessCalledOperand = [&](Value *V, Instruction *CtxI) { 9403 bool UsedAssumedInformation = false; 9404 Values.clear(); 9405 if (!A.getAssumedSimplifiedValues(IRPosition::value(*V), *this, Values, 9406 AA::AnyScope, UsedAssumedInformation)) { 9407 Values.push_back({*V, CtxI}); 9408 } 9409 for (auto &VAC : Values) 9410 VisitValue(*VAC.getValue(), VAC.getCtxI()); 9411 }; 9412 9413 CallBase *CB = cast<CallBase>(getCtxI()); 9414 9415 if (CB->isInlineAsm()) { 9416 if (!hasAssumption(*CB->getCaller(), "ompx_no_call_asm") && 9417 !hasAssumption(*CB, "ompx_no_call_asm")) 9418 setHasUnknownCallee(false, Change); 9419 return Change; 9420 } 9421 9422 // Process callee metadata if available. 9423 if (auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees)) { 9424 for (auto &Op : MD->operands()) { 9425 Function *Callee = mdconst::dyn_extract_or_null<Function>(Op); 9426 if (Callee) 9427 addCalledFunction(Callee, Change); 9428 } 9429 return Change; 9430 } 9431 9432 // The most simple case. 9433 ProcessCalledOperand(CB->getCalledOperand(), CB); 9434 9435 // Process callback functions. 9436 SmallVector<const Use *, 4u> CallbackUses; 9437 AbstractCallSite::getCallbackUses(*CB, CallbackUses); 9438 for (const Use *U : CallbackUses) 9439 ProcessCalledOperand(U->get(), CB); 9440 9441 return Change; 9442 } 9443 }; 9444 9445 struct AACallEdgesFunction : public AACallEdgesImpl { 9446 AACallEdgesFunction(const IRPosition &IRP, Attributor &A) 9447 : AACallEdgesImpl(IRP, A) {} 9448 9449 /// See AbstractAttribute::updateImpl(...). 9450 ChangeStatus updateImpl(Attributor &A) override { 9451 ChangeStatus Change = ChangeStatus::UNCHANGED; 9452 9453 auto ProcessCallInst = [&](Instruction &Inst) { 9454 CallBase &CB = cast<CallBase>(Inst); 9455 9456 auto &CBEdges = A.getAAFor<AACallEdges>( 9457 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9458 if (CBEdges.hasNonAsmUnknownCallee()) 9459 setHasUnknownCallee(true, Change); 9460 if (CBEdges.hasUnknownCallee()) 9461 setHasUnknownCallee(false, Change); 9462 9463 for (Function *F : CBEdges.getOptimisticEdges()) 9464 addCalledFunction(F, Change); 9465 9466 return true; 9467 }; 9468 9469 // Visit all callable instructions. 9470 bool UsedAssumedInformation = false; 9471 if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this, 9472 UsedAssumedInformation, 9473 /* CheckBBLivenessOnly */ true)) { 9474 // If we haven't looked at all call like instructions, assume that there 9475 // are unknown callees. 9476 setHasUnknownCallee(true, Change); 9477 } 9478 9479 return Change; 9480 } 9481 }; 9482 9483 struct AAFunctionReachabilityFunction : public AAFunctionReachability { 9484 private: 9485 struct QuerySet { 9486 void markReachable(const Function &Fn) { 9487 Reachable.insert(&Fn); 9488 Unreachable.erase(&Fn); 9489 } 9490 9491 /// If there is no information about the function None is returned. 9492 Optional<bool> isCachedReachable(const Function &Fn) { 9493 // Assume that we can reach the function. 9494 // TODO: Be more specific with the unknown callee. 9495 if (CanReachUnknownCallee) 9496 return true; 9497 9498 if (Reachable.count(&Fn)) 9499 return true; 9500 9501 if (Unreachable.count(&Fn)) 9502 return false; 9503 9504 return llvm::None; 9505 } 9506 9507 /// Set of functions that we know for sure is reachable. 9508 DenseSet<const Function *> Reachable; 9509 9510 /// Set of functions that are unreachable, but might become reachable. 9511 DenseSet<const Function *> Unreachable; 9512 9513 /// If we can reach a function with a call to a unknown function we assume 9514 /// that we can reach any function. 9515 bool CanReachUnknownCallee = false; 9516 }; 9517 9518 struct QueryResolver : public QuerySet { 9519 ChangeStatus update(Attributor &A, const AAFunctionReachability &AA, 9520 ArrayRef<const AACallEdges *> AAEdgesList) { 9521 ChangeStatus Change = ChangeStatus::UNCHANGED; 9522 9523 for (auto *AAEdges : AAEdgesList) { 9524 if (AAEdges->hasUnknownCallee()) { 9525 if (!CanReachUnknownCallee) { 9526 LLVM_DEBUG(dbgs() 9527 << "[QueryResolver] Edges include unknown callee!\n"); 9528 Change = ChangeStatus::CHANGED; 9529 } 9530 CanReachUnknownCallee = true; 9531 return Change; 9532 } 9533 } 9534 9535 for (const Function *Fn : make_early_inc_range(Unreachable)) { 9536 if (checkIfReachable(A, AA, AAEdgesList, *Fn)) { 9537 Change = ChangeStatus::CHANGED; 9538 markReachable(*Fn); 9539 } 9540 } 9541 return Change; 9542 } 9543 9544 bool isReachable(Attributor &A, AAFunctionReachability &AA, 9545 ArrayRef<const AACallEdges *> AAEdgesList, 9546 const Function &Fn) { 9547 Optional<bool> Cached = isCachedReachable(Fn); 9548 if (Cached) 9549 return Cached.value(); 9550 9551 // The query was not cached, thus it is new. We need to request an update 9552 // explicitly to make sure this the information is properly run to a 9553 // fixpoint. 9554 A.registerForUpdate(AA); 9555 9556 // We need to assume that this function can't reach Fn to prevent 9557 // an infinite loop if this function is recursive. 9558 Unreachable.insert(&Fn); 9559 9560 bool Result = checkIfReachable(A, AA, AAEdgesList, Fn); 9561 if (Result) 9562 markReachable(Fn); 9563 return Result; 9564 } 9565 9566 bool checkIfReachable(Attributor &A, const AAFunctionReachability &AA, 9567 ArrayRef<const AACallEdges *> AAEdgesList, 9568 const Function &Fn) const { 9569 9570 // Handle the most trivial case first. 9571 for (auto *AAEdges : AAEdgesList) { 9572 const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges(); 9573 9574 if (Edges.count(const_cast<Function *>(&Fn))) 9575 return true; 9576 } 9577 9578 SmallVector<const AAFunctionReachability *, 8> Deps; 9579 for (auto &AAEdges : AAEdgesList) { 9580 const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges(); 9581 9582 for (Function *Edge : Edges) { 9583 // Functions that do not call back into the module can be ignored. 9584 if (Edge->hasFnAttribute(Attribute::NoCallback)) 9585 continue; 9586 9587 // We don't need a dependency if the result is reachable. 9588 const AAFunctionReachability &EdgeReachability = 9589 A.getAAFor<AAFunctionReachability>( 9590 AA, IRPosition::function(*Edge), DepClassTy::NONE); 9591 Deps.push_back(&EdgeReachability); 9592 9593 if (EdgeReachability.canReach(A, Fn)) 9594 return true; 9595 } 9596 } 9597 9598 // The result is false for now, set dependencies and leave. 9599 for (auto *Dep : Deps) 9600 A.recordDependence(*Dep, AA, DepClassTy::REQUIRED); 9601 9602 return false; 9603 } 9604 }; 9605 9606 /// Get call edges that can be reached by this instruction. 9607 bool getReachableCallEdges(Attributor &A, const AAReachability &Reachability, 9608 const Instruction &Inst, 9609 SmallVector<const AACallEdges *> &Result) const { 9610 // Determine call like instructions that we can reach from the inst. 9611 auto CheckCallBase = [&](Instruction &CBInst) { 9612 if (!Reachability.isAssumedReachable(A, Inst, CBInst)) 9613 return true; 9614 9615 auto &CB = cast<CallBase>(CBInst); 9616 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9617 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9618 9619 Result.push_back(&AAEdges); 9620 return true; 9621 }; 9622 9623 bool UsedAssumedInformation = false; 9624 return A.checkForAllCallLikeInstructions(CheckCallBase, *this, 9625 UsedAssumedInformation, 9626 /* CheckBBLivenessOnly */ true); 9627 } 9628 9629 public: 9630 AAFunctionReachabilityFunction(const IRPosition &IRP, Attributor &A) 9631 : AAFunctionReachability(IRP, A) {} 9632 9633 bool canReach(Attributor &A, const Function &Fn) const override { 9634 if (!isValidState()) 9635 return true; 9636 9637 const AACallEdges &AAEdges = 9638 A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED); 9639 9640 // Attributor returns attributes as const, so this function has to be 9641 // const for users of this attribute to use it without having to do 9642 // a const_cast. 9643 // This is a hack for us to be able to cache queries. 9644 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9645 bool Result = NonConstThis->WholeFunction.isReachable(A, *NonConstThis, 9646 {&AAEdges}, Fn); 9647 9648 return Result; 9649 } 9650 9651 /// Can \p CB reach \p Fn 9652 bool canReach(Attributor &A, CallBase &CB, 9653 const Function &Fn) const override { 9654 if (!isValidState()) 9655 return true; 9656 9657 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9658 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 9659 9660 // Attributor returns attributes as const, so this function has to be 9661 // const for users of this attribute to use it without having to do 9662 // a const_cast. 9663 // This is a hack for us to be able to cache queries. 9664 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9665 QueryResolver &CBQuery = NonConstThis->CBQueries[&CB]; 9666 9667 bool Result = CBQuery.isReachable(A, *NonConstThis, {&AAEdges}, Fn); 9668 9669 return Result; 9670 } 9671 9672 bool instructionCanReach(Attributor &A, const Instruction &Inst, 9673 const Function &Fn) const override { 9674 if (!isValidState()) 9675 return true; 9676 9677 const auto &Reachability = A.getAAFor<AAReachability>( 9678 *this, IRPosition::function(*getAssociatedFunction()), 9679 DepClassTy::REQUIRED); 9680 9681 SmallVector<const AACallEdges *> CallEdges; 9682 bool AllKnown = getReachableCallEdges(A, Reachability, Inst, CallEdges); 9683 // Attributor returns attributes as const, so this function has to be 9684 // const for users of this attribute to use it without having to do 9685 // a const_cast. 9686 // This is a hack for us to be able to cache queries. 9687 auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this); 9688 QueryResolver &InstQSet = NonConstThis->InstQueries[&Inst]; 9689 if (!AllKnown) { 9690 LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges known, " 9691 "may reach unknown callee!\n"); 9692 InstQSet.CanReachUnknownCallee = true; 9693 } 9694 9695 return InstQSet.isReachable(A, *NonConstThis, CallEdges, Fn); 9696 } 9697 9698 /// See AbstractAttribute::updateImpl(...). 9699 ChangeStatus updateImpl(Attributor &A) override { 9700 const AACallEdges &AAEdges = 9701 A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED); 9702 ChangeStatus Change = ChangeStatus::UNCHANGED; 9703 9704 Change |= WholeFunction.update(A, *this, {&AAEdges}); 9705 9706 for (auto &CBPair : CBQueries) { 9707 const AACallEdges &AAEdges = A.getAAFor<AACallEdges>( 9708 *this, IRPosition::callsite_function(*CBPair.first), 9709 DepClassTy::REQUIRED); 9710 9711 Change |= CBPair.second.update(A, *this, {&AAEdges}); 9712 } 9713 9714 // Update the Instruction queries. 9715 if (!InstQueries.empty()) { 9716 const AAReachability *Reachability = &A.getAAFor<AAReachability>( 9717 *this, IRPosition::function(*getAssociatedFunction()), 9718 DepClassTy::REQUIRED); 9719 9720 // Check for local callbases first. 9721 for (auto &InstPair : InstQueries) { 9722 SmallVector<const AACallEdges *> CallEdges; 9723 bool AllKnown = 9724 getReachableCallEdges(A, *Reachability, *InstPair.first, CallEdges); 9725 // Update will return change if we this effects any queries. 9726 if (!AllKnown) { 9727 LLVM_DEBUG(dbgs() << "[AAReachability] Not all reachable edges " 9728 "known, may reach unknown callee!\n"); 9729 InstPair.second.CanReachUnknownCallee = true; 9730 } 9731 Change |= InstPair.second.update(A, *this, CallEdges); 9732 } 9733 } 9734 9735 return Change; 9736 } 9737 9738 const std::string getAsStr() const override { 9739 size_t QueryCount = 9740 WholeFunction.Reachable.size() + WholeFunction.Unreachable.size(); 9741 9742 return "FunctionReachability [" + 9743 (canReachUnknownCallee() 9744 ? "unknown" 9745 : (std::to_string(WholeFunction.Reachable.size()) + "," + 9746 std::to_string(QueryCount))) + 9747 "]"; 9748 } 9749 9750 void trackStatistics() const override {} 9751 9752 private: 9753 bool canReachUnknownCallee() const override { 9754 return WholeFunction.CanReachUnknownCallee; 9755 } 9756 9757 /// Used to answer if a the whole function can reacha a specific function. 9758 QueryResolver WholeFunction; 9759 9760 /// Used to answer if a call base inside this function can reach a specific 9761 /// function. 9762 MapVector<const CallBase *, QueryResolver> CBQueries; 9763 9764 /// This is for instruction queries than scan "forward". 9765 MapVector<const Instruction *, QueryResolver> InstQueries; 9766 }; 9767 } // namespace 9768 9769 template <typename AAType> 9770 static Optional<Constant *> 9771 askForAssumedConstant(Attributor &A, const AbstractAttribute &QueryingAA, 9772 const IRPosition &IRP, Type &Ty) { 9773 if (!Ty.isIntegerTy()) 9774 return nullptr; 9775 9776 // This will also pass the call base context. 9777 const auto &AA = A.getAAFor<AAType>(QueryingAA, IRP, DepClassTy::NONE); 9778 9779 Optional<Constant *> COpt = AA.getAssumedConstant(A); 9780 9781 if (!COpt.has_value()) { 9782 A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL); 9783 return llvm::None; 9784 } 9785 if (auto *C = COpt.value()) { 9786 A.recordDependence(AA, QueryingAA, DepClassTy::OPTIONAL); 9787 return C; 9788 } 9789 return nullptr; 9790 } 9791 9792 Value *AAPotentialValues::getSingleValue( 9793 Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP, 9794 SmallVectorImpl<AA::ValueAndContext> &Values) { 9795 Type &Ty = *IRP.getAssociatedType(); 9796 Optional<Value *> V; 9797 for (auto &It : Values) { 9798 V = AA::combineOptionalValuesInAAValueLatice(V, It.getValue(), &Ty); 9799 if (V.has_value() && !V.value()) 9800 break; 9801 } 9802 if (!V.has_value()) 9803 return UndefValue::get(&Ty); 9804 return V.value(); 9805 } 9806 9807 namespace { 9808 struct AAPotentialValuesImpl : AAPotentialValues { 9809 using StateType = PotentialLLVMValuesState; 9810 9811 AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A) 9812 : AAPotentialValues(IRP, A) {} 9813 9814 /// See AbstractAttribute::initialize(..). 9815 void initialize(Attributor &A) override { 9816 if (A.hasSimplificationCallback(getIRPosition())) { 9817 indicatePessimisticFixpoint(); 9818 return; 9819 } 9820 Value *Stripped = getAssociatedValue().stripPointerCasts(); 9821 if (isa<Constant>(Stripped)) { 9822 addValue(A, getState(), *Stripped, getCtxI(), AA::AnyScope, 9823 getAnchorScope()); 9824 indicateOptimisticFixpoint(); 9825 return; 9826 } 9827 AAPotentialValues::initialize(A); 9828 } 9829 9830 /// See AbstractAttribute::getAsStr(). 9831 const std::string getAsStr() const override { 9832 std::string Str; 9833 llvm::raw_string_ostream OS(Str); 9834 OS << getState(); 9835 return OS.str(); 9836 } 9837 9838 template <typename AAType> 9839 static Optional<Value *> askOtherAA(Attributor &A, 9840 const AbstractAttribute &AA, 9841 const IRPosition &IRP, Type &Ty) { 9842 if (isa<Constant>(IRP.getAssociatedValue())) 9843 return &IRP.getAssociatedValue(); 9844 Optional<Constant *> C = askForAssumedConstant<AAType>(A, AA, IRP, Ty); 9845 if (!C) 9846 return llvm::None; 9847 if (C.value()) 9848 if (auto *CC = AA::getWithType(**C, Ty)) 9849 return CC; 9850 return nullptr; 9851 } 9852 9853 void addValue(Attributor &A, StateType &State, Value &V, 9854 const Instruction *CtxI, AA::ValueScope S, 9855 Function *AnchorScope) const { 9856 9857 IRPosition ValIRP = IRPosition::value(V); 9858 if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) { 9859 for (auto &U : CB->args()) { 9860 if (U.get() != &V) 9861 continue; 9862 ValIRP = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 9863 break; 9864 } 9865 } 9866 9867 Value *VPtr = &V; 9868 if (ValIRP.getAssociatedType()->isIntegerTy()) { 9869 Type &Ty = *getAssociatedType(); 9870 Optional<Value *> SimpleV = 9871 askOtherAA<AAValueConstantRange>(A, *this, ValIRP, Ty); 9872 if (SimpleV.has_value() && !SimpleV.value()) { 9873 auto &PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>( 9874 *this, ValIRP, DepClassTy::OPTIONAL); 9875 if (PotentialConstantsAA.isValidState()) { 9876 for (auto &It : PotentialConstantsAA.getAssumedSet()) { 9877 State.unionAssumed({{*ConstantInt::get(&Ty, It), nullptr}, S}); 9878 } 9879 assert(!PotentialConstantsAA.undefIsContained() && 9880 "Undef should be an explicit value!"); 9881 return; 9882 } 9883 } 9884 if (!SimpleV.has_value()) 9885 return; 9886 9887 if (SimpleV.value()) 9888 VPtr = SimpleV.value(); 9889 } 9890 9891 if (isa<ConstantInt>(VPtr)) 9892 CtxI = nullptr; 9893 if (!AA::isValidInScope(*VPtr, AnchorScope)) 9894 S = AA::ValueScope(S | AA::Interprocedural); 9895 9896 State.unionAssumed({{*VPtr, CtxI}, S}); 9897 } 9898 9899 /// Helper struct to tie a value+context pair together with the scope for 9900 /// which this is the simplified version. 9901 struct ItemInfo { 9902 AA::ValueAndContext I; 9903 AA::ValueScope S; 9904 }; 9905 9906 bool recurseForValue(Attributor &A, const IRPosition &IRP, AA::ValueScope S) { 9907 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap; 9908 for (auto CS : {AA::Intraprocedural, AA::Interprocedural}) { 9909 if (!(CS & S)) 9910 continue; 9911 9912 bool UsedAssumedInformation = false; 9913 SmallVector<AA::ValueAndContext> Values; 9914 if (!A.getAssumedSimplifiedValues(IRP, this, Values, CS, 9915 UsedAssumedInformation)) 9916 return false; 9917 9918 for (auto &It : Values) 9919 ValueScopeMap[It] += CS; 9920 } 9921 for (auto &It : ValueScopeMap) 9922 addValue(A, getState(), *It.first.getValue(), It.first.getCtxI(), 9923 AA::ValueScope(It.second), getAnchorScope()); 9924 9925 return true; 9926 } 9927 9928 void giveUpOnIntraprocedural(Attributor &A) { 9929 auto NewS = StateType::getBestState(getState()); 9930 for (auto &It : getAssumedSet()) { 9931 if (It.second == AA::Intraprocedural) 9932 continue; 9933 addValue(A, NewS, *It.first.getValue(), It.first.getCtxI(), 9934 AA::Interprocedural, getAnchorScope()); 9935 } 9936 assert(!undefIsContained() && "Undef should be an explicit value!"); 9937 addValue(A, NewS, getAssociatedValue(), getCtxI(), AA::Intraprocedural, 9938 getAnchorScope()); 9939 getState() = NewS; 9940 } 9941 9942 /// See AbstractState::indicatePessimisticFixpoint(...). 9943 ChangeStatus indicatePessimisticFixpoint() override { 9944 getState() = StateType::getBestState(getState()); 9945 getState().unionAssumed({{getAssociatedValue(), getCtxI()}, AA::AnyScope}); 9946 AAPotentialValues::indicateOptimisticFixpoint(); 9947 return ChangeStatus::CHANGED; 9948 } 9949 9950 /// See AbstractAttribute::updateImpl(...). 9951 ChangeStatus updateImpl(Attributor &A) override { 9952 return indicatePessimisticFixpoint(); 9953 } 9954 9955 /// See AbstractAttribute::manifest(...). 9956 ChangeStatus manifest(Attributor &A) override { 9957 SmallVector<AA::ValueAndContext> Values; 9958 for (AA::ValueScope S : {AA::Interprocedural, AA::Intraprocedural}) { 9959 Values.clear(); 9960 if (!getAssumedSimplifiedValues(A, Values, S)) 9961 continue; 9962 Value &OldV = getAssociatedValue(); 9963 if (isa<UndefValue>(OldV)) 9964 continue; 9965 Value *NewV = getSingleValue(A, *this, getIRPosition(), Values); 9966 if (!NewV || NewV == &OldV) 9967 continue; 9968 if (getCtxI() && 9969 !AA::isValidAtPosition({*NewV, *getCtxI()}, A.getInfoCache())) 9970 continue; 9971 if (A.changeAfterManifest(getIRPosition(), *NewV)) 9972 return ChangeStatus::CHANGED; 9973 } 9974 return ChangeStatus::UNCHANGED; 9975 } 9976 9977 bool getAssumedSimplifiedValues(Attributor &A, 9978 SmallVectorImpl<AA::ValueAndContext> &Values, 9979 AA::ValueScope S) const override { 9980 if (!isValidState()) 9981 return false; 9982 for (auto &It : getAssumedSet()) 9983 if (It.second & S) 9984 Values.push_back(It.first); 9985 assert(!undefIsContained() && "Undef should be an explicit value!"); 9986 return true; 9987 } 9988 }; 9989 9990 struct AAPotentialValuesFloating : AAPotentialValuesImpl { 9991 AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A) 9992 : AAPotentialValuesImpl(IRP, A) {} 9993 9994 /// See AbstractAttribute::updateImpl(...). 9995 ChangeStatus updateImpl(Attributor &A) override { 9996 auto AssumedBefore = getAssumed(); 9997 9998 genericValueTraversal(A); 9999 10000 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10001 : ChangeStatus::CHANGED; 10002 } 10003 10004 /// Helper struct to remember which AAIsDead instances we actually used. 10005 struct LivenessInfo { 10006 const AAIsDead *LivenessAA = nullptr; 10007 bool AnyDead = false; 10008 }; 10009 10010 /// Check if \p Cmp is a comparison we can simplify. 10011 /// 10012 /// We handle multiple cases, one in which at least one operand is an 10013 /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other 10014 /// operand. Return true if successful, in that case Worklist will be updated. 10015 bool handleCmp(Attributor &A, CmpInst &Cmp, ItemInfo II, 10016 SmallVectorImpl<ItemInfo> &Worklist) { 10017 Value *LHS = Cmp.getOperand(0); 10018 Value *RHS = Cmp.getOperand(1); 10019 10020 // Simplify the operands first. 10021 bool UsedAssumedInformation = false; 10022 const auto &SimplifiedLHS = A.getAssumedSimplified( 10023 IRPosition::value(*LHS, getCallBaseContext()), *this, 10024 UsedAssumedInformation, AA::Intraprocedural); 10025 if (!SimplifiedLHS.has_value()) 10026 return true; 10027 if (!SimplifiedLHS.value()) 10028 return false; 10029 LHS = *SimplifiedLHS; 10030 10031 const auto &SimplifiedRHS = A.getAssumedSimplified( 10032 IRPosition::value(*RHS, getCallBaseContext()), *this, 10033 UsedAssumedInformation, AA::Intraprocedural); 10034 if (!SimplifiedRHS.has_value()) 10035 return true; 10036 if (!SimplifiedRHS.value()) 10037 return false; 10038 RHS = *SimplifiedRHS; 10039 10040 LLVMContext &Ctx = Cmp.getContext(); 10041 // Handle the trivial case first in which we don't even need to think about 10042 // null or non-null. 10043 if (LHS == RHS && (Cmp.isTrueWhenEqual() || Cmp.isFalseWhenEqual())) { 10044 Constant *NewV = 10045 ConstantInt::get(Type::getInt1Ty(Ctx), Cmp.isTrueWhenEqual()); 10046 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S, 10047 getAnchorScope()); 10048 return true; 10049 } 10050 10051 // From now on we only handle equalities (==, !=). 10052 ICmpInst *ICmp = dyn_cast<ICmpInst>(&Cmp); 10053 if (!ICmp || !ICmp->isEquality()) 10054 return false; 10055 10056 bool LHSIsNull = isa<ConstantPointerNull>(LHS); 10057 bool RHSIsNull = isa<ConstantPointerNull>(RHS); 10058 if (!LHSIsNull && !RHSIsNull) 10059 return false; 10060 10061 // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the 10062 // non-nullptr operand and if we assume it's non-null we can conclude the 10063 // result of the comparison. 10064 assert((LHSIsNull || RHSIsNull) && 10065 "Expected nullptr versus non-nullptr comparison at this point"); 10066 10067 // The index is the operand that we assume is not null. 10068 unsigned PtrIdx = LHSIsNull; 10069 auto &PtrNonNullAA = A.getAAFor<AANonNull>( 10070 *this, IRPosition::value(*ICmp->getOperand(PtrIdx)), 10071 DepClassTy::REQUIRED); 10072 if (!PtrNonNullAA.isAssumedNonNull()) 10073 return false; 10074 10075 // The new value depends on the predicate, true for != and false for ==. 10076 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx), 10077 ICmp->getPredicate() == CmpInst::ICMP_NE); 10078 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S, getAnchorScope()); 10079 return true; 10080 } 10081 10082 bool handleSelectInst(Attributor &A, SelectInst &SI, ItemInfo II, 10083 SmallVectorImpl<ItemInfo> &Worklist) { 10084 const Instruction *CtxI = II.I.getCtxI(); 10085 bool UsedAssumedInformation = false; 10086 10087 Optional<Constant *> C = 10088 A.getAssumedConstant(*SI.getCondition(), *this, UsedAssumedInformation); 10089 bool NoValueYet = !C.has_value(); 10090 if (NoValueYet || isa_and_nonnull<UndefValue>(*C)) 10091 return true; 10092 if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) { 10093 if (CI->isZero()) 10094 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S}); 10095 else 10096 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S}); 10097 } else { 10098 // We could not simplify the condition, assume both values. 10099 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S}); 10100 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S}); 10101 } 10102 return true; 10103 } 10104 10105 bool handleLoadInst(Attributor &A, LoadInst &LI, ItemInfo II, 10106 SmallVectorImpl<ItemInfo> &Worklist) { 10107 SmallSetVector<Value *, 4> PotentialCopies; 10108 SmallSetVector<Instruction *, 4> PotentialValueOrigins; 10109 bool UsedAssumedInformation = false; 10110 if (!AA::getPotentiallyLoadedValues(A, LI, PotentialCopies, 10111 PotentialValueOrigins, *this, 10112 UsedAssumedInformation, 10113 /* OnlyExact */ true)) { 10114 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Failed to get potentially " 10115 "loaded values for load instruction " 10116 << LI << "\n"); 10117 return false; 10118 } 10119 10120 // Do not simplify loads that are only used in llvm.assume if we cannot also 10121 // remove all stores that may feed into the load. The reason is that the 10122 // assume is probably worth something as long as the stores are around. 10123 InformationCache &InfoCache = A.getInfoCache(); 10124 if (InfoCache.isOnlyUsedByAssume(LI)) { 10125 if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) { 10126 if (!I) 10127 return true; 10128 if (auto *SI = dyn_cast<StoreInst>(I)) 10129 return A.isAssumedDead(SI->getOperandUse(0), this, 10130 /* LivenessAA */ nullptr, 10131 UsedAssumedInformation, 10132 /* CheckBBLivenessOnly */ false); 10133 return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr, 10134 UsedAssumedInformation, 10135 /* CheckBBLivenessOnly */ false); 10136 })) { 10137 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Load is onl used by assumes " 10138 "and we cannot delete all the stores: " 10139 << LI << "\n"); 10140 return false; 10141 } 10142 } 10143 10144 // Values have to be dynamically unique or we loose the fact that a 10145 // single llvm::Value might represent two runtime values (e.g., 10146 // stack locations in different recursive calls). 10147 const Instruction *CtxI = II.I.getCtxI(); 10148 bool ScopeIsLocal = (II.S & AA::Intraprocedural); 10149 bool AllLocal = ScopeIsLocal; 10150 bool DynamicallyUnique = llvm::all_of(PotentialCopies, [&](Value *PC) { 10151 AllLocal &= AA::isValidInScope(*PC, getAnchorScope()); 10152 return AA::isDynamicallyUnique(A, *this, *PC); 10153 }); 10154 if (!DynamicallyUnique) { 10155 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Not all potentially loaded " 10156 "values are dynamically unique: " 10157 << LI << "\n"); 10158 return false; 10159 } 10160 10161 for (auto *PotentialCopy : PotentialCopies) { 10162 if (AllLocal) { 10163 Worklist.push_back({{*PotentialCopy, CtxI}, II.S}); 10164 } else { 10165 Worklist.push_back({{*PotentialCopy, CtxI}, AA::Interprocedural}); 10166 } 10167 } 10168 if (!AllLocal && ScopeIsLocal) 10169 addValue(A, getState(), LI, CtxI, AA::Intraprocedural, getAnchorScope()); 10170 return true; 10171 } 10172 10173 bool handlePHINode( 10174 Attributor &A, PHINode &PHI, ItemInfo II, 10175 SmallVectorImpl<ItemInfo> &Worklist, 10176 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) { 10177 auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & { 10178 LivenessInfo &LI = LivenessAAs[&F]; 10179 if (!LI.LivenessAA) 10180 LI.LivenessAA = &A.getAAFor<AAIsDead>(*this, IRPosition::function(F), 10181 DepClassTy::NONE); 10182 return LI; 10183 }; 10184 10185 LivenessInfo &LI = GetLivenessInfo(*PHI.getFunction()); 10186 for (unsigned u = 0, e = PHI.getNumIncomingValues(); u < e; u++) { 10187 BasicBlock *IncomingBB = PHI.getIncomingBlock(u); 10188 if (LI.LivenessAA->isEdgeDead(IncomingBB, PHI.getParent())) { 10189 LI.AnyDead = true; 10190 continue; 10191 } 10192 Worklist.push_back( 10193 {{*PHI.getIncomingValue(u), IncomingBB->getTerminator()}, II.S}); 10194 } 10195 return true; 10196 } 10197 10198 /// Use the generic, non-optimistic InstSimplfy functionality if we managed to 10199 /// simplify any operand of the instruction \p I. Return true if successful, 10200 /// in that case Worklist will be updated. 10201 bool handleGenericInst(Attributor &A, Instruction &I, ItemInfo II, 10202 SmallVectorImpl<ItemInfo> &Worklist) { 10203 bool SomeSimplified = false; 10204 bool UsedAssumedInformation = false; 10205 10206 SmallVector<Value *, 8> NewOps(I.getNumOperands()); 10207 int Idx = 0; 10208 for (Value *Op : I.operands()) { 10209 const auto &SimplifiedOp = A.getAssumedSimplified( 10210 IRPosition::value(*Op, getCallBaseContext()), *this, 10211 UsedAssumedInformation, AA::Intraprocedural); 10212 // If we are not sure about any operand we are not sure about the entire 10213 // instruction, we'll wait. 10214 if (!SimplifiedOp.has_value()) 10215 return true; 10216 10217 if (SimplifiedOp.value()) 10218 NewOps[Idx] = SimplifiedOp.value(); 10219 else 10220 NewOps[Idx] = Op; 10221 10222 SomeSimplified |= (NewOps[Idx] != Op); 10223 ++Idx; 10224 } 10225 10226 // We won't bother with the InstSimplify interface if we didn't simplify any 10227 // operand ourselves. 10228 if (!SomeSimplified) 10229 return false; 10230 10231 InformationCache &InfoCache = A.getInfoCache(); 10232 Function *F = I.getFunction(); 10233 const auto *DT = 10234 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F); 10235 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 10236 auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F); 10237 OptimizationRemarkEmitter *ORE = nullptr; 10238 10239 const DataLayout &DL = I.getModule()->getDataLayout(); 10240 SimplifyQuery Q(DL, TLI, DT, AC, &I); 10241 Value *NewV = simplifyInstructionWithOperands(&I, NewOps, Q, ORE); 10242 if (!NewV || NewV == &I) 10243 return false; 10244 10245 LLVM_DEBUG(dbgs() << "Generic inst " << I << " assumed simplified to " 10246 << *NewV << "\n"); 10247 Worklist.push_back({{*NewV, II.I.getCtxI()}, II.S}); 10248 return true; 10249 } 10250 10251 bool simplifyInstruction( 10252 Attributor &A, Instruction &I, ItemInfo II, 10253 SmallVectorImpl<ItemInfo> &Worklist, 10254 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) { 10255 if (auto *CI = dyn_cast<CmpInst>(&I)) 10256 if (handleCmp(A, *CI, II, Worklist)) 10257 return true; 10258 10259 switch (I.getOpcode()) { 10260 case Instruction::Select: 10261 return handleSelectInst(A, cast<SelectInst>(I), II, Worklist); 10262 case Instruction::PHI: 10263 return handlePHINode(A, cast<PHINode>(I), II, Worklist, LivenessAAs); 10264 case Instruction::Load: 10265 return handleLoadInst(A, cast<LoadInst>(I), II, Worklist); 10266 default: 10267 return handleGenericInst(A, I, II, Worklist); 10268 }; 10269 return false; 10270 } 10271 10272 void genericValueTraversal(Attributor &A) { 10273 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs; 10274 10275 Value *InitialV = &getAssociatedValue(); 10276 SmallSet<AA::ValueAndContext, 16> Visited; 10277 SmallVector<ItemInfo, 16> Worklist; 10278 Worklist.push_back({{*InitialV, getCtxI()}, AA::AnyScope}); 10279 10280 int Iteration = 0; 10281 do { 10282 ItemInfo II = Worklist.pop_back_val(); 10283 Value *V = II.I.getValue(); 10284 assert(V); 10285 const Instruction *CtxI = II.I.getCtxI(); 10286 AA::ValueScope S = II.S; 10287 10288 // Check if we should process the current value. To prevent endless 10289 // recursion keep a record of the values we followed! 10290 if (!Visited.insert(II.I).second) 10291 continue; 10292 10293 // Make sure we limit the compile time for complex expressions. 10294 if (Iteration++ >= MaxPotentialValuesIterations) { 10295 LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: " 10296 << Iteration << "!\n"); 10297 addValue(A, getState(), *V, CtxI, S, getAnchorScope()); 10298 continue; 10299 } 10300 10301 // Explicitly look through calls with a "returned" attribute if we do 10302 // not have a pointer as stripPointerCasts only works on them. 10303 Value *NewV = nullptr; 10304 if (V->getType()->isPointerTy()) { 10305 NewV = AA::getWithType(*V->stripPointerCasts(), *V->getType()); 10306 } else { 10307 auto *CB = dyn_cast<CallBase>(V); 10308 if (CB && CB->getCalledFunction()) { 10309 for (Argument &Arg : CB->getCalledFunction()->args()) 10310 if (Arg.hasReturnedAttr()) { 10311 NewV = CB->getArgOperand(Arg.getArgNo()); 10312 break; 10313 } 10314 } 10315 } 10316 if (NewV && NewV != V) { 10317 Worklist.push_back({{*NewV, CtxI}, S}); 10318 continue; 10319 } 10320 10321 if (auto *I = dyn_cast<Instruction>(V)) { 10322 if (simplifyInstruction(A, *I, II, Worklist, LivenessAAs)) 10323 continue; 10324 } 10325 10326 if (V != InitialV || isa<Argument>(V)) 10327 if (recurseForValue(A, IRPosition::value(*V), II.S)) 10328 continue; 10329 10330 // If we haven't stripped anything we give up. 10331 if (V == InitialV && CtxI == getCtxI()) { 10332 indicatePessimisticFixpoint(); 10333 return; 10334 } 10335 10336 addValue(A, getState(), *V, CtxI, S, getAnchorScope()); 10337 } while (!Worklist.empty()); 10338 10339 // If we actually used liveness information so we have to record a 10340 // dependence. 10341 for (auto &It : LivenessAAs) 10342 if (It.second.AnyDead) 10343 A.recordDependence(*It.second.LivenessAA, *this, DepClassTy::OPTIONAL); 10344 } 10345 10346 /// See AbstractAttribute::trackStatistics() 10347 void trackStatistics() const override { 10348 STATS_DECLTRACK_FLOATING_ATTR(potential_values) 10349 } 10350 }; 10351 10352 struct AAPotentialValuesArgument final : AAPotentialValuesImpl { 10353 using Base = AAPotentialValuesImpl; 10354 AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A) 10355 : Base(IRP, A) {} 10356 10357 /// See AbstractAttribute::initialize(..). 10358 void initialize(Attributor &A) override { 10359 auto &Arg = cast<Argument>(getAssociatedValue()); 10360 if (Arg.hasPointeeInMemoryValueAttr()) 10361 indicatePessimisticFixpoint(); 10362 } 10363 10364 /// See AbstractAttribute::updateImpl(...). 10365 ChangeStatus updateImpl(Attributor &A) override { 10366 auto AssumedBefore = getAssumed(); 10367 10368 unsigned CSArgNo = getCallSiteArgNo(); 10369 10370 bool UsedAssumedInformation = false; 10371 SmallVector<AA::ValueAndContext> Values; 10372 auto CallSitePred = [&](AbstractCallSite ACS) { 10373 const auto CSArgIRP = IRPosition::callsite_argument(ACS, CSArgNo); 10374 if (CSArgIRP.getPositionKind() == IRP_INVALID) 10375 return false; 10376 10377 if (!A.getAssumedSimplifiedValues(CSArgIRP, this, Values, 10378 AA::Interprocedural, 10379 UsedAssumedInformation)) 10380 return false; 10381 10382 return isValidState(); 10383 }; 10384 10385 if (!A.checkForAllCallSites(CallSitePred, *this, 10386 /* RequireAllCallSites */ true, 10387 UsedAssumedInformation)) 10388 return indicatePessimisticFixpoint(); 10389 10390 Function *Fn = getAssociatedFunction(); 10391 bool AnyNonLocal = false; 10392 for (auto &It : Values) { 10393 if (isa<Constant>(It.getValue())) { 10394 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope, 10395 getAnchorScope()); 10396 continue; 10397 } 10398 if (!AA::isDynamicallyUnique(A, *this, *It.getValue())) 10399 return indicatePessimisticFixpoint(); 10400 10401 if (auto *Arg = dyn_cast<Argument>(It.getValue())) 10402 if (Arg->getParent() == Fn) { 10403 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope, 10404 getAnchorScope()); 10405 continue; 10406 } 10407 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::Interprocedural, 10408 getAnchorScope()); 10409 AnyNonLocal = true; 10410 } 10411 if (undefIsContained()) 10412 unionAssumedWithUndef(); 10413 if (AnyNonLocal) 10414 giveUpOnIntraprocedural(A); 10415 10416 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10417 : ChangeStatus::CHANGED; 10418 } 10419 10420 /// See AbstractAttribute::trackStatistics() 10421 void trackStatistics() const override { 10422 STATS_DECLTRACK_ARG_ATTR(potential_values) 10423 } 10424 }; 10425 10426 struct AAPotentialValuesReturned 10427 : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> { 10428 using Base = 10429 AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>; 10430 AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A) 10431 : Base(IRP, A) {} 10432 10433 /// See AbstractAttribute::initialize(..). 10434 void initialize(Attributor &A) override { 10435 if (A.hasSimplificationCallback(getIRPosition())) 10436 indicatePessimisticFixpoint(); 10437 else 10438 AAPotentialValues::initialize(A); 10439 } 10440 10441 ChangeStatus manifest(Attributor &A) override { 10442 // We queried AAValueSimplify for the returned values so they will be 10443 // replaced if a simplified form was found. Nothing to do here. 10444 return ChangeStatus::UNCHANGED; 10445 } 10446 10447 ChangeStatus indicatePessimisticFixpoint() override { 10448 return AAPotentialValues::indicatePessimisticFixpoint(); 10449 } 10450 10451 /// See AbstractAttribute::trackStatistics() 10452 void trackStatistics() const override { 10453 STATS_DECLTRACK_FNRET_ATTR(potential_values) 10454 } 10455 }; 10456 10457 struct AAPotentialValuesFunction : AAPotentialValuesImpl { 10458 AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A) 10459 : AAPotentialValuesImpl(IRP, A) {} 10460 10461 /// See AbstractAttribute::updateImpl(...). 10462 ChangeStatus updateImpl(Attributor &A) override { 10463 llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will " 10464 "not be called"); 10465 } 10466 10467 /// See AbstractAttribute::trackStatistics() 10468 void trackStatistics() const override { 10469 STATS_DECLTRACK_FN_ATTR(potential_values) 10470 } 10471 }; 10472 10473 struct AAPotentialValuesCallSite : AAPotentialValuesFunction { 10474 AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A) 10475 : AAPotentialValuesFunction(IRP, A) {} 10476 10477 /// See AbstractAttribute::trackStatistics() 10478 void trackStatistics() const override { 10479 STATS_DECLTRACK_CS_ATTR(potential_values) 10480 } 10481 }; 10482 10483 struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl { 10484 AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A) 10485 : AAPotentialValuesImpl(IRP, A) {} 10486 10487 /// See AbstractAttribute::updateImpl(...). 10488 ChangeStatus updateImpl(Attributor &A) override { 10489 auto AssumedBefore = getAssumed(); 10490 10491 Function *Callee = getAssociatedFunction(); 10492 if (!Callee) 10493 return indicatePessimisticFixpoint(); 10494 10495 bool UsedAssumedInformation = false; 10496 auto *CB = cast<CallBase>(getCtxI()); 10497 if (CB->isMustTailCall() && 10498 !A.isAssumedDead(IRPosition::inst(*CB), this, nullptr, 10499 UsedAssumedInformation)) 10500 return indicatePessimisticFixpoint(); 10501 10502 SmallVector<AA::ValueAndContext> Values; 10503 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this, 10504 Values, AA::Intraprocedural, 10505 UsedAssumedInformation)) 10506 return indicatePessimisticFixpoint(); 10507 10508 Function *Caller = CB->getCaller(); 10509 10510 bool AnyNonLocal = false; 10511 for (auto &It : Values) { 10512 Value *V = It.getValue(); 10513 Optional<Value *> CallerV = A.translateArgumentToCallSiteContent( 10514 V, *CB, *this, UsedAssumedInformation); 10515 if (!CallerV.has_value()) { 10516 // Nothing to do as long as no value was determined. 10517 continue; 10518 } 10519 V = CallerV.value() ? CallerV.value() : V; 10520 if (AA::isDynamicallyUnique(A, *this, *V) && 10521 AA::isValidInScope(*V, Caller)) { 10522 if (CallerV.value()) { 10523 SmallVector<AA::ValueAndContext> ArgValues; 10524 IRPosition IRP = IRPosition::value(*V); 10525 if (auto *Arg = dyn_cast<Argument>(V)) 10526 if (Arg->getParent() == CB->getCalledFunction()) 10527 IRP = IRPosition::callsite_argument(*CB, Arg->getArgNo()); 10528 if (recurseForValue(A, IRP, AA::AnyScope)) 10529 continue; 10530 } 10531 addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope()); 10532 } else { 10533 AnyNonLocal = true; 10534 break; 10535 } 10536 } 10537 if (AnyNonLocal) { 10538 Values.clear(); 10539 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this, 10540 Values, AA::Interprocedural, 10541 UsedAssumedInformation)) 10542 return indicatePessimisticFixpoint(); 10543 AnyNonLocal = false; 10544 getState() = PotentialLLVMValuesState::getBestState(); 10545 for (auto &It : Values) { 10546 Value *V = It.getValue(); 10547 if (!AA::isDynamicallyUnique(A, *this, *V)) 10548 return indicatePessimisticFixpoint(); 10549 if (AA::isValidInScope(*V, Caller)) { 10550 addValue(A, getState(), *V, CB, AA::AnyScope, getAnchorScope()); 10551 } else { 10552 AnyNonLocal = true; 10553 addValue(A, getState(), *V, CB, AA::Interprocedural, 10554 getAnchorScope()); 10555 } 10556 } 10557 if (AnyNonLocal) 10558 giveUpOnIntraprocedural(A); 10559 } 10560 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED 10561 : ChangeStatus::CHANGED; 10562 } 10563 10564 ChangeStatus indicatePessimisticFixpoint() override { 10565 return AAPotentialValues::indicatePessimisticFixpoint(); 10566 } 10567 10568 /// See AbstractAttribute::trackStatistics() 10569 void trackStatistics() const override { 10570 STATS_DECLTRACK_CSRET_ATTR(potential_values) 10571 } 10572 }; 10573 10574 struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating { 10575 AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A) 10576 : AAPotentialValuesFloating(IRP, A) {} 10577 10578 /// See AbstractAttribute::trackStatistics() 10579 void trackStatistics() const override { 10580 STATS_DECLTRACK_CSARG_ATTR(potential_values) 10581 } 10582 }; 10583 } // namespace 10584 10585 /// ---------------------- Assumption Propagation ------------------------------ 10586 namespace { 10587 struct AAAssumptionInfoImpl : public AAAssumptionInfo { 10588 AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A, 10589 const DenseSet<StringRef> &Known) 10590 : AAAssumptionInfo(IRP, A, Known) {} 10591 10592 bool hasAssumption(const StringRef Assumption) const override { 10593 return isValidState() && setContains(Assumption); 10594 } 10595 10596 /// See AbstractAttribute::getAsStr() 10597 const std::string getAsStr() const override { 10598 const SetContents &Known = getKnown(); 10599 const SetContents &Assumed = getAssumed(); 10600 10601 const std::string KnownStr = 10602 llvm::join(Known.getSet().begin(), Known.getSet().end(), ","); 10603 const std::string AssumedStr = 10604 (Assumed.isUniversal()) 10605 ? "Universal" 10606 : llvm::join(Assumed.getSet().begin(), Assumed.getSet().end(), ","); 10607 10608 return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]"; 10609 } 10610 }; 10611 10612 /// Propagates assumption information from parent functions to all of their 10613 /// successors. An assumption can be propagated if the containing function 10614 /// dominates the called function. 10615 /// 10616 /// We start with a "known" set of assumptions already valid for the associated 10617 /// function and an "assumed" set that initially contains all possible 10618 /// assumptions. The assumed set is inter-procedurally updated by narrowing its 10619 /// contents as concrete values are known. The concrete values are seeded by the 10620 /// first nodes that are either entries into the call graph, or contains no 10621 /// assumptions. Each node is updated as the intersection of the assumed state 10622 /// with all of its predecessors. 10623 struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl { 10624 AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A) 10625 : AAAssumptionInfoImpl(IRP, A, 10626 getAssumptions(*IRP.getAssociatedFunction())) {} 10627 10628 /// See AbstractAttribute::manifest(...). 10629 ChangeStatus manifest(Attributor &A) override { 10630 const auto &Assumptions = getKnown(); 10631 10632 // Don't manifest a universal set if it somehow made it here. 10633 if (Assumptions.isUniversal()) 10634 return ChangeStatus::UNCHANGED; 10635 10636 Function *AssociatedFunction = getAssociatedFunction(); 10637 10638 bool Changed = addAssumptions(*AssociatedFunction, Assumptions.getSet()); 10639 10640 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10641 } 10642 10643 /// See AbstractAttribute::updateImpl(...). 10644 ChangeStatus updateImpl(Attributor &A) override { 10645 bool Changed = false; 10646 10647 auto CallSitePred = [&](AbstractCallSite ACS) { 10648 const auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>( 10649 *this, IRPosition::callsite_function(*ACS.getInstruction()), 10650 DepClassTy::REQUIRED); 10651 // Get the set of assumptions shared by all of this function's callers. 10652 Changed |= getIntersection(AssumptionAA.getAssumed()); 10653 return !getAssumed().empty() || !getKnown().empty(); 10654 }; 10655 10656 bool UsedAssumedInformation = false; 10657 // Get the intersection of all assumptions held by this node's predecessors. 10658 // If we don't know all the call sites then this is either an entry into the 10659 // call graph or an empty node. This node is known to only contain its own 10660 // assumptions and can be propagated to its successors. 10661 if (!A.checkForAllCallSites(CallSitePred, *this, true, 10662 UsedAssumedInformation)) 10663 return indicatePessimisticFixpoint(); 10664 10665 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10666 } 10667 10668 void trackStatistics() const override {} 10669 }; 10670 10671 /// Assumption Info defined for call sites. 10672 struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl { 10673 10674 AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A) 10675 : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {} 10676 10677 /// See AbstractAttribute::initialize(...). 10678 void initialize(Attributor &A) override { 10679 const IRPosition &FnPos = IRPosition::function(*getAnchorScope()); 10680 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED); 10681 } 10682 10683 /// See AbstractAttribute::manifest(...). 10684 ChangeStatus manifest(Attributor &A) override { 10685 // Don't manifest a universal set if it somehow made it here. 10686 if (getKnown().isUniversal()) 10687 return ChangeStatus::UNCHANGED; 10688 10689 CallBase &AssociatedCall = cast<CallBase>(getAssociatedValue()); 10690 bool Changed = addAssumptions(AssociatedCall, getAssumed().getSet()); 10691 10692 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10693 } 10694 10695 /// See AbstractAttribute::updateImpl(...). 10696 ChangeStatus updateImpl(Attributor &A) override { 10697 const IRPosition &FnPos = IRPosition::function(*getAnchorScope()); 10698 auto &AssumptionAA = 10699 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED); 10700 bool Changed = getIntersection(AssumptionAA.getAssumed()); 10701 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 10702 } 10703 10704 /// See AbstractAttribute::trackStatistics() 10705 void trackStatistics() const override {} 10706 10707 private: 10708 /// Helper to initialized the known set as all the assumptions this call and 10709 /// the callee contain. 10710 DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) { 10711 const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue()); 10712 auto Assumptions = getAssumptions(CB); 10713 if (Function *F = IRP.getAssociatedFunction()) 10714 set_union(Assumptions, getAssumptions(*F)); 10715 if (Function *F = IRP.getAssociatedFunction()) 10716 set_union(Assumptions, getAssumptions(*F)); 10717 return Assumptions; 10718 } 10719 }; 10720 } // namespace 10721 10722 AACallGraphNode *AACallEdgeIterator::operator*() const { 10723 return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>( 10724 &A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I)))); 10725 } 10726 10727 void AttributorCallGraph::print() { llvm::WriteGraph(outs(), this); } 10728 10729 const char AAReturnedValues::ID = 0; 10730 const char AANoUnwind::ID = 0; 10731 const char AANoSync::ID = 0; 10732 const char AANoFree::ID = 0; 10733 const char AANonNull::ID = 0; 10734 const char AANoRecurse::ID = 0; 10735 const char AAWillReturn::ID = 0; 10736 const char AAUndefinedBehavior::ID = 0; 10737 const char AANoAlias::ID = 0; 10738 const char AAReachability::ID = 0; 10739 const char AANoReturn::ID = 0; 10740 const char AAIsDead::ID = 0; 10741 const char AADereferenceable::ID = 0; 10742 const char AAAlign::ID = 0; 10743 const char AAInstanceInfo::ID = 0; 10744 const char AANoCapture::ID = 0; 10745 const char AAValueSimplify::ID = 0; 10746 const char AAHeapToStack::ID = 0; 10747 const char AAPrivatizablePtr::ID = 0; 10748 const char AAMemoryBehavior::ID = 0; 10749 const char AAMemoryLocation::ID = 0; 10750 const char AAValueConstantRange::ID = 0; 10751 const char AAPotentialConstantValues::ID = 0; 10752 const char AAPotentialValues::ID = 0; 10753 const char AANoUndef::ID = 0; 10754 const char AACallEdges::ID = 0; 10755 const char AAFunctionReachability::ID = 0; 10756 const char AAPointerInfo::ID = 0; 10757 const char AAAssumptionInfo::ID = 0; 10758 10759 // Macro magic to create the static generator function for attributes that 10760 // follow the naming scheme. 10761 10762 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 10763 case IRPosition::PK: \ 10764 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 10765 10766 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 10767 case IRPosition::PK: \ 10768 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \ 10769 ++NumAAs; \ 10770 break; 10771 10772 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10773 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10774 CLASS *AA = nullptr; \ 10775 switch (IRP.getPositionKind()) { \ 10776 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10777 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 10778 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 10779 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10780 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 10781 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 10782 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10783 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10784 } \ 10785 return *AA; \ 10786 } 10787 10788 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10789 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10790 CLASS *AA = nullptr; \ 10791 switch (IRP.getPositionKind()) { \ 10792 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10793 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 10794 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 10795 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10796 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10797 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 10798 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10799 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10800 } \ 10801 return *AA; \ 10802 } 10803 10804 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10805 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10806 CLASS *AA = nullptr; \ 10807 switch (IRP.getPositionKind()) { \ 10808 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10809 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10810 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10811 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10812 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10813 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 10814 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10815 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10816 } \ 10817 return *AA; \ 10818 } 10819 10820 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10821 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10822 CLASS *AA = nullptr; \ 10823 switch (IRP.getPositionKind()) { \ 10824 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10825 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 10826 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 10827 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10828 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 10829 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 10830 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 10831 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10832 } \ 10833 return *AA; \ 10834 } 10835 10836 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 10837 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 10838 CLASS *AA = nullptr; \ 10839 switch (IRP.getPositionKind()) { \ 10840 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 10841 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 10842 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 10843 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 10844 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 10845 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 10846 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 10847 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 10848 } \ 10849 return *AA; \ 10850 } 10851 10852 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 10853 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 10854 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 10855 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 10856 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 10857 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 10858 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation) 10859 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AACallEdges) 10860 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAssumptionInfo) 10861 10862 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 10863 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 10864 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr) 10865 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 10866 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 10867 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAInstanceInfo) 10868 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture) 10869 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange) 10870 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialConstantValues) 10871 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues) 10872 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef) 10873 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPointerInfo) 10874 10875 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify) 10876 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 10877 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 10878 10879 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack) 10880 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability) 10881 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior) 10882 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAFunctionReachability) 10883 10884 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior) 10885 10886 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION 10887 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 10888 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION 10889 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 10890 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 10891 #undef SWITCH_PK_CREATE 10892 #undef SWITCH_PK_INV 10893