LLVM 24.0.0git
AttributorAttributes.cpp
Go to the documentation of this file.
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 "IPOOptions.h"
17
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/MapVector.h"
24#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/Statistic.h"
42#include "llvm/IR/Argument.h"
43#include "llvm/IR/Assumptions.h"
45#include "llvm/IR/Attributes.h"
46#include "llvm/IR/BasicBlock.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/InlineAsm.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/IntrinsicsAMDGPU.h"
59#include "llvm/IR/IntrinsicsNVPTX.h"
60#include "llvm/IR/LLVMContext.h"
61#include "llvm/IR/MDBuilder.h"
62#include "llvm/IR/NoFolder.h"
63#include "llvm/IR/Value.h"
64#include "llvm/IR/ValueHandle.h"
78#include <cassert>
79#include <numeric>
80#include <optional>
81#include <string>
82
83using namespace llvm;
84
85#define DEBUG_TYPE "attributor"
86
87STATISTIC(NumAAs, "Number of abstract attributes created");
88STATISTIC(NumIndirectCallsPromoted, "Number of indirect calls promoted");
89
90// Some helper macros to deal with statistics tracking.
91//
92// Usage:
93// For simple IR attribute tracking overload trackStatistics in the abstract
94// attribute and choose the right STATS_DECLTRACK_********* macro,
95// e.g.,:
96// void trackStatistics() const override {
97// STATS_DECLTRACK_ARG_ATTR(returned)
98// }
99// If there is a single "increment" side one can use the macro
100// STATS_DECLTRACK with a custom message. If there are multiple increment
101// sides, STATS_DECL and STATS_TRACK can also be used separately.
102//
103#define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \
104 ("Number of " #TYPE " marked '" #NAME "'")
105#define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
106#define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
107#define STATS_DECL(NAME, TYPE, MSG) \
108 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
109#define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
110#define STATS_DECLTRACK(NAME, TYPE, MSG) \
111 {STATS_DECL(NAME, TYPE, MSG) STATS_TRACK(NAME, TYPE)}
112#define STATS_DECLTRACK_ARG_ATTR(NAME) \
113 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
114#define STATS_DECLTRACK_CSARG_ATTR(NAME) \
115 STATS_DECLTRACK(NAME, CSArguments, \
116 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
117#define STATS_DECLTRACK_FN_ATTR(NAME) \
118 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
119#define STATS_DECLTRACK_CS_ATTR(NAME) \
120 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
121#define STATS_DECLTRACK_FNRET_ATTR(NAME) \
122 STATS_DECLTRACK(NAME, FunctionReturn, \
123 BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
124#define STATS_DECLTRACK_CSRET_ATTR(NAME) \
125 STATS_DECLTRACK(NAME, CSReturn, \
126 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
127#define STATS_DECLTRACK_FLOATING_ATTR(NAME) \
128 STATS_DECLTRACK(NAME, Floating, \
129 ("Number of floating values known to be '" #NAME "'"))
130
131// Specialization of the operator<< for abstract attributes subclasses. This
132// disambiguates situations where multiple operators are applicable.
133namespace llvm {
134#define PIPE_OPERATOR(CLASS) \
135 raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \
136 return OS << static_cast<const AbstractAttribute &>(AA); \
137 }
138
178
179#undef PIPE_OPERATOR
180
181template <>
183 const DerefState &R) {
184 ChangeStatus CS0 =
185 clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
186 ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
187 return CS0 | CS1;
188}
189
190} // namespace llvm
191
192static bool mayBeInCycle(const CycleInfo *CI, const Instruction *I,
193 bool HeaderOnly, CycleRef *CPtr = nullptr) {
194 if (!CI)
195 return true;
196 auto *BB = I->getParent();
197 CycleRef C = CI->getCycle(BB);
198 if (!C)
199 return false;
200 if (CPtr)
201 *CPtr = C;
202 return !HeaderOnly || BB == CI->getHeader(C);
203}
204
205/// Checks if a type could have padding bytes.
206static bool isDenselyPacked(Type *Ty, const DataLayout &DL) {
207 // There is no size information, so be conservative.
208 if (!Ty->isSized())
209 return false;
210
211 // If the alloc size is not equal to the storage size, then there are padding
212 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
213 if (DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty))
214 return false;
215
216 // FIXME: This isn't the right way to check for padding in vectors with
217 // non-byte-size elements.
218 if (VectorType *SeqTy = dyn_cast<VectorType>(Ty))
219 return isDenselyPacked(SeqTy->getElementType(), DL);
220
221 // For array types, check for padding within members.
222 if (ArrayType *SeqTy = dyn_cast<ArrayType>(Ty))
223 return isDenselyPacked(SeqTy->getElementType(), DL);
224
225 if (!isa<StructType>(Ty))
226 return true;
227
228 // Check for padding within and between elements of a struct.
229 StructType *StructTy = cast<StructType>(Ty);
230 const StructLayout *Layout = DL.getStructLayout(StructTy);
231 uint64_t StartPos = 0;
232 for (unsigned I = 0, E = StructTy->getNumElements(); I < E; ++I) {
233 Type *ElTy = StructTy->getElementType(I);
234 if (!isDenselyPacked(ElTy, DL))
235 return false;
236 if (StartPos != Layout->getElementOffsetInBits(I))
237 return false;
238 StartPos += DL.getTypeAllocSizeInBits(ElTy);
239 }
240
241 // Check for tail padding.
242 return StartPos == Layout->getSizeInBits();
243}
244
245/// Get pointer operand of memory accessing instruction. If \p I is
246/// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
247/// is set to false and the instruction is volatile, return nullptr.
249 bool AllowVolatile) {
250 if (!AllowVolatile && I->isVolatile())
251 return nullptr;
252
253 if (auto *LI = dyn_cast<LoadInst>(I)) {
254 return LI->getPointerOperand();
255 }
256
257 if (auto *SI = dyn_cast<StoreInst>(I)) {
258 return SI->getPointerOperand();
259 }
260
261 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
262 return CXI->getPointerOperand();
263 }
264
265 if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
266 return RMWI->getPointerOperand();
267 }
268
269 return nullptr;
270}
271
272/// Helper function to create a pointer based on \p Ptr, and advanced by \p
273/// Offset bytes.
274static Value *constructPointer(Value *Ptr, int64_t Offset,
275 IRBuilder<NoFolder> &IRB) {
276 LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
277 << "-bytes\n");
278
279 if (Offset)
281 Ptr, Offset, Ptr->getName() + ".b" + Twine(Offset));
282 return Ptr;
283}
284
285static const Value *
287 const Value *Val, const DataLayout &DL, APInt &Offset,
288 bool GetMinOffset, bool AllowNonInbounds,
289 bool UseAssumed = false) {
290
291 auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool {
292 const IRPosition &Pos = IRPosition::value(V);
293 // Only track dependence if we are going to use the assumed info.
294 const AAValueConstantRange *ValueConstantRangeAA =
295 A.getAAFor<AAValueConstantRange>(QueryingAA, Pos,
296 UseAssumed ? DepClassTy::OPTIONAL
298 if (!ValueConstantRangeAA)
299 return false;
300 ConstantRange Range = UseAssumed ? ValueConstantRangeAA->getAssumed()
301 : ValueConstantRangeAA->getKnown();
302 if (Range.isFullSet())
303 return false;
304
305 // We can only use the lower part of the range because the upper part can
306 // be higher than what the value can really be.
307 if (GetMinOffset)
308 ROffset = Range.getSignedMin();
309 else
310 ROffset = Range.getSignedMax();
311 return true;
312 };
313
314 return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds,
315 /* AllowInvariant */ true,
316 AttributorAnalysis);
317}
318
319static const Value *
321 const Value *Ptr, int64_t &BytesOffset,
322 const DataLayout &DL, bool AllowNonInbounds = false) {
323 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
324 const Value *Base =
325 stripAndAccumulateOffsets(A, QueryingAA, Ptr, DL, OffsetAPInt,
326 /* GetMinOffset */ true, AllowNonInbounds);
327
328 BytesOffset = OffsetAPInt.getSExtValue();
329 return Base;
330}
331
332/// Clamp the information known for all returned values of a function
333/// (identified by \p QueryingAA) into \p S.
334template <typename AAType, typename StateType = typename AAType::StateType,
335 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind,
336 bool RecurseForSelectAndPHI = true>
338 Attributor &A, const AAType &QueryingAA, StateType &S,
339 const IRPosition::CallBaseContext *CBContext = nullptr) {
340 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
341 << QueryingAA << " into " << S << "\n");
342
343 assert((QueryingAA.getIRPosition().getPositionKind() ==
345 QueryingAA.getIRPosition().getPositionKind() ==
347 "Can only clamp returned value states for a function returned or call "
348 "site returned position!");
349
350 // Use an optional state as there might not be any return values and we want
351 // to join (IntegerState::operator&) the state of all there are.
352 std::optional<StateType> T;
353
354 // Callback for each possibly returned value.
355 auto CheckReturnValue = [&](Value &RV) -> bool {
356 const IRPosition &RVPos = IRPosition::value(RV, CBContext);
357 // If possible, use the hasAssumedIRAttr interface.
358 if (Attribute::isEnumAttrKind(IRAttributeKind)) {
359 bool IsKnown;
361 A, &QueryingAA, RVPos, DepClassTy::REQUIRED, IsKnown);
362 }
363
364 const AAType *AA =
365 A.getAAFor<AAType>(QueryingAA, RVPos, DepClassTy::REQUIRED);
366 if (!AA)
367 return false;
368 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV
369 << " AA: " << AA->getAsStr(&A) << " @ " << RVPos << "\n");
370 const StateType &AAS = AA->getState();
371 if (!T)
372 T = StateType::getBestState(AAS);
373 *T &= AAS;
374 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
375 << "\n");
376 return T->isValidState();
377 };
378
379 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA,
381 RecurseForSelectAndPHI))
382 S.indicatePessimisticFixpoint();
383 else if (T)
384 S ^= *T;
385}
386
387namespace {
388/// Helper class for generic deduction: return value -> returned position.
389template <typename AAType, typename BaseType,
390 typename StateType = typename BaseType::StateType,
391 bool PropagateCallBaseContext = false,
392 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind,
393 bool RecurseForSelectAndPHI = true>
394struct AAReturnedFromReturnedValues : public BaseType {
395 AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A)
396 : BaseType(IRP, A) {}
397
398 ChangeStatus updateImpl(Attributor &A) override {
399 StateType S(StateType::getBestState(this->getState()));
400 clampReturnedValueStates<AAType, StateType, IRAttributeKind,
401 RecurseForSelectAndPHI>(
402 A, *this, S,
403 PropagateCallBaseContext ? this->getCallBaseContext() : nullptr);
404 // TODO: If we know we visited all returned values, thus no are assumed
405 // dead, we can take the known information from the state T.
406 return clampStateAndIndicateChange<StateType>(this->getState(), S);
407 }
408};
409
410/// Clamp the information known at all call sites for a given argument
411/// (identified by \p QueryingAA) into \p S.
412template <typename AAType, typename StateType = typename AAType::StateType,
413 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind>
414static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
415 StateType &S) {
416 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
417 << QueryingAA << " into " << S << "\n");
418
419 assert(QueryingAA.getIRPosition().getPositionKind() ==
421 "Can only clamp call site argument states for an argument position!");
422
423 // Use an optional state as there might not be any return values and we want
424 // to join (IntegerState::operator&) the state of all there are.
425 std::optional<StateType> T;
426
427 // The argument number which is also the call site argument number.
428 unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo();
429
430 auto CallSiteCheck = [&](AbstractCallSite ACS) {
431 const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
432 // Check if a coresponding argument was found or if it is on not associated
433 // (which can happen for callback calls).
434 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
435 return false;
436
437 // If possible, use the hasAssumedIRAttr interface.
438 if (Attribute::isEnumAttrKind(IRAttributeKind)) {
439 bool IsKnown;
441 A, &QueryingAA, ACSArgPos, DepClassTy::REQUIRED, IsKnown);
442 }
443
444 const AAType *AA =
445 A.getAAFor<AAType>(QueryingAA, ACSArgPos, DepClassTy::REQUIRED);
446 if (!AA)
447 return false;
448 LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
449 << " AA: " << AA->getAsStr(&A) << " @" << ACSArgPos
450 << "\n");
451 const StateType &AAS = AA->getState();
452 if (!T)
453 T = StateType::getBestState(AAS);
454 *T &= AAS;
455 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
456 << "\n");
457 return T->isValidState();
458 };
459
460 bool UsedAssumedInformation = false;
461 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
462 UsedAssumedInformation))
463 S.indicatePessimisticFixpoint();
464 else if (T)
465 S ^= *T;
466}
467
468/// This function is the bridge between argument position and the call base
469/// context.
470template <typename AAType, typename BaseType,
471 typename StateType = typename AAType::StateType,
472 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind>
473bool getArgumentStateFromCallBaseContext(Attributor &A,
474 BaseType &QueryingAttribute,
475 IRPosition &Pos, StateType &State) {
477 "Expected an 'argument' position !");
478 const CallBase *CBContext = Pos.getCallBaseContext();
479 if (!CBContext)
480 return false;
481
482 int ArgNo = Pos.getCallSiteArgNo();
483 assert(ArgNo >= 0 && "Invalid Arg No!");
484 const IRPosition CBArgPos = IRPosition::callsite_argument(*CBContext, ArgNo);
485
486 // If possible, use the hasAssumedIRAttr interface.
487 if (Attribute::isEnumAttrKind(IRAttributeKind)) {
488 bool IsKnown;
490 A, &QueryingAttribute, CBArgPos, DepClassTy::REQUIRED, IsKnown);
491 }
492
493 const auto *AA =
494 A.getAAFor<AAType>(QueryingAttribute, CBArgPos, DepClassTy::REQUIRED);
495 if (!AA)
496 return false;
497 const StateType &CBArgumentState =
498 static_cast<const StateType &>(AA->getState());
499
500 LLVM_DEBUG(dbgs() << "[Attributor] Briding Call site context to argument"
501 << "Position:" << Pos << "CB Arg state:" << CBArgumentState
502 << "\n");
503
504 // NOTE: If we want to do call site grouping it should happen here.
505 State ^= CBArgumentState;
506 return true;
507}
508
509/// Helper class for generic deduction: call site argument -> argument position.
510template <typename AAType, typename BaseType,
511 typename StateType = typename AAType::StateType,
512 bool BridgeCallBaseContext = false,
513 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind>
514struct AAArgumentFromCallSiteArguments : public BaseType {
515 AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A)
516 : BaseType(IRP, A) {}
517
518 ChangeStatus updateImpl(Attributor &A) override {
519 StateType S = StateType::getBestState(this->getState());
520
521 if (BridgeCallBaseContext) {
522 bool Success =
523 getArgumentStateFromCallBaseContext<AAType, BaseType, StateType,
524 IRAttributeKind>(
525 A, *this, this->getIRPosition(), S);
526 if (Success)
527 return clampStateAndIndicateChange<StateType>(this->getState(), S);
528 }
529 clampCallSiteArgumentStates<AAType, StateType, IRAttributeKind>(A, *this,
530 S);
531
532 // TODO: If we know we visited all incoming values, thus no are assumed
533 // dead, we can take the known information from the state T.
534 return clampStateAndIndicateChange<StateType>(this->getState(), S);
535 }
536};
537
538/// Helper class for generic replication: function returned -> cs returned.
539template <typename AAType, typename BaseType,
540 typename StateType = typename BaseType::StateType,
541 bool IntroduceCallBaseContext = false,
542 Attribute::AttrKind IRAttributeKind = AAType::IRAttributeKind>
543struct AACalleeToCallSite : public BaseType {
544 AACalleeToCallSite(const IRPosition &IRP, Attributor &A) : BaseType(IRP, A) {}
545
546 ChangeStatus updateImpl(Attributor &A) override {
547 auto IRPKind = this->getIRPosition().getPositionKind();
549 IRPKind == IRPosition::IRP_CALL_SITE) &&
550 "Can only wrap function returned positions for call site "
551 "returned positions!");
552 auto &S = this->getState();
553
554 CallBase &CB = cast<CallBase>(this->getAnchorValue());
555 if (IntroduceCallBaseContext)
556 LLVM_DEBUG(dbgs() << "[Attributor] Introducing call base context:" << CB
557 << "\n");
558
559 ChangeStatus Changed = ChangeStatus::UNCHANGED;
560 auto CalleePred = [&](ArrayRef<const Function *> Callees) {
561 for (const Function *Callee : Callees) {
562 // The returned position of the callee does not describe the call if
563 // the call uses a different return type.
564 if (IRPKind == IRPosition::IRP_CALL_SITE_RETURNED &&
565 Callee->getReturnType() != CB.getType())
566 return false;
567 IRPosition FnPos =
569 ? IRPosition::returned(*Callee,
570 IntroduceCallBaseContext ? &CB : nullptr)
571 : IRPosition::function(
572 *Callee, IntroduceCallBaseContext ? &CB : nullptr);
573 // If possible, use the hasAssumedIRAttr interface.
574 if (Attribute::isEnumAttrKind(IRAttributeKind)) {
575 bool IsKnown;
577 A, this, FnPos, DepClassTy::REQUIRED, IsKnown))
578 return false;
579 continue;
580 }
581
582 const AAType *AA =
583 A.getAAFor<AAType>(*this, FnPos, DepClassTy::REQUIRED);
584 if (!AA)
585 return false;
586 Changed |= clampStateAndIndicateChange(S, AA->getState());
587 if (S.isAtFixpoint())
588 return S.isValidState();
589 }
590 return true;
591 };
592 if (!A.checkForAllCallees(CalleePred, *this, CB))
593 return S.indicatePessimisticFixpoint();
594 return Changed;
595 }
596};
597
598/// Helper function to accumulate uses.
599template <class AAType, typename StateType = typename AAType::StateType>
600static void followUsesInContext(AAType &AA, Attributor &A,
602 const Instruction *CtxI,
604 StateType &State) {
605 for (unsigned u = 0; u < Uses.size(); ++u) {
606 const Use *U = Uses[u];
607 if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
608 bool Found = Explorer.isInContextOf(UserI, CtxI);
609 if (Found && AA.followUseInMBEC(A, U, UserI, State))
610 Uses.insert_range(llvm::make_pointer_range(UserI->uses()));
611 }
612 }
613}
614
615/// Use the must-be-executed-context around \p I to add information into \p S.
616/// The AAType class is required to have `followUseInMBEC` method with the
617/// following signature and behaviour:
618///
619/// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I)
620/// U - Underlying use.
621/// I - The user of the \p U.
622/// Returns true if the value should be tracked transitively.
623///
624template <class AAType, typename StateType = typename AAType::StateType>
625static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S,
626 Instruction &CtxI) {
627 if (!A.canUseBodyFor(AA.getIRPosition()))
628 return;
629
630 const Value &Val = AA.getIRPosition().getAssociatedValue();
631 if (isa<ConstantData>(Val))
632 return;
633
635 A.getInfoCache().getMustBeExecutedContextExplorer();
636 if (!Explorer)
637 return;
638
639 // Container for (transitive) uses of the associated value.
641 for (const Use &U : Val.uses())
642 Uses.insert(&U);
643
644 followUsesInContext<AAType>(AA, A, *Explorer, &CtxI, Uses, S);
645
646 if (S.isAtFixpoint())
647 return;
648
650 auto Pred = [&](const Instruction *I) {
651 if (const CondBrInst *Br = dyn_cast<CondBrInst>(I))
652 BrInsts.push_back(Br);
653 return true;
654 };
655
656 // Here, accumulate conditional branch instructions in the context. We
657 // explore the child paths and collect the known states. The disjunction of
658 // those states can be merged to its own state. Let ParentState_i be a state
659 // to indicate the known information for an i-th branch instruction in the
660 // context. ChildStates are created for its successors respectively.
661 //
662 // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
663 // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
664 // ...
665 // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
666 //
667 // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
668 //
669 // FIXME: Currently, recursive branches are not handled. For example, we
670 // can't deduce that ptr must be dereferenced in below function.
671 //
672 // void f(int a, int c, int *ptr) {
673 // if(a)
674 // if (b) {
675 // *ptr = 0;
676 // } else {
677 // *ptr = 1;
678 // }
679 // else {
680 // if (b) {
681 // *ptr = 0;
682 // } else {
683 // *ptr = 1;
684 // }
685 // }
686 // }
687
688 Explorer->checkForAllTerminatorsInContext(&CtxI, Pred);
689 for (const CondBrInst *Br : BrInsts) {
690 StateType ParentState;
691
692 // The known state of the parent state is a conjunction of children's
693 // known states so it is initialized with a best state.
694 ParentState.indicateOptimisticFixpoint();
695
696 for (const BasicBlock *BB : Br->successors()) {
697 StateType ChildState;
698
699 size_t BeforeSize = Uses.size();
700 followUsesInContext(AA, A, *Explorer, &BB->front(), Uses, ChildState);
701
702 // Erase uses which only appear in the child.
703 for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
704 It = Uses.erase(It);
705
706 ParentState &= ChildState;
707 }
708
709 // Use only known state.
710 S += ParentState;
711 }
712}
713} // namespace
714
715/// ------------------------ PointerInfo ---------------------------------------
716
717namespace llvm {
718namespace AA {
719namespace PointerInfo {
720
721struct State;
722
723} // namespace PointerInfo
724} // namespace AA
725
726/// Helper for AA::PointerInfo::Access DenseMap/Set usage.
727template <>
730 static unsigned getHashValue(const Access &A);
731 static bool isEqual(const Access &LHS, const Access &RHS);
732};
733
734/// Helper that allows RangeTy as a key in a DenseMap.
735template <> struct DenseMapInfo<AA::RangeTy> {
741
742 static bool isEqual(const AA::RangeTy &A, const AA::RangeTy B) {
743 return A == B;
744 }
745};
746
747} // namespace llvm
748
749/// A type to track pointer/struct usage and accesses for AAPointerInfo.
751 /// Return the best possible representable state.
752 static State getBestState(const State &SIS) { return State(); }
753
754 /// Return the worst possible representable state.
755 static State getWorstState(const State &SIS) {
756 State R;
757 R.indicatePessimisticFixpoint();
758 return R;
759 }
760
761 State() = default;
762 State(State &&SIS) = default;
763
764 const State &getAssumed() const { return *this; }
765
766 bool isValidState() const override { return BS.isValidState(); }
767
768 bool isAtFixpoint() const override { return BS.isAtFixpoint(); }
769
771 BS.indicateOptimisticFixpoint();
773 }
774
776 BS.indicatePessimisticFixpoint();
778 }
779
780 State &operator=(const State &R) {
781 if (this == &R)
782 return *this;
783 BS = R.BS;
784 AccessList = R.AccessList;
785 OffsetBins = R.OffsetBins;
786 RemoteIMap = R.RemoteIMap;
787 ReturnedOffsets = R.ReturnedOffsets;
788 return *this;
789 }
790
792 if (this == &R)
793 return *this;
794 std::swap(BS, R.BS);
795 std::swap(AccessList, R.AccessList);
796 std::swap(OffsetBins, R.OffsetBins);
797 std::swap(RemoteIMap, R.RemoteIMap);
798 std::swap(ReturnedOffsets, R.ReturnedOffsets);
799 return *this;
800 }
801
802 /// Add a new Access to the state at offset \p Offset and with size \p Size.
803 /// The access is associated with \p I, writes \p Content (if anything), and
804 /// is of kind \p Kind. If an Access already exists for the same \p I and same
805 /// \p RemoteI, the two are combined, potentially losing information about
806 /// offset and size. The resulting access must now be moved from its original
807 /// OffsetBin to the bin for its new offset.
808 ///
809 /// \Returns CHANGED, if the state changed, UNCHANGED otherwise.
811 Instruction &I, std::optional<Value *> Content,
813 Instruction *RemoteI = nullptr);
814
817 int64_t numOffsetBins() const { return OffsetBins.size(); }
818
819 const AAPointerInfo::Access &getAccess(unsigned Index) const {
820 return AccessList[Index];
821 }
822
823protected:
824 // Every memory instruction results in an Access object. We maintain a list of
825 // all Access objects that we own, along with the following maps:
826 //
827 // - OffsetBins: RangeTy -> { Access }
828 // - RemoteIMap: RemoteI x LocalI -> Access
829 //
830 // A RemoteI is any instruction that accesses memory. RemoteI is different
831 // from LocalI if and only if LocalI is a call; then RemoteI is some
832 // instruction in the callgraph starting from LocalI. Multiple paths in the
833 // callgraph from LocalI to RemoteI may produce multiple accesses, but these
834 // are all combined into a single Access object. This may result in loss of
835 // information in RangeTy in the Access object.
839
840 /// Flag to determine if the underlying pointer is reaching a return statement
841 /// in the associated function or not. Returns in other functions cause
842 /// invalidation.
844
845 /// See AAPointerInfo::forallInterferingAccesses.
846 template <typename F>
848 if (!isValidState() || !ReturnedOffsets.isUnassigned())
849 return false;
850
851 for (const auto &It : OffsetBins) {
852 AA::RangeTy ItRange = It.getFirst();
853 if (!Range.mayOverlap(ItRange))
854 continue;
855 bool IsExact = Range == ItRange && !Range.offsetOrSizeAreUnknown();
856 for (auto Index : It.getSecond()) {
857 auto &Access = AccessList[Index];
858 if (!CB(Access, IsExact))
859 return false;
860 }
861 }
862 return true;
863 }
864
865 /// See AAPointerInfo::forallInterferingAccesses.
866 template <typename F>
868 AA::RangeTy &Range) const {
869 if (!isValidState() || !ReturnedOffsets.isUnassigned())
870 return false;
871
872 auto LocalList = RemoteIMap.find(&I);
873 if (LocalList == RemoteIMap.end()) {
874 return true;
875 }
876
877 for (unsigned Index : LocalList->getSecond()) {
878 for (auto &R : AccessList[Index]) {
879 Range &= R;
880 if (Range.offsetAndSizeAreUnknown())
881 break;
882 }
883 }
885 }
886
887private:
888 /// State to track fixpoint and validity.
889 BooleanState BS;
890};
891
894 std::optional<Value *> Content, AAPointerInfo::AccessKind Kind, Type *Ty,
895 Instruction *RemoteI) {
896 RemoteI = RemoteI ? RemoteI : &I;
897
898 // Check if we have an access for this instruction, if not, simply add it.
899 auto &LocalList = RemoteIMap[RemoteI];
900 bool AccExists = false;
901 unsigned AccIndex = AccessList.size();
902 for (auto Index : LocalList) {
903 auto &A = AccessList[Index];
904 if (A.getLocalInst() == &I) {
905 AccExists = true;
906 AccIndex = Index;
907 break;
908 }
909 }
910
911 auto AddToBins = [&](const AAPointerInfo::RangeList &ToAdd) {
912 LLVM_DEBUG(if (ToAdd.size()) dbgs()
913 << "[AAPointerInfo] Inserting access in new offset bins\n";);
914
915 for (auto Key : ToAdd) {
916 LLVM_DEBUG(dbgs() << " key " << Key << "\n");
917 OffsetBins[Key].insert(AccIndex);
918 }
919 };
920
921 if (!AccExists) {
922 AccessList.emplace_back(&I, RemoteI, Ranges, Content, Kind, Ty);
923 assert((AccessList.size() == AccIndex + 1) &&
924 "New Access should have been at AccIndex");
925 LocalList.push_back(AccIndex);
926 AddToBins(AccessList[AccIndex].getRanges());
928 }
929
930 // Combine the new Access with the existing Access, and then update the
931 // mapping in the offset bins.
932 AAPointerInfo::Access Acc(&I, RemoteI, Ranges, Content, Kind, Ty);
933 auto &Current = AccessList[AccIndex];
934 auto Before = Current;
935 Current &= Acc;
936 if (Current == Before)
938
939 auto &ExistingRanges = Before.getRanges();
940 auto &NewRanges = Current.getRanges();
941
942 // Ranges that are in the old access but not the new access need to be removed
943 // from the offset bins.
945 AAPointerInfo::RangeList::set_difference(ExistingRanges, NewRanges, ToRemove);
946 LLVM_DEBUG(if (ToRemove.size()) dbgs()
947 << "[AAPointerInfo] Removing access from old offset bins\n";);
948
949 for (auto Key : ToRemove) {
950 LLVM_DEBUG(dbgs() << " key " << Key << "\n");
951 assert(OffsetBins.count(Key) && "Existing Access must be in some bin.");
952 auto &Bin = OffsetBins[Key];
953 assert(Bin.count(AccIndex) &&
954 "Expected bin to actually contain the Access.");
955 Bin.erase(AccIndex);
956 }
957
958 // Ranges that are in the new access but not the old access need to be added
959 // to the offset bins.
961 AAPointerInfo::RangeList::set_difference(NewRanges, ExistingRanges, ToAdd);
962 AddToBins(ToAdd);
964}
965
966namespace {
967
968#ifndef NDEBUG
970 const AAPointerInfo::OffsetInfo &OI) {
971 OS << llvm::interleaved_array(OI);
972 return OS;
973}
974#endif // NDEBUG
975
976struct AAPointerInfoImpl
977 : public StateWrapper<AA::PointerInfo::State, AAPointerInfo> {
979 AAPointerInfoImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {}
980
981 const std::string getAsStr(Attributor *A) const override {
982 return std::string("PointerInfo ") +
983 (isValidState() ? (std::string("#") +
984 std::to_string(OffsetBins.size()) + " bins")
985 : "<invalid>") +
986 (reachesReturn()
987 ? (" (returned:" +
988 join(map_range(ReturnedOffsets,
989 [](int64_t O) { return std::to_string(O); }),
990 ", ") +
991 ")")
992 : "");
993 }
994
995 ChangeStatus manifest(Attributor &A) override {
996 return AAPointerInfo::manifest(A);
997 }
998
999 const_bin_iterator begin() const override { return State::begin(); }
1000 const_bin_iterator end() const override { return State::end(); }
1001 int64_t numOffsetBins() const override { return State::numOffsetBins(); }
1002 bool reachesReturn() const override {
1003 return !ReturnedOffsets.isUnassigned();
1004 }
1005 void addReturnedOffsetsTo(OffsetInfo &OI) const override {
1006 if (ReturnedOffsets.isUnknown()) {
1007 OI.setUnknown();
1008 return;
1009 }
1010
1011 OffsetInfo MergedOI;
1012 for (auto Offset : ReturnedOffsets) {
1013 OffsetInfo TmpOI = OI;
1014 TmpOI.addToAll(Offset);
1015 MergedOI.merge(TmpOI);
1016 }
1017 OI = std::move(MergedOI);
1018 }
1019
1020 ChangeStatus setReachesReturn(const OffsetInfo &ReachedReturnedOffsets) {
1021 if (ReturnedOffsets.isUnknown())
1022 return ChangeStatus::UNCHANGED;
1023 if (ReachedReturnedOffsets.isUnknown()) {
1024 ReturnedOffsets.setUnknown();
1025 return ChangeStatus::CHANGED;
1026 }
1027 if (ReturnedOffsets.merge(ReachedReturnedOffsets))
1028 return ChangeStatus::CHANGED;
1029 return ChangeStatus::UNCHANGED;
1030 }
1031
1032 bool forallInterferingAccesses(
1033 AA::RangeTy Range,
1034 function_ref<bool(const AAPointerInfo::Access &, bool)> CB)
1035 const override {
1036 return State::forallInterferingAccesses(Range, CB);
1037 }
1038
1039 bool forallInterferingAccesses(
1040 Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I,
1041 bool FindInterferingWrites, bool FindInterferingReads,
1042 function_ref<bool(const Access &, bool)> UserCB, bool &HasBeenWrittenTo,
1043 AA::RangeTy &Range,
1044 function_ref<bool(const Access &)> SkipCB) const override {
1045 HasBeenWrittenTo = false;
1046
1047 SmallPtrSet<const Access *, 8> DominatingWrites;
1048 SmallVector<std::pair<const Access *, bool>, 8> InterferingAccesses;
1049
1050 Function &Scope = *I.getFunction();
1051 bool IsKnownNoSync;
1052 bool IsAssumedNoSync = AA::hasAssumedIRAttr<Attribute::NoSync>(
1053 A, &QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL,
1054 IsKnownNoSync);
1055 const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>(
1056 IRPosition::function(Scope), &QueryingAA, DepClassTy::NONE);
1057 bool AllInSameNoSyncFn = IsAssumedNoSync;
1058 bool InstIsExecutedByInitialThreadOnly =
1059 ExecDomainAA && ExecDomainAA->isExecutedByInitialThreadOnly(I);
1060
1061 // If the function is not ending in aligned barriers, we need the stores to
1062 // be in aligned barriers. The load being in one is not sufficient since the
1063 // store might be executed by a thread that disappears after, causing the
1064 // aligned barrier guarding the load to unblock and the load to read a value
1065 // that has no CFG path to the load.
1066 bool InstIsExecutedInAlignedRegion =
1067 FindInterferingReads && ExecDomainAA &&
1068 ExecDomainAA->isExecutedInAlignedRegion(A, I);
1069
1070 if (InstIsExecutedInAlignedRegion || InstIsExecutedByInitialThreadOnly)
1071 A.recordDependence(*ExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1072
1073 InformationCache &InfoCache = A.getInfoCache();
1074 bool IsThreadLocalObj =
1075 AA::isAssumedThreadLocalObject(A, getAssociatedValue(), *this);
1076
1077 // Helper to determine if we need to consider threading, which we cannot
1078 // right now. However, if the function is (assumed) nosync or the thread
1079 // executing all instructions is the main thread only we can ignore
1080 // threading. Also, thread-local objects do not require threading reasoning.
1081 // Finally, we can ignore threading if either access is executed in an
1082 // aligned region.
1083 auto CanIgnoreThreadingForInst = [&](const Instruction &I) -> bool {
1084 if (IsThreadLocalObj || AllInSameNoSyncFn)
1085 return true;
1086 const auto *FnExecDomainAA =
1087 I.getFunction() == &Scope
1088 ? ExecDomainAA
1089 : A.lookupAAFor<AAExecutionDomain>(
1090 IRPosition::function(*I.getFunction()), &QueryingAA,
1091 DepClassTy::NONE);
1092 if (!FnExecDomainAA)
1093 return false;
1094 if (InstIsExecutedInAlignedRegion ||
1095 (FindInterferingWrites &&
1096 FnExecDomainAA->isExecutedInAlignedRegion(A, I))) {
1097 A.recordDependence(*FnExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1098 return true;
1099 }
1100 if (InstIsExecutedByInitialThreadOnly &&
1101 FnExecDomainAA->isExecutedByInitialThreadOnly(I)) {
1102 A.recordDependence(*FnExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1103 return true;
1104 }
1105 return false;
1106 };
1107
1108 // Helper to determine if the access is executed by the same thread as the
1109 // given instruction, for now it is sufficient to avoid any potential
1110 // threading effects as we cannot deal with them anyway.
1111 auto CanIgnoreThreading = [&](const Access &Acc) -> bool {
1112 return CanIgnoreThreadingForInst(*Acc.getRemoteInst()) ||
1113 (Acc.getRemoteInst() != Acc.getLocalInst() &&
1114 CanIgnoreThreadingForInst(*Acc.getLocalInst()));
1115 };
1116
1117 // TODO: Use inter-procedural reachability and dominance.
1118 bool IsKnownNoRecurse;
1120 A, this, IRPosition::function(Scope), DepClassTy::OPTIONAL,
1121 IsKnownNoRecurse);
1122
1123 // TODO: Use reaching kernels from AAKernelInfo (or move it to
1124 // AAExecutionDomain) such that we allow scopes other than kernels as long
1125 // as the reaching kernels are disjoint.
1126 bool InstInKernel = A.getInfoCache().isKernel(Scope);
1127 bool ObjHasKernelLifetime = false;
1128 const bool UseDominanceReasoning =
1129 FindInterferingWrites && IsKnownNoRecurse;
1130 const DominatorTree *DT =
1131 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(Scope);
1132
1133 // Helper to check if a value has "kernel lifetime", that is it will not
1134 // outlive a GPU kernel. This is true for shared, constant, and local
1135 // globals on AMD and NVIDIA GPUs.
1136 auto HasKernelLifetime = [&](Value *V, Module &M) {
1137 if (!AA::isGPU(M))
1138 return false;
1139 unsigned VAS = V->getType()->getPointerAddressSpace();
1140 return AA::isGPUSharedAddressSpace(M, VAS) ||
1143 };
1144
1145 // The IsLiveInCalleeCB will be used by the AA::isPotentiallyReachable query
1146 // to determine if we should look at reachability from the callee. For
1147 // certain pointers we know the lifetime and we do not have to step into the
1148 // callee to determine reachability as the pointer would be dead in the
1149 // callee. See the conditional initialization below.
1150 std::function<bool(const Function &)> IsLiveInCalleeCB;
1151
1152 if (auto *AI = dyn_cast<AllocaInst>(&getAssociatedValue())) {
1153 // If the alloca containing function is not recursive the alloca
1154 // must be dead in the callee.
1155 const Function *AIFn = AI->getFunction();
1156 ObjHasKernelLifetime = A.getInfoCache().isKernel(*AIFn);
1157 bool IsKnownNoRecurse;
1159 A, this, IRPosition::function(*AIFn), DepClassTy::OPTIONAL,
1160 IsKnownNoRecurse)) {
1161 IsLiveInCalleeCB = [AIFn](const Function &Fn) { return AIFn != &Fn; };
1162 }
1163 } else if (auto *GV = dyn_cast<GlobalValue>(&getAssociatedValue())) {
1164 // If the global has kernel lifetime we can stop if we reach a kernel
1165 // as it is "dead" in the (unknown) callees.
1166 ObjHasKernelLifetime = HasKernelLifetime(GV, *GV->getParent());
1167 if (ObjHasKernelLifetime)
1168 IsLiveInCalleeCB = [&A](const Function &Fn) {
1169 return !A.getInfoCache().isKernel(Fn);
1170 };
1171 }
1172
1173 // Set of accesses/instructions that will overwrite the result and are
1174 // therefore blockers in the reachability traversal.
1175 AA::InstExclusionSetTy ExclusionSet;
1176
1177 auto AccessCB = [&](const Access &Acc, bool Exact) {
1178 Function *AccScope = Acc.getRemoteInst()->getFunction();
1179 bool AccInSameScope = AccScope == &Scope;
1180
1181 // If the object has kernel lifetime we can ignore accesses only reachable
1182 // by other kernels. For now we only skip accesses *in* other kernels.
1183 if (InstInKernel && ObjHasKernelLifetime && !AccInSameScope &&
1184 A.getInfoCache().isKernel(*AccScope))
1185 return true;
1186
1187 if (Exact && Acc.isMustAccess() && Acc.getRemoteInst() != &I) {
1188 if (Acc.isWrite() || (isa<LoadInst>(I) && Acc.isWriteOrAssumption()))
1189 ExclusionSet.insert(Acc.getRemoteInst());
1190 }
1191
1192 if ((!FindInterferingWrites || !Acc.isWriteOrAssumption()) &&
1193 (!FindInterferingReads || !Acc.isRead()))
1194 return true;
1195
1196 bool Dominates = FindInterferingWrites && DT && Exact &&
1197 Acc.isMustAccess() && AccInSameScope &&
1198 DT->dominates(Acc.getRemoteInst(), &I);
1199 if (Dominates)
1200 DominatingWrites.insert(&Acc);
1201
1202 // Track if all interesting accesses are in the same `nosync` function as
1203 // the given instruction.
1204 AllInSameNoSyncFn &= Acc.getRemoteInst()->getFunction() == &Scope;
1205
1206 InterferingAccesses.push_back({&Acc, Exact});
1207 return true;
1208 };
1209 if (!State::forallInterferingAccesses(I, AccessCB, Range))
1210 return false;
1211
1212 HasBeenWrittenTo = !DominatingWrites.empty();
1213
1214 // Dominating writes form a chain, find the least/lowest member.
1215 Instruction *LeastDominatingWriteInst = nullptr;
1216 for (const Access *Acc : DominatingWrites) {
1217 if (!LeastDominatingWriteInst) {
1218 LeastDominatingWriteInst = Acc->getRemoteInst();
1219 } else if (DT->dominates(LeastDominatingWriteInst,
1220 Acc->getRemoteInst())) {
1221 LeastDominatingWriteInst = Acc->getRemoteInst();
1222 }
1223 }
1224
1225 // Helper to determine if we can skip a specific write access.
1226 auto CanSkipAccess = [&](const Access &Acc, bool Exact) {
1227 if (SkipCB && SkipCB(Acc))
1228 return true;
1229 if (!CanIgnoreThreading(Acc))
1230 return false;
1231
1232 // Check read (RAW) dependences and write (WAR) dependences as necessary.
1233 // If we successfully excluded all effects we are interested in, the
1234 // access can be skipped.
1235 bool ReadChecked = !FindInterferingReads;
1236 bool WriteChecked = !FindInterferingWrites;
1237
1238 // If the instruction cannot reach the access, the former does not
1239 // interfere with what the access reads.
1240 if (!ReadChecked) {
1241 if (!AA::isPotentiallyReachable(A, I, *Acc.getRemoteInst(), QueryingAA,
1242 &ExclusionSet, IsLiveInCalleeCB))
1243 ReadChecked = true;
1244 }
1245 // If the instruction cannot be reach from the access, the latter does not
1246 // interfere with what the instruction reads.
1247 if (!WriteChecked) {
1248 if (!AA::isPotentiallyReachable(A, *Acc.getRemoteInst(), I, QueryingAA,
1249 &ExclusionSet, IsLiveInCalleeCB))
1250 WriteChecked = true;
1251 }
1252
1253 // If we still might be affected by the write of the access but there are
1254 // dominating writes in the function of the instruction
1255 // (HasBeenWrittenTo), we can try to reason that the access is overwritten
1256 // by them. This would have happend above if they are all in the same
1257 // function, so we only check the inter-procedural case. Effectively, we
1258 // want to show that there is no call after the dominting write that might
1259 // reach the access, and when it returns reach the instruction with the
1260 // updated value. To this end, we iterate all call sites, check if they
1261 // might reach the instruction without going through another access
1262 // (ExclusionSet) and at the same time might reach the access. However,
1263 // that is all part of AAInterFnReachability.
1264 if (!WriteChecked && HasBeenWrittenTo &&
1265 Acc.getRemoteInst()->getFunction() != &Scope) {
1266
1267 const auto *FnReachabilityAA = A.getAAFor<AAInterFnReachability>(
1268 QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL);
1269 if (FnReachabilityAA) {
1270 // Without going backwards in the call tree, can we reach the access
1271 // from the least dominating write. No exclusion set is used: writes
1272 // between the dominating write and the access do not hide the access,
1273 // and the instruction itself may be in a cycle, so the access can
1274 // happen after it and still be observed by a later execution of it.
1275 if (!FnReachabilityAA->instructionCanReach(
1276 A, *LeastDominatingWriteInst,
1277 *Acc.getRemoteInst()->getFunction()))
1278 WriteChecked = true;
1279 }
1280 }
1281
1282 if (ReadChecked && WriteChecked)
1283 return true;
1284
1285 if (!DT || !UseDominanceReasoning)
1286 return false;
1287 if (!DominatingWrites.count(&Acc))
1288 return false;
1289 return LeastDominatingWriteInst != Acc.getRemoteInst();
1290 };
1291
1292 // Run the user callback on all accesses we cannot skip and return if
1293 // that succeeded for all or not.
1294 for (auto &It : InterferingAccesses) {
1295 if ((!AllInSameNoSyncFn && !IsThreadLocalObj && !ExecDomainAA) ||
1296 !CanSkipAccess(*It.first, It.second)) {
1297 if (!UserCB(*It.first, It.second))
1298 return false;
1299 }
1300 }
1301 return true;
1302 }
1303
1304 ChangeStatus translateAndAddStateFromCallee(Attributor &A,
1305 const AAPointerInfo &OtherAA,
1306 CallBase &CB) {
1307 using namespace AA::PointerInfo;
1308 if (!OtherAA.getState().isValidState() || !isValidState())
1309 return indicatePessimisticFixpoint();
1310
1311 ChangeStatus Changed = ChangeStatus::UNCHANGED;
1312 const auto &OtherAAImpl = static_cast<const AAPointerInfoImpl &>(OtherAA);
1313 bool IsByval = OtherAAImpl.getAssociatedArgument()->hasByValAttr();
1314 Changed |= setReachesReturn(OtherAAImpl.ReturnedOffsets);
1315
1316 // Combine the accesses bin by bin.
1317 const auto &State = OtherAAImpl.getState();
1318 for (const auto &It : State) {
1319 for (auto Index : It.getSecond()) {
1320 const auto &RAcc = State.getAccess(Index);
1321 if (IsByval && !RAcc.isRead())
1322 continue;
1323 bool UsedAssumedInformation = false;
1324 AccessKind AK = RAcc.getKind();
1325 auto Content = A.translateArgumentToCallSiteContent(
1326 RAcc.getContent(), CB, *this, UsedAssumedInformation);
1327 AK = AccessKind(AK & (IsByval ? AccessKind::AK_R : AccessKind::AK_RW));
1328 AK = AccessKind(AK | (RAcc.isMayAccess() ? AK_MAY : AK_MUST));
1329
1330 Changed |= addAccess(A, RAcc.getRanges(), CB, Content, AK,
1331 RAcc.getType(), RAcc.getRemoteInst());
1332 }
1333 }
1334 return Changed;
1335 }
1336
1337 ChangeStatus translateAndAddState(Attributor &A, const AAPointerInfo &OtherAA,
1338 const OffsetInfo &Offsets, CallBase &CB,
1339 bool IsMustAcc) {
1340 using namespace AA::PointerInfo;
1341 if (!OtherAA.getState().isValidState() || !isValidState())
1342 return indicatePessimisticFixpoint();
1343
1344 const auto &OtherAAImpl = static_cast<const AAPointerInfoImpl &>(OtherAA);
1345
1346 // Combine the accesses bin by bin.
1347 ChangeStatus Changed = ChangeStatus::UNCHANGED;
1348 const auto &State = OtherAAImpl.getState();
1349 for (const auto &It : State) {
1350 for (auto Index : It.getSecond()) {
1351 const auto &RAcc = State.getAccess(Index);
1352 if (!IsMustAcc && RAcc.isAssumption())
1353 continue;
1354 for (auto Offset : Offsets) {
1355 auto NewRanges = Offset == AA::RangeTy::Unknown
1357 : RAcc.getRanges();
1358 if (!NewRanges.isUnknown()) {
1359 NewRanges.addToAllOffsets(Offset);
1360 }
1361 AccessKind AK = RAcc.getKind();
1362 if (!IsMustAcc)
1363 AK = AccessKind((AK & ~AK_MUST) | AK_MAY);
1364 Changed |= addAccess(A, NewRanges, CB, RAcc.getContent(), AK,
1365 RAcc.getType(), RAcc.getRemoteInst());
1366 }
1367 }
1368 }
1369 return Changed;
1370 }
1371
1372 /// Statistic tracking for all AAPointerInfo implementations.
1373 void trackPointerInfoStatistics(const IRPosition &IRP) const {}
1374
1375 /// Dump the state into \p O.
1376 void dumpState(raw_ostream &O) {
1377 for (auto &It : OffsetBins) {
1378 O << "[" << It.first.Offset << "-" << It.first.Offset + It.first.Size
1379 << "] : " << It.getSecond().size() << "\n";
1380 for (auto AccIndex : It.getSecond()) {
1381 auto &Acc = AccessList[AccIndex];
1382 O << " - " << Acc.getKind() << " - " << *Acc.getLocalInst() << "\n";
1383 if (Acc.getLocalInst() != Acc.getRemoteInst())
1384 O << " --> " << *Acc.getRemoteInst()
1385 << "\n";
1386 if (!Acc.isWrittenValueYetUndetermined()) {
1387 if (isa_and_nonnull<Function>(Acc.getWrittenValue()))
1388 O << " - c: func " << Acc.getWrittenValue()->getName()
1389 << "\n";
1390 else if (Acc.getWrittenValue())
1391 O << " - c: " << *Acc.getWrittenValue() << "\n";
1392 else
1393 O << " - c: <unknown>\n";
1394 }
1395 }
1396 }
1397 }
1398};
1399
1400struct AAPointerInfoFloating : public AAPointerInfoImpl {
1402 AAPointerInfoFloating(const IRPosition &IRP, Attributor &A)
1403 : AAPointerInfoImpl(IRP, A) {}
1404
1405 /// Deal with an access and signal if it was handled successfully.
1406 bool handleAccess(Attributor &A, Instruction &I,
1407 std::optional<Value *> Content, AccessKind Kind,
1408 OffsetInfo::VecTy &Offsets, ChangeStatus &Changed,
1409 Type &Ty) {
1410 using namespace AA::PointerInfo;
1412 const DataLayout &DL = A.getDataLayout();
1413 TypeSize AccessSize = DL.getTypeStoreSize(&Ty);
1414 if (!AccessSize.isScalable())
1415 Size = AccessSize.getFixedValue();
1416
1417 // Make a strictly ascending list of offsets as required by addAccess()
1418 SmallVector<int64_t> OffsetsSorted(Offsets.begin(), Offsets.end());
1419 llvm::sort(OffsetsSorted);
1420
1422 if (!VT || VT->getElementCount().isScalable() ||
1423 !Content.value_or(nullptr) || !isa<Constant>(*Content) ||
1424 (*Content)->getType() != VT ||
1425 DL.getTypeStoreSize(VT->getElementType()).isScalable()) {
1426 Changed =
1427 Changed | addAccess(A, {OffsetsSorted, Size}, I, Content, Kind, &Ty);
1428 } else {
1429 // Handle vector stores with constant content element-wise.
1430 // TODO: We could look for the elements or create instructions
1431 // representing them.
1432 // TODO: We need to push the Content into the range abstraction
1433 // (AA::RangeTy) to allow different content values for different
1434 // ranges. ranges. Hence, support vectors storing different values.
1435 Type *ElementType = VT->getElementType();
1436 int64_t ElementSize = DL.getTypeStoreSize(ElementType).getFixedValue();
1437 auto *ConstContent = cast<Constant>(*Content);
1438 Type *Int32Ty = Type::getInt32Ty(ElementType->getContext());
1439 SmallVector<int64_t> ElementOffsets(OffsetsSorted.begin(),
1440 OffsetsSorted.end());
1441
1442 for (int i = 0, e = VT->getElementCount().getFixedValue(); i != e; ++i) {
1443 Value *ElementContent = ConstantExpr::getExtractElement(
1444 ConstContent, ConstantInt::get(Int32Ty, i));
1445
1446 // Add the element access.
1447 Changed = Changed | addAccess(A, {ElementOffsets, ElementSize}, I,
1448 ElementContent, Kind, ElementType);
1449
1450 // Advance the offsets for the next element.
1451 for (auto &ElementOffset : ElementOffsets)
1452 ElementOffset += ElementSize;
1453 }
1454 }
1455 return true;
1456 };
1457
1458 ChangeStatus updateImpl(Attributor &A) override;
1459
1460 /// If the indices to \p GEP can be traced to constants, incorporate all
1461 /// of these into \p UsrOI.
1462 ///
1463 /// \return true iff \p UsrOI is updated.
1464 bool collectConstantsForGEP(Attributor &A, const DataLayout &DL,
1465 OffsetInfo &UsrOI, const OffsetInfo &PtrOI,
1466 const GEPOperator *GEP);
1467
1468 void trackStatistics() const override {
1469 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1470 }
1471};
1472
1473bool AAPointerInfoFloating::collectConstantsForGEP(Attributor &A,
1474 const DataLayout &DL,
1475 OffsetInfo &UsrOI,
1476 const OffsetInfo &PtrOI,
1477 const GEPOperator *GEP) {
1478 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1479 SmallMapVector<Value *, APInt, 4> VariableOffsets;
1480 APInt ConstantOffset(BitWidth, 0);
1481
1482 assert(!UsrOI.isUnknown() && !PtrOI.isUnknown() &&
1483 "Don't look for constant values if the offset has already been "
1484 "determined to be unknown.");
1485
1486 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) {
1487 UsrOI.setUnknown();
1488 return true;
1489 }
1490
1491 LLVM_DEBUG(dbgs() << "[AAPointerInfo] GEP offset is "
1492 << (VariableOffsets.empty() ? "" : "not") << " constant "
1493 << *GEP << "\n");
1494
1495 auto Union = PtrOI;
1496 Union.addToAll(ConstantOffset.getSExtValue());
1497
1498 // Each VI in VariableOffsets has a set of potential constant values. Every
1499 // combination of elements, picked one each from these sets, is separately
1500 // added to the original set of offsets, thus resulting in more offsets.
1501 for (const auto &VI : VariableOffsets) {
1502 auto *PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>(
1503 *this, IRPosition::value(*VI.first), DepClassTy::OPTIONAL);
1504 if (!PotentialConstantsAA || !PotentialConstantsAA->isValidState()) {
1505 UsrOI.setUnknown();
1506 return true;
1507 }
1508
1509 // UndefValue is treated as a zero, which leaves Union as is.
1510 if (PotentialConstantsAA->undefIsContained())
1511 continue;
1512
1513 // We need at least one constant in every set to compute an actual offset.
1514 // Otherwise, we end up pessimizing AAPointerInfo by respecting offsets that
1515 // don't actually exist. In other words, the absence of constant values
1516 // implies that the operation can be assumed dead for now.
1517 auto &AssumedSet = PotentialConstantsAA->getAssumedSet();
1518 if (AssumedSet.empty())
1519 return false;
1520
1521 OffsetInfo Product;
1522 for (const auto &ConstOffset : AssumedSet) {
1523 auto CopyPerOffset = Union;
1524 CopyPerOffset.addToAll(ConstOffset.getSExtValue() *
1525 VI.second.getZExtValue());
1526 Product.merge(CopyPerOffset);
1527 }
1528 Union = Product;
1529 }
1530
1531 UsrOI = std::move(Union);
1532 return true;
1533}
1534
1535ChangeStatus AAPointerInfoFloating::updateImpl(Attributor &A) {
1536 using namespace AA::PointerInfo;
1538 const DataLayout &DL = A.getDataLayout();
1539 Value &AssociatedValue = getAssociatedValue();
1540
1541 DenseMap<Value *, OffsetInfo> OffsetInfoMap;
1542 OffsetInfoMap[&AssociatedValue].insert(0);
1543
1544 auto HandlePassthroughUser = [&](Value *Usr, Value *CurPtr, bool &Follow) {
1545 // One does not simply walk into a map and assign a reference to a possibly
1546 // new location. That can cause an invalidation before the assignment
1547 // happens, like so:
1548 //
1549 // OffsetInfoMap[Usr] = OffsetInfoMap[CurPtr]; /* bad idea! */
1550 //
1551 // The RHS is a reference that may be invalidated by an insertion caused by
1552 // the LHS. So we ensure that the side-effect of the LHS happens first.
1553
1554 assert(OffsetInfoMap.contains(CurPtr) &&
1555 "CurPtr does not exist in the map!");
1556
1557 auto &UsrOI = OffsetInfoMap[Usr];
1558 auto &PtrOI = OffsetInfoMap[CurPtr];
1559 assert(!PtrOI.isUnassigned() &&
1560 "Cannot pass through if the input Ptr was not visited!");
1561 UsrOI.merge(PtrOI);
1562 Follow = true;
1563 return true;
1564 };
1565
1566 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
1567 Value *CurPtr = U.get();
1568 User *Usr = U.getUser();
1569 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Analyze " << *CurPtr << " in " << *Usr
1570 << "\n");
1571 assert(OffsetInfoMap.count(CurPtr) &&
1572 "The current pointer offset should have been seeded!");
1573 assert(!OffsetInfoMap[CurPtr].isUnassigned() &&
1574 "Current pointer should be assigned");
1575
1576 // Only address space casts are followed; other casts of a pointer (e.g.,
1577 // ptrtoint, ptrtoaddr, or a bitcast to a byte type) do not produce a
1578 // pointer that can be tracked.
1580 return HandlePassthroughUser(Usr, CurPtr, Follow);
1581
1582 if (auto *GEP = dyn_cast<GEPOperator>(Usr)) {
1583 // Note the order here, the Usr access might change the map, CurPtr is
1584 // already in it though.
1585 auto &UsrOI = OffsetInfoMap[Usr];
1586 auto &PtrOI = OffsetInfoMap[CurPtr];
1587
1588 if (UsrOI.isUnknown())
1589 return true;
1590
1591 if (PtrOI.isUnknown()) {
1592 Follow = true;
1593 UsrOI.setUnknown();
1594 return true;
1595 }
1596
1597 Follow = collectConstantsForGEP(A, DL, UsrOI, PtrOI, GEP);
1598 return true;
1599 }
1600 if (isa<SelectInst>(Usr))
1601 return HandlePassthroughUser(Usr, CurPtr, Follow);
1602 // Returns are allowed if they are in the associated functions. Users can
1603 // then check the call site return. Returns from other functions can't be
1604 // tracked and are cause for invalidation.
1605 if (auto *RI = dyn_cast<ReturnInst>(Usr)) {
1606 if (RI->getFunction() == getAssociatedFunction()) {
1607 auto &PtrOI = OffsetInfoMap[CurPtr];
1608 Changed |= setReachesReturn(PtrOI);
1609 return true;
1610 }
1611 return false;
1612 }
1613
1614 // For PHIs we need to take care of the recurrence explicitly as the value
1615 // might change while we iterate through a loop. For now, we give up if
1616 // the PHI is not invariant.
1617 if (auto *PHI = dyn_cast<PHINode>(Usr)) {
1618 // Note the order here, the Usr access might change the map, CurPtr is
1619 // already in it though.
1620 auto [PhiIt, IsFirstPHIUser] = OffsetInfoMap.try_emplace(PHI);
1621 auto &UsrOI = PhiIt->second;
1622 auto &PtrOI = OffsetInfoMap[CurPtr];
1623
1624 // Check if the PHI operand has already an unknown offset as we can't
1625 // improve on that anymore.
1626 if (PtrOI.isUnknown()) {
1627 LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI operand offset unknown "
1628 << *CurPtr << " in " << *PHI << "\n");
1629 Follow = !UsrOI.isUnknown();
1630 UsrOI.setUnknown();
1631 return true;
1632 }
1633
1634 // Check if the PHI is invariant (so far).
1635 if (UsrOI == PtrOI) {
1636 assert(!PtrOI.isUnassigned() &&
1637 "Cannot assign if the current Ptr was not visited!");
1638 LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI is invariant (so far)");
1639 return true;
1640 }
1641
1642 // Check if the PHI operand can be traced back to AssociatedValue.
1643 APInt Offset(
1644 DL.getIndexSizeInBits(CurPtr->getType()->getPointerAddressSpace()),
1645 0);
1646 Value *CurPtrBase = CurPtr->stripAndAccumulateConstantOffsets(
1647 DL, Offset, /* AllowNonInbounds */ true);
1648 auto It = OffsetInfoMap.find(CurPtrBase);
1649 if (It == OffsetInfoMap.end()) {
1650 LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI operand is too complex "
1651 << *CurPtr << " in " << *PHI
1652 << " (base: " << *CurPtrBase << ")\n");
1653 UsrOI.setUnknown();
1654 Follow = true;
1655 return true;
1656 }
1657
1658 // Check if the PHI operand is not dependent on the PHI itself. Every
1659 // recurrence is a cyclic net of PHIs in the data flow, and has an
1660 // equivalent Cycle in the control flow. One of those PHIs must be in the
1661 // header of that control flow Cycle. This is independent of the choice of
1662 // Cycles reported by CycleInfo. It is sufficient to check the PHIs in
1663 // every Cycle header; if such a node is marked unknown, this will
1664 // eventually propagate through the whole net of PHIs in the recurrence.
1665 const auto *CI =
1666 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
1667 *PHI->getFunction());
1668 if (mayBeInCycle(CI, cast<Instruction>(Usr), /* HeaderOnly */ true)) {
1669 auto BaseOI = It->getSecond();
1670 BaseOI.addToAll(Offset.getZExtValue());
1671 if (IsFirstPHIUser || BaseOI == UsrOI) {
1672 LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI is invariant " << *CurPtr
1673 << " in " << *Usr << "\n");
1674 return HandlePassthroughUser(Usr, CurPtr, Follow);
1675 }
1676
1677 LLVM_DEBUG(
1678 dbgs() << "[AAPointerInfo] PHI operand pointer offset mismatch "
1679 << *CurPtr << " in " << *PHI << "\n");
1680 UsrOI.setUnknown();
1681 Follow = true;
1682 return true;
1683 }
1684
1685 UsrOI.merge(PtrOI);
1686 Follow = true;
1687 return true;
1688 }
1689
1690 if (auto *LoadI = dyn_cast<LoadInst>(Usr)) {
1691 // If the access is to a pointer that may or may not be the associated
1692 // value, e.g. due to a PHI, we cannot assume it will be read.
1693 AccessKind AK = AccessKind::AK_R;
1694 if (getUnderlyingObject(CurPtr) == &AssociatedValue)
1695 AK = AccessKind(AK | AccessKind::AK_MUST);
1696 else
1697 AK = AccessKind(AK | AccessKind::AK_MAY);
1698 if (!handleAccess(A, *LoadI, /* Content */ nullptr, AK,
1699 OffsetInfoMap[CurPtr].Offsets, Changed,
1700 *LoadI->getType()))
1701 return false;
1702
1703 auto IsAssumption = [](Instruction &I) {
1704 if (auto *II = dyn_cast<IntrinsicInst>(&I))
1705 return II->isAssumeLikeIntrinsic();
1706 return false;
1707 };
1708
1709 auto IsImpactedInRange = [&](Instruction *FromI, Instruction *ToI) {
1710 // Check if the assumption and the load are executed together without
1711 // memory modification.
1712 do {
1713 if (FromI->mayWriteToMemory() && !IsAssumption(*FromI))
1714 return true;
1715 FromI = FromI->getNextNode();
1716 } while (FromI && FromI != ToI);
1717 return false;
1718 };
1719
1720 BasicBlock *BB = LoadI->getParent();
1721 auto IsValidAssume = [&](IntrinsicInst &IntrI) {
1722 if (IntrI.getIntrinsicID() != Intrinsic::assume)
1723 return false;
1724 BasicBlock *IntrBB = IntrI.getParent();
1725 if (IntrI.getParent() == BB) {
1726 if (IsImpactedInRange(LoadI->getNextNode(), &IntrI))
1727 return false;
1728 } else {
1729 auto PredIt = pred_begin(IntrBB);
1730 if (PredIt == pred_end(IntrBB))
1731 return false;
1732 if ((*PredIt) != BB)
1733 return false;
1734 if (++PredIt != pred_end(IntrBB))
1735 return false;
1736 for (auto *SuccBB : successors(BB)) {
1737 if (SuccBB == IntrBB)
1738 continue;
1739 if (isa<UnreachableInst>(SuccBB->getTerminator()))
1740 continue;
1741 return false;
1742 }
1743 if (IsImpactedInRange(LoadI->getNextNode(), BB->getTerminator()))
1744 return false;
1745 if (IsImpactedInRange(&IntrBB->front(), &IntrI))
1746 return false;
1747 }
1748 return true;
1749 };
1750
1751 std::pair<Value *, IntrinsicInst *> Assumption;
1752 for (const Use &LoadU : LoadI->uses()) {
1753 if (auto *CmpI = dyn_cast<CmpInst>(LoadU.getUser())) {
1754 if (!CmpI->isEquality() || !CmpI->isTrueWhenEqual())
1755 continue;
1756 for (const Use &CmpU : CmpI->uses()) {
1757 if (auto *IntrI = dyn_cast<IntrinsicInst>(CmpU.getUser())) {
1758 if (!IsValidAssume(*IntrI))
1759 continue;
1760 int Idx = CmpI->getOperandUse(0) == LoadU;
1761 Assumption = {CmpI->getOperand(Idx), IntrI};
1762 break;
1763 }
1764 }
1765 }
1766 if (Assumption.first)
1767 break;
1768 }
1769
1770 // Check if we found an assumption associated with this load.
1771 if (!Assumption.first || !Assumption.second)
1772 return true;
1773
1774 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Assumption found "
1775 << *Assumption.second << ": " << *LoadI
1776 << " == " << *Assumption.first << "\n");
1777 bool UsedAssumedInformation = false;
1778 std::optional<Value *> Content = nullptr;
1779 if (Assumption.first)
1780 Content =
1781 A.getAssumedSimplified(*Assumption.first, *this,
1782 UsedAssumedInformation, AA::Interprocedural);
1783 return handleAccess(
1784 A, *Assumption.second, Content, AccessKind::AK_ASSUMPTION,
1785 OffsetInfoMap[CurPtr].Offsets, Changed, *LoadI->getType());
1786 }
1787
1788 auto HandleStoreLike = [&](Instruction &I, Value *ValueOp, Type &ValueTy,
1789 ArrayRef<Value *> OtherOps, AccessKind AK) {
1790 for (auto *OtherOp : OtherOps) {
1791 if (OtherOp == CurPtr) {
1792 LLVM_DEBUG(
1793 dbgs()
1794 << "[AAPointerInfo] Escaping use in store like instruction " << I
1795 << "\n");
1796 return false;
1797 }
1798 }
1799
1800 // If the access is to a pointer that may or may not be the associated
1801 // value, e.g. due to a PHI, we cannot assume it will be written.
1802 if (getUnderlyingObject(CurPtr) == &AssociatedValue)
1803 AK = AccessKind(AK | AccessKind::AK_MUST);
1804 else
1805 AK = AccessKind(AK | AccessKind::AK_MAY);
1806 bool UsedAssumedInformation = false;
1807 std::optional<Value *> Content = nullptr;
1808 if (ValueOp)
1809 Content = A.getAssumedSimplified(
1810 *ValueOp, *this, UsedAssumedInformation, AA::Interprocedural);
1811 return handleAccess(A, I, Content, AK, OffsetInfoMap[CurPtr].Offsets,
1812 Changed, ValueTy);
1813 };
1814
1815 if (auto *StoreI = dyn_cast<StoreInst>(Usr))
1816 return HandleStoreLike(*StoreI, StoreI->getValueOperand(),
1817 *StoreI->getValueOperand()->getType(),
1818 {StoreI->getValueOperand()}, AccessKind::AK_W);
1819 if (auto *RMWI = dyn_cast<AtomicRMWInst>(Usr))
1820 return HandleStoreLike(*RMWI, nullptr, *RMWI->getValOperand()->getType(),
1821 {RMWI->getValOperand()}, AccessKind::AK_RW);
1822 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(Usr))
1823 return HandleStoreLike(
1824 *CXI, nullptr, *CXI->getNewValOperand()->getType(),
1825 {CXI->getCompareOperand(), CXI->getNewValOperand()},
1826 AccessKind::AK_RW);
1827
1828 if (auto *CB = dyn_cast<CallBase>(Usr)) {
1829 if (CB->isLifetimeStartOrEnd())
1830 return true;
1831 const auto *TLI =
1832 A.getInfoCache().getTargetLibraryInfoForFunction(*CB->getFunction());
1833 if (getFreedOperand(CB, TLI) == U)
1834 return true;
1835 if (CB->isArgOperand(&U)) {
1836 unsigned ArgNo = CB->getArgOperandNo(&U);
1837 const auto *CSArgPI = A.getAAFor<AAPointerInfo>(
1838 *this, IRPosition::callsite_argument(*CB, ArgNo),
1840 if (!CSArgPI)
1841 return false;
1842 bool IsArgMustAcc = (getUnderlyingObject(CurPtr) == &AssociatedValue);
1843 Changed = translateAndAddState(A, *CSArgPI, OffsetInfoMap[CurPtr], *CB,
1844 IsArgMustAcc) |
1845 Changed;
1846 if (!CSArgPI->reachesReturn())
1847 return isValidState();
1848
1850 if (!Callee || Callee->arg_size() <= ArgNo)
1851 return false;
1852 bool UsedAssumedInformation = false;
1853 auto ReturnedValue = A.getAssumedSimplified(
1854 IRPosition::returned(*Callee), *this, UsedAssumedInformation,
1856 auto *ReturnedArg =
1857 dyn_cast_or_null<Argument>(ReturnedValue.value_or(nullptr));
1858 auto *Arg = Callee->getArg(ArgNo);
1859 if (ReturnedArg && Arg != ReturnedArg)
1860 return true;
1861 bool IsRetMustAcc = IsArgMustAcc && (ReturnedArg == Arg);
1862 const auto *CSRetPI = A.getAAFor<AAPointerInfo>(
1864 if (!CSRetPI)
1865 return false;
1866 OffsetInfo OI = OffsetInfoMap[CurPtr];
1867 CSArgPI->addReturnedOffsetsTo(OI);
1868 Changed =
1869 translateAndAddState(A, *CSRetPI, OI, *CB, IsRetMustAcc) | Changed;
1870 return isValidState();
1871 }
1872 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Call user not handled " << *CB
1873 << "\n");
1874 return false;
1875 }
1876
1877 LLVM_DEBUG(dbgs() << "[AAPointerInfo] User not handled " << *Usr << "\n");
1878 return false;
1879 };
1880 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
1881 assert(OffsetInfoMap.count(OldU) && "Old use should be known already!");
1882 assert(!OffsetInfoMap[OldU].isUnassigned() && "Old use should be assinged");
1883 if (OffsetInfoMap.count(NewU)) {
1884 LLVM_DEBUG({
1885 if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) {
1886 dbgs() << "[AAPointerInfo] Equivalent use callback failed: "
1887 << OffsetInfoMap[NewU] << " vs " << OffsetInfoMap[OldU]
1888 << "\n";
1889 }
1890 });
1891 return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1892 }
1893 bool Unused;
1894 return HandlePassthroughUser(NewU.get(), OldU.get(), Unused);
1895 };
1896 if (!A.checkForAllUses(UsePred, *this, AssociatedValue,
1897 /* CheckBBLivenessOnly */ true, DepClassTy::OPTIONAL,
1898 /* IgnoreDroppableUses */ true, EquivalentUseCB)) {
1899 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Check for all uses failed, abort!\n");
1900 return indicatePessimisticFixpoint();
1901 }
1902
1903 LLVM_DEBUG({
1904 dbgs() << "Accesses by bin after update:\n";
1905 dumpState(dbgs());
1906 });
1907
1908 return Changed;
1909}
1910
1911struct AAPointerInfoReturned final : AAPointerInfoImpl {
1912 AAPointerInfoReturned(const IRPosition &IRP, Attributor &A)
1913 : AAPointerInfoImpl(IRP, A) {}
1914
1915 ChangeStatus updateImpl(Attributor &A) override {
1916 return indicatePessimisticFixpoint();
1917 }
1918
1919 void trackStatistics() const override {
1920 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1921 }
1922};
1923
1924struct AAPointerInfoArgument final : AAPointerInfoFloating {
1925 AAPointerInfoArgument(const IRPosition &IRP, Attributor &A)
1926 : AAPointerInfoFloating(IRP, A) {}
1927
1928 void trackStatistics() const override {
1929 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1930 }
1931};
1932
1933struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1934 AAPointerInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
1935 : AAPointerInfoFloating(IRP, A) {}
1936
1937 ChangeStatus updateImpl(Attributor &A) override {
1938 using namespace AA::PointerInfo;
1939 // We handle memory intrinsics explicitly, at least the first (=
1940 // destination) and second (=source) arguments as we know how they are
1941 // accessed.
1942 if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) {
1943 int64_t LengthVal = AA::RangeTy::Unknown;
1944 if (auto Length = MI->getLengthInBytes())
1945 LengthVal = Length->getSExtValue();
1946 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1947 ChangeStatus Changed = ChangeStatus::UNCHANGED;
1948 if (ArgNo > 1) {
1949 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled memory intrinsic "
1950 << *MI << "\n");
1951 return indicatePessimisticFixpoint();
1952 } else {
1953 auto Kind =
1954 ArgNo == 0 ? AccessKind::AK_MUST_WRITE : AccessKind::AK_MUST_READ;
1955 Changed =
1956 Changed | addAccess(A, {0, LengthVal}, *MI, nullptr, Kind, nullptr);
1957 }
1958 LLVM_DEBUG({
1959 dbgs() << "Accesses by bin after update:\n";
1960 dumpState(dbgs());
1961 });
1962
1963 return Changed;
1964 }
1965
1966 // TODO: Once we have call site specific value information we can provide
1967 // call site specific liveness information and then it makes
1968 // sense to specialize attributes for call sites arguments instead of
1969 // redirecting requests to the callee argument.
1970 Argument *Arg = getAssociatedArgument();
1971 if (Arg) {
1972 const IRPosition &ArgPos = IRPosition::argument(*Arg);
1973 auto *ArgAA =
1974 A.getAAFor<AAPointerInfo>(*this, ArgPos, DepClassTy::REQUIRED);
1975 if (ArgAA && ArgAA->getState().isValidState())
1976 return translateAndAddStateFromCallee(A, *ArgAA,
1977 *cast<CallBase>(getCtxI()));
1978 if (!Arg->getParent()->isDeclaration())
1979 return indicatePessimisticFixpoint();
1980 }
1981
1982 bool IsKnownNoCapture;
1984 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoCapture))
1985 return indicatePessimisticFixpoint();
1986
1987 bool IsKnown = false;
1988 if (AA::isAssumedReadNone(A, getIRPosition(), *this, IsKnown))
1989 return ChangeStatus::UNCHANGED;
1990 bool ReadOnly = AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown);
1991 auto Kind =
1992 ReadOnly ? AccessKind::AK_MAY_READ : AccessKind::AK_MAY_READ_WRITE;
1993 return addAccess(A, AA::RangeTy::getUnknown(), *getCtxI(), nullptr, Kind,
1994 nullptr);
1995 }
1996
1997 void trackStatistics() const override {
1998 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1999 }
2000};
2001
2002struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
2003 AAPointerInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
2004 : AAPointerInfoFloating(IRP, A) {}
2005
2006 void trackStatistics() const override {
2007 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2008 }
2009};
2010} // namespace
2011
2012/// -----------------------NoUnwind Function Attribute--------------------------
2013
2014namespace {
2015struct AANoUnwindImpl : AANoUnwind {
2016 AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
2017
2018 void initialize(Attributor &A) override {
2019 bool IsKnown;
2021 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2022 (void)IsKnown;
2023 }
2024
2025 const std::string getAsStr(Attributor *A) const override {
2026 return getAssumed() ? "nounwind" : "may-unwind";
2027 }
2028
2029 ChangeStatus updateImpl(Attributor &A) override {
2030 auto Opcodes = {
2031 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
2032 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet,
2033 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
2034
2035 auto CheckForNoUnwind = [&](Instruction &I) {
2036 if (!I.mayThrow(/* IncludePhaseOneUnwind */ true))
2037 return true;
2038
2039 if (const auto *CB = dyn_cast<CallBase>(&I)) {
2040 bool IsKnownNoUnwind;
2042 A, this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED,
2043 IsKnownNoUnwind);
2044 }
2045 return false;
2046 };
2047
2048 bool UsedAssumedInformation = false;
2049 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes,
2050 UsedAssumedInformation))
2051 return indicatePessimisticFixpoint();
2052
2053 return ChangeStatus::UNCHANGED;
2054 }
2055};
2056
2057struct AANoUnwindFunction final : public AANoUnwindImpl {
2058 AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
2059 : AANoUnwindImpl(IRP, A) {}
2060
2061 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
2062};
2063
2064/// NoUnwind attribute deduction for a call sites.
2065struct AANoUnwindCallSite final
2066 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl> {
2067 AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
2068 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl>(IRP, A) {}
2069
2070 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
2071};
2072} // namespace
2073
2074/// ------------------------ NoSync Function Attribute -------------------------
2075
2076bool AANoSync::isAlignedBarrier(const CallBase &CB, bool ExecutedAligned) {
2077 switch (CB.getIntrinsicID()) {
2078 case Intrinsic::nvvm_barrier_cta_sync_aligned_all:
2079 case Intrinsic::nvvm_barrier_cta_sync_aligned_count:
2080 case Intrinsic::nvvm_barrier_cta_red_and_aligned_all:
2081 case Intrinsic::nvvm_barrier_cta_red_and_aligned_count:
2082 case Intrinsic::nvvm_barrier_cta_red_or_aligned_all:
2083 case Intrinsic::nvvm_barrier_cta_red_or_aligned_count:
2084 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_all:
2085 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_count:
2086 return true;
2087 case Intrinsic::amdgcn_s_barrier:
2088 if (ExecutedAligned)
2089 return true;
2090 break;
2091 default:
2092 break;
2093 }
2094 return hasAssumption(CB, KnownAssumptionString("ompx_aligned_barrier"));
2095}
2096
2098 if (!I->isAtomic())
2099 return false;
2100
2101 if (auto *FI = dyn_cast<FenceInst>(I))
2102 // All legal orderings for fence are stronger than monotonic.
2103 return FI->getSyncScopeID() != SyncScope::SingleThread;
2104 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
2105 // Unordered is not a legal ordering for cmpxchg.
2106 return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic ||
2107 AI->getFailureOrdering() != AtomicOrdering::Monotonic);
2108 }
2109
2110 AtomicOrdering Ordering;
2111 switch (I->getOpcode()) {
2112 case Instruction::AtomicRMW:
2113 Ordering = cast<AtomicRMWInst>(I)->getOrdering();
2114 break;
2115 case Instruction::Store:
2116 Ordering = cast<StoreInst>(I)->getOrdering();
2117 break;
2118 case Instruction::Load:
2119 Ordering = cast<LoadInst>(I)->getOrdering();
2120 break;
2121 default:
2123 "New atomic operations need to be known in the attributor.");
2124 }
2125
2126 return (Ordering != AtomicOrdering::Unordered &&
2127 Ordering != AtomicOrdering::Monotonic);
2128}
2129
2130namespace {
2131struct AANoSyncImpl : AANoSync {
2132 AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
2133
2134 void initialize(Attributor &A) override {
2135 bool IsKnown;
2136 assert(!AA::hasAssumedIRAttr<Attribute::NoSync>(A, nullptr, getIRPosition(),
2137 DepClassTy::NONE, IsKnown));
2138 (void)IsKnown;
2139 }
2140
2141 const std::string getAsStr(Attributor *A) const override {
2142 return getAssumed() ? "nosync" : "may-sync";
2143 }
2144
2145 ChangeStatus updateImpl(Attributor &A) override;
2146};
2147
2148ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
2149
2150 auto CheckRWInstForNoSync = [&](Instruction &I) {
2151 return AA::isNoSyncInst(A, I, *this);
2152 };
2153
2154 auto CheckForNoSync = [&](Instruction &I) {
2155 // At this point we handled all read/write effects and they are all
2156 // nosync, so they can be skipped.
2157 if (I.mayReadOrWriteMemory())
2158 return true;
2159
2160 bool IsKnown;
2161 CallBase &CB = cast<CallBase>(I);
2164 IsKnown))
2165 return true;
2166
2167 // non-convergent and readnone imply nosync.
2168 return !CB.isConvergent();
2169 };
2170
2171 bool UsedAssumedInformation = false;
2172 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this,
2173 UsedAssumedInformation) ||
2174 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this,
2175 UsedAssumedInformation))
2176 return indicatePessimisticFixpoint();
2177
2179}
2180
2181struct AANoSyncFunction final : public AANoSyncImpl {
2182 AANoSyncFunction(const IRPosition &IRP, Attributor &A)
2183 : AANoSyncImpl(IRP, A) {}
2184
2185 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
2186};
2187
2188/// NoSync attribute deduction for a call sites.
2189struct AANoSyncCallSite final : AACalleeToCallSite<AANoSync, AANoSyncImpl> {
2190 AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
2191 : AACalleeToCallSite<AANoSync, AANoSyncImpl>(IRP, A) {}
2192
2193 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
2194};
2195} // namespace
2196
2197/// ------------------------ No-Free Attributes ----------------------------
2198
2199namespace {
2200struct AANoFreeImpl : public AANoFree {
2201 AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
2202
2203 void initialize(Attributor &A) override {
2204 bool IsKnown;
2205 assert(!AA::hasAssumedIRAttr<Attribute::NoFree>(A, nullptr, getIRPosition(),
2206 DepClassTy::NONE, IsKnown));
2207 (void)IsKnown;
2208 }
2209
2210 ChangeStatus updateImpl(Attributor &A) override {
2211 auto CheckForNoFree = [&](Instruction &I) {
2212 if (auto *CB = dyn_cast<CallBase>(&I)) {
2213 bool IsKnown;
2215 A, this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED,
2216 IsKnown);
2217 }
2218 // Make sure that synchronization cannot establish happens-before with a
2219 // free on another thread.
2220 return AA::isNoSyncInst(A, I, *this);
2221 };
2222
2223 bool UsedAssumedInformation = false;
2224 if (!A.checkForAllReadWriteInstructions(CheckForNoFree, *this,
2225 UsedAssumedInformation) ||
2226 !A.checkForAllCallLikeInstructions(CheckForNoFree, *this,
2227 UsedAssumedInformation))
2228 return indicatePessimisticFixpoint();
2229
2230 return ChangeStatus::UNCHANGED;
2231 }
2232
2233 const std::string getAsStr(Attributor *A) const override {
2234 return getAssumed() ? "nofree" : "may-free";
2235 }
2236};
2237
2238struct AANoFreeFunction final : public AANoFreeImpl {
2239 AANoFreeFunction(const IRPosition &IRP, Attributor &A)
2240 : AANoFreeImpl(IRP, A) {}
2241
2242 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
2243};
2244
2245/// NoFree attribute deduction for a call sites.
2246struct AANoFreeCallSite final : AACalleeToCallSite<AANoFree, AANoFreeImpl> {
2247 AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
2248 : AACalleeToCallSite<AANoFree, AANoFreeImpl>(IRP, A) {}
2249
2250 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
2251};
2252
2253/// NoFree attribute for floating values.
2254struct AANoFreeFloating : AANoFreeImpl {
2255 AANoFreeFloating(const IRPosition &IRP, Attributor &A)
2256 : AANoFreeImpl(IRP, A) {}
2257
2258 void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
2259
2260 /// See Abstract Attribute::updateImpl(...).
2261 ChangeStatus updateImpl(Attributor &A) override {
2262 const IRPosition &IRP = getIRPosition();
2263
2264 bool IsKnown;
2267 DepClassTy::OPTIONAL, IsKnown))
2268 return ChangeStatus::UNCHANGED;
2269
2270 Value &AssociatedValue = getIRPosition().getAssociatedValue();
2271 auto Pred = [&](const Use &U, bool &Follow) -> bool {
2272 Instruction *UserI = cast<Instruction>(U.getUser());
2273 if (auto *CB = dyn_cast<CallBase>(UserI)) {
2274 if (CB->isBundleOperand(&U))
2275 return false;
2276 if (!CB->isArgOperand(&U))
2277 return true;
2278 unsigned ArgNo = CB->getArgOperandNo(&U);
2279
2280 // Even if the argument is nofree, we still need to check for nocapture,
2281 // as the call may capture the argument without freeing it, and the
2282 // captured argument is freed later.
2283 bool IsKnown;
2285 A, this, IRPosition::callsite_argument(*CB, ArgNo),
2286 DepClassTy::REQUIRED, IsKnown))
2287 return false;
2288
2289 const AANoCapture *NoCaptureAA = nullptr;
2291 A, this, IRPosition::callsite_argument(*CB, ArgNo),
2292 DepClassTy::REQUIRED, IsKnown,
2293 /*IgnoreSubsumingPositions=*/false, &NoCaptureAA)) {
2294 if (NoCaptureAA && NoCaptureAA->isAssumedNoCaptureMaybeReturned()) {
2295 Follow = true;
2296 return true;
2297 }
2298 return false;
2299 }
2300
2301 return true;
2302 }
2303
2304 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
2305 if (!capturesAnyProvenance(CI))
2306 return true;
2308 Follow = true;
2309 return true;
2310 }
2311
2312 if (isa<ReturnInst>(UserI) && getIRPosition().isArgumentPosition())
2313 return true;
2314
2315 // Capturing user.
2316 return false;
2317 };
2318 if (!A.checkForAllUses(Pred, *this, AssociatedValue))
2319 return indicatePessimisticFixpoint();
2320
2321 return ChangeStatus::UNCHANGED;
2322 }
2323};
2324
2325/// NoFree attribute for a call site argument.
2326struct AANoFreeArgument final : AANoFreeFloating {
2327 AANoFreeArgument(const IRPosition &IRP, Attributor &A)
2328 : AANoFreeFloating(IRP, A) {}
2329
2330 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
2331};
2332
2333/// NoFree attribute for call site arguments.
2334struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2335 AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
2336 : AANoFreeFloating(IRP, A) {}
2337
2338 ChangeStatus updateImpl(Attributor &A) override {
2339 // TODO: Once we have call site specific value information we can provide
2340 // call site specific liveness information and then it makes
2341 // sense to specialize attributes for call sites arguments instead of
2342 // redirecting requests to the callee argument.
2343 Argument *Arg = getAssociatedArgument();
2344 if (!Arg)
2345 return indicatePessimisticFixpoint();
2346 const IRPosition &ArgPos = IRPosition::argument(*Arg);
2347 bool IsKnown;
2349 DepClassTy::REQUIRED, IsKnown))
2350 return ChangeStatus::UNCHANGED;
2351 return indicatePessimisticFixpoint();
2352 }
2353
2354 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nofree) };
2355};
2356
2357/// NoFree attribute for function return value.
2358struct AANoFreeReturned final : AANoFreeFloating {
2359 AANoFreeReturned(const IRPosition &IRP, Attributor &A)
2360 : AANoFreeFloating(IRP, A) {
2361 llvm_unreachable("NoFree is not applicable to function returns!");
2362 }
2363
2364 void initialize(Attributor &A) override {
2365 llvm_unreachable("NoFree is not applicable to function returns!");
2366 }
2367
2368 ChangeStatus updateImpl(Attributor &A) override {
2369 llvm_unreachable("NoFree is not applicable to function returns!");
2370 }
2371
2372 void trackStatistics() const override {}
2373};
2374
2375/// NoFree attribute deduction for a call site return value.
2376struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2377 AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
2378 : AANoFreeFloating(IRP, A) {}
2379
2380 ChangeStatus manifest(Attributor &A) override {
2381 return ChangeStatus::UNCHANGED;
2382 }
2383 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
2384};
2385} // namespace
2386
2387/// ------------------------ NonNull Argument Attribute ------------------------
2388
2390 Attribute::AttrKind ImpliedAttributeKind,
2391 bool IgnoreSubsumingPositions) {
2393 AttrKinds.push_back(Attribute::NonNull);
2396 AttrKinds.push_back(Attribute::Dereferenceable);
2397 if (A.hasAttr(IRP, AttrKinds, IgnoreSubsumingPositions, Attribute::NonNull))
2398 return true;
2399
2400 if (!A.canUseBodyFor(IRP))
2401 return false;
2402
2403 DominatorTree *DT = nullptr;
2404 AssumptionCache *AC = nullptr;
2405 InformationCache &InfoCache = A.getInfoCache();
2406 if (const Function *Fn = IRP.getAnchorScope()) {
2407 if (!Fn->isDeclaration()) {
2410 }
2411 }
2412
2414 if (IRP.getPositionKind() != IRP_RETURNED) {
2415 Worklist.push_back({IRP.getAssociatedValue(), IRP.getCtxI()});
2416 } else {
2417 bool UsedAssumedInformation = false;
2418 if (!A.checkForAllInstructions(
2419 [&](Instruction &I) {
2420 Worklist.push_back({*cast<ReturnInst>(I).getReturnValue(), &I});
2421 return true;
2422 },
2423 IRP.getAssociatedFunction(), nullptr, {Instruction::Ret},
2424 UsedAssumedInformation, false, /*CheckPotentiallyDead=*/true))
2425 return false;
2426 }
2427
2428 if (llvm::any_of(Worklist, [&](AA::ValueAndContext VAC) {
2429 return !isKnownNonZero(
2430 VAC.getValue(),
2431 SimplifyQuery(A.getDataLayout(), DT, AC, VAC.getCtxI()));
2432 }))
2433 return false;
2434
2435 A.manifestAttrs(IRP, {Attribute::get(IRP.getAnchorValue().getContext(),
2436 Attribute::NonNull)});
2437 return true;
2438}
2439
2440namespace {
2441static int64_t getKnownNonNullAndDerefBytesForUse(
2442 Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
2443 const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
2444 TrackUse = false;
2445
2446 const Value *UseV = U->get();
2447 if (!UseV->getType()->isPointerTy())
2448 return 0;
2449
2450 // We need to follow common pointer manipulation uses to the accesses they
2451 // feed into. We can try to be smart to avoid looking through things we do not
2452 // like for now, e.g., non-inbounds GEPs.
2453 if (isa<CastInst>(I)) {
2454 TrackUse = true;
2455 return 0;
2456 }
2457
2459 TrackUse = true;
2460 return 0;
2461 }
2462
2463 Type *PtrTy = UseV->getType();
2464 const Function *F = I->getFunction();
2467 const DataLayout &DL = A.getInfoCache().getDL();
2468 if (const auto *CB = dyn_cast<CallBase>(I)) {
2469 if (CB->isBundleOperand(U)) {
2470 auto OBU = CB->getOperandBundleForOperand(U->getOperandNo());
2471 switch (getBundleAttrFromOBU(OBU)) {
2472 case BundleAttr::NonNull:
2473 IsNonNull = true;
2474 break;
2475 case BundleAttr::Dereferenceable: {
2476 IsNonNull |= !NullPointerIsDefined;
2478 if (auto *CI = dyn_cast<ConstantInt>(Count))
2479 return CI->getZExtValue();
2480 } break;
2481 default:
2482 break;
2483 }
2484 return 0;
2485 }
2486
2487 if (CB->isCallee(U)) {
2488 IsNonNull |= !NullPointerIsDefined;
2489 return 0;
2490 }
2491
2492 unsigned ArgNo = CB->getArgOperandNo(U);
2493 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
2494 // As long as we only use known information there is no need to track
2495 // dependences here.
2496 bool IsKnownNonNull;
2498 DepClassTy::NONE, IsKnownNonNull);
2499 IsNonNull |= IsKnownNonNull;
2500 auto *DerefAA =
2501 A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE);
2502 return DerefAA ? DerefAA->getKnownDereferenceableBytes() : 0;
2503 }
2504
2505 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
2506 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
2507 Loc->Size.isScalable() || I->isVolatile())
2508 return 0;
2509
2510 int64_t Offset;
2511 const Value *Base =
2512 getMinimalBaseOfPointer(A, QueryingAA, Loc->Ptr, Offset, DL);
2513 if (Base && Base == &AssociatedValue) {
2514 int64_t DerefBytes = Loc->Size.getValue() + Offset;
2515 IsNonNull |= !NullPointerIsDefined;
2516 return std::max(int64_t(0), DerefBytes);
2517 }
2518
2519 /// Corner case when an offset is 0.
2521 /*AllowNonInbounds*/ true);
2522 if (Base && Base == &AssociatedValue && Offset == 0) {
2523 int64_t DerefBytes = Loc->Size.getValue();
2524 IsNonNull |= !NullPointerIsDefined;
2525 return std::max(int64_t(0), DerefBytes);
2526 }
2527
2528 return 0;
2529}
2530
2531struct AANonNullImpl : AANonNull {
2532 AANonNullImpl(const IRPosition &IRP, Attributor &A) : AANonNull(IRP, A) {}
2533
2534 void initialize(Attributor &A) override {
2535 Value &V = *getAssociatedValue().stripPointerCasts();
2537 indicatePessimisticFixpoint();
2538 return;
2539 }
2540
2541 if (Instruction *CtxI = getCtxI())
2542 followUsesInMBEC(*this, A, getState(), *CtxI);
2543 }
2544
2545 /// See followUsesInMBEC
2546 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
2547 AANonNull::StateType &State) {
2548 bool IsNonNull = false;
2549 bool TrackUse = false;
2550 getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
2551 IsNonNull, TrackUse);
2552 State.setKnown(IsNonNull);
2553 return TrackUse;
2554 }
2555
2556 const std::string getAsStr(Attributor *A) const override {
2557 return getAssumed() ? "nonnull" : "may-null";
2558 }
2559};
2560
2561/// NonNull attribute for a floating value.
2562struct AANonNullFloating : public AANonNullImpl {
2563 AANonNullFloating(const IRPosition &IRP, Attributor &A)
2564 : AANonNullImpl(IRP, A) {}
2565
2566 ChangeStatus updateImpl(Attributor &A) override {
2567 auto CheckIRP = [&](const IRPosition &IRP) {
2568 bool IsKnownNonNull;
2570 A, *this, IRP, DepClassTy::OPTIONAL, IsKnownNonNull);
2571 };
2572
2573 bool Stripped;
2574 bool UsedAssumedInformation = false;
2575 Value *AssociatedValue = &getAssociatedValue();
2577 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
2578 AA::AnyScope, UsedAssumedInformation))
2579 Stripped = false;
2580 else
2581 Stripped =
2582 Values.size() != 1 || Values.front().getValue() != AssociatedValue;
2583
2584 if (!Stripped) {
2585 bool IsKnown;
2586 if (auto *PHI = dyn_cast<PHINode>(AssociatedValue))
2587 if (llvm::all_of(PHI->incoming_values(), [&](Value *Op) {
2588 return AA::hasAssumedIRAttr<Attribute::NonNull>(
2589 A, this, IRPosition::value(*Op), DepClassTy::OPTIONAL,
2590 IsKnown);
2591 }))
2592 return ChangeStatus::UNCHANGED;
2593 if (auto *Select = dyn_cast<SelectInst>(AssociatedValue))
2595 A, this, IRPosition::value(*Select->getFalseValue()),
2596 DepClassTy::OPTIONAL, IsKnown) &&
2598 A, this, IRPosition::value(*Select->getTrueValue()),
2599 DepClassTy::OPTIONAL, IsKnown))
2600 return ChangeStatus::UNCHANGED;
2601
2602 // If we haven't stripped anything we might still be able to use a
2603 // different AA, but only if the IRP changes. Effectively when we
2604 // interpret this not as a call site value but as a floating/argument
2605 // value.
2606 const IRPosition AVIRP = IRPosition::value(*AssociatedValue);
2607 if (AVIRP == getIRPosition() || !CheckIRP(AVIRP))
2608 return indicatePessimisticFixpoint();
2609 return ChangeStatus::UNCHANGED;
2610 }
2611
2612 for (const auto &VAC : Values)
2613 if (!CheckIRP(IRPosition::value(*VAC.getValue())))
2614 return indicatePessimisticFixpoint();
2615
2616 return ChangeStatus::UNCHANGED;
2617 }
2618
2619 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2620};
2621
2622/// NonNull attribute for function return value.
2623struct AANonNullReturned final
2624 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2625 false, AANonNull::IRAttributeKind, false> {
2626 AANonNullReturned(const IRPosition &IRP, Attributor &A)
2627 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2628 false, Attribute::NonNull, false>(IRP, A) {
2629 }
2630
2631 const std::string getAsStr(Attributor *A) const override {
2632 return getAssumed() ? "nonnull" : "may-null";
2633 }
2634
2635 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2636};
2637
2638/// NonNull attribute for function argument.
2639struct AANonNullArgument final
2640 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2641 AANonNullArgument(const IRPosition &IRP, Attributor &A)
2642 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {}
2643
2644 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
2645};
2646
2647struct AANonNullCallSiteArgument final : AANonNullFloating {
2648 AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
2649 : AANonNullFloating(IRP, A) {}
2650
2651 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
2652};
2653
2654/// NonNull attribute for a call site return position.
2655struct AANonNullCallSiteReturned final
2656 : AACalleeToCallSite<AANonNull, AANonNullImpl> {
2657 AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
2658 : AACalleeToCallSite<AANonNull, AANonNullImpl>(IRP, A) {}
2659
2660 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
2661};
2662} // namespace
2663
2664/// ------------------------ Must-Progress Attributes --------------------------
2665namespace {
2666struct AAMustProgressImpl : public AAMustProgress {
2667 AAMustProgressImpl(const IRPosition &IRP, Attributor &A)
2668 : AAMustProgress(IRP, A) {}
2669
2670 void initialize(Attributor &A) override {
2671 bool IsKnown;
2673 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2674 (void)IsKnown;
2675 }
2676
2677 const std::string getAsStr(Attributor *A) const override {
2678 return getAssumed() ? "mustprogress" : "may-not-progress";
2679 }
2680};
2681
2682struct AAMustProgressFunction final : AAMustProgressImpl {
2683 AAMustProgressFunction(const IRPosition &IRP, Attributor &A)
2684 : AAMustProgressImpl(IRP, A) {}
2685
2686 ChangeStatus updateImpl(Attributor &A) override {
2687 bool IsKnown;
2689 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnown)) {
2690 if (IsKnown)
2691 return indicateOptimisticFixpoint();
2692 return ChangeStatus::UNCHANGED;
2693 }
2694
2695 auto CheckForMustProgress = [&](AbstractCallSite ACS) {
2696 IRPosition IPos = IRPosition::callsite_function(*ACS.getInstruction());
2697 bool IsKnownMustProgress;
2699 A, this, IPos, DepClassTy::REQUIRED, IsKnownMustProgress,
2700 /* IgnoreSubsumingPositions */ true);
2701 };
2702
2703 bool AllCallSitesKnown = true;
2704 if (!A.checkForAllCallSites(CheckForMustProgress, *this,
2705 /* RequireAllCallSites */ true,
2706 AllCallSitesKnown))
2707 return indicatePessimisticFixpoint();
2708
2709 return ChangeStatus::UNCHANGED;
2710 }
2711
2712 void trackStatistics() const override {
2713 STATS_DECLTRACK_FN_ATTR(mustprogress)
2714 }
2715};
2716
2717/// MustProgress attribute deduction for a call sites.
2718struct AAMustProgressCallSite final : AAMustProgressImpl {
2719 AAMustProgressCallSite(const IRPosition &IRP, Attributor &A)
2720 : AAMustProgressImpl(IRP, A) {}
2721
2722 ChangeStatus updateImpl(Attributor &A) override {
2723 // TODO: Once we have call site specific value information we can provide
2724 // call site specific liveness information and then it makes
2725 // sense to specialize attributes for call sites arguments instead of
2726 // redirecting requests to the callee argument.
2727 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
2728 bool IsKnownMustProgress;
2730 A, this, FnPos, DepClassTy::REQUIRED, IsKnownMustProgress))
2731 return indicatePessimisticFixpoint();
2732 return ChangeStatus::UNCHANGED;
2733 }
2734
2735 void trackStatistics() const override {
2736 STATS_DECLTRACK_CS_ATTR(mustprogress);
2737 }
2738};
2739} // namespace
2740
2741/// ------------------------ No-Recurse Attributes ----------------------------
2742
2743namespace {
2744struct AANoRecurseImpl : public AANoRecurse {
2745 AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
2746
2747 void initialize(Attributor &A) override {
2748 bool IsKnown;
2750 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2751 (void)IsKnown;
2752 }
2753
2754 const std::string getAsStr(Attributor *A) const override {
2755 return getAssumed() ? "norecurse" : "may-recurse";
2756 }
2757};
2758
2759struct AANoRecurseFunction final : AANoRecurseImpl {
2760 AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
2761 : AANoRecurseImpl(IRP, A) {}
2762
2763 ChangeStatus updateImpl(Attributor &A) override {
2764
2765 // If all live call sites are known to be no-recurse, we are as well.
2766 auto CallSitePred = [&](AbstractCallSite ACS) {
2767 bool IsKnownNoRecurse;
2769 A, this,
2770 IRPosition::function(*ACS.getInstruction()->getFunction()),
2771 DepClassTy::NONE, IsKnownNoRecurse))
2772 return false;
2773 return IsKnownNoRecurse;
2774 };
2775 bool UsedAssumedInformation = false;
2776 if (A.checkForAllCallSites(CallSitePred, *this, true,
2777 UsedAssumedInformation)) {
2778 // If we know all call sites and all are known no-recurse, we are done.
2779 // If all known call sites, which might not be all that exist, are known
2780 // to be no-recurse, we are not done but we can continue to assume
2781 // no-recurse. If one of the call sites we have not visited will become
2782 // live, another update is triggered.
2783 if (!UsedAssumedInformation)
2784 indicateOptimisticFixpoint();
2785 return ChangeStatus::UNCHANGED;
2786 }
2787
2788 const AAInterFnReachability *EdgeReachability =
2789 A.getAAFor<AAInterFnReachability>(*this, getIRPosition(),
2790 DepClassTy::REQUIRED);
2791 if (EdgeReachability && EdgeReachability->canReach(A, *getAnchorScope()))
2792 return indicatePessimisticFixpoint();
2793 return ChangeStatus::UNCHANGED;
2794 }
2795
2796 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
2797};
2798
2799/// NoRecurse attribute deduction for a call sites.
2800struct AANoRecurseCallSite final
2801 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl> {
2802 AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
2803 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl>(IRP, A) {}
2804
2805 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
2806};
2807} // namespace
2808
2809/// ------------------------ No-Convergent Attribute --------------------------
2810
2811namespace {
2812struct AANonConvergentImpl : public AANonConvergent {
2813 AANonConvergentImpl(const IRPosition &IRP, Attributor &A)
2814 : AANonConvergent(IRP, A) {}
2815
2816 const std::string getAsStr(Attributor *A) const override {
2817 return getAssumed() ? "non-convergent" : "may-be-convergent";
2818 }
2819};
2820
2821struct AANonConvergentFunction final : AANonConvergentImpl {
2822 AANonConvergentFunction(const IRPosition &IRP, Attributor &A)
2823 : AANonConvergentImpl(IRP, A) {}
2824
2825 ChangeStatus updateImpl(Attributor &A) override {
2826 // If all function calls are known to not be convergent, we are not
2827 // convergent.
2828 auto CalleeIsNotConvergent = [&](Instruction &Inst) {
2829 CallBase &CB = cast<CallBase>(Inst);
2831 if (!Callee || Callee->isIntrinsic()) {
2832 return false;
2833 }
2834 if (Callee->isDeclaration()) {
2835 return !Callee->hasFnAttribute(Attribute::Convergent);
2836 }
2837 const auto *ConvergentAA = A.getAAFor<AANonConvergent>(
2838 *this, IRPosition::function(*Callee), DepClassTy::REQUIRED);
2839 return ConvergentAA && ConvergentAA->isAssumedNotConvergent();
2840 };
2841
2842 bool UsedAssumedInformation = false;
2843 if (!A.checkForAllCallLikeInstructions(CalleeIsNotConvergent, *this,
2844 UsedAssumedInformation)) {
2845 return indicatePessimisticFixpoint();
2846 }
2847 return ChangeStatus::UNCHANGED;
2848 }
2849
2850 ChangeStatus manifest(Attributor &A) override {
2851 if (isKnownNotConvergent() &&
2852 A.hasAttr(getIRPosition(), Attribute::Convergent)) {
2853 A.removeAttrs(getIRPosition(), {Attribute::Convergent});
2854 return ChangeStatus::CHANGED;
2855 }
2856 return ChangeStatus::UNCHANGED;
2857 }
2858
2859 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(convergent) }
2860};
2861} // namespace
2862
2863/// -------------------- Undefined-Behavior Attributes ------------------------
2864
2865namespace {
2866struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
2867 AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
2868 : AAUndefinedBehavior(IRP, A) {}
2869
2870 struct UBInfo {
2871 enum Kind {
2872 NullPtrAccess,
2873 UndefPtrAccess,
2874 UndefBranchCondition,
2875 UndefReturnValue,
2876 NullReturnViolatesNonNull,
2877 UndefCallArgument,
2878 NullArgViolatesNonNull,
2879 };
2880
2881 Kind K;
2882 std::optional<unsigned> ArgNo;
2883
2884 UBInfo(Kind K) : K(K), ArgNo(std::nullopt) {}
2885
2886 UBInfo(Kind K, std::optional<unsigned> ArgNo) : K(K), ArgNo(ArgNo) {}
2887 };
2888
2889 ChangeStatus updateImpl(Attributor &A) override {
2890 const size_t UBPrevSize = KnownUBInsts.size();
2891 const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2892
2893 auto InspectMemAccessInstForUB = [&](Instruction &I) {
2894 // Volatile accesses on null are not necessarily UB.
2895 if (I.isVolatile())
2896 return true;
2897
2898 // Skip instructions that are already saved.
2899 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2900 return true;
2901
2902 // If we reach here, we know we have an instruction
2903 // that accesses memory through a pointer operand,
2904 // for which getPointerOperand() should give it to us.
2905 Value *PtrOp =
2906 const_cast<Value *>(getPointerOperand(&I, /* AllowVolatile */ true));
2907 assert(PtrOp &&
2908 "Expected pointer operand of memory accessing instruction");
2909
2910 // Either we stopped and the appropriate action was taken,
2911 // or we got back a simplified value to continue.
2912 std::optional<Value *> SimplifiedPtrOp =
2913 stopOnUndefOrAssumed(A, PtrOp, &I, UBInfo::UndefPtrAccess);
2914 if (!SimplifiedPtrOp || !*SimplifiedPtrOp)
2915 return true;
2916 const Value *PtrOpVal = *SimplifiedPtrOp;
2917
2918 // A memory access through a pointer is considered UB
2919 // only if the pointer has constant null value.
2920 // TODO: Expand it to not only check constant values.
2921 if (!isa<ConstantPointerNull>(PtrOpVal)) {
2922 AssumedNoUBInsts.insert(&I);
2923 return true;
2924 }
2925 const Type *PtrTy = PtrOpVal->getType();
2926
2927 // Because we only consider instructions inside functions,
2928 // assume that a parent function exists.
2929 const Function *F = I.getFunction();
2930
2931 // A memory access using constant null pointer is only considered UB
2932 // if null pointer is _not_ defined for the target platform.
2934 AssumedNoUBInsts.insert(&I);
2935 else
2936 KnownUBInsts.try_emplace(&I, UBInfo::NullPtrAccess);
2937 return true;
2938 };
2939
2940 auto InspectBrInstForUB = [&](Instruction &I) {
2941 // A conditional branch instruction is considered UB if it has `undef`
2942 // condition.
2943
2944 // Skip instructions that are already saved.
2945 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2946 return true;
2947
2948 // We know we have a branch instruction.
2949 auto *BrInst = cast<CondBrInst>(&I);
2950
2951 // Either we stopped and the appropriate action was taken,
2952 // or we got back a simplified value to continue.
2953 std::optional<Value *> SimplifiedCond = stopOnUndefOrAssumed(
2954 A, BrInst->getCondition(), BrInst, UBInfo::UndefBranchCondition);
2955 if (!SimplifiedCond || !*SimplifiedCond)
2956 return true;
2957 AssumedNoUBInsts.insert(&I);
2958 return true;
2959 };
2960
2961 auto InspectCallSiteForUB = [&](Instruction &I) {
2962 // Check whether a callsite always cause UB or not
2963
2964 // Skip instructions that are already saved.
2965 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2966 return true;
2967
2968 // Check nonnull and noundef argument attribute violation for each
2969 // callsite.
2970 CallBase &CB = cast<CallBase>(I);
2972 if (!Callee)
2973 return true;
2974 for (unsigned idx = 0; idx < CB.arg_size(); idx++) {
2975 // If current argument is known to be simplified to null pointer and the
2976 // corresponding argument position is known to have nonnull attribute,
2977 // the argument is poison. Furthermore, if the argument is poison and
2978 // the position is known to have noundef attriubte, this callsite is
2979 // considered UB.
2980 if (idx >= Callee->arg_size())
2981 break;
2982 Value *ArgVal = CB.getArgOperand(idx);
2983 if (!ArgVal)
2984 continue;
2985 // Here, we handle three cases.
2986 // (1) Not having a value means it is dead. (we can replace the value
2987 // with undef)
2988 // (2) Simplified to undef. The argument violate noundef attriubte.
2989 // (3) Simplified to null pointer where known to be nonnull.
2990 // The argument is a poison value and violate noundef attribute.
2991 IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
2992 bool IsKnownNoUndef;
2994 A, this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNoUndef);
2995 if (!IsKnownNoUndef)
2996 continue;
2997 bool UsedAssumedInformation = false;
2998 std::optional<Value *> SimplifiedVal =
2999 A.getAssumedSimplified(IRPosition::value(*ArgVal), *this,
3000 UsedAssumedInformation, AA::Interprocedural);
3001 if (UsedAssumedInformation)
3002 continue;
3003 if (SimplifiedVal && !*SimplifiedVal)
3004 return true;
3005 if (!SimplifiedVal || isa<UndefValue>(**SimplifiedVal)) {
3006 KnownUBInsts.try_emplace(&I, UBInfo(UBInfo::UndefCallArgument, idx));
3007 continue;
3008 }
3009 if (!ArgVal->getType()->isPointerTy() ||
3010 !isa<ConstantPointerNull>(**SimplifiedVal))
3011 continue;
3012 bool IsKnownNonNull;
3014 A, this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNonNull);
3015 if (IsKnownNonNull)
3016 KnownUBInsts.try_emplace(&I,
3017 UBInfo(UBInfo::NullArgViolatesNonNull, idx));
3018 }
3019 return true;
3020 };
3021
3022 auto InspectReturnInstForUB = [&](Instruction &I) {
3023 auto &RI = cast<ReturnInst>(I);
3024 // Either we stopped and the appropriate action was taken,
3025 // or we got back a simplified return value to continue.
3026 std::optional<Value *> SimplifiedRetValue = stopOnUndefOrAssumed(
3027 A, RI.getReturnValue(), &I, UBInfo::UndefReturnValue);
3028 if (!SimplifiedRetValue || !*SimplifiedRetValue)
3029 return true;
3030
3031 // Check if a return instruction always cause UB or not
3032 // Note: It is guaranteed that the returned position of the anchor
3033 // scope has noundef attribute when this is called.
3034 // We also ensure the return position is not "assumed dead"
3035 // because the returned value was then potentially simplified to
3036 // `undef` in AAReturnedValues without removing the `noundef`
3037 // attribute yet.
3038
3039 // When the returned position has noundef attriubte, UB occurs in the
3040 // following cases.
3041 // (1) Returned value is known to be undef.
3042 // (2) The value is known to be a null pointer and the returned
3043 // position has nonnull attribute (because the returned value is
3044 // poison).
3045 if (isa<ConstantPointerNull>(*SimplifiedRetValue)) {
3046 bool IsKnownNonNull;
3048 A, this, IRPosition::returned(*getAnchorScope()), DepClassTy::NONE,
3049 IsKnownNonNull);
3050 if (IsKnownNonNull)
3051 KnownUBInsts.try_emplace(&I, UBInfo::NullReturnViolatesNonNull);
3052 }
3053
3054 return true;
3055 };
3056
3057 bool UsedAssumedInformation = false;
3058 A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
3059 {Instruction::Load, Instruction::Store,
3060 Instruction::AtomicCmpXchg,
3061 Instruction::AtomicRMW},
3062 UsedAssumedInformation,
3063 /* CheckBBLivenessOnly */ true);
3064 A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::CondBr},
3065 UsedAssumedInformation,
3066 /* CheckBBLivenessOnly */ true);
3067 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this,
3068 UsedAssumedInformation);
3069
3070 // If the returned position of the anchor scope has noundef attriubte, check
3071 // all returned instructions.
3072 if (!getAnchorScope()->getReturnType()->isVoidTy()) {
3073 const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope());
3074 if (!A.isAssumedDead(ReturnIRP, this, nullptr, UsedAssumedInformation)) {
3075 bool IsKnownNoUndef;
3077 A, this, ReturnIRP, DepClassTy::NONE, IsKnownNoUndef);
3078 if (IsKnownNoUndef)
3079 A.checkForAllInstructions(InspectReturnInstForUB, *this,
3080 {Instruction::Ret}, UsedAssumedInformation,
3081 /* CheckBBLivenessOnly */ true);
3082 }
3083 }
3084
3085 if (NoUBPrevSize != AssumedNoUBInsts.size() ||
3086 UBPrevSize != KnownUBInsts.size())
3087 return ChangeStatus::CHANGED;
3088 return ChangeStatus::UNCHANGED;
3089 }
3090
3091 bool isKnownToCauseUB(Instruction *I) const override {
3092 return KnownUBInsts.count(I);
3093 }
3094
3095 bool isAssumedToCauseUB(Instruction *I) const override {
3096 // In simple words, if an instruction is not in the assumed to _not_
3097 // cause UB, then it is assumed UB (that includes those
3098 // in the KnownUBInsts set). The rest is boilerplate
3099 // is to ensure that it is one of the instructions we test
3100 // for UB.
3101
3102 switch (I->getOpcode()) {
3103 case Instruction::Load:
3104 case Instruction::Store:
3105 case Instruction::AtomicCmpXchg:
3106 case Instruction::AtomicRMW:
3107 case Instruction::CondBr:
3108 return !AssumedNoUBInsts.count(I);
3109 default:
3110 return false;
3111 }
3112 return false;
3113 }
3114
3115 /// Emit an optimization remark explaining why \p I is known to cause UB,
3116 /// per \p Info, right before it is replaced with 'unreachable'.
3117 static void emitUBRemark(Attributor &A, Instruction *I, const UBInfo &Info) {
3118 auto Remark = [&](OptimizationRemark OR) {
3119 switch (Info.K) {
3120 case UBInfo::NullPtrAccess:
3121 case UBInfo::UndefPtrAccess: {
3122 return OR << "Memory access through a pointer known to be "
3123 << ore::NV("Pointer",
3124 getPointerOperand(I, /*AllowVolatile*/ true))
3125 << " is undefined behavior; replacing with 'unreachable'.";
3126 }
3127 case UBInfo::UndefBranchCondition:
3128 return OR << "Branch condition known to be "
3129 << ore::NV("Condition", cast<CondBrInst>(I)->getCondition())
3130 << " is undefined behavior; replacing with 'unreachable'.";
3131 case UBInfo::UndefReturnValue:
3132 case UBInfo::NullReturnViolatesNonNull:
3133 return OR << "Value returned known to be "
3134 << ore::NV("ReturnValue",
3135 cast<ReturnInst>(I)->getReturnValue())
3136 << " is undefined behavior; replacing with 'unreachable'.";
3137 case UBInfo::UndefCallArgument:
3138 case UBInfo::NullArgViolatesNonNull: {
3139 bool IsUndef = Info.K == UBInfo::UndefCallArgument;
3140 CallBase &CB = *cast<CallBase>(I);
3141 OR << "Argument " << ore::NV("ArgNo", *Info.ArgNo)
3142 << " passed to parameter of ";
3143 if (auto *Callee = dyn_cast_if_present<Function>(CB.getCalledOperand()))
3144 OR << ore::NV("Callee", Callee);
3145 else
3146 OR << "the callee";
3147 return OR << " known to be "
3148 << ore::NV("Argument", IsUndef ? "undef" : "null")
3149 << " is undefined behavior; replacing with 'unreachable'.";
3150 }
3151 }
3152 llvm_unreachable("Unknown UBInfo::Kind");
3153 };
3154 A.emitRemark<OptimizationRemark>(I, "UndefinedBehavior", Remark);
3155 }
3156
3157 ChangeStatus manifest(Attributor &A) override {
3158 if (KnownUBInsts.empty())
3159 return ChangeStatus::UNCHANGED;
3160 for (const auto &[I, Info] : KnownUBInsts) {
3161 emitUBRemark(A, I, Info);
3162 A.changeToUnreachableAfterManifest(I);
3163 }
3164 return ChangeStatus::CHANGED;
3165 }
3166
3167 const std::string getAsStr(Attributor *A) const override {
3168 return getAssumed() ? "undefined-behavior" : "no-ub";
3169 }
3170
3171 /// Note: The correctness of this analysis depends on the fact that the
3172 /// following 2 sets will stop changing after some point.
3173 /// "Change" here means that their size changes.
3174 /// The size of each set is monotonically increasing
3175 /// (we only add items to them) and it is upper bounded by the number of
3176 /// instructions in the processed function (we can never save more
3177 /// elements in either set than this number). Hence, at some point,
3178 /// they will stop increasing.
3179 /// Consequently, at some point, both sets will have stopped
3180 /// changing, effectively making the analysis reach a fixpoint.
3181
3182 /// Note: These 2 sets are disjoint and an instruction can be considered
3183 /// one of 3 things:
3184 /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
3185 /// the KnownUBInsts set.
3186 /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
3187 /// has a reason to assume it).
3188 /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
3189 /// could not find a reason to assume or prove that it can cause UB,
3190 /// hence it assumes it doesn't. We have a set for these instructions
3191 /// so that we don't reprocess them in every update.
3192 /// Note however that instructions in this set may cause UB.
3193
3194protected:
3195 /// A map from all live instructions _known_ to cause UB to the reason why,
3196 /// used to build actionable optimization remarks in manifest().
3197 MapVector<Instruction *, UBInfo> KnownUBInsts;
3198
3199private:
3200 /// A set of all the (live) instructions that are assumed to _not_ cause UB.
3201 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
3202
3203 // Should be called on updates in which if we're processing an instruction
3204 // \p I that depends on a value \p V, one of the following has to happen:
3205 // - If the value is assumed, then stop.
3206 // - If the value is known but undef, then consider it UB for \p K.
3207 // - Otherwise, do specific processing with the simplified value.
3208 // We return std::nullopt in the first 2 cases to signify that an appropriate
3209 // action was taken and the caller should stop.
3210 // Otherwise, we return the simplified value that the caller should
3211 // use for specific processing.
3212 std::optional<Value *> stopOnUndefOrAssumed(Attributor &A, Value *V,
3213 Instruction *I, UBInfo::Kind K) {
3214 bool UsedAssumedInformation = false;
3215 std::optional<Value *> SimplifiedV =
3216 A.getAssumedSimplified(IRPosition::value(*V), *this,
3217 UsedAssumedInformation, AA::Interprocedural);
3218 if (!UsedAssumedInformation) {
3219 // Don't depend on assumed values.
3220 if (!SimplifiedV) {
3221 // If it is known (which we tested above) but it doesn't have a value,
3222 // then we can assume `undef` and hence the instruction is UB.
3223 KnownUBInsts.try_emplace(I, K);
3224 return std::nullopt;
3225 }
3226 if (!*SimplifiedV)
3227 return nullptr;
3228 V = *SimplifiedV;
3229 }
3230 if (isa<UndefValue>(V)) {
3231 KnownUBInsts.try_emplace(I, K);
3232 return std::nullopt;
3233 }
3234 return V;
3235 }
3236};
3237
3238struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
3239 AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
3240 : AAUndefinedBehaviorImpl(IRP, A) {}
3241
3242 void trackStatistics() const override {
3243 STATS_DECL(UndefinedBehaviorInstruction, Instruction,
3244 "Number of instructions known to have UB");
3245 BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
3246 KnownUBInsts.size();
3247 }
3248};
3249} // namespace
3250
3251/// ------------------------ Will-Return Attributes ----------------------------
3252
3253namespace {
3254// Helper function that checks whether a function has any cycle which we don't
3255// know if it is bounded or not.
3256// Loops with maximum trip count are considered bounded, any other cycle not.
3257static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
3258 ScalarEvolution *SE =
3259 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
3260 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
3261 // If either SCEV or LoopInfo is not available for the function then we assume
3262 // any cycle to be unbounded cycle.
3263 // We use scc_iterator which uses Tarjan algorithm to find all the maximal
3264 // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
3265 if (!SE || !LI) {
3266 for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
3267 if (SCCI.hasCycle())
3268 return true;
3269 return false;
3270 }
3271
3272 // If there's irreducible control, the function may contain non-loop cycles.
3274 return true;
3275
3276 // Any loop that does not have a max trip count is considered unbounded cycle.
3277 for (auto *L : LI->getLoopsInPreorder()) {
3278 if (!SE->getSmallConstantMaxTripCount(L))
3279 return true;
3280 }
3281 return false;
3282}
3283
3284struct AAWillReturnImpl : public AAWillReturn {
3285 AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
3286 : AAWillReturn(IRP, A) {}
3287
3288 void initialize(Attributor &A) override {
3289 bool IsKnown;
3291 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
3292 (void)IsKnown;
3293 }
3294
3295 /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
3296 bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) {
3297 if (!A.hasAttr(getIRPosition(), {Attribute::MustProgress}))
3298 return false;
3299
3300 bool IsKnown;
3301 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3302 return IsKnown || !KnownOnly;
3303 return false;
3304 }
3305
3306 ChangeStatus updateImpl(Attributor &A) override {
3307 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
3308 return ChangeStatus::UNCHANGED;
3309
3310 auto CheckForWillReturn = [&](Instruction &I) {
3312 bool IsKnown;
3314 A, this, IPos, DepClassTy::REQUIRED, IsKnown)) {
3315 if (IsKnown)
3316 return true;
3317 } else {
3318 return false;
3319 }
3320 bool IsKnownNoRecurse;
3322 A, this, IPos, DepClassTy::REQUIRED, IsKnownNoRecurse);
3323 };
3324
3325 bool UsedAssumedInformation = false;
3326 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this,
3327 UsedAssumedInformation))
3328 return indicatePessimisticFixpoint();
3329
3330 auto CheckForVolatile = [&](Instruction &I) {
3331 // Volatile operations are not willreturn.
3332 return !I.isVolatile();
3333 };
3334 if (!A.checkForAllInstructions(CheckForVolatile, *this,
3335 {Instruction::Load, Instruction::Store,
3336 Instruction::AtomicCmpXchg,
3337 Instruction::AtomicRMW},
3338 UsedAssumedInformation))
3339 return indicatePessimisticFixpoint();
3340
3341 return ChangeStatus::UNCHANGED;
3342 }
3343
3344 const std::string getAsStr(Attributor *A) const override {
3345 return getAssumed() ? "willreturn" : "may-noreturn";
3346 }
3347};
3348
3349struct AAWillReturnFunction final : AAWillReturnImpl {
3350 AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
3351 : AAWillReturnImpl(IRP, A) {}
3352
3353 void initialize(Attributor &A) override {
3354 AAWillReturnImpl::initialize(A);
3355
3356 Function *F = getAnchorScope();
3357 assert(F && "Did expect an anchor function");
3358 if (F->isDeclaration() || mayContainUnboundedCycle(*F, A))
3359 indicatePessimisticFixpoint();
3360 }
3361
3362 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
3363};
3364
3365/// WillReturn attribute deduction for a call sites.
3366struct AAWillReturnCallSite final
3367 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl> {
3368 AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
3369 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl>(IRP, A) {}
3370
3371 ChangeStatus updateImpl(Attributor &A) override {
3372 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
3373 return ChangeStatus::UNCHANGED;
3374
3375 return AACalleeToCallSite::updateImpl(A);
3376 }
3377
3378 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
3379};
3380} // namespace
3381
3382/// -------------------AAIntraFnReachability Attribute--------------------------
3383
3384/// All information associated with a reachability query. This boilerplate code
3385/// is used by both AAIntraFnReachability and AAInterFnReachability, with
3386/// different \p ToTy values.
3387template <typename ToTy> struct ReachabilityQueryInfo {
3388 enum class Reachable {
3391 };
3392
3393 /// Start here,
3394 const Instruction *From = nullptr;
3395 /// reach this place,
3396 const ToTy *To = nullptr;
3397 /// without going through any of these instructions,
3399 /// and remember if it worked:
3401
3402 /// Precomputed hash for this RQI.
3403 unsigned Hash = 0;
3404
3405 unsigned computeHashValue() const {
3406 assert(Hash == 0 && "Computed hash twice!");
3409 return const_cast<ReachabilityQueryInfo<ToTy> *>(this)->Hash =
3410 detail::combineHashValue(PairDMI ::getHashValue({From, To}),
3411 InstSetDMI::getHashValue(ExclusionSet));
3412 }
3413
3415 : From(From), To(To) {}
3416
3417 /// Constructor replacement to ensure unique and stable sets are used for the
3418 /// cache.
3420 const AA::InstExclusionSetTy *ES, bool MakeUnique)
3421 : From(&From), To(&To), ExclusionSet(ES) {
3422
3423 if (!ES || ES->empty()) {
3424 ExclusionSet = nullptr;
3425 } else if (MakeUnique) {
3426 ExclusionSet = A.getInfoCache().getOrCreateUniqueBlockExecutionSet(ES);
3427 }
3428 }
3429
3432};
3433
3434namespace llvm {
3435template <typename ToTy> struct DenseMapInfo<ReachabilityQueryInfo<ToTy> *> {
3438
3439 static unsigned getHashValue(const ReachabilityQueryInfo<ToTy> *RQI) {
3440 return RQI->Hash ? RQI->Hash : RQI->computeHashValue();
3441 }
3442 static bool isEqual(const ReachabilityQueryInfo<ToTy> *LHS,
3443 const ReachabilityQueryInfo<ToTy> *RHS) {
3444 if (!PairDMI::isEqual({LHS->From, LHS->To}, {RHS->From, RHS->To}))
3445 return false;
3446 return InstSetDMI::isEqual(LHS->ExclusionSet, RHS->ExclusionSet);
3447 }
3448};
3449
3450} // namespace llvm
3451
3452namespace {
3453
3454template <typename BaseTy, typename ToTy>
3455struct CachedReachabilityAA : public BaseTy {
3456 using RQITy = ReachabilityQueryInfo<ToTy>;
3457
3458 CachedReachabilityAA(const IRPosition &IRP, Attributor &A) : BaseTy(IRP, A) {}
3459
3460 bool isQueryAA() const override { return true; }
3461
3462 ChangeStatus updateImpl(Attributor &A) override {
3463 ChangeStatus Changed = ChangeStatus::UNCHANGED;
3464 for (unsigned u = 0, e = QueryVector.size(); u < e; ++u) {
3465 RQITy *RQI = QueryVector[u];
3466 if (RQI->Result == RQITy::Reachable::No &&
3467 isReachableImpl(A, *RQI, /*IsTemporaryRQI=*/false))
3468 Changed = ChangeStatus::CHANGED;
3469 }
3470 return Changed;
3471 }
3472
3473 virtual bool isReachableImpl(Attributor &A, RQITy &RQI,
3474 bool IsTemporaryRQI) = 0;
3475
3476 bool rememberResult(Attributor &A, typename RQITy::Reachable Result,
3477 RQITy &RQI, bool UsedExclusionSet, bool IsTemporaryRQI) {
3478 RQI.Result = Result;
3479
3480 // Remove the temporary RQI from the cache.
3481 if (IsTemporaryRQI)
3482 QueryCache.erase(&RQI);
3483
3484 // Insert a plain RQI (w/o exclusion set) if that makes sense. Two options:
3485 // 1) If it is reachable, it doesn't matter if we have an exclusion set for
3486 // this query. 2) We did not use the exclusion set, potentially because
3487 // there is none.
3488 if (Result == RQITy::Reachable::Yes || !UsedExclusionSet) {
3489 RQITy PlainRQI(RQI.From, RQI.To);
3490 if (!QueryCache.count(&PlainRQI)) {
3491 RQITy *RQIPtr = new (A.Allocator) RQITy(RQI.From, RQI.To);
3492 RQIPtr->Result = Result;
3493 QueryVector.push_back(RQIPtr);
3494 QueryCache.insert(RQIPtr);
3495 }
3496 }
3497
3498 // Check if we need to insert a new permanent RQI with the exclusion set.
3499 if (IsTemporaryRQI && Result != RQITy::Reachable::Yes && UsedExclusionSet) {
3500 assert((!RQI.ExclusionSet || !RQI.ExclusionSet->empty()) &&
3501 "Did not expect empty set!");
3502 RQITy *RQIPtr = new (A.Allocator)
3503 RQITy(A, *RQI.From, *RQI.To, RQI.ExclusionSet, true);
3504 assert(RQIPtr->Result == RQITy::Reachable::No && "Already reachable?");
3505 RQIPtr->Result = Result;
3506 assert(!QueryCache.count(RQIPtr));
3507 QueryVector.push_back(RQIPtr);
3508 QueryCache.insert(RQIPtr);
3509 }
3510
3511 if (Result == RQITy::Reachable::No && IsTemporaryRQI)
3512 A.registerForUpdate(*this);
3513 return Result == RQITy::Reachable::Yes;
3514 }
3515
3516 const std::string getAsStr(Attributor *A) const override {
3517 // TODO: Return the number of reachable queries.
3518 return "#queries(" + std::to_string(QueryVector.size()) + ")";
3519 }
3520
3521 bool checkQueryCache(Attributor &A, RQITy &StackRQI,
3522 typename RQITy::Reachable &Result) {
3523 if (!this->getState().isValidState()) {
3524 Result = RQITy::Reachable::Yes;
3525 return true;
3526 }
3527
3528 // If we have an exclusion set we might be able to find our answer by
3529 // ignoring it first.
3530 if (StackRQI.ExclusionSet) {
3531 RQITy PlainRQI(StackRQI.From, StackRQI.To);
3532 auto It = QueryCache.find(&PlainRQI);
3533 if (It != QueryCache.end() && (*It)->Result == RQITy::Reachable::No) {
3534 Result = RQITy::Reachable::No;
3535 return true;
3536 }
3537 }
3538
3539 auto It = QueryCache.find(&StackRQI);
3540 if (It != QueryCache.end()) {
3541 Result = (*It)->Result;
3542 return true;
3543 }
3544
3545 // Insert a temporary for recursive queries. We will replace it with a
3546 // permanent entry later.
3547 QueryCache.insert(&StackRQI);
3548 return false;
3549 }
3550
3551private:
3552 SmallVector<RQITy *> QueryVector;
3553 DenseSet<RQITy *> QueryCache;
3554};
3555
3556struct AAIntraFnReachabilityFunction final
3557 : public CachedReachabilityAA<AAIntraFnReachability, Instruction> {
3558 using Base = CachedReachabilityAA<AAIntraFnReachability, Instruction>;
3559 AAIntraFnReachabilityFunction(const IRPosition &IRP, Attributor &A)
3560 : Base(IRP, A) {
3561 DT = A.getInfoCache().getAnalysisResultForFunction<DominatorTreeAnalysis>(
3562 *IRP.getAssociatedFunction());
3563 }
3564
3565 bool isAssumedReachable(
3566 Attributor &A, const Instruction &From, const Instruction &To,
3567 const AA::InstExclusionSetTy *ExclusionSet) const override {
3568 auto *NonConstThis = const_cast<AAIntraFnReachabilityFunction *>(this);
3569 if (&From == &To)
3570 return true;
3571
3572 RQITy StackRQI(A, From, To, ExclusionSet, false);
3573 RQITy::Reachable Result;
3574 if (!NonConstThis->checkQueryCache(A, StackRQI, Result))
3575 return NonConstThis->isReachableImpl(A, StackRQI,
3576 /*IsTemporaryRQI=*/true);
3577 return Result == RQITy::Reachable::Yes;
3578 }
3579
3580 ChangeStatus updateImpl(Attributor &A) override {
3581 // We only depend on liveness. DeadEdges is all we care about, check if any
3582 // of them changed.
3583 auto *LivenessAA =
3584 A.getAAFor<AAIsDead>(*this, getIRPosition(), DepClassTy::OPTIONAL);
3585 if (LivenessAA &&
3586 llvm::all_of(DeadEdges,
3587 [&](const auto &DeadEdge) {
3588 return LivenessAA->isEdgeDead(DeadEdge.first,
3589 DeadEdge.second);
3590 }) &&
3591 llvm::all_of(DeadBlocks, [&](const BasicBlock *BB) {
3592 return LivenessAA->isAssumedDead(BB);
3593 })) {
3594 return ChangeStatus::UNCHANGED;
3595 }
3596 DeadEdges.clear();
3597 DeadBlocks.clear();
3598 return Base::updateImpl(A);
3599 }
3600
3601 bool isReachableImpl(Attributor &A, RQITy &RQI,
3602 bool IsTemporaryRQI) override {
3603 const Instruction *Origin = RQI.From;
3604 bool UsedExclusionSet = false;
3605
3606 auto WillReachInBlock = [&](const Instruction &From, const Instruction &To,
3607 const AA::InstExclusionSetTy *ExclusionSet) {
3608 const Instruction *IP = &From;
3609 while (IP && IP != &To) {
3610 if (ExclusionSet && IP != Origin && ExclusionSet->count(IP)) {
3611 UsedExclusionSet = true;
3612 break;
3613 }
3614 IP = IP->getNextNode();
3615 }
3616 return IP == &To;
3617 };
3618
3619 const BasicBlock *FromBB = RQI.From->getParent();
3620 const BasicBlock *ToBB = RQI.To->getParent();
3621 assert(FromBB->getParent() == ToBB->getParent() &&
3622 "Not an intra-procedural query!");
3623
3624 // Check intra-block reachability, however, other reaching paths are still
3625 // possible.
3626 if (FromBB == ToBB &&
3627 WillReachInBlock(*RQI.From, *RQI.To, RQI.ExclusionSet))
3628 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3629 IsTemporaryRQI);
3630
3631 // Check if reaching the ToBB block is sufficient or if even that would not
3632 // ensure reaching the target. In the latter case we are done.
3633 if (!WillReachInBlock(ToBB->front(), *RQI.To, RQI.ExclusionSet))
3634 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3635 IsTemporaryRQI);
3636
3637 const Function *Fn = FromBB->getParent();
3638 SmallPtrSet<const BasicBlock *, 16> ExclusionBlocks;
3639 if (RQI.ExclusionSet)
3640 for (auto *I : *RQI.ExclusionSet)
3641 if (I->getFunction() == Fn)
3642 ExclusionBlocks.insert(I->getParent());
3643
3644 // Check if we make it out of the FromBB block at all.
3645 if (ExclusionBlocks.count(FromBB) &&
3646 !WillReachInBlock(*RQI.From, *FromBB->getTerminator(),
3647 RQI.ExclusionSet))
3648 return rememberResult(A, RQITy::Reachable::No, RQI, true, IsTemporaryRQI);
3649
3650 auto *LivenessAA =
3651 A.getAAFor<AAIsDead>(*this, getIRPosition(), DepClassTy::OPTIONAL);
3652 if (LivenessAA && LivenessAA->isAssumedDead(ToBB)) {
3653 DeadBlocks.insert(ToBB);
3654 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3655 IsTemporaryRQI);
3656 }
3657
3658 SmallPtrSet<const BasicBlock *, 16> Visited;
3660 Worklist.push_back(FromBB);
3661
3662 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> LocalDeadEdges;
3663 while (!Worklist.empty()) {
3664 const BasicBlock *BB = Worklist.pop_back_val();
3665 if (!Visited.insert(BB).second)
3666 continue;
3667 for (const BasicBlock *SuccBB : successors(BB)) {
3668 if (LivenessAA && LivenessAA->isEdgeDead(BB, SuccBB)) {
3669 LocalDeadEdges.insert({BB, SuccBB});
3670 continue;
3671 }
3672 // We checked before if we just need to reach the ToBB block.
3673 if (SuccBB == ToBB)
3674 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3675 IsTemporaryRQI);
3676 if (DT && ExclusionBlocks.empty() && DT->dominates(BB, ToBB))
3677 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3678 IsTemporaryRQI);
3679
3680 if (ExclusionBlocks.count(SuccBB)) {
3681 UsedExclusionSet = true;
3682 continue;
3683 }
3684 Worklist.push_back(SuccBB);
3685 }
3686 }
3687
3688 DeadEdges.insert_range(LocalDeadEdges);
3689 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3690 IsTemporaryRQI);
3691 }
3692
3693 void trackStatistics() const override {}
3694
3695private:
3696 // Set of assumed dead blocks we used in the last query. If any changes we
3697 // update the state.
3698 DenseSet<const BasicBlock *> DeadBlocks;
3699
3700 // Set of assumed dead edges we used in the last query. If any changes we
3701 // update the state.
3702 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> DeadEdges;
3703
3704 /// The dominator tree of the function to short-circuit reasoning.
3705 const DominatorTree *DT = nullptr;
3706};
3707} // namespace
3708
3709/// ------------------------ NoAlias Argument Attribute ------------------------
3710
3712 Attribute::AttrKind ImpliedAttributeKind,
3713 bool IgnoreSubsumingPositions) {
3714 assert(ImpliedAttributeKind == Attribute::NoAlias &&
3715 "Unexpected attribute kind");
3716 Value *Val = &IRP.getAssociatedValue();
3718 if (isa<AllocaInst>(Val))
3719 return true;
3720 } else {
3721 IgnoreSubsumingPositions = true;
3722 }
3723
3724 if (isa<UndefValue>(Val))
3725 return true;
3726
3727 if (isa<ConstantPointerNull>(Val) &&
3730 return true;
3731
3732 if (A.hasAttr(IRP, {Attribute::ByVal, Attribute::NoAlias},
3733 IgnoreSubsumingPositions, Attribute::NoAlias))
3734 return true;
3735
3736 return false;
3737}
3738
3739namespace {
3740struct AANoAliasImpl : AANoAlias {
3741 AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
3742 assert(getAssociatedType()->isPointerTy() &&
3743 "Noalias is a pointer attribute");
3744 }
3745
3746 const std::string getAsStr(Attributor *A) const override {
3747 return getAssumed() ? "noalias" : "may-alias";
3748 }
3749};
3750
3751/// NoAlias attribute for a floating value.
3752struct AANoAliasFloating final : AANoAliasImpl {
3753 AANoAliasFloating(const IRPosition &IRP, Attributor &A)
3754 : AANoAliasImpl(IRP, A) {}
3755
3756 ChangeStatus updateImpl(Attributor &A) override {
3757 // TODO: Implement this.
3758 return indicatePessimisticFixpoint();
3759 }
3760
3761 void trackStatistics() const override {
3763 }
3764};
3765
3766/// NoAlias attribute for an argument.
3767struct AANoAliasArgument final
3768 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3769 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3770 AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3771
3772 ChangeStatus updateImpl(Attributor &A) override {
3773 // We have to make sure no-alias on the argument does not break
3774 // synchronization when this is a callback argument, see also [1] below.
3775 // If synchronization cannot be affected, we delegate to the base updateImpl
3776 // function, otherwise we give up for now.
3777
3778 // If the function is no-sync, no-alias cannot break synchronization.
3779 bool IsKnownNoSycn;
3781 A, this, IRPosition::function_scope(getIRPosition()),
3782 DepClassTy::OPTIONAL, IsKnownNoSycn))
3783 return Base::updateImpl(A);
3784
3785 // If the argument is read-only, no-alias cannot break synchronization.
3786 bool IsKnown;
3787 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3788 return Base::updateImpl(A);
3789
3790 // If the argument is never passed through callbacks, no-alias cannot break
3791 // synchronization.
3792 bool UsedAssumedInformation = false;
3793 if (A.checkForAllCallSites(
3794 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
3795 true, UsedAssumedInformation))
3796 return Base::updateImpl(A);
3797
3798 // TODO: add no-alias but make sure it doesn't break synchronization by
3799 // introducing fake uses. See:
3800 // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
3801 // International Workshop on OpenMP 2018,
3802 // http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
3803
3804 return indicatePessimisticFixpoint();
3805 }
3806
3807 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
3808};
3809
3810struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3811 AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
3812 : AANoAliasImpl(IRP, A) {}
3813
3814 /// Determine if the underlying value may alias with the call site argument
3815 /// \p OtherArgNo of \p ICS (= the underlying call site).
3816 bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
3817 const AAMemoryBehavior &MemBehaviorAA,
3818 const CallBase &CB, unsigned OtherArgNo) {
3819 // We do not need to worry about aliasing with the underlying IRP.
3820 if (this->getCallSiteArgNo() == (int)OtherArgNo)
3821 return false;
3822
3823 // If it is not a pointer or pointer vector we do not alias.
3824 const Value *ArgOp = CB.getArgOperand(OtherArgNo);
3825 if (!ArgOp->getType()->isPtrOrPtrVectorTy())
3826 return false;
3827
3828 auto *CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
3829 *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE);
3830
3831 // If the argument is readnone, there is no read-write aliasing.
3832 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadNone()) {
3833 A.recordDependence(*CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3834 return false;
3835 }
3836
3837 // If the argument is readonly and the underlying value is readonly, there
3838 // is no read-write aliasing.
3839 bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
3840 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadOnly() &&
3841 IsReadOnly) {
3842 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3843 A.recordDependence(*CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3844 return false;
3845 }
3846
3847 // We have to utilize actual alias analysis queries so we need the object.
3848 if (!AAR)
3849 AAR = A.getInfoCache().getAnalysisResultForFunction<AAManager>(
3850 *getAnchorScope());
3851
3852 // Try to rule it out at the call site.
3853 bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
3854 LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
3855 "callsite arguments: "
3856 << getAssociatedValue() << " " << *ArgOp << " => "
3857 << (IsAliasing ? "" : "no-") << "alias \n");
3858
3859 return IsAliasing;
3860 }
3861
3862 bool isKnownNoAliasDueToNoAliasPreservation(
3863 Attributor &A, AAResults *&AAR, const AAMemoryBehavior &MemBehaviorAA) {
3864 // We can deduce "noalias" if the following conditions hold.
3865 // (i) Associated value is assumed to be noalias in the definition.
3866 // (ii) Associated value is assumed to be no-capture in all the uses
3867 // possibly executed before this callsite.
3868 // (iii) There is no other pointer argument which could alias with the
3869 // value.
3870
3871 const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3872 const Function *ScopeFn = VIRP.getAnchorScope();
3873 // Check whether the value is captured in the scope using AANoCapture.
3874 // Look at CFG and check only uses possibly executed before this
3875 // callsite.
3876 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
3877 Instruction *UserI = cast<Instruction>(U.getUser());
3878
3879 // If UserI is the curr instruction and there is a single potential use of
3880 // the value in UserI we allow the use.
3881 // TODO: We should inspect the operands and allow those that cannot alias
3882 // with the value.
3883 if (UserI == getCtxI() && UserI->getNumOperands() == 1)
3884 return true;
3885
3886 if (ScopeFn) {
3887 if (auto *CB = dyn_cast<CallBase>(UserI)) {
3888 if (CB->isArgOperand(&U)) {
3889
3890 unsigned ArgNo = CB->getArgOperandNo(&U);
3891
3892 bool IsKnownNoCapture;
3894 A, this, IRPosition::callsite_argument(*CB, ArgNo),
3895 DepClassTy::OPTIONAL, IsKnownNoCapture))
3896 return true;
3897 }
3898 }
3899
3901 A, *UserI, *getCtxI(), *this, /* ExclusionSet */ nullptr,
3902 [ScopeFn](const Function &Fn) { return &Fn != ScopeFn; }))
3903 return true;
3904 }
3905
3906 // TODO: We should track the capturing uses in AANoCapture but the problem
3907 // is CGSCC runs. For those we would need to "allow" AANoCapture for
3908 // a value in the module slice.
3909 // TODO(captures): Make this more precise.
3910 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
3911 if (capturesNothing(CI))
3912 return true;
3913 if (CI.isPassthrough()) {
3914 Follow = true;
3915 return true;
3916 }
3917 LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *UserI << "\n");
3918 return false;
3919 };
3920
3921 bool IsKnownNoCapture;
3922 const AANoCapture *NoCaptureAA = nullptr;
3923 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
3924 A, this, VIRP, DepClassTy::NONE, IsKnownNoCapture, false, &NoCaptureAA);
3925 if (!IsAssumedNoCapture &&
3926 (!NoCaptureAA || !NoCaptureAA->isAssumedNoCaptureMaybeReturned())) {
3927 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
3928 LLVM_DEBUG(
3929 dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
3930 << " cannot be noalias as it is potentially captured\n");
3931 return false;
3932 }
3933 }
3934 if (NoCaptureAA)
3935 A.recordDependence(*NoCaptureAA, *this, DepClassTy::OPTIONAL);
3936
3937 // Check there is no other pointer argument which could alias with the
3938 // value passed at this call site.
3939 // TODO: AbstractCallSite
3940 const auto &CB = cast<CallBase>(getAnchorValue());
3941 for (unsigned OtherArgNo = 0; OtherArgNo < CB.arg_size(); OtherArgNo++)
3942 if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
3943 return false;
3944
3945 return true;
3946 }
3947
3948 ChangeStatus updateImpl(Attributor &A) override {
3949 // If the argument is readnone we are done as there are no accesses via the
3950 // argument.
3951 auto *MemBehaviorAA =
3952 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
3953 if (MemBehaviorAA && MemBehaviorAA->isAssumedReadNone()) {
3954 A.recordDependence(*MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3955 return ChangeStatus::UNCHANGED;
3956 }
3957
3958 bool IsKnownNoAlias;
3959 const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3961 A, this, VIRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
3962 LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
3963 << " is not no-alias at the definition\n");
3964 return indicatePessimisticFixpoint();
3965 }
3966
3967 AAResults *AAR = nullptr;
3968 if (MemBehaviorAA &&
3969 isKnownNoAliasDueToNoAliasPreservation(A, AAR, *MemBehaviorAA)) {
3970 LLVM_DEBUG(
3971 dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
3972 return ChangeStatus::UNCHANGED;
3973 }
3974
3975 return indicatePessimisticFixpoint();
3976 }
3977
3978 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
3979};
3980
3981/// NoAlias attribute for function return value.
3982struct AANoAliasReturned final : AANoAliasImpl {
3983 AANoAliasReturned(const IRPosition &IRP, Attributor &A)
3984 : AANoAliasImpl(IRP, A) {}
3985
3986 ChangeStatus updateImpl(Attributor &A) override {
3987
3988 auto CheckReturnValue = [&](Value &RV) -> bool {
3989 if (Constant *C = dyn_cast<Constant>(&RV))
3990 if (C->isNullValue() || isa<UndefValue>(C))
3991 return true;
3992
3993 /// For now, we can only deduce noalias if we have call sites.
3994 /// FIXME: add more support.
3995 if (!isa<CallBase>(&RV))
3996 return false;
3997
3998 const IRPosition &RVPos = IRPosition::value(RV);
3999 bool IsKnownNoAlias;
4001 A, this, RVPos, DepClassTy::REQUIRED, IsKnownNoAlias))
4002 return false;
4003
4004 bool IsKnownNoCapture;
4005 const AANoCapture *NoCaptureAA = nullptr;
4006 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
4007 A, this, RVPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
4008 &NoCaptureAA);
4009 return IsAssumedNoCapture ||
4010 (NoCaptureAA && NoCaptureAA->isAssumedNoCaptureMaybeReturned());
4011 };
4012
4013 if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
4014 return indicatePessimisticFixpoint();
4015
4016 return ChangeStatus::UNCHANGED;
4017 }
4018
4019 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
4020};
4021
4022/// NoAlias attribute deduction for a call site return value.
4023struct AANoAliasCallSiteReturned final
4024 : AACalleeToCallSite<AANoAlias, AANoAliasImpl> {
4025 AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
4026 : AACalleeToCallSite<AANoAlias, AANoAliasImpl>(IRP, A) {}
4027
4028 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
4029};
4030} // namespace
4031
4032/// -------------------AAIsDead Function Attribute-----------------------
4033
4034namespace {
4035struct AAIsDeadValueImpl : public AAIsDead {
4036 AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
4037
4038 bool isAssumedDead() const override { return isAssumed(IS_DEAD); }
4039
4040 bool isKnownDead() const override { return isKnown(IS_DEAD); }
4041
4042 bool isAssumedDead(const BasicBlock *BB) const override { return false; }
4043
4044 bool isKnownDead(const BasicBlock *BB) const override { return false; }
4045
4046 bool isAssumedDead(const Instruction *I) const override {
4047 return I == getCtxI() && isAssumedDead();
4048 }
4049
4050 bool isKnownDead(const Instruction *I) const override {
4051 return isAssumedDead(I) && isKnownDead();
4052 }
4053
4054 const std::string getAsStr(Attributor *A) const override {
4055 return isAssumedDead() ? "assumed-dead" : "assumed-live";
4056 }
4057
4058 /// Check if all uses are assumed dead.
4059 bool areAllUsesAssumedDead(Attributor &A, Value &V) {
4060 // Callers might not check the type, void has no uses.
4061 if (V.getType()->isVoidTy() || V.use_empty())
4062 return true;
4063
4064 // If we replace a value with a constant there are no uses left afterwards.
4065 if (!isa<Constant>(V)) {
4066 if (auto *I = dyn_cast<Instruction>(&V))
4067 if (!A.isRunOn(*I->getFunction()))
4068 return false;
4069 bool UsedAssumedInformation = false;
4070 std::optional<Constant *> C =
4071 A.getAssumedConstant(V, *this, UsedAssumedInformation);
4072 if (!C || *C)
4073 return true;
4074 }
4075
4076 auto UsePred = [&](const Use &U, bool &Follow) { return false; };
4077 // Explicitly set the dependence class to required because we want a long
4078 // chain of N dependent instructions to be considered live as soon as one is
4079 // without going through N update cycles. This is not required for
4080 // correctness.
4081 return A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ false,
4082 DepClassTy::REQUIRED,
4083 /* IgnoreDroppableUses */ false);
4084 }
4085
4086 /// Determine if \p I is assumed to be side-effect free.
4087 bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
4089 return true;
4090
4091 if (!I->isTerminator() && !I->mayHaveSideEffects())
4092 return true;
4093
4094 auto *CB = dyn_cast<CallBase>(I);
4095 if (!CB || isa<IntrinsicInst>(CB))
4096 return false;
4097
4098 const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
4099
4100 bool IsKnownNoUnwind;
4102 A, this, CallIRP, DepClassTy::OPTIONAL, IsKnownNoUnwind))
4103 return false;
4104
4105 bool IsKnown;
4106 return AA::isAssumedReadOnly(A, CallIRP, *this, IsKnown);
4107 }
4108};
4109
4110struct AAIsDeadFloating : public AAIsDeadValueImpl {
4111 AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
4112 : AAIsDeadValueImpl(IRP, A) {}
4113
4114 void initialize(Attributor &A) override {
4115 AAIsDeadValueImpl::initialize(A);
4116
4117 if (isa<UndefValue>(getAssociatedValue())) {
4118 indicatePessimisticFixpoint();
4119 return;
4120 }
4121
4122 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4123 if (!isAssumedSideEffectFree(A, I)) {
4125 indicatePessimisticFixpoint();
4126 else
4127 removeAssumedBits(HAS_NO_EFFECT);
4128 }
4129 }
4130
4131 bool isDeadFence(Attributor &A, FenceInst &FI) {
4132 const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>(
4133 IRPosition::function(*FI.getFunction()), *this, DepClassTy::NONE);
4134 if (!ExecDomainAA || !ExecDomainAA->isNoOpFence(FI))
4135 return false;
4136 A.recordDependence(*ExecDomainAA, *this, DepClassTy::OPTIONAL);
4137 return true;
4138 }
4139
4140 bool isDeadStore(Attributor &A, StoreInst &SI,
4141 SmallSetVector<Instruction *, 8> *AssumeOnlyInst = nullptr) {
4142 // Lang ref now states volatile store is not UB/dead, let's skip them.
4143 if (SI.isVolatile())
4144 return false;
4145
4146 // If we are collecting assumes to be deleted we are in the manifest stage.
4147 // It's problematic to collect the potential copies again now so we use the
4148 // cached ones.
4149 bool UsedAssumedInformation = false;
4150 if (!AssumeOnlyInst) {
4151 PotentialCopies.clear();
4152 if (!AA::getPotentialCopiesOfStoredValue(A, SI, PotentialCopies, *this,
4153 UsedAssumedInformation)) {
4154 LLVM_DEBUG(
4155 dbgs()
4156 << "[AAIsDead] Could not determine potential copies of store!\n");
4157 return false;
4158 }
4159 }
4160 LLVM_DEBUG(dbgs() << "[AAIsDead] Store has " << PotentialCopies.size()
4161 << " potential copies.\n");
4162
4163 InformationCache &InfoCache = A.getInfoCache();
4164 return llvm::all_of(PotentialCopies, [&](Value *V) {
4165 if (A.isAssumedDead(IRPosition::value(*V), this, nullptr,
4166 UsedAssumedInformation))
4167 return true;
4168 if (auto *LI = dyn_cast<LoadInst>(V)) {
4169 if (llvm::all_of(LI->uses(), [&](const Use &U) {
4170 auto &UserI = cast<Instruction>(*U.getUser());
4171 if (InfoCache.isOnlyUsedByAssume(UserI)) {
4172 if (AssumeOnlyInst)
4173 AssumeOnlyInst->insert(&UserI);
4174 return true;
4175 }
4176 return A.isAssumedDead(U, this, nullptr, UsedAssumedInformation);
4177 })) {
4178 return true;
4179 }
4180 }
4181 LLVM_DEBUG(dbgs() << "[AAIsDead] Potential copy " << *V
4182 << " is assumed live!\n");
4183 return false;
4184 });
4185 }
4186
4187 const std::string getAsStr(Attributor *A) const override {
4188 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4190 if (isValidState())
4191 return "assumed-dead-store";
4193 if (isValidState())
4194 return "assumed-dead-fence";
4195 return AAIsDeadValueImpl::getAsStr(A);
4196 }
4197
4198 ChangeStatus updateImpl(Attributor &A) override {
4199 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4200 if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
4201 if (!isDeadStore(A, *SI))
4202 return indicatePessimisticFixpoint();
4203 } else if (auto *FI = dyn_cast_or_null<FenceInst>(I)) {
4204 if (!isDeadFence(A, *FI))
4205 return indicatePessimisticFixpoint();
4206 } else {
4207 if (!isAssumedSideEffectFree(A, I))
4208 return indicatePessimisticFixpoint();
4209 if (!areAllUsesAssumedDead(A, getAssociatedValue()))
4210 return indicatePessimisticFixpoint();
4211 }
4213 }
4214
4215 bool isRemovableStore() const override {
4216 return isAssumed(IS_REMOVABLE) && isa<StoreInst>(&getAssociatedValue());
4217 }
4218
4219 ChangeStatus manifest(Attributor &A) override {
4220 Value &V = getAssociatedValue();
4221 if (auto *I = dyn_cast<Instruction>(&V)) {
4222 // If we get here we basically know the users are all dead. We check if
4223 // isAssumedSideEffectFree returns true here again because it might not be
4224 // the case and only the users are dead but the instruction (=call) is
4225 // still needed.
4226 if (auto *SI = dyn_cast<StoreInst>(I)) {
4227 SmallSetVector<Instruction *, 8> AssumeOnlyInst;
4228 bool IsDead = isDeadStore(A, *SI, &AssumeOnlyInst);
4229 (void)IsDead;
4230 assert(IsDead && "Store was assumed to be dead!");
4231 A.deleteAfterManifest(*I);
4232 for (size_t i = 0; i < AssumeOnlyInst.size(); ++i) {
4233 Instruction *AOI = AssumeOnlyInst[i];
4234 for (auto *Usr : AOI->users())
4235 AssumeOnlyInst.insert(cast<Instruction>(Usr));
4236 A.deleteAfterManifest(*AOI);
4237 }
4238 return ChangeStatus::CHANGED;
4239 }
4240 if (auto *FI = dyn_cast<FenceInst>(I)) {
4241 assert(isDeadFence(A, *FI));
4242 A.deleteAfterManifest(*FI);
4243 return ChangeStatus::CHANGED;
4244 }
4245 if (isAssumedSideEffectFree(A, I) && !I->isTerminator()) {
4246 A.deleteAfterManifest(*I);
4247 return ChangeStatus::CHANGED;
4248 }
4249 }
4251 }
4252
4253 void trackStatistics() const override {
4255 }
4256
4257private:
4258 // The potential copies of a dead store, used for deletion during manifest.
4259 SmallSetVector<Value *, 4> PotentialCopies;
4260};
4261
4262struct AAIsDeadArgument : public AAIsDeadFloating {
4263 AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
4264 : AAIsDeadFloating(IRP, A) {}
4265
4266 ChangeStatus manifest(Attributor &A) override {
4267 Argument &Arg = *getAssociatedArgument();
4268 if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
4269 if (A.registerFunctionSignatureRewrite(
4270 Arg, /* ReplacementTypes */ {},
4273 return ChangeStatus::CHANGED;
4274 }
4275 return ChangeStatus::UNCHANGED;
4276 }
4277
4278 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
4279};
4280
4281struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
4282 AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
4283 : AAIsDeadValueImpl(IRP, A) {}
4284
4285 void initialize(Attributor &A) override {
4286 AAIsDeadValueImpl::initialize(A);
4287 if (isa<UndefValue>(getAssociatedValue()))
4288 indicatePessimisticFixpoint();
4289 }
4290
4291 ChangeStatus updateImpl(Attributor &A) override {
4292 // TODO: Once we have call site specific value information we can provide
4293 // call site specific liveness information and then it makes
4294 // sense to specialize attributes for call sites arguments instead of
4295 // redirecting requests to the callee argument.
4296 Argument *Arg = getAssociatedArgument();
4297 if (!Arg)
4298 return indicatePessimisticFixpoint();
4299 const IRPosition &ArgPos = IRPosition::argument(*Arg);
4300 auto *ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED);
4301 if (!ArgAA)
4302 return indicatePessimisticFixpoint();
4303 return clampStateAndIndicateChange(getState(), ArgAA->getState());
4304 }
4305
4306 ChangeStatus manifest(Attributor &A) override {
4307 CallBase &CB = cast<CallBase>(getAnchorValue());
4308 Use &U = CB.getArgOperandUse(getCallSiteArgNo());
4309 assert(!isa<UndefValue>(U.get()) &&
4310 "Expected undef values to be filtered out!");
4311 UndefValue &UV = *UndefValue::get(U->getType());
4312 if (A.changeUseAfterManifest(U, UV))
4313 return ChangeStatus::CHANGED;
4314 return ChangeStatus::UNCHANGED;
4315 }
4316
4317 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
4318};
4319
4320struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
4321 AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
4322 : AAIsDeadFloating(IRP, A) {}
4323
4324 bool isAssumedDead() const override {
4325 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
4326 }
4327
4328 void initialize(Attributor &A) override {
4329 AAIsDeadFloating::initialize(A);
4330 if (isa<UndefValue>(getAssociatedValue())) {
4331 indicatePessimisticFixpoint();
4332 return;
4333 }
4334
4335 // We track this separately as a secondary state.
4336 IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
4337 }
4338
4339 ChangeStatus updateImpl(Attributor &A) override {
4340 ChangeStatus Changed = ChangeStatus::UNCHANGED;
4341 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
4342 IsAssumedSideEffectFree = false;
4343 Changed = ChangeStatus::CHANGED;
4344 }
4345 if (!areAllUsesAssumedDead(A, getAssociatedValue()))
4346 return indicatePessimisticFixpoint();
4347 return Changed;
4348 }
4349
4350 void trackStatistics() const override {
4351 if (IsAssumedSideEffectFree)
4353 else
4354 STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
4355 }
4356
4357 const std::string getAsStr(Attributor *A) const override {
4358 return isAssumedDead()
4359 ? "assumed-dead"
4360 : (getAssumed() ? "assumed-dead-users" : "assumed-live");
4361 }
4362
4363private:
4364 bool IsAssumedSideEffectFree = true;
4365};
4366
4367struct AAIsDeadReturned : public AAIsDeadValueImpl {
4368 AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
4369 : AAIsDeadValueImpl(IRP, A) {}
4370
4371 ChangeStatus updateImpl(Attributor &A) override {
4372
4373 bool UsedAssumedInformation = false;
4374 A.checkForAllInstructions([](Instruction &) { return true; }, *this,
4375 {Instruction::Ret}, UsedAssumedInformation);
4376
4377 auto PredForCallSite = [&](AbstractCallSite ACS) {
4378 if (ACS.isCallbackCall() || !ACS.getInstruction())
4379 return false;
4380 return areAllUsesAssumedDead(A, *ACS.getInstruction());
4381 };
4382
4383 if (!A.checkForAllCallSites(PredForCallSite, *this, true,
4384 UsedAssumedInformation))
4385 return indicatePessimisticFixpoint();
4386
4387 return ChangeStatus::UNCHANGED;
4388 }
4389
4390 ChangeStatus manifest(Attributor &A) override {
4391 // TODO: Rewrite the signature to return void?
4392 bool AnyChange = false;
4393 UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
4394 auto RetInstPred = [&](Instruction &I) {
4395 ReturnInst &RI = cast<ReturnInst>(I);
4397 AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
4398 return true;
4399 };
4400 bool UsedAssumedInformation = false;
4401 A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
4402 UsedAssumedInformation);
4403 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
4404 }
4405
4406 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
4407};
4408
4409struct AAIsDeadFunction : public AAIsDead {
4410 AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
4411
4412 void initialize(Attributor &A) override {
4413 Function *F = getAnchorScope();
4414 assert(F && "Did expect an anchor function");
4415 if (!isAssumedDeadInternalFunction(A)) {
4416 ToBeExploredFrom.insert(&F->getEntryBlock().front());
4417 assumeLive(A, F->getEntryBlock());
4418 }
4419 }
4420
4421 bool isAssumedDeadInternalFunction(Attributor &A) {
4422 if (!getAnchorScope()->hasLocalLinkage())
4423 return false;
4424 // An AA that will not be updated is fixed pessimistically right after
4425 // initialization, so an assumed-dead result would be discarded. Checking
4426 // the call sites recursively initializes the liveness of every internal
4427 // caller, which in CGSCC cleanup repeats for each callee SCC.
4428 if (!A.shouldUpdateAA<AAIsDead>(getIRPosition()))
4429 return false;
4430 bool UsedAssumedInformation = false;
4431 return A.checkForAllCallSites([](AbstractCallSite) { return false; }, *this,
4432 true, UsedAssumedInformation);
4433 }
4434
4435 const std::string getAsStr(Attributor *A) const override {
4436 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
4437 std::to_string(getAnchorScope()->size()) + "][#TBEP " +
4438 std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
4439 std::to_string(KnownDeadEnds.size()) + "]";
4440 }
4441
4442 ChangeStatus manifest(Attributor &A) override {
4443 assert(getState().isValidState() &&
4444 "Attempted to manifest an invalid state!");
4445
4446 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
4447 Function &F = *getAnchorScope();
4448
4449 if (AssumedLiveBlocks.empty()) {
4450 A.deleteAfterManifest(F);
4451 return ChangeStatus::CHANGED;
4452 }
4453
4454 // Flag to determine if we can change an invoke to a call assuming the
4455 // callee is nounwind. This is not possible if the personality of the
4456 // function allows to catch asynchronous exceptions.
4457 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
4458
4459 KnownDeadEnds.set_union(ToBeExploredFrom);
4460 for (const Instruction *DeadEndI : KnownDeadEnds) {
4461 auto *CB = dyn_cast<CallBase>(DeadEndI);
4462 if (!CB)
4463 continue;
4464 bool IsKnownNoReturn;
4466 A, this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL,
4467 IsKnownNoReturn);
4468 if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
4469 continue;
4470
4471 if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
4472 A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
4473 else
4474 A.changeToUnreachableAfterManifest(
4475 const_cast<Instruction *>(DeadEndI->getNextNode()));
4476 HasChanged = ChangeStatus::CHANGED;
4477 }
4478
4479 STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
4480 for (BasicBlock &BB : F)
4481 if (!AssumedLiveBlocks.count(&BB)) {
4482 A.deleteAfterManifest(BB);
4483 ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
4484 HasChanged = ChangeStatus::CHANGED;
4485 }
4486
4487 return HasChanged;
4488 }
4489
4490 ChangeStatus updateImpl(Attributor &A) override;
4491
4492 bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override {
4493 assert(From->getParent() == getAnchorScope() &&
4494 To->getParent() == getAnchorScope() &&
4495 "Used AAIsDead of the wrong function");
4496 return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
4497 }
4498
4499 void trackStatistics() const override {}
4500
4501 /// Returns true if the function is assumed dead.
4502 bool isAssumedDead() const override { return false; }
4503
4504 bool isKnownDead() const override { return false; }
4505
4506 bool isAssumedDead(const BasicBlock *BB) const override {
4507 assert(BB->getParent() == getAnchorScope() &&
4508 "BB must be in the same anchor scope function.");
4509
4510 if (!getAssumed())
4511 return false;
4512 return !AssumedLiveBlocks.count(BB);
4513 }
4514
4515 bool isKnownDead(const BasicBlock *BB) const override {
4516 return getKnown() && isAssumedDead(BB);
4517 }
4518
4519 bool isAssumedDead(const Instruction *I) const override {
4520 assert(I->getParent()->getParent() == getAnchorScope() &&
4521 "Instruction must be in the same anchor scope function.");
4522
4523 if (!getAssumed())
4524 return false;
4525
4526 // If it is not in AssumedLiveBlocks then it for sure dead.
4527 // Otherwise, it can still be after noreturn call in a live block.
4528 if (!AssumedLiveBlocks.count(I->getParent()))
4529 return true;
4530
4531 // If it is not after a liveness barrier it is live.
4532 const Instruction *PrevI = I->getPrevNode();
4533 while (PrevI) {
4534 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
4535 return true;
4536 PrevI = PrevI->getPrevNode();
4537 }
4538 return false;
4539 }
4540
4541 bool isKnownDead(const Instruction *I) const override {
4542 return getKnown() && isAssumedDead(I);
4543 }
4544
4545 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
4546 /// that internal function called from \p BB should now be looked at.
4547 bool assumeLive(Attributor &A, const BasicBlock &BB) {
4548 if (!AssumedLiveBlocks.insert(&BB).second)
4549 return false;
4550
4551 if (!A.isDuringDeduction())
4552 return true;
4553
4554 // We assume that all of BB is (probably) live now and if there are calls to
4555 // internal functions we will assume that those are now live as well. This
4556 // is a performance optimization for blocks with calls to a lot of internal
4557 // functions. It can however cause dead functions to be treated as live.
4558 for (const Instruction &I : BB)
4559 if (const auto *CB = dyn_cast<CallBase>(&I))
4561 if (F->hasLocalLinkage()) {
4562 LLVM_DEBUG({
4563 dbgs() << "[AAIsDead] Seeding live internal callee ";
4564 F->printAsOperand(dbgs(), /*PrintType=*/false);
4565 dbgs() << " from ";
4566 BB.getParent()->printAsOperand(dbgs(), /*PrintType=*/false);
4567 dbgs() << "\n";
4568 });
4569 A.markLiveInternalFunction(*F);
4570 }
4571 return true;
4572 }
4573
4574 /// Collection of instructions that need to be explored again, e.g., we
4575 /// did assume they do not transfer control to (one of their) successors.
4576 SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
4577
4578 /// Collection of instructions that are known to not transfer control.
4579 SmallSetVector<const Instruction *, 8> KnownDeadEnds;
4580
4581 /// Collection of all assumed live edges
4582 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
4583
4584 /// Collection of all assumed live BasicBlocks.
4585 DenseSet<const BasicBlock *> AssumedLiveBlocks;
4586};
4587
4588static bool
4589identifyAliveSuccessors(Attributor &A, const CallBase &CB,
4590 AbstractAttribute &AA,
4591 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4592 const IRPosition &IPos = IRPosition::callsite_function(CB);
4593
4594 bool IsKnownNoReturn;
4596 A, &AA, IPos, DepClassTy::OPTIONAL, IsKnownNoReturn))
4597 return !IsKnownNoReturn;
4598 if (CB.isTerminator())
4599 AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
4600 else
4601 AliveSuccessors.push_back(CB.getNextNode());
4602 return false;
4603}
4604
4605static bool
4606identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
4607 AbstractAttribute &AA,
4608 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4609 bool UsedAssumedInformation =
4610 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
4611
4612 // First, determine if we can change an invoke to a call assuming the
4613 // callee is nounwind. This is not possible if the personality of the
4614 // function allows to catch asynchronous exceptions.
4615 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
4616 AliveSuccessors.push_back(&II.getUnwindDest()->front());
4617 } else {
4618 const IRPosition &IPos = IRPosition::callsite_function(II);
4619
4620 bool IsKnownNoUnwind;
4622 A, &AA, IPos, DepClassTy::OPTIONAL, IsKnownNoUnwind)) {
4623 UsedAssumedInformation |= !IsKnownNoUnwind;
4624 } else {
4625 AliveSuccessors.push_back(&II.getUnwindDest()->front());
4626 }
4627 }
4628 return UsedAssumedInformation;
4629}
4630
4631static bool
4632identifyAliveSuccessors(Attributor &, const UncondBrInst &BI,
4633 AbstractAttribute &,
4634 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4635 AliveSuccessors.push_back(&BI.getSuccessor()->front());
4636 return false;
4637}
4638
4639static bool
4640identifyAliveSuccessors(Attributor &A, const CondBrInst &BI,
4641 AbstractAttribute &AA,
4642 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4643 bool UsedAssumedInformation = false;
4644 std::optional<Constant *> C =
4645 A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation);
4646 if (!C || isa_and_nonnull<UndefValue>(*C)) {
4647 // No value yet, assume both edges are dead.
4648 } else if (isa_and_nonnull<ConstantInt>(*C)) {
4649 const BasicBlock *SuccBB =
4650 BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue());
4651 AliveSuccessors.push_back(&SuccBB->front());
4652 } else {
4653 AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
4654 AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
4655 UsedAssumedInformation = false;
4656 }
4657 return UsedAssumedInformation;
4658}
4659
4660static bool
4661identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
4662 AbstractAttribute &AA,
4663 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4664 bool UsedAssumedInformation = false;
4666 if (!A.getAssumedSimplifiedValues(IRPosition::value(*SI.getCondition()), &AA,
4668 UsedAssumedInformation)) {
4669 // Something went wrong, assume all successors are live.
4670 for (const BasicBlock *SuccBB : successors(SI.getParent()))
4671 AliveSuccessors.push_back(&SuccBB->front());
4672 return false;
4673 }
4674
4675 if (Values.empty() ||
4676 (Values.size() == 1 &&
4677 isa_and_nonnull<UndefValue>(Values.front().getValue()))) {
4678 // No valid value yet, assume all edges are dead.
4679 return UsedAssumedInformation;
4680 }
4681
4682 Type &Ty = *SI.getCondition()->getType();
4683 SmallPtrSet<ConstantInt *, 8> Constants;
4684 auto CheckForConstantInt = [&](Value *V) {
4685 if (auto *CI = dyn_cast_if_present<ConstantInt>(AA::getWithType(*V, Ty))) {
4686 Constants.insert(CI);
4687 return true;
4688 }
4689 return false;
4690 };
4691
4692 if (!all_of(Values, [&](AA::ValueAndContext &VAC) {
4693 return CheckForConstantInt(VAC.getValue());
4694 })) {
4695 for (const BasicBlock *SuccBB : successors(SI.getParent()))
4696 AliveSuccessors.push_back(&SuccBB->front());
4697 return UsedAssumedInformation;
4698 }
4699
4700 unsigned MatchedCases = 0;
4701 for (const auto &CaseIt : SI.cases()) {
4702 if (Constants.count(CaseIt.getCaseValue())) {
4703 ++MatchedCases;
4704 AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
4705 }
4706 }
4707
4708 // If all potential values have been matched, we will not visit the default
4709 // case.
4710 if (MatchedCases < Constants.size())
4711 AliveSuccessors.push_back(&SI.getDefaultDest()->front());
4712 return UsedAssumedInformation;
4713}
4714
4715ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
4717
4718 if (AssumedLiveBlocks.empty()) {
4719 if (isAssumedDeadInternalFunction(A))
4721
4722 Function *F = getAnchorScope();
4723 ToBeExploredFrom.insert(&F->getEntryBlock().front());
4724 assumeLive(A, F->getEntryBlock());
4725 Change = ChangeStatus::CHANGED;
4726 }
4727
4728 LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
4729 << getAnchorScope()->size() << "] BBs and "
4730 << ToBeExploredFrom.size() << " exploration points and "
4731 << KnownDeadEnds.size() << " known dead ends\n");
4732
4733 // Copy and clear the list of instructions we need to explore from. It is
4734 // refilled with instructions the next update has to look at.
4735 SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
4736 ToBeExploredFrom.end());
4737 decltype(ToBeExploredFrom) NewToBeExploredFrom;
4738
4740 while (!Worklist.empty()) {
4741 const Instruction *I = Worklist.pop_back_val();
4742 LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
4743
4744 // Fast forward for uninteresting instructions. We could look for UB here
4745 // though.
4746 while (!I->isTerminator() && !isa<CallBase>(I))
4747 I = I->getNextNode();
4748
4749 AliveSuccessors.clear();
4750
4751 bool UsedAssumedInformation = false;
4752 switch (I->getOpcode()) {
4753 // TODO: look for (assumed) UB to backwards propagate "deadness".
4754 default:
4755 assert(I->isTerminator() &&
4756 "Expected non-terminators to be handled already!");
4757 for (const BasicBlock *SuccBB : successors(I->getParent()))
4758 AliveSuccessors.push_back(&SuccBB->front());
4759 break;
4760 case Instruction::Call:
4761 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
4762 *this, AliveSuccessors);
4763 break;
4764 case Instruction::Invoke:
4765 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
4766 *this, AliveSuccessors);
4767 break;
4768 case Instruction::UncondBr:
4769 UsedAssumedInformation = identifyAliveSuccessors(
4770 A, cast<UncondBrInst>(*I), *this, AliveSuccessors);
4771 break;
4772 case Instruction::CondBr:
4773 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CondBrInst>(*I),
4774 *this, AliveSuccessors);
4775 break;
4776 case Instruction::Switch:
4777 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
4778 *this, AliveSuccessors);
4779 break;
4780 }
4781
4782 if (UsedAssumedInformation) {
4783 NewToBeExploredFrom.insert(I);
4784 } else if (AliveSuccessors.empty() ||
4785 (I->isTerminator() &&
4786 AliveSuccessors.size() < I->getNumSuccessors())) {
4787 if (KnownDeadEnds.insert(I))
4788 Change = ChangeStatus::CHANGED;
4789 }
4790
4791 LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
4792 << AliveSuccessors.size() << " UsedAssumedInformation: "
4793 << UsedAssumedInformation << "\n");
4794
4795 for (const Instruction *AliveSuccessor : AliveSuccessors) {
4796 if (!I->isTerminator()) {
4797 assert(AliveSuccessors.size() == 1 &&
4798 "Non-terminator expected to have a single successor!");
4799 Worklist.push_back(AliveSuccessor);
4800 } else {
4801 // record the assumed live edge
4802 auto Edge = std::make_pair(I->getParent(), AliveSuccessor->getParent());
4803 if (AssumedLiveEdges.insert(Edge).second)
4804 Change = ChangeStatus::CHANGED;
4805 if (assumeLive(A, *AliveSuccessor->getParent()))
4806 Worklist.push_back(AliveSuccessor);
4807 }
4808 }
4809 }
4810
4811 // Check if the content of ToBeExploredFrom changed, ignore the order.
4812 if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4813 llvm::any_of(NewToBeExploredFrom, [&](const Instruction *I) {
4814 return !ToBeExploredFrom.count(I);
4815 })) {
4816 Change = ChangeStatus::CHANGED;
4817 ToBeExploredFrom = std::move(NewToBeExploredFrom);
4818 }
4819
4820 // If we know everything is live there is no need to query for liveness.
4821 // Instead, indicating a pessimistic fixpoint will cause the state to be
4822 // "invalid" and all queries to be answered conservatively without lookups.
4823 // To be in this state we have to (1) finished the exploration and (3) not
4824 // discovered any non-trivial dead end and (2) not ruled unreachable code
4825 // dead.
4826 if (ToBeExploredFrom.empty() &&
4827 getAnchorScope()->size() == AssumedLiveBlocks.size() &&
4828 llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
4829 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4830 }))
4831 return indicatePessimisticFixpoint();
4832 return Change;
4833}
4834
4835/// Liveness information for a call sites.
4836struct AAIsDeadCallSite final : AAIsDeadFunction {
4837 AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
4838 : AAIsDeadFunction(IRP, A) {}
4839
4840 void initialize(Attributor &A) override {
4841 // TODO: Once we have call site specific value information we can provide
4842 // call site specific liveness information and then it makes
4843 // sense to specialize attributes for call sites instead of
4844 // redirecting requests to the callee.
4845 llvm_unreachable("Abstract attributes for liveness are not "
4846 "supported for call sites yet!");
4847 }
4848
4849 ChangeStatus updateImpl(Attributor &A) override {
4850 return indicatePessimisticFixpoint();
4851 }
4852
4853 void trackStatistics() const override {}
4854};
4855} // namespace
4856
4857/// -------------------- Dereferenceable Argument Attribute --------------------
4858
4859namespace {
4860struct AADereferenceableImpl : AADereferenceable {
4861 AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
4862 : AADereferenceable(IRP, A) {}
4863 using StateType = DerefState;
4864
4865 void initialize(Attributor &A) override {
4866 Value &V = *getAssociatedValue().stripPointerCasts();
4868 A.getAttrs(getIRPosition(),
4869 {Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4870 Attrs, /* IgnoreSubsumingPositions */ false);
4871 for (const Attribute &Attr : Attrs)
4872 takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4873
4874 // Ensure we initialize the non-null AA (if necessary).
4875 bool IsKnownNonNull;
4877 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNonNull);
4878
4879 bool CanBeNull;
4880 takeKnownDerefBytesMaximum(V.getPointerDereferenceableBytes(
4881 A.getDataLayout(), CanBeNull, /*CanBeFreed=*/nullptr));
4882
4883 if (Instruction *CtxI = getCtxI())
4884 followUsesInMBEC(*this, A, getState(), *CtxI);
4885 }
4886
4887 StateType &getState() override { return *this; }
4888 const StateType &getState() const override { return *this; }
4889
4890 /// Helper function for collecting accessed bytes in must-be-executed-context
4891 void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
4892 DerefState &State) {
4893 const Value *UseV = U->get();
4894 if (!UseV->getType()->isPointerTy())
4895 return;
4896
4897 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
4898 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
4899 return;
4900
4901 int64_t Offset;
4903 Loc->Ptr, Offset, A.getDataLayout(), /*AllowNonInbounds*/ true);
4904 if (Base && Base == &getAssociatedValue())
4905 State.addAccessedBytes(Offset, Loc->Size.getValue());
4906 }
4907
4908 /// See followUsesInMBEC
4909 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4910 AADereferenceable::StateType &State) {
4911 bool IsNonNull = false;
4912 bool TrackUse = false;
4913 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4914 A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
4915 LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
4916 << " for instruction " << *I << "\n");
4917
4918 addAccessedBytesForUse(A, U, I, State);
4919 State.takeKnownDerefBytesMaximum(DerefBytes);
4920 return TrackUse;
4921 }
4922
4923 ChangeStatus manifest(Attributor &A) override {
4924 ChangeStatus Change = AADereferenceable::manifest(A);
4925 bool IsKnownNonNull;
4926 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
4927 A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4928 if (IsAssumedNonNull &&
4929 A.hasAttr(getIRPosition(), Attribute::DereferenceableOrNull)) {
4930 A.removeAttrs(getIRPosition(), {Attribute::DereferenceableOrNull});
4931 return ChangeStatus::CHANGED;
4932 }
4933 return Change;
4934 }
4935
4936 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
4937 SmallVectorImpl<Attribute> &Attrs) const override {
4938 // TODO: Add *_globally support
4939 bool IsKnownNonNull;
4940 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
4941 A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4942 if (IsAssumedNonNull)
4943 Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4944 Ctx, getAssumedDereferenceableBytes()));
4945 else
4946 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4947 Ctx, getAssumedDereferenceableBytes()));
4948 }
4949
4950 const std::string getAsStr(Attributor *A) const override {
4951 if (!getAssumedDereferenceableBytes())
4952 return "unknown-dereferenceable";
4953 bool IsKnownNonNull;
4954 bool IsAssumedNonNull = false;
4955 if (A)
4957 *A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4958 return std::string("dereferenceable") +
4959 (IsAssumedNonNull ? "" : "_or_null") +
4960 (isAssumedGlobal() ? "_globally" : "") + "<" +
4961 std::to_string(getKnownDereferenceableBytes()) + "-" +
4962 std::to_string(getAssumedDereferenceableBytes()) + ">" +
4963 (!A ? " [non-null is unknown]" : "");
4964 }
4965};
4966
4967/// Dereferenceable attribute for a floating value.
4968struct AADereferenceableFloating : AADereferenceableImpl {
4969 AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
4970 : AADereferenceableImpl(IRP, A) {}
4971
4972 ChangeStatus updateImpl(Attributor &A) override {
4973 bool Stripped;
4974 bool UsedAssumedInformation = false;
4976 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
4977 AA::AnyScope, UsedAssumedInformation)) {
4978 Values.push_back({getAssociatedValue(), getCtxI()});
4979 Stripped = false;
4980 } else {
4981 Stripped = Values.size() != 1 ||
4982 Values.front().getValue() != &getAssociatedValue();
4983 }
4984
4985 const DataLayout &DL = A.getDataLayout();
4986 DerefState T;
4987
4988 auto VisitValueCB = [&](const Value &V) -> bool {
4989 unsigned IdxWidth =
4990 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
4991 APInt Offset(IdxWidth, 0);
4993 A, *this, &V, DL, Offset, /* GetMinOffset */ false,
4994 /* AllowNonInbounds */ true);
4995
4996 const auto *AA = A.getAAFor<AADereferenceable>(
4997 *this, IRPosition::value(*Base), DepClassTy::REQUIRED);
4998 int64_t DerefBytes = 0;
4999 if (!AA || (!Stripped && this == AA)) {
5000 // Use IR information if we did not strip anything.
5001 // TODO: track globally.
5002 bool CanBeNull;
5003 DerefBytes = Base->getPointerDereferenceableBytes(
5004 DL, CanBeNull, /*CanBeFreed=*/nullptr);
5005 T.GlobalState.indicatePessimisticFixpoint();
5006 } else {
5007 const DerefState &DS = AA->getState();
5008 DerefBytes = DS.DerefBytesState.getAssumed();
5009 T.GlobalState &= DS.GlobalState;
5010 }
5011
5012 // For now we do not try to "increase" dereferenceability due to negative
5013 // indices as we first have to come up with code to deal with loops and
5014 // for overflows of the dereferenceable bytes.
5015 int64_t OffsetSExt = Offset.getSExtValue();
5016 if (OffsetSExt < 0)
5017 OffsetSExt = 0;
5018
5019 T.takeAssumedDerefBytesMinimum(
5020 std::max(int64_t(0), DerefBytes - OffsetSExt));
5021
5022 if (this == AA) {
5023 if (!Stripped) {
5024 // If nothing was stripped IR information is all we got.
5025 T.takeKnownDerefBytesMaximum(
5026 std::max(int64_t(0), DerefBytes - OffsetSExt));
5027 T.indicatePessimisticFixpoint();
5028 } else if (OffsetSExt > 0) {
5029 // If something was stripped but there is circular reasoning we look
5030 // for the offset. If it is positive we basically decrease the
5031 // dereferenceable bytes in a circular loop now, which will simply
5032 // drive them down to the known value in a very slow way which we
5033 // can accelerate.
5034 T.indicatePessimisticFixpoint();
5035 }
5036 }
5037
5038 return T.isValidState();
5039 };
5040
5041 for (const auto &VAC : Values)
5042 if (!VisitValueCB(*VAC.getValue()))
5043 return indicatePessimisticFixpoint();
5044
5045 return clampStateAndIndicateChange(getState(), T);
5046 }
5047
5048 void trackStatistics() const override {
5049 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
5050 }
5051};
5052
5053/// Dereferenceable attribute for a return value.
5054struct AADereferenceableReturned final
5055 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
5056 using Base =
5057 AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>;
5058 AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
5059 : Base(IRP, A) {}
5060
5061 void trackStatistics() const override {
5062 STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
5063 }
5064};
5065
5066/// Dereferenceable attribute for an argument
5067struct AADereferenceableArgument final
5068 : AAArgumentFromCallSiteArguments<AADereferenceable,
5069 AADereferenceableImpl> {
5070 using Base =
5071 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
5072 AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
5073 : Base(IRP, A) {}
5074
5075 void trackStatistics() const override {
5076 STATS_DECLTRACK_ARG_ATTR(dereferenceable)
5077 }
5078};
5079
5080/// Dereferenceable attribute for a call site argument.
5081struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
5082 AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
5083 : AADereferenceableFloating(IRP, A) {}
5084
5085 void trackStatistics() const override {
5086 STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
5087 }
5088};
5089
5090/// Dereferenceable attribute deduction for a call site return value.
5091struct AADereferenceableCallSiteReturned final
5092 : AACalleeToCallSite<AADereferenceable, AADereferenceableImpl> {
5093 using Base = AACalleeToCallSite<AADereferenceable, AADereferenceableImpl>;
5094 AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
5095 : Base(IRP, A) {}
5096
5097 void trackStatistics() const override {
5098 STATS_DECLTRACK_CS_ATTR(dereferenceable);
5099 }
5100};
5101} // namespace
5102
5103// ------------------------ Align Argument Attribute ------------------------
5104
5105namespace {
5106
5107static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA,
5108 Value &AssociatedValue, const Use *U,
5109 const Instruction *I, bool &TrackUse) {
5110 // We need to follow common pointer manipulation uses to the accesses they
5111 // feed into.
5112 if (isa<CastInst>(I)) {
5113 // Follow all but ptr2int casts.
5114 TrackUse = !isa<PtrToIntInst>(I);
5115 return 0;
5116 }
5117 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
5118 if (GEP->hasAllConstantIndices())
5119 TrackUse = true;
5120 return 0;
5121 }
5122 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
5123 switch (II->getIntrinsicID()) {
5124 case Intrinsic::ptrmask: {
5125 // Is it appropriate to pull attribute in initialization?
5126 const auto *ConstVals = A.getAAFor<AAPotentialConstantValues>(
5127 QueryingAA, IRPosition::value(*II->getOperand(1)), DepClassTy::NONE);
5128 const auto *AlignAA = A.getAAFor<AAAlign>(
5129 QueryingAA, IRPosition::value(*II), DepClassTy::NONE);
5130 if (ConstVals && ConstVals->isValidState() && ConstVals->isAtFixpoint()) {
5131 unsigned ShiftValue = std::min(ConstVals->getAssumedMinTrailingZeros(),
5133 Align ConstAlign = Align::fromLog2(ShiftValue);
5134 if (ConstAlign >= AlignAA->getKnownAlign())
5135 return Align(1).value();
5136 }
5137 if (AlignAA)
5138 return AlignAA->getKnownAlign().value();
5139 break;
5140 }
5141 case Intrinsic::amdgcn_make_buffer_rsrc: {
5142 const auto *AlignAA = A.getAAFor<AAAlign>(
5143 QueryingAA, IRPosition::value(*II), DepClassTy::NONE);
5144 if (AlignAA)
5145 return AlignAA->getKnownAlign().value();
5146 break;
5147 }
5148 default:
5149 break;
5150 }
5151
5152 MaybeAlign MA;
5153 if (const auto *CB = dyn_cast<CallBase>(I)) {
5154 if (CB->isBundleOperand(U) || CB->isCallee(U))
5155 return 0;
5156
5157 unsigned ArgNo = CB->getArgOperandNo(U);
5158 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
5159 // As long as we only use known information there is no need to track
5160 // dependences here.
5161 auto *AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE);
5162 if (AlignAA)
5163 MA = MaybeAlign(AlignAA->getKnownAlign());
5164 }
5165
5166 const DataLayout &DL = A.getDataLayout();
5167 const Value *UseV = U->get();
5168 if (auto *SI = dyn_cast<StoreInst>(I)) {
5169 if (SI->getPointerOperand() == UseV)
5170 MA = SI->getAlign();
5171 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
5172 if (LI->getPointerOperand() == UseV)
5173 MA = LI->getAlign();
5174 } else if (auto *AI = dyn_cast<AtomicRMWInst>(I)) {
5175 if (AI->getPointerOperand() == UseV)
5176 MA = AI->getAlign();
5177 } else if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
5178 if (AI->getPointerOperand() == UseV)
5179 MA = AI->getAlign();
5180 }
5181
5182 if (!MA || *MA <= QueryingAA.getKnownAlign())
5183 return 0;
5184
5185 unsigned Alignment = MA->value();
5186 int64_t Offset;
5187
5188 if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
5189 if (Base == &AssociatedValue) {
5190 // BasePointerAddr + Offset = Alignment * Q for some integer Q.
5191 // So we can say that the maximum power of two which is a divisor of
5192 // gcd(Offset, Alignment) is an alignment.
5193
5194 uint32_t gcd = std::gcd(uint32_t(abs((int32_t)Offset)), Alignment);
5196 }
5197 }
5198
5199 return Alignment;
5200}
5201
5202struct AAAlignImpl : AAAlign {
5203 AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
5204
5205 void initialize(Attributor &A) override {
5207 A.getAttrs(getIRPosition(), {Attribute::Alignment}, Attrs);
5208 for (const Attribute &Attr : Attrs)
5209 takeKnownMaximum(Attr.getValueAsInt());
5210
5211 Value &V = *getAssociatedValue().stripPointerCasts();
5212 takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
5213
5214 if (Instruction *CtxI = getCtxI())
5215 followUsesInMBEC(*this, A, getState(), *CtxI);
5216 }
5217
5218 ChangeStatus manifest(Attributor &A) override {
5219 ChangeStatus InstrChanged = ChangeStatus::UNCHANGED;
5220
5221 // Check for users that allow alignment annotations.
5222 Value &AssociatedValue = getAssociatedValue();
5223 if (isa<ConstantData>(AssociatedValue))
5224 return ChangeStatus::UNCHANGED;
5225
5226 for (const Use &U : AssociatedValue.uses()) {
5227 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
5228 if (SI->getPointerOperand() == &AssociatedValue)
5229 if (SI->getAlign() < getAssumedAlign()) {
5230 STATS_DECLTRACK(AAAlign, Store,
5231 "Number of times alignment added to a store");
5232 SI->setAlignment(getAssumedAlign());
5233 InstrChanged = ChangeStatus::CHANGED;
5234 }
5235 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
5236 if (LI->getPointerOperand() == &AssociatedValue)
5237 if (LI->getAlign() < getAssumedAlign()) {
5238 LI->setAlignment(getAssumedAlign());
5239 STATS_DECLTRACK(AAAlign, Load,
5240 "Number of times alignment added to a load");
5241 InstrChanged = ChangeStatus::CHANGED;
5242 }
5243 } else if (auto *RMW = dyn_cast<AtomicRMWInst>(U.getUser())) {
5244 if (RMW->getPointerOperand() == &AssociatedValue) {
5245 if (RMW->getAlign() < getAssumedAlign()) {
5246 STATS_DECLTRACK(AAAlign, AtomicRMW,
5247 "Number of times alignment added to atomicrmw");
5248
5249 RMW->setAlignment(getAssumedAlign());
5250 InstrChanged = ChangeStatus::CHANGED;
5251 }
5252 }
5253 } else if (auto *CAS = dyn_cast<AtomicCmpXchgInst>(U.getUser())) {
5254 if (CAS->getPointerOperand() == &AssociatedValue) {
5255 if (CAS->getAlign() < getAssumedAlign()) {
5256 STATS_DECLTRACK(AAAlign, AtomicCmpXchg,
5257 "Number of times alignment added to cmpxchg");
5258 CAS->setAlignment(getAssumedAlign());
5259 InstrChanged = ChangeStatus::CHANGED;
5260 }
5261 }
5262 }
5263 }
5264
5265 ChangeStatus Changed = AAAlign::manifest(A);
5266
5267 Align InheritAlign =
5268 getAssociatedValue().getPointerAlignment(A.getDataLayout());
5269 if (InheritAlign >= getAssumedAlign())
5270 return InstrChanged;
5271 return Changed | InstrChanged;
5272 }
5273
5274 // TODO: Provide a helper to determine the implied ABI alignment and check in
5275 // the existing manifest method and a new one for AAAlignImpl that value
5276 // to avoid making the alignment explicit if it did not improve.
5277
5278 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
5279 SmallVectorImpl<Attribute> &Attrs) const override {
5280 if (getAssumedAlign() > 1)
5281 Attrs.emplace_back(
5282 Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
5283 }
5284
5285 /// See followUsesInMBEC
5286 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
5287 AAAlign::StateType &State) {
5288 bool TrackUse = false;
5289
5290 unsigned int KnownAlign =
5291 getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
5292 State.takeKnownMaximum(KnownAlign);
5293
5294 return TrackUse;
5295 }
5296
5297 const std::string getAsStr(Attributor *A) const override {
5298 return "align<" + std::to_string(getKnownAlign().value()) + "-" +
5299 std::to_string(getAssumedAlign().value()) + ">";
5300 }
5301};
5302
5303/// Align attribute for a floating value.
5304struct AAAlignFloating : AAAlignImpl {
5305 AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
5306
5307 ChangeStatus updateImpl(Attributor &A) override {
5308 const DataLayout &DL = A.getDataLayout();
5309
5310 bool Stripped;
5311 bool UsedAssumedInformation = false;
5313 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
5314 AA::AnyScope, UsedAssumedInformation)) {
5315 Values.push_back({getAssociatedValue(), getCtxI()});
5316 Stripped = false;
5317 } else {
5318 Stripped = Values.size() != 1 ||
5319 Values.front().getValue() != &getAssociatedValue();
5320 }
5321
5322 StateType T;
5323 auto VisitValueCB = [&](Value &V) -> bool {
5325 return true;
5326 const auto *AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V),
5327 DepClassTy::REQUIRED);
5328 if (!AA || (!Stripped && this == AA)) {
5329 int64_t Offset;
5330 unsigned Alignment = 1;
5331 if (const Value *Base =
5333 // TODO: Use AAAlign for the base too.
5334 Align PA = Base->getPointerAlignment(DL);
5335 // BasePointerAddr + Offset = Alignment * Q for some integer Q.
5336 // So we can say that the maximum power of two which is a divisor of
5337 // gcd(Offset, Alignment) is an alignment.
5338
5339 uint32_t gcd =
5340 std::gcd(uint32_t(abs((int32_t)Offset)), uint32_t(PA.value()));
5342 } else {
5343 Alignment = V.getPointerAlignment(DL).value();
5344 }
5345 // Use only IR information if we did not strip anything.
5346 T.takeKnownMaximum(Alignment);
5347 T.indicatePessimisticFixpoint();
5348 } else {
5349 // Use abstract attribute information.
5350 const AAAlign::StateType &DS = AA->getState();
5351 T ^= DS;
5352 }
5353 return T.isValidState();
5354 };
5355
5356 for (const auto &VAC : Values) {
5357 if (!VisitValueCB(*VAC.getValue()))
5358 return indicatePessimisticFixpoint();
5359 }
5360
5361 // TODO: If we know we visited all incoming values, thus no are assumed
5362 // dead, we can take the known information from the state T.
5363 return clampStateAndIndicateChange(getState(), T);
5364 }
5365
5366 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
5367};
5368
5369/// Align attribute for function return value.
5370struct AAAlignReturned final
5371 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
5372 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
5373 AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
5374
5375 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
5376};
5377
5378/// Align attribute for function argument.
5379struct AAAlignArgument final
5380 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
5381 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
5382 AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
5383
5384 ChangeStatus manifest(Attributor &A) override {
5385 // If the associated argument is involved in a must-tail call we give up
5386 // because we would need to keep the argument alignments of caller and
5387 // callee in-sync. Just does not seem worth the trouble right now.
5388 if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
5389 return ChangeStatus::UNCHANGED;
5390 return Base::manifest(A);
5391 }
5392
5393 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
5394};
5395
5396struct AAAlignCallSiteArgument final : AAAlignFloating {
5397 AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
5398 : AAAlignFloating(IRP, A) {}
5399
5400 ChangeStatus manifest(Attributor &A) override {
5401 // If the associated argument is involved in a must-tail call we give up
5402 // because we would need to keep the argument alignments of caller and
5403 // callee in-sync. Just does not seem worth the trouble right now.
5404 if (Argument *Arg = getAssociatedArgument())
5405 if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
5406 return ChangeStatus::UNCHANGED;
5407 ChangeStatus Changed = AAAlignImpl::manifest(A);
5408 Align InheritAlign =
5409 getAssociatedValue().getPointerAlignment(A.getDataLayout());
5410 if (InheritAlign >= getAssumedAlign())
5411 Changed = ChangeStatus::UNCHANGED;
5412 return Changed;
5413 }
5414
5415 ChangeStatus updateImpl(Attributor &A) override {
5416 ChangeStatus Changed = AAAlignFloating::updateImpl(A);
5417 if (Argument *Arg = getAssociatedArgument()) {
5418 // We only take known information from the argument
5419 // so we do not need to track a dependence.
5420 const auto *ArgAlignAA = A.getAAFor<AAAlign>(
5421 *this, IRPosition::argument(*Arg), DepClassTy::NONE);
5422 if (ArgAlignAA)
5423 takeKnownMaximum(ArgAlignAA->getKnownAlign().value());
5424 }
5425 return Changed;
5426 }
5427
5428 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
5429};
5430
5431/// Align attribute deduction for a call site return value.
5432struct AAAlignCallSiteReturned final
5433 : AACalleeToCallSite<AAAlign, AAAlignImpl> {
5434 using Base = AACalleeToCallSite<AAAlign, AAAlignImpl>;
5435 AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
5436 : Base(IRP, A) {}
5437
5438 ChangeStatus updateImpl(Attributor &A) override {
5439 Instruction *I = getIRPosition().getCtxI();
5440 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
5441 switch (II->getIntrinsicID()) {
5442 case Intrinsic::ptrmask: {
5444 bool Valid = false;
5445
5446 const auto *ConstVals = A.getAAFor<AAPotentialConstantValues>(
5447 *this, IRPosition::value(*II->getOperand(1)), DepClassTy::REQUIRED);
5448 if (ConstVals && ConstVals->isValidState()) {
5449 unsigned ShiftValue =
5450 std::min(ConstVals->getAssumedMinTrailingZeros(),
5451 Value::MaxAlignmentExponent);
5452 Alignment = Align::fromLog2(ShiftValue);
5453 Valid = true;
5454 }
5455
5456 const auto *AlignAA =
5457 A.getAAFor<AAAlign>(*this, IRPosition::value(*(II->getOperand(0))),
5458 DepClassTy::REQUIRED);
5459 if (AlignAA) {
5460 Alignment = std::max(AlignAA->getAssumedAlign(), Alignment);
5461 Valid = true;
5462 }
5463
5464 if (Valid)
5466 this->getState(),
5467 std::min(this->getAssumedAlign(), Alignment).value());
5468 break;
5469 }
5470 // FIXME: Should introduce target specific sub-attributes and letting
5471 // getAAfor<AAAlign> lead to create sub-attribute to handle target
5472 // specific intrinsics.
5473 case Intrinsic::amdgcn_make_buffer_rsrc: {
5474 const auto *AlignAA =
5475 A.getAAFor<AAAlign>(*this, IRPosition::value(*(II->getOperand(0))),
5476 DepClassTy::REQUIRED);
5477 if (AlignAA)
5479 this->getState(), AlignAA->getAssumedAlign().value());
5480 break;
5481 }
5482 default:
5483 break;
5484 }
5485 }
5486 return Base::updateImpl(A);
5487 };
5488 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
5489};
5490} // namespace
5491
5492/// ------------------ Function No-Return Attribute ----------------------------
5493namespace {
5494struct AANoReturnImpl : public AANoReturn {
5495 AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
5496
5497 void initialize(Attributor &A) override {
5498 bool IsKnown;
5500 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5501 (void)IsKnown;
5502 }
5503
5504 const std::string getAsStr(Attributor *A) const override {
5505 return getAssumed() ? "noreturn" : "may-return";
5506 }
5507
5508 ChangeStatus updateImpl(Attributor &A) override {
5509 auto CheckForNoReturn = [](Instruction &) { return false; };
5510 bool UsedAssumedInformation = false;
5511 if (!A.checkForAllInstructions(CheckForNoReturn, *this,
5512 {(unsigned)Instruction::Ret},
5513 UsedAssumedInformation))
5514 return indicatePessimisticFixpoint();
5515 return ChangeStatus::UNCHANGED;
5516 }
5517};
5518
5519struct AANoReturnFunction final : AANoReturnImpl {
5520 AANoReturnFunction(const IRPosition &IRP, Attributor &A)
5521 : AANoReturnImpl(IRP, A) {}
5522
5523 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
5524};
5525
5526/// NoReturn attribute deduction for a call sites.
5527struct AANoReturnCallSite final
5528 : AACalleeToCallSite<AANoReturn, AANoReturnImpl> {
5529 AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
5530 : AACalleeToCallSite<AANoReturn, AANoReturnImpl>(IRP, A) {}
5531
5532 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
5533};
5534} // namespace
5535
5536/// ----------------------- Instance Info ---------------------------------
5537
5538namespace {
5539/// A class to hold the state of for no-capture attributes.
5540struct AAInstanceInfoImpl : public AAInstanceInfo {
5541 AAInstanceInfoImpl(const IRPosition &IRP, Attributor &A)
5542 : AAInstanceInfo(IRP, A) {}
5543
5544 void initialize(Attributor &A) override {
5545 Value &V = getAssociatedValue();
5546 if (auto *C = dyn_cast<Constant>(&V)) {
5547 if (C->isThreadDependent())
5548 indicatePessimisticFixpoint();
5549 else
5550 indicateOptimisticFixpoint();
5551 return;
5552 }
5553 if (auto *CB = dyn_cast<CallBase>(&V))
5554 if (CB->arg_size() == 0 && !CB->mayHaveSideEffects() &&
5555 !CB->mayReadFromMemory()) {
5556 indicateOptimisticFixpoint();
5557 return;
5558 }
5559 if (auto *I = dyn_cast<Instruction>(&V)) {
5560 const auto *CI =
5561 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
5562 *I->getFunction());
5563 if (mayBeInCycle(CI, I, /* HeaderOnly */ false)) {
5564 indicatePessimisticFixpoint();
5565 return;
5566 }
5567 }
5568 }
5569
5570 ChangeStatus updateImpl(Attributor &A) override {
5571 ChangeStatus Changed = ChangeStatus::UNCHANGED;
5572
5573 Value &V = getAssociatedValue();
5574 const Function *Scope = nullptr;
5575 if (auto *I = dyn_cast<Instruction>(&V))
5576 Scope = I->getFunction();
5577 if (auto *A = dyn_cast<Argument>(&V)) {
5578 Scope = A->getParent();
5579 if (!Scope->hasLocalLinkage())
5580 return Changed;
5581 }
5582 if (!Scope)
5583 return indicateOptimisticFixpoint();
5584
5585 bool IsKnownNoRecurse;
5587 A, this, IRPosition::function(*Scope), DepClassTy::OPTIONAL,
5588 IsKnownNoRecurse))
5589 return Changed;
5590
5591 auto UsePred = [&](const Use &U, bool &Follow) {
5592 const Instruction *UserI = dyn_cast<Instruction>(U.getUser());
5593 if (!UserI || isa<GetElementPtrInst>(UserI) || isa<CastInst>(UserI) ||
5594 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
5595 Follow = true;
5596 return true;
5597 }
5598 if (isa<LoadInst>(UserI) || isa<CmpInst>(UserI) ||
5599 (isa<StoreInst>(UserI) &&
5600 cast<StoreInst>(UserI)->getValueOperand() != U.get()))
5601 return true;
5602 if (auto *CB = dyn_cast<CallBase>(UserI)) {
5603 // This check is not guaranteeing uniqueness but for now that we cannot
5604 // end up with two versions of \p U thinking it was one.
5606 if (!Callee || !Callee->hasLocalLinkage())
5607 return true;
5608 if (!CB->isArgOperand(&U))
5609 return false;
5610 const auto *ArgInstanceInfoAA = A.getAAFor<AAInstanceInfo>(
5612 DepClassTy::OPTIONAL);
5613 if (!ArgInstanceInfoAA ||
5614 !ArgInstanceInfoAA->isAssumedUniqueForAnalysis())
5615 return false;
5616 // If this call base might reach the scope again we might forward the
5617 // argument back here. This is very conservative.
5619 A, *CB, *Scope, *this, /* ExclusionSet */ nullptr,
5620 [Scope](const Function &Fn) { return &Fn != Scope; }))
5621 return false;
5622 return true;
5623 }
5624 return false;
5625 };
5626
5627 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
5628 if (auto *SI = dyn_cast<StoreInst>(OldU.getUser())) {
5629 auto *Ptr = SI->getPointerOperand()->stripPointerCasts();
5630 if ((isa<AllocaInst>(Ptr) || isNoAliasCall(Ptr)) &&
5631 AA::isDynamicallyUnique(A, *this, *Ptr))
5632 return true;
5633 }
5634 return false;
5635 };
5636
5637 if (!A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ true,
5638 DepClassTy::OPTIONAL,
5639 /* IgnoreDroppableUses */ true, EquivalentUseCB))
5640 return indicatePessimisticFixpoint();
5641
5642 return Changed;
5643 }
5644
5645 const std::string getAsStr(Attributor *A) const override {
5646 return isAssumedUniqueForAnalysis() ? "<unique [fAa]>" : "<unknown>";
5647 }
5648
5649 void trackStatistics() const override {}
5650};
5651
5652/// InstanceInfo attribute for floating values.
5653struct AAInstanceInfoFloating : AAInstanceInfoImpl {
5654 AAInstanceInfoFloating(const IRPosition &IRP, Attributor &A)
5655 : AAInstanceInfoImpl(IRP, A) {}
5656};
5657
5658/// NoCapture attribute for function arguments.
5659struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
5660 AAInstanceInfoArgument(const IRPosition &IRP, Attributor &A)
5661 : AAInstanceInfoFloating(IRP, A) {}
5662};
5663
5664/// InstanceInfo attribute for call site arguments.
5665struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
5666 AAInstanceInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
5667 : AAInstanceInfoImpl(IRP, A) {}
5668
5669 ChangeStatus updateImpl(Attributor &A) override {
5670 // TODO: Once we have call site specific value information we can provide
5671 // call site specific liveness information and then it makes
5672 // sense to specialize attributes for call sites arguments instead of
5673 // redirecting requests to the callee argument.
5674 Argument *Arg = getAssociatedArgument();
5675 if (!Arg)
5676 return indicatePessimisticFixpoint();
5677 const IRPosition &ArgPos = IRPosition::argument(*Arg);
5678 auto *ArgAA =
5679 A.getAAFor<AAInstanceInfo>(*this, ArgPos, DepClassTy::REQUIRED);
5680 if (!ArgAA)
5681 return indicatePessimisticFixpoint();
5682 return clampStateAndIndicateChange(getState(), ArgAA->getState());
5683 }
5684};
5685
5686/// InstanceInfo attribute for function return value.
5687struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
5688 AAInstanceInfoReturned(const IRPosition &IRP, Attributor &A)
5689 : AAInstanceInfoImpl(IRP, A) {
5690 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5691 }
5692
5693 void initialize(Attributor &A) override {
5694 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5695 }
5696
5697 ChangeStatus updateImpl(Attributor &A) override {
5698 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5699 }
5700};
5701
5702/// InstanceInfo attribute deduction for a call site return value.
5703struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
5704 AAInstanceInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
5705 : AAInstanceInfoFloating(IRP, A) {}
5706};
5707} // namespace
5708
5709/// ----------------------- Variable Capturing ---------------------------------
5711 Attribute::AttrKind ImpliedAttributeKind,
5712 bool IgnoreSubsumingPositions) {
5713 assert(ImpliedAttributeKind == Attribute::Captures &&
5714 "Unexpected attribute kind");
5715 Value &V = IRP.getAssociatedValue();
5716 if (!isa<Constant>(V) && !IRP.isArgumentPosition())
5717 return V.use_empty();
5718
5719 // You cannot "capture" null if it is not a valid pointer.
5720 if (isa<UndefValue>(V) ||
5724 return true;
5725 }
5726
5728 A.getAttrs(IRP, {Attribute::Captures}, Attrs,
5729 /* IgnoreSubsumingPositions */ true);
5730 for (const Attribute &Attr : Attrs)
5731 if (capturesNothing(Attr.getCaptureInfo()))
5732 return true;
5733
5735 if (Argument *Arg = IRP.getAssociatedArgument()) {
5737 A.getAttrs(IRPosition::argument(*Arg),
5738 {Attribute::Captures, Attribute::ByVal}, Attrs,
5739 /* IgnoreSubsumingPositions */ true);
5740 bool ArgNoCapture = any_of(Attrs, [](Attribute Attr) {
5741 return Attr.getKindAsEnum() == Attribute::ByVal ||
5743 });
5744 if (ArgNoCapture) {
5745 A.manifestAttrs(IRP, Attribute::getWithCaptureInfo(
5746 V.getContext(), CaptureInfo::none()));
5747 return true;
5748 }
5749 }
5750
5751 if (const Function *F = IRP.getAssociatedFunction()) {
5752 // Check what state the associated function can actually capture.
5755 if (State.isKnown(NO_CAPTURE)) {
5756 A.manifestAttrs(IRP, Attribute::getWithCaptureInfo(V.getContext(),
5758 return true;
5759 }
5760 }
5761
5762 return false;
5763}
5764
5765/// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
5766/// depending on the ability of the function associated with \p IRP to capture
5767/// state in memory and through "returning/throwing", respectively.
5769 const Function &F,
5770 BitIntegerState &State) {
5771 // TODO: Once we have memory behavior attributes we should use them here.
5772
5773 // If we know we cannot communicate or write to memory, we do not care about
5774 // ptr2int anymore. The value can still be captured by whether the function
5775 // returns.
5776 bool ReadOnly = F.onlyReadsMemory();
5777 bool NoThrow = F.doesNotThrow();
5778 bool WillReturn = F.willReturn();
5779 bool IsVoidReturn = F.getReturnType()->isVoidTy();
5780 if (ReadOnly && NoThrow && WillReturn && IsVoidReturn) {
5781 State.addKnownBits(NO_CAPTURE);
5782 return;
5783 }
5784
5785 // A function cannot capture state in memory if it only reads memory, it can
5786 // however return/throw state and the state might be influenced by the
5787 // pointer value, e.g., loading from a returned pointer might reveal a bit.
5788 if (ReadOnly)
5789 State.addKnownBits(NOT_CAPTURED_IN_MEM);
5790
5791 // A function cannot communicate state back if it does not through
5792 // exceptions and doesn not return values.
5793 if (NoThrow && IsVoidReturn)
5794 State.addKnownBits(NOT_CAPTURED_IN_RET);
5795
5796 // Check existing "returned" attributes.
5797 int ArgNo = IRP.getCalleeArgNo();
5798 if (!NoThrow || ArgNo < 0 ||
5799 !F.getAttributes().hasAttrSomewhere(Attribute::Returned))
5800 return;
5801
5802 for (unsigned U = 0, E = F.arg_size(); U < E; ++U)
5803 if (F.hasParamAttribute(U, Attribute::Returned)) {
5804 if (U == unsigned(ArgNo))
5805 State.removeAssumedBits(NOT_CAPTURED_IN_RET);
5806 else if (ReadOnly && WillReturn)
5807 State.addKnownBits(NO_CAPTURE);
5808 else
5809 State.addKnownBits(NOT_CAPTURED_IN_RET);
5810 break;
5811 }
5812}
5813
5814namespace {
5815/// A class to hold the state of for no-capture attributes.
5816struct AANoCaptureImpl : public AANoCapture {
5817 AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
5818
5819 void initialize(Attributor &A) override {
5820 bool IsKnown;
5822 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5823 (void)IsKnown;
5824 }
5825
5826 ChangeStatus updateImpl(Attributor &A) override;
5827
5828 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
5829 SmallVectorImpl<Attribute> &Attrs) const override {
5830 if (!isAssumedNoCaptureMaybeReturned())
5831 return;
5832
5833 if (isArgumentPosition()) {
5834 if (isAssumedNoCapture())
5835 Attrs.emplace_back(Attribute::get(Ctx, Attribute::Captures));
5836 else if (A.Opts.attributor_manifest_internal)
5837 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
5838 }
5839 }
5840
5841 const std::string getAsStr(Attributor *A) const override {
5842 if (isKnownNoCapture())
5843 return "known not-captured";
5844 if (isAssumedNoCapture())
5845 return "assumed not-captured";
5846 if (isKnownNoCaptureMaybeReturned())
5847 return "known not-captured-maybe-returned";
5848 if (isAssumedNoCaptureMaybeReturned())
5849 return "assumed not-captured-maybe-returned";
5850 return "assumed-captured";
5851 }
5852
5853 /// Check the use \p U and update \p State accordingly. Return true if we
5854 /// should continue to update the state.
5855 bool checkUse(Attributor &A, AANoCapture::StateType &State, const Use &U,
5856 bool &Follow) {
5857 Instruction *UInst = cast<Instruction>(U.getUser());
5858 LLVM_DEBUG(dbgs() << "[AANoCapture] Check use: " << *U.get() << " in "
5859 << *UInst << "\n");
5860
5861 // Deal with ptr2int by following uses.
5862 if (isa<PtrToIntInst>(UInst)) {
5863 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
5864 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5865 /* Return */ true);
5866 }
5867
5868 // For stores we already checked if we can follow them, if they make it
5869 // here we give up.
5870 if (isa<StoreInst>(UInst))
5871 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5872 /* Return */ true);
5873
5874 // Explicitly catch return instructions.
5875 if (isa<ReturnInst>(UInst)) {
5876 if (UInst->getFunction() == getAnchorScope())
5877 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5878 /* Return */ true);
5879 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5880 /* Return */ true);
5881 }
5882
5883 // For now we only use special logic for call sites. However, the tracker
5884 // itself knows about a lot of other non-capturing cases already.
5885 auto *CB = dyn_cast<CallBase>(UInst);
5886 if (!CB || !CB->isArgOperand(&U))
5887 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5888 /* Return */ true);
5889
5890 unsigned ArgNo = CB->getArgOperandNo(&U);
5891 const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
5892 // If we have a abstract no-capture attribute for the argument we can use
5893 // it to justify a non-capture attribute here. This allows recursion!
5894 bool IsKnownNoCapture;
5895 const AANoCapture *ArgNoCaptureAA = nullptr;
5896 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
5897 A, this, CSArgPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
5898 &ArgNoCaptureAA);
5899 if (IsAssumedNoCapture)
5900 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5901 /* Return */ false);
5902 if (ArgNoCaptureAA && ArgNoCaptureAA->isAssumedNoCaptureMaybeReturned()) {
5903 Follow = true;
5904 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5905 /* Return */ false);
5906 }
5907
5908 // Lastly, we could not find a reason no-capture can be assumed so we don't.
5909 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5910 /* Return */ true);
5911 }
5912
5913 /// Update \p State according to \p CapturedInMem, \p CapturedInInt, and
5914 /// \p CapturedInRet, then return true if we should continue updating the
5915 /// state.
5916 static bool isCapturedIn(AANoCapture::StateType &State, bool CapturedInMem,
5917 bool CapturedInInt, bool CapturedInRet) {
5918 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
5919 << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
5920 if (CapturedInMem)
5921 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
5922 if (CapturedInInt)
5923 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
5924 if (CapturedInRet)
5925 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
5926 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
5927 }
5928};
5929
5930ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
5931 const IRPosition &IRP = getIRPosition();
5932 Value *V = isArgumentPosition() ? IRP.getAssociatedArgument()
5933 : &IRP.getAssociatedValue();
5934 if (!V)
5935 return indicatePessimisticFixpoint();
5936
5937 const Function *F =
5938 isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
5939
5940 // TODO: Is the checkForAllUses below useful for constants?
5941 if (!F)
5942 return indicatePessimisticFixpoint();
5943
5945 const IRPosition &FnPos = IRPosition::function(*F);
5946
5947 // Readonly means we cannot capture through memory.
5948 bool IsKnown;
5949 if (AA::isAssumedReadOnly(A, FnPos, *this, IsKnown)) {
5950 T.addKnownBits(NOT_CAPTURED_IN_MEM);
5951 if (IsKnown)
5952 addKnownBits(NOT_CAPTURED_IN_MEM);
5953 }
5954
5955 // Make sure all returned values are different than the underlying value.
5956 // TODO: we could do this in a more sophisticated way inside
5957 // AAReturnedValues, e.g., track all values that escape through returns
5958 // directly somehow.
5959 auto CheckReturnedArgs = [&](bool &UsedAssumedInformation) {
5961 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*F), this, Values,
5963 UsedAssumedInformation))
5964 return false;
5965 bool SeenConstant = false;
5966 for (const AA::ValueAndContext &VAC : Values) {
5967 if (isa<Constant>(VAC.getValue())) {
5968 if (SeenConstant)
5969 return false;
5970 SeenConstant = true;
5971 } else if (!isa<Argument>(VAC.getValue()) ||
5972 VAC.getValue() == getAssociatedArgument())
5973 return false;
5974 }
5975 return true;
5976 };
5977
5978 bool IsKnownNoUnwind;
5980 A, this, FnPos, DepClassTy::OPTIONAL, IsKnownNoUnwind)) {
5981 bool IsVoidTy = F->getReturnType()->isVoidTy();
5982 bool UsedAssumedInformation = false;
5983 if (IsVoidTy || CheckReturnedArgs(UsedAssumedInformation)) {
5984 T.addKnownBits(NOT_CAPTURED_IN_RET);
5985 // If the function only reads memory and does not return the value, the
5986 // value can still be captured by whether the function returns.
5987 bool IsKnownWillReturn;
5988 bool IsAssumedWillReturn = AA::hasAssumedIRAttr<Attribute::WillReturn>(
5989 A, this, FnPos, DepClassTy::OPTIONAL, IsKnownWillReturn);
5990 if (IsAssumedWillReturn && T.isKnown(NOT_CAPTURED_IN_MEM))
5992 if (IsKnownNoUnwind && (IsVoidTy || !UsedAssumedInformation)) {
5993 addKnownBits(NOT_CAPTURED_IN_RET);
5994 if (IsKnownWillReturn && isKnown(NOT_CAPTURED_IN_MEM))
5995 return indicateOptimisticFixpoint();
5996 }
5997 }
5998 }
5999
6000 auto UseCheck = [&](const Use &U, bool &Follow) -> bool {
6001 // TODO(captures): Make this more precise.
6002 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
6003 if (capturesNothing(CI))
6004 return true;
6005 if (CI.isPassthrough()) {
6006 Follow = true;
6007 return true;
6008 }
6009 return checkUse(A, T, U, Follow);
6010 };
6011
6012 if (!A.checkForAllUses(UseCheck, *this, *V))
6013 return indicatePessimisticFixpoint();
6014
6015 AANoCapture::StateType &S = getState();
6016 auto Assumed = S.getAssumed();
6017 S.intersectAssumedBits(T.getAssumed());
6018 if (!isAssumedNoCaptureMaybeReturned())
6019 return indicatePessimisticFixpoint();
6020 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
6022}
6023
6024/// NoCapture attribute for function arguments.
6025struct AANoCaptureArgument final : AANoCaptureImpl {
6026 AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
6027 : AANoCaptureImpl(IRP, A) {}
6028
6029 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
6030};
6031
6032/// NoCapture attribute for call site arguments.
6033struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
6034 AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
6035 : AANoCaptureImpl(IRP, A) {}
6036
6037 ChangeStatus updateImpl(Attributor &A) override {
6038 // TODO: Once we have call site specific value information we can provide
6039 // call site specific liveness information and then it makes
6040 // sense to specialize attributes for call sites arguments instead of
6041 // redirecting requests to the callee argument.
6042 Argument *Arg = getAssociatedArgument();
6043 if (!Arg)
6044 return indicatePessimisticFixpoint();
6045 const IRPosition &ArgPos = IRPosition::argument(*Arg);
6046 bool IsKnownNoCapture;
6047 const AANoCapture *ArgAA = nullptr;
6049 A, this, ArgPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
6050 &ArgAA))
6051 return ChangeStatus::UNCHANGED;
6052 if (!ArgAA || !ArgAA->isAssumedNoCaptureMaybeReturned())
6053 return indicatePessimisticFixpoint();
6054 return clampStateAndIndicateChange(getState(), ArgAA->getState());
6055 }
6056
6057 void trackStatistics() const override {
6059 };
6060};
6061
6062/// NoCapture attribute for floating values.
6063struct AANoCaptureFloating final : AANoCaptureImpl {
6064 AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
6065 : AANoCaptureImpl(IRP, A) {}
6066
6067 void trackStatistics() const override {
6069 }
6070};
6071
6072/// NoCapture attribute for function return value.
6073struct AANoCaptureReturned final : AANoCaptureImpl {
6074 AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
6075 : AANoCaptureImpl(IRP, A) {
6076 llvm_unreachable("NoCapture is not applicable to function returns!");
6077 }
6078
6079 void initialize(Attributor &A) override {
6080 llvm_unreachable("NoCapture is not applicable to function returns!");
6081 }
6082
6083 ChangeStatus updateImpl(Attributor &A) override {
6084 llvm_unreachable("NoCapture is not applicable to function returns!");
6085 }
6086
6087 void trackStatistics() const override {}
6088};
6089
6090/// NoCapture attribute deduction for a call site return value.
6091struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
6092 AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
6093 : AANoCaptureImpl(IRP, A) {}
6094
6095 void initialize(Attributor &A) override {
6096 const Function *F = getAnchorScope();
6097 // Check what state the associated function can actually capture.
6098 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
6099 }
6100
6101 void trackStatistics() const override {
6103 }
6104};
6105} // namespace
6106
6107/// ------------------ Value Simplify Attribute ----------------------------
6108
6109bool ValueSimplifyStateType::unionAssumed(std::optional<Value *> Other) {
6110 // FIXME: Add a typecast support.
6113 if (SimplifiedAssociatedValue == std::optional<Value *>(nullptr))
6114 return false;
6115
6116 LLVM_DEBUG({
6118 dbgs() << "[ValueSimplify] is assumed to be "
6119 << **SimplifiedAssociatedValue << "\n";
6120 else
6121 dbgs() << "[ValueSimplify] is assumed to be <none>\n";
6122 });
6123 return true;
6124}
6125
6126namespace {
6127struct AAValueSimplifyImpl : AAValueSimplify {
6128 AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
6129 : AAValueSimplify(IRP, A) {}
6130
6131 void initialize(Attributor &A) override {
6132 if (getAssociatedValue().getType()->isVoidTy())
6133 indicatePessimisticFixpoint();
6134 if (A.hasSimplificationCallback(getIRPosition()))
6135 indicatePessimisticFixpoint();
6136 }
6137
6138 const std::string getAsStr(Attributor *A) const override {
6139 LLVM_DEBUG({
6140 dbgs() << "SAV: " << (bool)SimplifiedAssociatedValue << " ";
6141 if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
6142 dbgs() << "SAV: " << **SimplifiedAssociatedValue << " ";
6143 });
6144 return isValidState() ? (isAtFixpoint() ? "simplified" : "maybe-simple")
6145 : "not-simple";
6146 }
6147
6148 void trackStatistics() const override {}
6149
6150 std::optional<Value *>
6151 getAssumedSimplifiedValue(Attributor &A) const override {
6152 return SimplifiedAssociatedValue;
6153 }
6154
6155 /// Ensure the return value is \p V with type \p Ty, if not possible return
6156 /// nullptr. If \p Check is true we will only verify such an operation would
6157 /// suceed and return a non-nullptr value if that is the case. No IR is
6158 /// generated or modified.
6159 static Value *ensureType(Attributor &A, Value &V, Type &Ty, Instruction *CtxI,
6160 bool Check) {
6161 if (auto *TypedV = AA::getWithType(V, Ty))
6162 return TypedV;
6163 if (CtxI && V.getType()->canLosslesslyBitCastTo(&Ty))
6164 return Check ? &V
6165 : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6166 &V, &Ty, "", CtxI->getIterator());
6167 return nullptr;
6168 }
6169
6170 /// Reproduce \p I with type \p Ty or return nullptr if that is not posisble.
6171 /// If \p Check is true we will only verify such an operation would suceed and
6172 /// return a non-nullptr value if that is the case. No IR is generated or
6173 /// modified.
6174 static Value *reproduceInst(Attributor &A,
6175 const AbstractAttribute &QueryingAA,
6176 Instruction &I, Type &Ty, Instruction *CtxI,
6177 bool Check, ValueToValueMapTy &VMap) {
6178 assert(CtxI && "Cannot reproduce an instruction without context!");
6179 if (Check && (I.mayReadFromMemory() ||
6180 !isSafeToSpeculativelyExecute(&I, CtxI, /* DT */ nullptr,
6181 /* TLI */ nullptr)))
6182 return nullptr;
6183 for (Value *Op : I.operands()) {
6184 Value *NewOp = reproduceValue(A, QueryingAA, *Op, Ty, CtxI, Check, VMap);
6185 if (!NewOp) {
6186 assert(Check && "Manifest of new value unexpectedly failed!");
6187 return nullptr;
6188 }
6189 if (!Check)
6190 VMap[Op] = NewOp;
6191 }
6192 if (Check)
6193 return &I;
6194
6195 Instruction *CloneI = I.clone();
6196 // TODO: Try to salvage debug information here.
6197 CloneI->setDebugLoc(DebugLoc());
6198 VMap[&I] = CloneI;
6199 CloneI->insertBefore(CtxI->getIterator());
6200 RemapInstruction(CloneI, VMap);
6201 return CloneI;
6202 }
6203
6204 /// Reproduce \p V with type \p Ty or return nullptr if that is not posisble.
6205 /// If \p Check is true we will only verify such an operation would suceed and
6206 /// return a non-nullptr value if that is the case. No IR is generated or
6207 /// modified.
6208 static Value *reproduceValue(Attributor &A,
6209 const AbstractAttribute &QueryingAA, Value &V,
6210 Type &Ty, Instruction *CtxI, bool Check,
6211 ValueToValueMapTy &VMap) {
6212 if (const auto &NewV = VMap.lookup(&V))
6213 return NewV;
6214 bool UsedAssumedInformation = false;
6215 std::optional<Value *> SimpleV = A.getAssumedSimplified(
6216 V, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
6217 if (!SimpleV.has_value())
6218 return PoisonValue::get(&Ty);
6219 Value *EffectiveV = &V;
6220 if (*SimpleV)
6221 EffectiveV = *SimpleV;
6222 if (auto *C = dyn_cast<Constant>(EffectiveV))
6223 return C;
6224 if (CtxI && AA::isValidAtPosition(AA::ValueAndContext(*EffectiveV, *CtxI),
6225 A.getInfoCache()))
6226 return ensureType(A, *EffectiveV, Ty, CtxI, Check);
6227 if (auto *I = dyn_cast<Instruction>(EffectiveV))
6228 if (Value *NewV = reproduceInst(A, QueryingAA, *I, Ty, CtxI, Check, VMap))
6229 return ensureType(A, *NewV, Ty, CtxI, Check);
6230 return nullptr;
6231 }
6232
6233 /// Return a value we can use as replacement for the associated one, or
6234 /// nullptr if we don't have one that makes sense.
6235 Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const {
6236 Value *NewV = SimplifiedAssociatedValue
6237 ? *SimplifiedAssociatedValue
6238 : UndefValue::get(getAssociatedType());
6239 if (NewV && NewV != &getAssociatedValue()) {
6240 ValueToValueMapTy VMap;
6241 // First verify we can reprduce the value with the required type at the
6242 // context location before we actually start modifying the IR.
6243 if (reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
6244 /* CheckOnly */ true, VMap))
6245 return reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
6246 /* CheckOnly */ false, VMap);
6247 }
6248 return nullptr;
6249 }
6250
6251 /// Helper function for querying AAValueSimplify and updating candidate.
6252 /// \param IRP The value position we are trying to unify with SimplifiedValue
6253 bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
6254 const IRPosition &IRP, bool Simplify = true) {
6255 bool UsedAssumedInformation = false;
6256 std::optional<Value *> QueryingValueSimplified = &IRP.getAssociatedValue();
6257 if (Simplify)
6258 QueryingValueSimplified = A.getAssumedSimplified(
6259 IRP, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
6260 return unionAssumed(QueryingValueSimplified);
6261 }
6262
6263 /// Returns a candidate is found or not
6264 template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
6265 if (!getAssociatedValue().getType()->isIntegerTy())
6266 return false;
6267
6268 // This will also pass the call base context.
6269 const auto *AA =
6270 A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE);
6271 if (!AA)
6272 return false;
6273
6274 std::optional<Constant *> COpt = AA->getAssumedConstant(A);
6275
6276 if (!COpt) {
6277 SimplifiedAssociatedValue = std::nullopt;
6278 A.recordDependence(*AA, *this, DepClassTy::OPTIONAL);
6279 return true;
6280 }
6281 if (auto *C = *COpt) {
6282 SimplifiedAssociatedValue = C;
6283 A.recordDependence(*AA, *this, DepClassTy::OPTIONAL);
6284 return true;
6285 }
6286 return false;
6287 }
6288
6289 bool askSimplifiedValueForOtherAAs(Attributor &A) {
6290 if (askSimplifiedValueFor<AAValueConstantRange>(A))
6291 return true;
6292 if (askSimplifiedValueFor<AAPotentialConstantValues>(A))
6293 return true;
6294 return false;
6295 }
6296
6297 ChangeStatus manifest(Attributor &A) override {
6298 ChangeStatus Changed = ChangeStatus::UNCHANGED;
6299 for (auto &U : getAssociatedValue().uses()) {
6300 // Check if we need to adjust the insertion point to make sure the IR is
6301 // valid.
6302 Instruction *IP = dyn_cast<Instruction>(U.getUser());
6303 if (auto *PHI = dyn_cast_or_null<PHINode>(IP))
6304 IP = PHI->getIncomingBlock(U)->getTerminator();
6305 if (auto *NewV = manifestReplacementValue(A, IP)) {
6306 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue()
6307 << " -> " << *NewV << " :: " << *this << "\n");
6308 if (A.changeUseAfterManifest(U, *NewV))
6309 Changed = ChangeStatus::CHANGED;
6310 }
6311 }
6312
6313 return Changed | AAValueSimplify::manifest(A);
6314 }
6315
6316 ChangeStatus indicatePessimisticFixpoint() override {
6317 SimplifiedAssociatedValue = &getAssociatedValue();
6318 return AAValueSimplify::indicatePessimisticFixpoint();
6319 }
6320};
6321
6322struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
6323 AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
6324 : AAValueSimplifyImpl(IRP, A) {}
6325
6326 void initialize(Attributor &A) override {
6327 AAValueSimplifyImpl::initialize(A);
6328 if (A.hasAttr(getIRPosition(),
6329 {Attribute::InAlloca, Attribute::Preallocated,
6330 Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
6331 /* IgnoreSubsumingPositions */ true))
6332 indicatePessimisticFixpoint();
6333 }
6334
6335 ChangeStatus updateImpl(Attributor &A) override {
6336 // Byval is only replacable if it is readonly otherwise we would write into
6337 // the replaced value and not the copy that byval creates implicitly.
6338 Argument *Arg = getAssociatedArgument();
6339 if (Arg->hasByValAttr()) {
6340 // TODO: We probably need to verify synchronization is not an issue, e.g.,
6341 // there is no race by not copying a constant byval.
6342 bool IsKnown;
6343 if (!AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
6344 return indicatePessimisticFixpoint();
6345 }
6346
6347 auto Before = SimplifiedAssociatedValue;
6348
6349 auto PredForCallSite = [&](AbstractCallSite ACS) {
6350 const IRPosition &ACSArgPos =
6351 IRPosition::callsite_argument(ACS, getCallSiteArgNo());
6352 // Check if a coresponding argument was found or if it is on not
6353 // associated (which can happen for callback calls).
6354 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
6355 return false;
6356
6357 // Simplify the argument operand explicitly and check if the result is
6358 // valid in the current scope. This avoids refering to simplified values
6359 // in other functions, e.g., we don't want to say a an argument in a
6360 // static function is actually an argument in a different function.
6361 bool UsedAssumedInformation = false;
6362 std::optional<Constant *> SimpleArgOp =
6363 A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation);
6364 if (!SimpleArgOp)
6365 return true;
6366 if (!*SimpleArgOp)
6367 return false;
6368 if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp))
6369 return false;
6370 return unionAssumed(*SimpleArgOp);
6371 };
6372
6373 // Generate a answer specific to a call site context.
6374 bool Success;
6375 bool UsedAssumedInformation = false;
6376 if (hasCallBaseContext() &&
6377 getCallBaseContext()->getCalledOperand() == Arg->getParent())
6378 Success = PredForCallSite(
6379 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
6380 else
6381 Success = A.checkForAllCallSites(PredForCallSite, *this, true,
6382 UsedAssumedInformation);
6383
6384 if (!Success)
6385 if (!askSimplifiedValueForOtherAAs(A))
6386 return indicatePessimisticFixpoint();
6387
6388 // If a candidate was found in this update, return CHANGED.
6389 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6390 : ChangeStatus ::CHANGED;
6391 }
6392
6393 void trackStatistics() const override {
6394 STATS_DECLTRACK_ARG_ATTR(value_simplify)
6395 }
6396};
6397
6398struct AAValueSimplifyReturned : AAValueSimplifyImpl {
6399 AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
6400 : AAValueSimplifyImpl(IRP, A) {}
6401
6402 std::optional<Value *>
6403 getAssumedSimplifiedValue(Attributor &A) const override {
6404 if (!isValidState())
6405 return nullptr;
6406 return SimplifiedAssociatedValue;
6407 }
6408
6409 ChangeStatus updateImpl(Attributor &A) override {
6410 auto Before = SimplifiedAssociatedValue;
6411
6412 auto ReturnInstCB = [&](Instruction &I) {
6413 auto &RI = cast<ReturnInst>(I);
6414 return checkAndUpdate(
6415 A, *this,
6416 IRPosition::value(*RI.getReturnValue(), getCallBaseContext()));
6417 };
6418
6419 bool UsedAssumedInformation = false;
6420 if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
6421 UsedAssumedInformation))
6422 if (!askSimplifiedValueForOtherAAs(A))
6423 return indicatePessimisticFixpoint();
6424
6425 // If a candidate was found in this update, return CHANGED.
6426 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6427 : ChangeStatus ::CHANGED;
6428 }
6429
6430 ChangeStatus manifest(Attributor &A) override {
6431 // We queried AAValueSimplify for the returned values so they will be
6432 // replaced if a simplified form was found. Nothing to do here.
6433 return ChangeStatus::UNCHANGED;
6434 }
6435
6436 void trackStatistics() const override {
6437 STATS_DECLTRACK_FNRET_ATTR(value_simplify)
6438 }
6439};
6440
6441struct AAValueSimplifyFloating : AAValueSimplifyImpl {
6442 AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
6443 : AAValueSimplifyImpl(IRP, A) {}
6444
6445 void initialize(Attributor &A) override {
6446 AAValueSimplifyImpl::initialize(A);
6447 Value &V = getAnchorValue();
6448
6449 // TODO: add other stuffs
6450 if (isa<Constant>(V))
6451 indicatePessimisticFixpoint();
6452 }
6453
6454 ChangeStatus updateImpl(Attributor &A) override {
6455 auto Before = SimplifiedAssociatedValue;
6456 if (!askSimplifiedValueForOtherAAs(A))
6457 return indicatePessimisticFixpoint();
6458
6459 // If a candidate was found in this update, return CHANGED.
6460 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6461 : ChangeStatus ::CHANGED;
6462 }
6463
6464 void trackStatistics() const override {
6465 STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
6466 }
6467};
6468
6469struct AAValueSimplifyFunction : AAValueSimplifyImpl {
6470 AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
6471 : AAValueSimplifyImpl(IRP, A) {}
6472
6473 void initialize(Attributor &A) override {
6474 SimplifiedAssociatedValue = nullptr;
6475 indicateOptimisticFixpoint();
6476 }
6477 ChangeStatus updateImpl(Attributor &A) override {
6479 "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
6480 }
6481 void trackStatistics() const override {
6482 STATS_DECLTRACK_FN_ATTR(value_simplify)
6483 }
6484};
6485
6486struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
6487 AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
6488 : AAValueSimplifyFunction(IRP, A) {}
6489 void trackStatistics() const override {
6490 STATS_DECLTRACK_CS_ATTR(value_simplify)
6491 }
6492};
6493
6494struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
6495 AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
6496 : AAValueSimplifyImpl(IRP, A) {}
6497
6498 void initialize(Attributor &A) override {
6499 AAValueSimplifyImpl::initialize(A);
6500 Function *Fn = getAssociatedFunction();
6501 assert(Fn && "Did expect an associted function");
6502 for (Argument &Arg : Fn->args()) {
6503 if (Arg.hasReturnedAttr()) {
6504 auto IRP = IRPosition::callsite_argument(*cast<CallBase>(getCtxI()),
6505 Arg.getArgNo());
6507 checkAndUpdate(A, *this, IRP))
6508 indicateOptimisticFixpoint();
6509 else
6510 indicatePessimisticFixpoint();
6511 return;
6512 }
6513 }
6514 }
6515
6516 ChangeStatus updateImpl(Attributor &A) override {
6517 return indicatePessimisticFixpoint();
6518 }
6519
6520 void trackStatistics() const override {
6521 STATS_DECLTRACK_CSRET_ATTR(value_simplify)
6522 }
6523};
6524
6525struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
6526 AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
6527 : AAValueSimplifyFloating(IRP, A) {}
6528
6529 ChangeStatus manifest(Attributor &A) override {
6530 ChangeStatus Changed = ChangeStatus::UNCHANGED;
6531 // TODO: We should avoid simplification duplication to begin with.
6532 auto *FloatAA = A.lookupAAFor<AAValueSimplify>(
6533 IRPosition::value(getAssociatedValue()), this, DepClassTy::NONE);
6534 if (FloatAA && FloatAA->getState().isValidState())
6535 return Changed;
6536
6537 if (auto *NewV = manifestReplacementValue(A, getCtxI())) {
6538 Use &U = cast<CallBase>(&getAnchorValue())
6539 ->getArgOperandUse(getCallSiteArgNo());
6540 if (A.changeUseAfterManifest(U, *NewV))
6541 Changed = ChangeStatus::CHANGED;
6542 }
6543
6544 return Changed | AAValueSimplify::manifest(A);
6545 }
6546
6547 void trackStatistics() const override {
6548 STATS_DECLTRACK_CSARG_ATTR(value_simplify)
6549 }
6550};
6551} // namespace
6552
6553/// Collect the non-musttail tail calls in the function of \p QueryingAA. Tail
6554/// calls cannot access allocas of the caller.
6555/// TODO: Be smarter about new allocas escaping into tail calls.
6556static bool collectTailCalls(Attributor &A, const AbstractAttribute &QueryingAA,
6557 SmallVectorImpl<CallInst *> &TailCalls) {
6558 bool UsedAssumedInformation = false;
6559 return A.checkForAllInstructions(
6560 [&](Instruction &I) {
6561 auto &CI = cast<CallInst>(I);
6562 if (CI.isTailCall() && !CI.isMustTailCall())
6563 TailCalls.push_back(&CI);
6564 return true;
6565 },
6566 QueryingAA, {Instruction::Call}, UsedAssumedInformation);
6567}
6568
6569/// ----------------------- Heap-To-Stack Conversion ---------------------------
6570namespace {
6571struct AAHeapToStackFunction final : public AAHeapToStack {
6572
6573 static bool isGlobalizedLocal(const CallBase &CB) {
6574 Attribute A = CB.getFnAttr("alloc-family");
6575 return A.isValid() && A.getValueAsString() == "__kmpc_alloc_shared";
6576 }
6577
6578 struct AllocationInfo {
6579 /// The call that allocates the memory.
6580 CallBase *const CB;
6581
6582 /// Whether this allocation is an OpenMP globalized local variable.
6583 bool IsGlobalizedLocal = false;
6584
6585 /// The status wrt. a rewrite.
6586 enum {
6587 STACK_DUE_TO_USE,
6588 STACK_DUE_TO_FREE,
6589 INVALID,
6590 } Status = STACK_DUE_TO_USE;
6591
6592 /// Flag to indicate if we encountered a use that might free this allocation
6593 /// but which is not in the deallocation infos.
6594 bool HasPotentiallyFreeingUnknownUses = false;
6595
6596 /// Flag to indicate that we should place the new alloca in the function
6597 /// entry block rather than where the call site (CB) is.
6598 bool MoveAllocaIntoEntry = true;
6599
6600 /// The set of free calls that use this allocation.
6601 SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
6602 };
6603
6604 struct DeallocationInfo {
6605 /// The call that deallocates the memory.
6606 CallBase *const CB;
6607 /// The value freed by the call.
6608 Value *FreedOp;
6609
6610 /// Flag to indicate if we don't know all objects this deallocation might
6611 /// free.
6612 bool MightFreeUnknownObjects = false;
6613
6614 /// The set of allocation calls that are potentially freed.
6615 SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
6616 };
6617
6618 AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
6619 : AAHeapToStack(IRP, A) {}
6620
6621 ~AAHeapToStackFunction() override {
6622 // Ensure we call the destructor so we release any memory allocated in the
6623 // sets.
6624 for (auto &It : AllocationInfos)
6625 It.second->~AllocationInfo();
6626 for (auto &It : DeallocationInfos)
6627 It.second->~DeallocationInfo();
6628 }
6629
6630 void initialize(Attributor &A) override {
6631 AAHeapToStack::initialize(A);
6632
6633 const Function *F = getAnchorScope();
6634 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6635
6636 auto AllocationIdentifierCB = [&](Instruction &I) {
6637 CallBase *CB = dyn_cast<CallBase>(&I);
6638 if (!CB)
6639 return true;
6640 if (Value *FreedOp = getFreedOperand(CB, TLI)) {
6641 DeallocationInfos[CB] = new (A.Allocator) DeallocationInfo{CB, FreedOp};
6642 return true;
6643 }
6644 // To do heap to stack, we need to know that the allocation itself is
6645 // removable once uses are rewritten, and that we can initialize the
6646 // alloca to the same pattern as the original allocation result.
6647 if (isRemovableAlloc(CB, TLI)) {
6648 auto *I8Ty = Type::getInt8Ty(CB->getParent()->getContext());
6649 if (nullptr != getInitialValueOfAllocation(CB, TLI, I8Ty)) {
6650 AllocationInfo *AI = new (A.Allocator) AllocationInfo{CB};
6651 AllocationInfos[CB] = AI;
6652 AI->IsGlobalizedLocal = isGlobalizedLocal(*CB);
6653 }
6654 }
6655 return true;
6656 };
6657
6658 bool UsedAssumedInformation = false;
6659 bool Success = A.checkForAllCallLikeInstructions(
6660 AllocationIdentifierCB, *this, UsedAssumedInformation,
6661 /* CheckBBLivenessOnly */ false,
6662 /* CheckPotentiallyDead */ true);
6663 (void)Success;
6664 assert(Success && "Did not expect the call base visit callback to fail!");
6665
6667 [](const IRPosition &, const AbstractAttribute *,
6668 bool &) -> std::optional<Value *> { return nullptr; };
6669 for (const auto &It : AllocationInfos)
6670 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6671 SCB);
6672 for (const auto &It : DeallocationInfos)
6673 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6674 SCB);
6675 }
6676
6677 const std::string getAsStr(Attributor *A) const override {
6678 unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
6679 for (const auto &It : AllocationInfos) {
6680 if (It.second->Status == AllocationInfo::INVALID)
6681 ++NumInvalidMallocs;
6682 else
6683 ++NumH2SMallocs;
6684 }
6685 return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) + "/" +
6686 std::to_string(NumInvalidMallocs);
6687 }
6688
6689 void trackStatistics() const override {
6690 STATS_DECL(
6691 MallocCalls, Function,
6692 "Number of malloc/calloc/aligned_alloc calls converted to allocas");
6693 for (const auto &It : AllocationInfos)
6694 if (It.second->Status != AllocationInfo::INVALID)
6695 ++BUILD_STAT_NAME(MallocCalls, Function);
6696 }
6697
6698 bool isAssumedHeapToStack(const CallBase &CB) const override {
6699 if (isValidState())
6700 if (AllocationInfo *AI =
6701 AllocationInfos.lookup(const_cast<CallBase *>(&CB)))
6702 return AI->Status != AllocationInfo::INVALID;
6703 return false;
6704 }
6705
6706 bool isAssumedHeapToStackRemovedFree(CallBase &CB) const override {
6707 if (!isValidState())
6708 return false;
6709
6710 for (const auto &It : AllocationInfos) {
6711 AllocationInfo &AI = *It.second;
6712 if (AI.Status == AllocationInfo::INVALID)
6713 continue;
6714
6715 if (AI.PotentialFreeCalls.count(&CB))
6716 return true;
6717 }
6718
6719 return false;
6720 }
6721
6722 ChangeStatus manifest(Attributor &A) override {
6723 assert(getState().isValidState() &&
6724 "Attempted to manifest an invalid state!");
6725
6726 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
6727 Function *F = getAnchorScope();
6728 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6729
6730 // The new allocas may escape into tail calls.
6732 if (any_of(AllocationInfos,
6733 [](const std::pair<CallBase *, AllocationInfo *> &It) {
6734 return It.second->Status != AllocationInfo::INVALID;
6735 }) &&
6736 !collectTailCalls(A, *this, TailCalls))
6737 return ChangeStatus::UNCHANGED;
6738
6739 for (auto &It : AllocationInfos) {
6740 AllocationInfo &AI = *It.second;
6741 if (AI.Status == AllocationInfo::INVALID)
6742 continue;
6743
6744 for (CallBase *FreeCall : AI.PotentialFreeCalls) {
6745 LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
6746 A.deleteAfterManifest(*FreeCall);
6747 HasChanged = ChangeStatus::CHANGED;
6748 }
6749
6750 LLVM_DEBUG(dbgs() << "H2S: Removing malloc-like call: " << *AI.CB
6751 << "\n");
6752
6753 auto Remark = [&](OptimizationRemark OR) {
6754 if (AI.IsGlobalizedLocal)
6755 return OR << "Moving globalized variable to the stack.";
6756 return OR << "Moving memory allocation from the heap to the stack.";
6757 };
6758 if (AI.IsGlobalizedLocal)
6759 A.emitRemark<OptimizationRemark>(AI.CB, "OMP110", Remark);
6760 else
6761 A.emitRemark<OptimizationRemark>(AI.CB, "HeapToStack", Remark);
6762
6763 const DataLayout &DL = A.getInfoCache().getDL();
6764 Value *Size;
6765 std::optional<APInt> SizeAPI = getSize(A, *this, AI);
6766 if (SizeAPI) {
6767 Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
6768 } else {
6769 ObjectSizeOpts Opts;
6770 ObjectSizeOffsetEvaluator Eval(*AI.CB->getModule(), TLI, Opts);
6771 SizeOffsetValue SizeOffsetPair = Eval.compute(AI.CB);
6772 assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() &&
6773 cast<ConstantInt>(SizeOffsetPair.Offset)->isZero());
6774 Size = SizeOffsetPair.Size;
6775 }
6776
6777 BasicBlock::iterator IP = AI.MoveAllocaIntoEntry
6778 ? F->getEntryBlock().begin()
6779 : AI.CB->getIterator();
6780
6781 Align Alignment(1);
6782 if (MaybeAlign RetAlign = AI.CB->getRetAlign())
6783 Alignment = std::max(Alignment, *RetAlign);
6784 if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
6785 std::optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align);
6786 assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 &&
6787 "Expected an alignment during manifest!");
6788 Alignment =
6789 std::max(Alignment, assumeAligned(AlignmentAPI->getZExtValue()));
6790 }
6791
6792 // TODO: Hoist the alloca towards the function entry.
6793 unsigned AS = DL.getAllocaAddrSpace();
6794 Instruction *Alloca =
6795 new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
6796 AI.CB->getName() + ".h2s", IP);
6797
6798 if (Alloca->getType() != AI.CB->getType())
6799 Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6800 Alloca, AI.CB->getType(), "malloc_cast", AI.CB->getIterator());
6801
6802 auto *I8Ty = Type::getInt8Ty(F->getContext());
6803 auto *InitVal = getInitialValueOfAllocation(AI.CB, TLI, I8Ty);
6804 assert(InitVal &&
6805 "Must be able to materialize initial memory state of allocation");
6806
6807 A.changeAfterManifest(IRPosition::inst(*AI.CB), *Alloca);
6808
6809 if (auto *II = dyn_cast<InvokeInst>(AI.CB)) {
6810 auto *NBB = II->getNormalDest();
6811 UncondBrInst::Create(NBB, AI.CB->getParent());
6812 A.deleteAfterManifest(*AI.CB);
6813 } else {
6814 A.deleteAfterManifest(*AI.CB);
6815 }
6816
6817 // Initialize the alloca with the same value as used by the allocation
6818 // function. We can skip undef as the initial value of an alloc is
6819 // undef, and the memset would simply end up being DSEd.
6820 if (!isa<UndefValue>(InitVal)) {
6821 IRBuilder<> Builder(Alloca->getNextNode());
6822 // TODO: Use alignment above if align!=1
6823 Builder.CreateMemSet(Alloca, InitVal, Size, std::nullopt);
6824 }
6825 HasChanged = ChangeStatus::CHANGED;
6826 }
6827
6828 for (CallInst *CI : TailCalls)
6829 CI->setTailCall(false);
6830
6831 return HasChanged;
6832 }
6833
6834 std::optional<APInt> getAPInt(Attributor &A, const AbstractAttribute &AA,
6835 Value &V) {
6836 bool UsedAssumedInformation = false;
6837 std::optional<Constant *> SimpleV =
6838 A.getAssumedConstant(V, AA, UsedAssumedInformation);
6839 if (!SimpleV)
6840 return APInt(64, 0);
6841 if (auto *CI = dyn_cast_or_null<ConstantInt>(*SimpleV))
6842 return CI->getValue();
6843 return std::nullopt;
6844 }
6845
6846 std::optional<APInt> getSize(Attributor &A, const AbstractAttribute &AA,
6847 AllocationInfo &AI) {
6848 auto Mapper = [&](const Value *V) -> const Value * {
6849 bool UsedAssumedInformation = false;
6850 if (std::optional<Constant *> SimpleV =
6851 A.getAssumedConstant(*V, AA, UsedAssumedInformation))
6852 if (*SimpleV)
6853 return *SimpleV;
6854 return V;
6855 };
6856
6857 const Function *F = getAnchorScope();
6858 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6859 return getAllocSize(AI.CB, TLI, Mapper);
6860 }
6861
6862 /// Collection of all malloc-like calls in a function with associated
6863 /// information.
6864 MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6865
6866 /// Collection of all free-like calls in a function with associated
6867 /// information.
6868 MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6869
6870 ChangeStatus updateImpl(Attributor &A) override;
6871};
6872
6873ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) {
6875 const Function *F = getAnchorScope();
6876 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6877
6878 const auto *LivenessAA =
6879 A.getAAFor<AAIsDead>(*this, IRPosition::function(*F), DepClassTy::NONE);
6880
6881 MustBeExecutedContextExplorer *Explorer =
6882 A.getInfoCache().getMustBeExecutedContextExplorer();
6883
6884 bool StackIsAccessibleByOtherThreads =
6885 A.getInfoCache().stackIsAccessibleByOtherThreads();
6886
6887 LoopInfo *LI =
6888 A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F);
6889 std::optional<bool> MayContainIrreducibleControl;
6890 auto IsInLoop = [&](BasicBlock &BB) {
6891 if (&F->getEntryBlock() == &BB)
6892 return false;
6893 if (!MayContainIrreducibleControl.has_value())
6894 MayContainIrreducibleControl = mayContainIrreducibleControl(*F, LI);
6895 if (*MayContainIrreducibleControl)
6896 return true;
6897 if (!LI)
6898 return true;
6899 return LI->getLoopFor(&BB) != nullptr;
6900 };
6901
6902 // Flag to ensure we update our deallocation information at most once per
6903 // updateImpl call and only if we use the free check reasoning.
6904 bool HasUpdatedFrees = false;
6905
6906 auto UpdateFrees = [&]() {
6907 HasUpdatedFrees = true;
6908
6909 for (auto &It : DeallocationInfos) {
6910 DeallocationInfo &DI = *It.second;
6911 // For now we cannot use deallocations that have unknown inputs, skip
6912 // them.
6913 if (DI.MightFreeUnknownObjects)
6914 continue;
6915
6916 // No need to analyze dead calls, ignore them instead.
6917 bool UsedAssumedInformation = false;
6918 if (A.isAssumedDead(*DI.CB, this, LivenessAA, UsedAssumedInformation,
6919 /* CheckBBLivenessOnly */ true))
6920 continue;
6921
6922 // Use the non-optimistic version to get the freed object.
6923 Value *Obj = getUnderlyingObject(DI.FreedOp);
6924 if (!Obj) {
6925 LLVM_DEBUG(dbgs() << "[H2S] Unknown underlying object for free!\n");
6926 DI.MightFreeUnknownObjects = true;
6927 continue;
6928 }
6929
6930 // Free of null and undef can be ignored as no-ops (or UB in the latter
6931 // case).
6933 continue;
6934
6935 CallBase *ObjCB = dyn_cast<CallBase>(Obj);
6936 if (!ObjCB) {
6937 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-call object: " << *Obj
6938 << "\n");
6939 DI.MightFreeUnknownObjects = true;
6940 continue;
6941 }
6942
6943 AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6944 if (!AI) {
6945 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-allocation object: " << *Obj
6946 << "\n");
6947 DI.MightFreeUnknownObjects = true;
6948 continue;
6949 }
6950
6951 DI.PotentialAllocationCalls.insert(ObjCB);
6952 }
6953 };
6954
6955 auto FreeCheck = [&](AllocationInfo &AI) {
6956 // If the stack is not accessible by other threads, the "must-free" logic
6957 // doesn't apply as the pointer could be shared and needs to be places in
6958 // "shareable" memory.
6959 if (!StackIsAccessibleByOtherThreads) {
6960 bool IsKnownNoSycn;
6962 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoSycn)) {
6963 LLVM_DEBUG(
6964 dbgs() << "[H2S] found an escaping use, stack is not accessible by "
6965 "other threads and function is not nosync:\n");
6966 return false;
6967 }
6968 }
6969 if (!HasUpdatedFrees)
6970 UpdateFrees();
6971
6972 // TODO: Allow multi exit functions that have different free calls.
6973 if (AI.PotentialFreeCalls.size() != 1) {
6974 LLVM_DEBUG(dbgs() << "[H2S] did not find one free call but "
6975 << AI.PotentialFreeCalls.size() << "\n");
6976 return false;
6977 }
6978 CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6979 DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6980 if (!DI) {
6981 LLVM_DEBUG(
6982 dbgs() << "[H2S] unique free call was not known as deallocation call "
6983 << *UniqueFree << "\n");
6984 return false;
6985 }
6986 if (DI->MightFreeUnknownObjects) {
6987 LLVM_DEBUG(
6988 dbgs() << "[H2S] unique free call might free unknown allocations\n");
6989 return false;
6990 }
6991 if (DI->PotentialAllocationCalls.empty())
6992 return true;
6993 if (DI->PotentialAllocationCalls.size() > 1) {
6994 LLVM_DEBUG(dbgs() << "[H2S] unique free call might free "
6995 << DI->PotentialAllocationCalls.size()
6996 << " different allocations\n");
6997 return false;
6998 }
6999 if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
7000 LLVM_DEBUG(
7001 dbgs()
7002 << "[H2S] unique free call not known to free this allocation but "
7003 << **DI->PotentialAllocationCalls.begin() << "\n");
7004 return false;
7005 }
7006
7007 // __kmpc_alloc_shared and __kmpc_free_shared are by construction matched.
7008 if (!AI.IsGlobalizedLocal) {
7009 Instruction *CtxI = isa<InvokeInst>(AI.CB) ? AI.CB : AI.CB->getNextNode();
7010 if (!Explorer || !Explorer->isInContextOf(UniqueFree, CtxI)) {
7011 LLVM_DEBUG(dbgs() << "[H2S] unique free call might not be executed "
7012 "with the allocation "
7013 << *UniqueFree << "\n");
7014 return false;
7015 }
7016 }
7017 return true;
7018 };
7019
7020 auto UsesCheck = [&](AllocationInfo &AI) {
7021 bool ValidUsesOnly = true;
7022
7023 auto Pred = [&](const Use &U, bool &Follow) -> bool {
7024 Instruction *UserI = cast<Instruction>(U.getUser());
7025 if (isa<LoadInst>(UserI))
7026 return true;
7027 if (auto *SI = dyn_cast<StoreInst>(UserI)) {
7028 if (SI->getValueOperand() == U.get()) {
7030 << "[H2S] escaping store to memory: " << *UserI << "\n");
7031 ValidUsesOnly = false;
7032 } else {
7033 // A store into the malloc'ed memory is fine.
7034 }
7035 return true;
7036 }
7037 if (auto *CB = dyn_cast<CallBase>(UserI)) {
7038 // A musttail call cannot access allocas of the caller, and its marker
7039 // cannot be removed.
7040 if (CB->isMustTailCall()) {
7041 LLVM_DEBUG(dbgs() << "[H2S] musttail user: " << *UserI << "\n");
7042 ValidUsesOnly = false;
7043 return true;
7044 }
7045
7046 if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
7047 return true;
7048 if (DeallocationInfos.count(CB)) {
7049 AI.PotentialFreeCalls.insert(CB);
7050 return true;
7051 }
7052
7053 unsigned ArgNo = CB->getArgOperandNo(&U);
7054 auto CBIRP = IRPosition::callsite_argument(*CB, ArgNo);
7055
7056 bool IsKnownNoCapture;
7057 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
7058 A, this, CBIRP, DepClassTy::OPTIONAL, IsKnownNoCapture);
7059
7060 // If a call site argument use is nofree, we are fine.
7061 bool IsKnownNoFree;
7062 bool IsAssumedNoFree = AA::hasAssumedIRAttr<Attribute::NoFree>(
7063 A, this, CBIRP, DepClassTy::OPTIONAL, IsKnownNoFree);
7064
7065 if (!IsAssumedNoCapture ||
7066 (!AI.IsGlobalizedLocal && !IsAssumedNoFree)) {
7067 AI.HasPotentiallyFreeingUnknownUses |= !IsAssumedNoFree;
7068
7069 // Emit a missed remark if this is missed OpenMP globalization.
7070 auto Remark = [&](OptimizationRemarkMissed ORM) {
7071 return ORM
7072 << "Could not move globalized variable to the stack. "
7073 "Variable is potentially captured in call. Mark "
7074 "parameter as `__attribute__((noescape))` to override.";
7075 };
7076
7077 if (ValidUsesOnly && AI.IsGlobalizedLocal)
7078 A.emitRemark<OptimizationRemarkMissed>(CB, "OMP113", Remark);
7079
7080 LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
7081 ValidUsesOnly = false;
7082 }
7083 return true;
7084 }
7085
7086 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
7087 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
7088 Follow = true;
7089 return true;
7090 }
7091 // Unknown user for which we can not track uses further (in a way that
7092 // makes sense).
7093 LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
7094 ValidUsesOnly = false;
7095 return true;
7096 };
7097 if (!A.checkForAllUses(Pred, *this, *AI.CB, /* CheckBBLivenessOnly */ false,
7098 DepClassTy::OPTIONAL, /* IgnoreDroppableUses */ true,
7099 [&](const Use &OldU, const Use &NewU) {
7100 auto *SI = dyn_cast<StoreInst>(OldU.getUser());
7101 return !SI || StackIsAccessibleByOtherThreads ||
7102 AA::isAssumedThreadLocalObject(
7103 A, *SI->getPointerOperand(), *this);
7104 }))
7105 return false;
7106 return ValidUsesOnly;
7107 };
7108
7109 // The actual update starts here. We look at all allocations and depending on
7110 // their status perform the appropriate check(s).
7111 for (auto &It : AllocationInfos) {
7112 AllocationInfo &AI = *It.second;
7113 if (AI.Status == AllocationInfo::INVALID)
7114 continue;
7115
7116 if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
7117 std::optional<APInt> APAlign = getAPInt(A, *this, *Align);
7118 if (!APAlign) {
7119 // Can't generate an alloca which respects the required alignment
7120 // on the allocation.
7121 LLVM_DEBUG(dbgs() << "[H2S] Unknown allocation alignment: " << *AI.CB
7122 << "\n");
7123 AI.Status = AllocationInfo::INVALID;
7125 continue;
7126 }
7127 if (APAlign->ugt(llvm::Value::MaximumAlignment) ||
7128 !APAlign->isPowerOf2()) {
7129 LLVM_DEBUG(dbgs() << "[H2S] Invalid allocation alignment: " << APAlign
7130 << "\n");
7131 AI.Status = AllocationInfo::INVALID;
7133 continue;
7134 }
7135 }
7136
7137 std::optional<APInt> Size = getSize(A, *this, AI);
7138 if (!AI.IsGlobalizedLocal && A.Opts.max_heap_to_stack_size != -1) {
7139 if (!Size || Size->ugt(A.Opts.max_heap_to_stack_size)) {
7140 LLVM_DEBUG({
7141 if (!Size)
7142 dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n";
7143 else
7144 dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. "
7145 << A.Opts.max_heap_to_stack_size << "\n";
7146 });
7147
7148 AI.Status = AllocationInfo::INVALID;
7150 continue;
7151 }
7152 }
7153
7154 switch (AI.Status) {
7155 case AllocationInfo::STACK_DUE_TO_USE:
7156 if (UsesCheck(AI))
7157 break;
7158 AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
7159 [[fallthrough]];
7160 case AllocationInfo::STACK_DUE_TO_FREE:
7161 if (FreeCheck(AI))
7162 break;
7163 AI.Status = AllocationInfo::INVALID;
7165 break;
7166 case AllocationInfo::INVALID:
7167 llvm_unreachable("Invalid allocations should never reach this point!");
7168 };
7169
7170 // Check if we still think we can move it into the entry block. If the
7171 // alloca comes from a converted __kmpc_alloc_shared then we can usually
7172 // ignore the potential complications associated with loops.
7173 bool IsGlobalizedLocal = AI.IsGlobalizedLocal;
7174 if (AI.MoveAllocaIntoEntry &&
7175 (!Size.has_value() ||
7176 (!IsGlobalizedLocal && IsInLoop(*AI.CB->getParent()))))
7177 AI.MoveAllocaIntoEntry = false;
7178 }
7179
7180 return Changed;
7181}
7182} // namespace
7183
7184/// ----------------------- Privatizable Pointers ------------------------------
7185namespace {
7186struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
7187 AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
7188 : AAPrivatizablePtr(IRP, A), PrivatizableType(std::nullopt) {}
7189
7190 ChangeStatus indicatePessimisticFixpoint() override {
7191 AAPrivatizablePtr::indicatePessimisticFixpoint();
7192 PrivatizableType = nullptr;
7193 return ChangeStatus::CHANGED;
7194 }
7195
7196 /// Identify the type we can chose for a private copy of the underlying
7197 /// argument. std::nullopt means it is not clear yet, nullptr means there is
7198 /// none.
7199 virtual std::optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
7200
7201 /// Return a privatizable type that encloses both T0 and T1.
7202 /// TODO: This is merely a stub for now as we should manage a mapping as well.
7203 std::optional<Type *> combineTypes(std::optional<Type *> T0,
7204 std::optional<Type *> T1) {
7205 if (!T0)
7206 return T1;
7207 if (!T1)
7208 return T0;
7209 if (T0 == T1)
7210 return T0;
7211 return nullptr;
7212 }
7213
7214 std::optional<Type *> getPrivatizableType() const override {
7215 return PrivatizableType;
7216 }
7217
7218 const std::string getAsStr(Attributor *A) const override {
7219 return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
7220 }
7221
7222protected:
7223 std::optional<Type *> PrivatizableType;
7224};
7225
7226// TODO: Do this for call site arguments (probably also other values) as well.
7227
7228struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
7229 AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
7230 : AAPrivatizablePtrImpl(IRP, A) {}
7231
7232 std::optional<Type *> identifyPrivatizableType(Attributor &A) override {
7233 // If this is a byval argument and we know all the call sites (so we can
7234 // rewrite them), there is no need to check them explicitly.
7235 bool UsedAssumedInformation = false;
7237 A.getAttrs(getIRPosition(), {Attribute::ByVal}, Attrs,
7238 /* IgnoreSubsumingPositions */ true);
7239 if (!Attrs.empty() &&
7240 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
7241 true, UsedAssumedInformation))
7242 return Attrs[0].getValueAsType();
7243
7244 std::optional<Type *> Ty;
7245 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
7246
7247 // Make sure the associated call site argument has the same type at all call
7248 // sites and it is an allocation we know is safe to privatize, for now that
7249 // means we only allow alloca instructions.
7250 // TODO: We can additionally analyze the accesses in the callee to create
7251 // the type from that information instead. That is a little more
7252 // involved and will be done in a follow up patch.
7253 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7254 IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
7255 // Check if a coresponding argument was found or if it is one not
7256 // associated (which can happen for callback calls).
7257 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
7258 return false;
7259
7260 // Check that all call sites agree on a type.
7261 auto *PrivCSArgAA =
7262 A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED);
7263 if (!PrivCSArgAA)
7264 return false;
7265 std::optional<Type *> CSTy = PrivCSArgAA->getPrivatizableType();
7266
7267 LLVM_DEBUG({
7268 dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
7269 if (CSTy && *CSTy)
7270 (*CSTy)->print(dbgs());
7271 else if (CSTy)
7272 dbgs() << "<nullptr>";
7273 else
7274 dbgs() << "<none>";
7275 });
7276
7277 Ty = combineTypes(Ty, CSTy);
7278
7279 LLVM_DEBUG({
7280 dbgs() << " : New Type: ";
7281 if (Ty && *Ty)
7282 (*Ty)->print(dbgs());
7283 else if (Ty)
7284 dbgs() << "<nullptr>";
7285 else
7286 dbgs() << "<none>";
7287 dbgs() << "\n";
7288 });
7289
7290 return !Ty || *Ty;
7291 };
7292
7293 if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
7294 UsedAssumedInformation))
7295 return nullptr;
7296 return Ty;
7297 }
7298
7299 ChangeStatus updateImpl(Attributor &A) override {
7300 PrivatizableType = identifyPrivatizableType(A);
7301 if (!PrivatizableType)
7302 return ChangeStatus::UNCHANGED;
7303 if (!*PrivatizableType)
7304 return indicatePessimisticFixpoint();
7305
7306 // The dependence is optional so we don't give up once we give up on the
7307 // alignment.
7308 A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
7309 DepClassTy::OPTIONAL);
7310
7311 // Avoid arguments with padding for now.
7312 if (!A.hasAttr(getIRPosition(), Attribute::ByVal) &&
7313 !isDenselyPacked(*PrivatizableType, A.getInfoCache().getDL())) {
7314 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
7315 return indicatePessimisticFixpoint();
7316 }
7317
7318 // Collect the types that will replace the privatizable type in the function
7319 // signature.
7320 SmallVector<Type *, 16> ReplacementTypes;
7321 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7322
7323 // Verify callee and caller agree on how the promoted argument would be
7324 // passed.
7325 Function &Fn = *getIRPosition().getAnchorScope();
7326 const auto *TTI =
7327 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
7328 if (!TTI) {
7329 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Missing TTI for function "
7330 << Fn.getName() << "\n");
7331 return indicatePessimisticFixpoint();
7332 }
7333
7334 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7335 CallBase *CB = ACS.getInstruction();
7336 return TTI->areTypesABICompatible(
7337 CB->getCaller(),
7339 ReplacementTypes);
7340 };
7341 bool UsedAssumedInformation = false;
7342 if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
7343 UsedAssumedInformation)) {
7344 LLVM_DEBUG(
7345 dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
7346 << Fn.getName() << "\n");
7347 return indicatePessimisticFixpoint();
7348 }
7349
7350 // Register a rewrite of the argument.
7351 Argument *Arg = getAssociatedArgument();
7352 if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
7353 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
7354 return indicatePessimisticFixpoint();
7355 }
7356
7357 unsigned ArgNo = Arg->getArgNo();
7358
7359 // Helper to check if for the given call site the associated argument is
7360 // passed to a callback where the privatization would be different.
7361 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
7362 SmallVector<const Use *, 4> CallbackUses;
7363 AbstractCallSite::getCallbackUses(CB, CallbackUses);
7364 for (const Use *U : CallbackUses) {
7365 AbstractCallSite CBACS(U);
7366 assert(CBACS && CBACS.isCallbackCall());
7367 for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
7368 int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
7369
7370 LLVM_DEBUG({
7371 dbgs()
7372 << "[AAPrivatizablePtr] Argument " << *Arg
7373 << "check if can be privatized in the context of its parent ("
7374 << Arg->getParent()->getName()
7375 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7376 "callback ("
7377 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
7378 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
7379 << CBACS.getCallArgOperand(CBArg) << " vs "
7380 << CB.getArgOperand(ArgNo) << "\n"
7381 << "[AAPrivatizablePtr] " << CBArg << " : "
7382 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
7383 });
7384
7385 if (CBArgNo != int(ArgNo))
7386 continue;
7387 const auto *CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
7388 *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED);
7389 if (CBArgPrivAA && CBArgPrivAA->isValidState()) {
7390 auto CBArgPrivTy = CBArgPrivAA->getPrivatizableType();
7391 if (!CBArgPrivTy)
7392 continue;
7393 if (*CBArgPrivTy == PrivatizableType)
7394 continue;
7395 }
7396
7397 LLVM_DEBUG({
7398 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7399 << " cannot be privatized in the context of its parent ("
7400 << Arg->getParent()->getName()
7401 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7402 "callback ("
7403 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
7404 << ").\n[AAPrivatizablePtr] for which the argument "
7405 "privatization is not compatible.\n";
7406 });
7407 return false;
7408 }
7409 }
7410 return true;
7411 };
7412
7413 // Helper to check if for the given call site the associated argument is
7414 // passed to a direct call where the privatization would be different.
7415 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
7416 CallBase *DC = cast<CallBase>(ACS.getInstruction());
7417 int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
7418 assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->arg_size() &&
7419 "Expected a direct call operand for callback call operand");
7420
7421 Function *DCCallee =
7423 LLVM_DEBUG({
7424 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7425 << " check if be privatized in the context of its parent ("
7426 << Arg->getParent()->getName()
7427 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7428 "direct call of ("
7429 << DCArgNo << "@" << DCCallee->getName() << ").\n";
7430 });
7431
7432 if (unsigned(DCArgNo) < DCCallee->arg_size()) {
7433 const auto *DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
7434 *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)),
7435 DepClassTy::REQUIRED);
7436 if (DCArgPrivAA && DCArgPrivAA->isValidState()) {
7437 auto DCArgPrivTy = DCArgPrivAA->getPrivatizableType();
7438 if (!DCArgPrivTy)
7439 return true;
7440 if (*DCArgPrivTy == PrivatizableType)
7441 return true;
7442 }
7443 }
7444
7445 LLVM_DEBUG({
7446 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7447 << " cannot be privatized in the context of its parent ("
7448 << Arg->getParent()->getName()
7449 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7450 "direct call of ("
7452 << ").\n[AAPrivatizablePtr] for which the argument "
7453 "privatization is not compatible.\n";
7454 });
7455 return false;
7456 };
7457
7458 // Helper to check if the associated argument is used at the given abstract
7459 // call site in a way that is incompatible with the privatization assumed
7460 // here.
7461 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
7462 if (ACS.isDirectCall())
7463 return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
7464 if (ACS.isCallbackCall())
7465 return IsCompatiblePrivArgOfDirectCS(ACS);
7466 return false;
7467 };
7468
7469 if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
7470 UsedAssumedInformation))
7471 return indicatePessimisticFixpoint();
7472
7473 return ChangeStatus::UNCHANGED;
7474 }
7475
7476 /// Given a type to private \p PrivType, collect the constituates (which are
7477 /// used) in \p ReplacementTypes.
7478 static void
7479 identifyReplacementTypes(Type *PrivType,
7480 SmallVectorImpl<Type *> &ReplacementTypes) {
7481 // TODO: For now we expand the privatization type to the fullest which can
7482 // lead to dead arguments that need to be removed later.
7483 assert(PrivType && "Expected privatizable type!");
7484
7485 // Traverse the type, extract constituate types on the outermost level.
7486 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7487 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
7488 ReplacementTypes.push_back(PrivStructType->getElementType(u));
7489 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7490 ReplacementTypes.append(PrivArrayType->getNumElements(),
7491 PrivArrayType->getElementType());
7492 } else {
7493 ReplacementTypes.push_back(PrivType);
7494 }
7495 }
7496
7497 /// Initialize \p Base according to the type \p PrivType at position \p IP.
7498 /// The values needed are taken from the arguments of \p F starting at
7499 /// position \p ArgNo.
7500 static void createInitialization(Type *PrivType, Value &Base, Function &F,
7501 unsigned ArgNo, BasicBlock::iterator IP) {
7502 assert(PrivType && "Expected privatizable type!");
7503
7504 IRBuilder<NoFolder> IRB(IP);
7505 const DataLayout &DL = F.getDataLayout();
7506
7507 // Traverse the type, build GEPs and stores.
7508 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7509 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
7510 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7511 Value *Ptr =
7512 constructPointer(&Base, PrivStructLayout->getElementOffset(u), IRB);
7513 new StoreInst(F.getArg(ArgNo + u), Ptr, IP);
7514 }
7515 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7516 Type *PointeeTy = PrivArrayType->getElementType();
7517 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
7518 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7519 Value *Ptr = constructPointer(&Base, u * PointeeTySize, IRB);
7520 new StoreInst(F.getArg(ArgNo + u), Ptr, IP);
7521 }
7522 } else {
7523 new StoreInst(F.getArg(ArgNo), &Base, IP);
7524 }
7525 }
7526
7527 /// Extract values from \p Base according to the type \p PrivType at the
7528 /// call position \p ACS. The values are appended to \p ReplacementValues.
7529 void createReplacementValues(Align Alignment, Type *PrivType,
7530 AbstractCallSite ACS, Value *Base,
7531 SmallVectorImpl<Value *> &ReplacementValues) {
7532 assert(Base && "Expected base value!");
7533 assert(PrivType && "Expected privatizable type!");
7534 Instruction *IP = ACS.getInstruction();
7535
7536 IRBuilder<NoFolder> IRB(IP);
7537 const DataLayout &DL = IP->getDataLayout();
7538
7539 // Traverse the type, build GEPs and loads.
7540 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7541 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
7542 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7543 Type *PointeeTy = PrivStructType->getElementType(u);
7544 Value *Ptr =
7545 constructPointer(Base, PrivStructLayout->getElementOffset(u), IRB);
7546 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP->getIterator());
7547 L->setAlignment(Alignment);
7548 ReplacementValues.push_back(L);
7549 }
7550 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7551 Type *PointeeTy = PrivArrayType->getElementType();
7552 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
7553 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7554 Value *Ptr = constructPointer(Base, u * PointeeTySize, IRB);
7555 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP->getIterator());
7556 L->setAlignment(Alignment);
7557 ReplacementValues.push_back(L);
7558 }
7559 } else {
7560 LoadInst *L = new LoadInst(PrivType, Base, "", IP->getIterator());
7561 L->setAlignment(Alignment);
7562 ReplacementValues.push_back(L);
7563 }
7564 }
7565
7566 ChangeStatus manifest(Attributor &A) override {
7567 if (!PrivatizableType)
7568 return ChangeStatus::UNCHANGED;
7569 assert(*PrivatizableType && "Expected privatizable type!");
7570
7571 Argument *Arg = getAssociatedArgument();
7572 // Query AAAlign attribute for alignment of associated argument to
7573 // determine the best alignment of loads.
7574 const auto *AlignAA =
7575 A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE);
7576
7577 // Callback to repair the associated function. A new alloca is placed at the
7578 // beginning and initialized with the values passed through arguments. The
7579 // new alloca replaces the use of the old pointer argument.
7581 [=](const Attributor::ArgumentReplacementInfo &ARI,
7582 Function &ReplacementFn, Function::arg_iterator ArgIt) {
7583 BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
7585 const DataLayout &DL = IP->getDataLayout();
7586 unsigned AS = DL.getAllocaAddrSpace();
7587 Instruction *AI = new AllocaInst(*PrivatizableType, AS,
7588 Arg->getName() + ".priv", IP);
7589 createInitialization(*PrivatizableType, *AI, ReplacementFn,
7590 ArgIt->getArgNo(), IP);
7591
7592 if (AI->getType() != Arg->getType())
7593 AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
7594 AI, Arg->getType(), "", IP);
7595 Arg->replaceAllUsesWith(AI);
7596
7597 // The new alloca may escape into tail calls. Find them here, as calls
7598 // may have been replaced or deleted since manifest.
7599 for (Instruction &I : instructions(ReplacementFn)) {
7600 auto *CI = dyn_cast<CallInst>(&I);
7601 if (CI && CI->isTailCall() && !CI->isMustTailCall())
7602 CI->setTailCall(false);
7603 }
7604 };
7605
7606 // Callback to repair a call site of the associated function. The elements
7607 // of the privatizable type are loaded prior to the call and passed to the
7608 // new function version.
7610 [=](const Attributor::ArgumentReplacementInfo &ARI,
7611 AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
7612 // When no alignment is specified for the load instruction,
7613 // natural alignment is assumed.
7614 createReplacementValues(
7615 AlignAA ? AlignAA->getAssumedAlign() : Align(0),
7616 *PrivatizableType, ACS,
7617 ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
7618 NewArgOperands);
7619 };
7620
7621 // Collect the types that will replace the privatizable type in the function
7622 // signature.
7623 SmallVector<Type *, 16> ReplacementTypes;
7624 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7625
7626 // Register a rewrite of the argument.
7627 if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
7628 std::move(FnRepairCB),
7629 std::move(ACSRepairCB)))
7630 return ChangeStatus::CHANGED;
7631 return ChangeStatus::UNCHANGED;
7632 }
7633
7634 void trackStatistics() const override {
7635 STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
7636 }
7637};
7638
7639struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
7640 AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
7641 : AAPrivatizablePtrImpl(IRP, A) {}
7642
7643 void initialize(Attributor &A) override {
7644 // TODO: We can privatize more than arguments.
7645 indicatePessimisticFixpoint();
7646 }
7647
7648 ChangeStatus updateImpl(Attributor &A) override {
7649 llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
7650 "updateImpl will not be called");
7651 }
7652
7653 std::optional<Type *> identifyPrivatizableType(Attributor &A) override {
7654 Value *Obj = getUnderlyingObject(&getAssociatedValue());
7655 if (!Obj) {
7656 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
7657 return nullptr;
7658 }
7659
7660 if (auto *AI = dyn_cast<AllocaInst>(Obj))
7661 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
7662 if (CI->isOne())
7663 return AI->getAllocatedType();
7664 if (auto *Arg = dyn_cast<Argument>(Obj)) {
7665 auto *PrivArgAA = A.getAAFor<AAPrivatizablePtr>(
7666 *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED);
7667 if (PrivArgAA && PrivArgAA->isAssumedPrivatizablePtr())
7668 return PrivArgAA->getPrivatizableType();
7669 }
7670
7671 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
7672 "alloca nor privatizable argument: "
7673 << *Obj << "!\n");
7674 return nullptr;
7675 }
7676
7677 void trackStatistics() const override {
7678 STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
7679 }
7680};
7681
7682struct AAPrivatizablePtrCallSiteArgument final
7683 : public AAPrivatizablePtrFloating {
7684 AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
7685 : AAPrivatizablePtrFloating(IRP, A) {}
7686
7687 void initialize(Attributor &A) override {
7688 if (A.hasAttr(getIRPosition(), Attribute::ByVal))
7689 indicateOptimisticFixpoint();
7690 }
7691
7692 ChangeStatus updateImpl(Attributor &A) override {
7693 PrivatizableType = identifyPrivatizableType(A);
7694 if (!PrivatizableType)
7695 return ChangeStatus::UNCHANGED;
7696 if (!*PrivatizableType)
7697 return indicatePessimisticFixpoint();
7698
7699 const IRPosition &IRP = getIRPosition();
7700 bool IsKnownNoCapture;
7701 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
7702 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoCapture);
7703 if (!IsAssumedNoCapture) {
7704 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
7705 return indicatePessimisticFixpoint();
7706 }
7707
7708 bool IsKnownNoAlias;
7710 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
7711 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
7712 return indicatePessimisticFixpoint();
7713 }
7714
7715 bool IsKnown;
7716 if (!AA::isAssumedReadOnly(A, IRP, *this, IsKnown)) {
7717 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
7718 return indicatePessimisticFixpoint();
7719 }
7720
7721 return ChangeStatus::UNCHANGED;
7722 }
7723
7724 void trackStatistics() const override {
7725 STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
7726 }
7727};
7728
7729struct AAPrivatizablePtrCallSiteReturned final
7730 : public AAPrivatizablePtrFloating {
7731 AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
7732 : AAPrivatizablePtrFloating(IRP, A) {}
7733
7734 void initialize(Attributor &A) override {
7735 // TODO: We can privatize more than arguments.
7736 indicatePessimisticFixpoint();
7737 }
7738
7739 void trackStatistics() const override {
7740 STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
7741 }
7742};
7743
7744struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
7745 AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
7746 : AAPrivatizablePtrFloating(IRP, A) {}
7747
7748 void initialize(Attributor &A) override {
7749 // TODO: We can privatize more than arguments.
7750 indicatePessimisticFixpoint();
7751 }
7752
7753 void trackStatistics() const override {
7754 STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
7755 }
7756};
7757} // namespace
7758
7759/// -------------------- Memory Behavior Attributes ----------------------------
7760/// Includes read-none, read-only, and write-only.
7761/// ----------------------------------------------------------------------------
7762namespace {
7763struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
7764 AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
7765 : AAMemoryBehavior(IRP, A) {}
7766
7767 void initialize(Attributor &A) override {
7768 intersectAssumedBits(BEST_STATE);
7769 getKnownStateFromValue(A, getIRPosition(), getState());
7770 AAMemoryBehavior::initialize(A);
7771 }
7772
7773 /// Return the memory behavior information encoded in the IR for \p IRP.
7774 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
7775 BitIntegerState &State,
7776 bool IgnoreSubsumingPositions = false) {
7778 A.getAttrs(IRP, AttrKinds, Attrs, IgnoreSubsumingPositions);
7779 for (const Attribute &Attr : Attrs) {
7780 switch (Attr.getKindAsEnum()) {
7781 case Attribute::ReadNone:
7782 State.addKnownBits(NO_ACCESSES);
7783 break;
7784 case Attribute::ReadOnly:
7785 State.addKnownBits(NO_WRITES);
7786 break;
7787 case Attribute::WriteOnly:
7788 State.addKnownBits(NO_READS);
7789 break;
7790 default:
7791 llvm_unreachable("Unexpected attribute!");
7792 }
7793 }
7794
7795 // Only a call site anchor performs the accesses of the position. A floating
7796 // value is only defined by its anchor, e.g., a loaded pointer may be
7797 // written through even though the load does not write.
7799 if (Kind == IRPosition::IRP_CALL_SITE ||
7801 if (auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue())) {
7803 if (!isRefSet(MR))
7804 State.addKnownBits(NO_READS);
7805 if (!isModSet(MR))
7806 State.addKnownBits(NO_WRITES);
7807 }
7808 }
7809 }
7810
7811 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
7812 SmallVectorImpl<Attribute> &Attrs) const override {
7813 assert(Attrs.size() == 0);
7814 if (isAssumedReadNone())
7815 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7816 else if (isAssumedReadOnly())
7817 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7818 else if (isAssumedWriteOnly())
7819 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7820 assert(Attrs.size() <= 1);
7821 }
7822
7823 ChangeStatus manifest(Attributor &A) override {
7824 const IRPosition &IRP = getIRPosition();
7825
7826 if (A.hasAttr(IRP, Attribute::ReadNone,
7827 /* IgnoreSubsumingPositions */ true))
7828 return ChangeStatus::UNCHANGED;
7829
7830 // Check if we would improve the existing attributes first.
7831 SmallVector<Attribute, 4> DeducedAttrs;
7832 getDeducedAttributes(A, IRP.getAnchorValue().getContext(), DeducedAttrs);
7833 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7834 return A.hasAttr(IRP, Attr.getKindAsEnum(),
7835 /* IgnoreSubsumingPositions */ true);
7836 }))
7837 return ChangeStatus::UNCHANGED;
7838
7839 // Clear existing attributes.
7840 A.removeAttrs(IRP, AttrKinds);
7841 // Clear conflicting writable attribute.
7842 if (isAssumedReadOnly())
7843 A.removeAttrs(IRP, Attribute::Writable);
7844
7845 // Use the generic manifest method.
7846 return IRAttribute::manifest(A);
7847 }
7848
7849 const std::string getAsStr(Attributor *A) const override {
7850 if (isAssumedReadNone())
7851 return "readnone";
7852 if (isAssumedReadOnly())
7853 return "readonly";
7854 if (isAssumedWriteOnly())
7855 return "writeonly";
7856 return "may-read/write";
7857 }
7858
7859 /// The set of IR attributes AAMemoryBehavior deals with.
7860 static const Attribute::AttrKind AttrKinds[3];
7861};
7862
7863const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
7864 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7865
7866/// Memory behavior attribute for a floating value.
7867struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7868 AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
7869 : AAMemoryBehaviorImpl(IRP, A) {}
7870
7871 ChangeStatus updateImpl(Attributor &A) override;
7872
7873 void trackStatistics() const override {
7874 if (isAssumedReadNone())
7876 else if (isAssumedReadOnly())
7878 else if (isAssumedWriteOnly())
7880 }
7881
7882private:
7883 /// Return true if users of \p UserI might access the underlying
7884 /// variable/location described by \p U and should therefore be analyzed.
7885 bool followUsersOfUseIn(Attributor &A, const Use &U,
7886 const Instruction *UserI);
7887
7888 /// Update the state according to the effect of use \p U in \p UserI.
7889 void analyzeUseIn(Attributor &A, const Use &U, const Instruction *UserI);
7890};
7891
7892/// Memory behavior attribute for function argument.
7893struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7894 AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
7895 : AAMemoryBehaviorFloating(IRP, A) {}
7896
7897 void initialize(Attributor &A) override {
7898 intersectAssumedBits(BEST_STATE);
7899 const IRPosition &IRP = getIRPosition();
7900 // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
7901 // can query it when we use has/getAttr. That would allow us to reuse the
7902 // initialize of the base class here.
7903 bool HasByVal = A.hasAttr(IRP, {Attribute::ByVal},
7904 /* IgnoreSubsumingPositions */ true);
7905 getKnownStateFromValue(A, IRP, getState(),
7906 /* IgnoreSubsumingPositions */ HasByVal);
7907 }
7908
7909 ChangeStatus manifest(Attributor &A) override {
7910 // TODO: Pointer arguments are not supported on vectors of pointers yet.
7911 if (!getAssociatedValue().getType()->isPointerTy())
7912 return ChangeStatus::UNCHANGED;
7913
7914 // TODO: From readattrs.ll: "inalloca parameters are always
7915 // considered written"
7916 if (A.hasAttr(getIRPosition(),
7917 {Attribute::InAlloca, Attribute::Preallocated})) {
7918 removeKnownBits(NO_WRITES);
7919 removeAssumedBits(NO_WRITES);
7920 }
7921 A.removeAttrs(getIRPosition(), AttrKinds);
7922 return AAMemoryBehaviorFloating::manifest(A);
7923 }
7924
7925 void trackStatistics() const override {
7926 if (isAssumedReadNone())
7927 STATS_DECLTRACK_ARG_ATTR(readnone)
7928 else if (isAssumedReadOnly())
7929 STATS_DECLTRACK_ARG_ATTR(readonly)
7930 else if (isAssumedWriteOnly())
7931 STATS_DECLTRACK_ARG_ATTR(writeonly)
7932 }
7933};
7934
7935struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7936 AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
7937 : AAMemoryBehaviorArgument(IRP, A) {}
7938
7939 void initialize(Attributor &A) override {
7940 // If we don't have an associated attribute this is either a variadic call
7941 // or an indirect call, either way, nothing to do here.
7942 Argument *Arg = getAssociatedArgument();
7943 if (!Arg) {
7944 indicatePessimisticFixpoint();
7945 return;
7946 }
7947 if (Arg->hasByValAttr()) {
7948 addKnownBits(NO_WRITES);
7949 removeKnownBits(NO_READS);
7950 removeAssumedBits(NO_READS);
7951 }
7952 AAMemoryBehaviorArgument::initialize(A);
7953 if (getAssociatedFunction()->isDeclaration())
7954 indicatePessimisticFixpoint();
7955 }
7956
7957 ChangeStatus updateImpl(Attributor &A) override {
7958 // TODO: Once we have call site specific value information we can provide
7959 // call site specific liveness liveness information and then it makes
7960 // sense to specialize attributes for call sites arguments instead of
7961 // redirecting requests to the callee argument.
7962 Argument *Arg = getAssociatedArgument();
7963 const IRPosition &ArgPos = IRPosition::argument(*Arg);
7964 auto *ArgAA =
7965 A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED);
7966 if (!ArgAA)
7967 return indicatePessimisticFixpoint();
7968 return clampStateAndIndicateChange(getState(), ArgAA->getState());
7969 }
7970
7971 void trackStatistics() const override {
7972 if (isAssumedReadNone())
7974 else if (isAssumedReadOnly())
7976 else if (isAssumedWriteOnly())
7978 }
7979};
7980
7981/// Memory behavior attribute for a call site return position.
7982struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7983 AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
7984 : AAMemoryBehaviorFloating(IRP, A) {}
7985
7986 void initialize(Attributor &A) override {
7987 AAMemoryBehaviorImpl::initialize(A);
7988 }
7989 ChangeStatus manifest(Attributor &A) override {
7990 // We do not annotate returned values.
7991 return ChangeStatus::UNCHANGED;
7992 }
7993
7994 void trackStatistics() const override {}
7995};
7996
7997/// An AA to represent the memory behavior function attributes.
7998struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
7999 AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
8000 : AAMemoryBehaviorImpl(IRP, A) {}
8001
8002 ChangeStatus updateImpl(Attributor &A) override;
8003
8004 ChangeStatus manifest(Attributor &A) override {
8005 // TODO: It would be better to merge this with AAMemoryLocation, so that
8006 // we could determine read/write per location. This would also have the
8007 // benefit of only one place trying to manifest the memory attribute.
8008 Function &F = cast<Function>(getAnchorValue());
8010 if (isAssumedReadNone())
8011 ME = MemoryEffects::none();
8012 else if (isAssumedReadOnly())
8014 else if (isAssumedWriteOnly())
8016
8017 A.removeAttrs(getIRPosition(), AttrKinds);
8018 // Clear conflicting writable attribute.
8019 if (ME.onlyReadsMemory())
8020 for (Argument &Arg : F.args())
8021 A.removeAttrs(IRPosition::argument(Arg), Attribute::Writable);
8022 return A.manifestAttrs(getIRPosition(),
8023 Attribute::getWithMemoryEffects(F.getContext(), ME));
8024 }
8025
8026 void trackStatistics() const override {
8027 if (isAssumedReadNone())
8028 STATS_DECLTRACK_FN_ATTR(readnone)
8029 else if (isAssumedReadOnly())
8030 STATS_DECLTRACK_FN_ATTR(readonly)
8031 else if (isAssumedWriteOnly())
8032 STATS_DECLTRACK_FN_ATTR(writeonly)
8033 }
8034};
8035
8036/// AAMemoryBehavior attribute for call sites.
8037struct AAMemoryBehaviorCallSite final
8038 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl> {
8039 AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
8040 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl>(IRP, A) {}
8041
8042 ChangeStatus manifest(Attributor &A) override {
8043 // TODO: Deduplicate this with AAMemoryBehaviorFunction.
8044 CallBase &CB = cast<CallBase>(getAnchorValue());
8046 if (isAssumedReadNone())
8047 ME = MemoryEffects::none();
8048 else if (isAssumedReadOnly())
8050 else if (isAssumedWriteOnly())
8052
8053 A.removeAttrs(getIRPosition(), AttrKinds);
8054 // Clear conflicting writable attribute.
8055 if (ME.onlyReadsMemory())
8056 for (Use &U : CB.args())
8057 A.removeAttrs(IRPosition::callsite_argument(CB, U.getOperandNo()),
8058 Attribute::Writable);
8059 return A.manifestAttrs(
8060 getIRPosition(), Attribute::getWithMemoryEffects(CB.getContext(), ME));
8061 }
8062
8063 void trackStatistics() const override {
8064 if (isAssumedReadNone())
8065 STATS_DECLTRACK_CS_ATTR(readnone)
8066 else if (isAssumedReadOnly())
8067 STATS_DECLTRACK_CS_ATTR(readonly)
8068 else if (isAssumedWriteOnly())
8069 STATS_DECLTRACK_CS_ATTR(writeonly)
8070 }
8071};
8072
8073ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
8074
8075 // The current assumed state used to determine a change.
8076 auto AssumedState = getAssumed();
8077
8078 auto CheckRWInst = [&](Instruction &I) {
8079 // If the instruction has an own memory behavior state, use it to restrict
8080 // the local state. No further analysis is required as the other memory
8081 // state is as optimistic as it gets.
8082 if (const auto *CB = dyn_cast<CallBase>(&I)) {
8083 const auto *MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
8085 if (MemBehaviorAA) {
8086 intersectAssumedBits(MemBehaviorAA->getAssumed());
8087 return !isAtFixpoint();
8088 }
8089 }
8090
8091 // Remove access kind modifiers if necessary.
8092 if (I.mayReadFromMemory())
8093 removeAssumedBits(NO_READS);
8094 if (I.mayWriteToMemory())
8095 removeAssumedBits(NO_WRITES);
8096 return !isAtFixpoint();
8097 };
8098
8099 bool UsedAssumedInformation = false;
8100 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
8101 UsedAssumedInformation))
8102 return indicatePessimisticFixpoint();
8103
8104 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8106}
8107
8108ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
8109
8110 const IRPosition &IRP = getIRPosition();
8111 const IRPosition &FnPos = IRPosition::function_scope(IRP);
8112 AAMemoryBehavior::StateType &S = getState();
8113
8114 // First, check the function scope. We take the known information and we avoid
8115 // work if the assumed information implies the current assumed information for
8116 // this attribute. This is a valid for all but byval arguments.
8117 Argument *Arg = IRP.getAssociatedArgument();
8118 AAMemoryBehavior::base_t FnMemAssumedState =
8120 if (!Arg || !Arg->hasByValAttr()) {
8121 const auto *FnMemAA =
8122 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL);
8123 if (FnMemAA) {
8124 FnMemAssumedState = FnMemAA->getAssumed();
8125 S.addKnownBits(FnMemAA->getKnown());
8126 if ((S.getAssumed() & FnMemAA->getAssumed()) == S.getAssumed())
8128 }
8129 }
8130
8131 // The current assumed state used to determine a change.
8132 auto AssumedState = S.getAssumed();
8133
8134 // Make sure the value is not captured (except through "return"), if
8135 // it is, any information derived would be irrelevant anyway as we cannot
8136 // check the potential aliases introduced by the capture. However, no need
8137 // to fall back to anythign less optimistic than the function state.
8138 bool IsKnownNoCapture;
8139 const AANoCapture *ArgNoCaptureAA = nullptr;
8140 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
8141 A, this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture, false,
8142 &ArgNoCaptureAA);
8143
8144 if (!IsAssumedNoCapture &&
8145 (!ArgNoCaptureAA || !ArgNoCaptureAA->isAssumedNoCaptureMaybeReturned())) {
8146 S.intersectAssumedBits(FnMemAssumedState);
8147 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8149 }
8150
8151 // Visit and expand uses until all are analyzed or a fixpoint is reached.
8152 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
8153 Instruction *UserI = cast<Instruction>(U.getUser());
8154 LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << *U << " in " << *UserI
8155 << " \n");
8156
8157 // Droppable users, e.g., llvm::assume does not actually perform any action.
8158 if (UserI->isDroppable())
8159 return true;
8160
8161 // Check if the users of UserI should also be visited.
8162 Follow = followUsersOfUseIn(A, U, UserI);
8163
8164 // If UserI might touch memory we analyze the use in detail.
8165 if (UserI->mayReadOrWriteMemory())
8166 analyzeUseIn(A, U, UserI);
8167
8168 return !isAtFixpoint();
8169 };
8170
8171 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue()))
8172 return indicatePessimisticFixpoint();
8173
8174 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8176}
8177
8178bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use &U,
8179 const Instruction *UserI) {
8180 // The loaded value is unrelated to the pointer argument, no need to
8181 // follow the users of the load.
8182 if (isa<LoadInst>(UserI) || isa<ReturnInst>(UserI))
8183 return false;
8184
8185 // By default we follow all uses assuming UserI might leak information on U,
8186 // we have special handling for call sites operands though.
8187 const auto *CB = dyn_cast<CallBase>(UserI);
8188 if (!CB || !CB->isArgOperand(&U))
8189 return true;
8190
8191 // If the use is a call argument known not to be captured, the users of
8192 // the call do not need to be visited because they have to be unrelated to
8193 // the input. Note that this check is not trivial even though we disallow
8194 // general capturing of the underlying argument. The reason is that the
8195 // call might the argument "through return", which we allow and for which we
8196 // need to check call users.
8197 if (U.get()->getType()->isPointerTy()) {
8198 unsigned ArgNo = CB->getArgOperandNo(&U);
8199 bool IsKnownNoCapture;
8201 A, this, IRPosition::callsite_argument(*CB, ArgNo),
8202 DepClassTy::OPTIONAL, IsKnownNoCapture);
8203 }
8204
8205 return true;
8206}
8207
8208void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use &U,
8209 const Instruction *UserI) {
8210 assert(UserI->mayReadOrWriteMemory());
8211
8212 switch (UserI->getOpcode()) {
8213 default:
8214 // TODO: Handle all atomics and other side-effect operations we know of.
8215 break;
8216 case Instruction::Load:
8217 // Loads cause the NO_READS property to disappear.
8218 removeAssumedBits(NO_READS);
8219 return;
8220
8221 case Instruction::Store:
8222 // Stores cause the NO_WRITES property to disappear if the use is the
8223 // pointer operand. Note that while capturing was taken care of somewhere
8224 // else we need to deal with stores of the value that is not looked through.
8225 if (cast<StoreInst>(UserI)->getPointerOperand() == U.get())
8226 removeAssumedBits(NO_WRITES);
8227 else
8228 indicatePessimisticFixpoint();
8229 return;
8230
8231 case Instruction::Call:
8232 case Instruction::CallBr:
8233 case Instruction::Invoke: {
8234 // For call sites we look at the argument memory behavior attribute (this
8235 // could be recursive!) in order to restrict our own state.
8236 const auto *CB = cast<CallBase>(UserI);
8237
8238 // Give up on operand bundles.
8239 if (CB->isBundleOperand(&U)) {
8240 indicatePessimisticFixpoint();
8241 return;
8242 }
8243
8244 // Calling a function does read the function pointer, maybe write it if the
8245 // function is self-modifying.
8246 if (CB->isCallee(&U)) {
8247 removeAssumedBits(NO_READS);
8248 break;
8249 }
8250
8251 // Adjust the possible access behavior based on the information on the
8252 // argument.
8253 IRPosition Pos;
8254 if (U.get()->getType()->isPointerTy())
8256 else
8258 const auto *MemBehaviorAA =
8259 A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL);
8260 if (!MemBehaviorAA)
8261 break;
8262 // "assumed" has at most the same bits as the MemBehaviorAA assumed
8263 // and at least "known".
8264 intersectAssumedBits(MemBehaviorAA->getAssumed());
8265 return;
8266 }
8267 };
8268
8269 // Generally, look at the "may-properties" and adjust the assumed state if we
8270 // did not trigger special handling before.
8271 if (UserI->mayReadFromMemory())
8272 removeAssumedBits(NO_READS);
8273 if (UserI->mayWriteToMemory())
8274 removeAssumedBits(NO_WRITES);
8275}
8276} // namespace
8277
8278/// -------------------- Memory Locations Attributes ---------------------------
8279/// Includes read-none, argmemonly, inaccessiblememonly,
8280/// inaccessiblememorargmemonly
8281/// ----------------------------------------------------------------------------
8282
8285 if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
8286 return "all memory";
8288 return "no memory";
8289 std::string S = "memory:";
8290 if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
8291 S += "stack,";
8292 if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
8293 S += "constant,";
8295 S += "internal global,";
8297 S += "external global,";
8298 if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
8299 S += "argument,";
8301 S += "inaccessible,";
8302 if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
8303 S += "malloced,";
8304 if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
8305 S += "unknown,";
8306 S.pop_back();
8307 return S;
8308}
8309
8310namespace {
8311struct AAMemoryLocationImpl : public AAMemoryLocation {
8312
8313 AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
8314 : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
8315 AccessKind2Accesses.fill(nullptr);
8316 }
8317
8318 ~AAMemoryLocationImpl() override {
8319 // The AccessSets are allocated via a BumpPtrAllocator, we call
8320 // the destructor manually.
8321 for (AccessSet *AS : AccessKind2Accesses)
8322 if (AS)
8323 AS->~AccessSet();
8324 }
8325
8326 void initialize(Attributor &A) override {
8327 intersectAssumedBits(BEST_STATE);
8328 getKnownStateFromValue(A, getIRPosition(), getState());
8329 AAMemoryLocation::initialize(A);
8330 }
8331
8332 /// Return the memory behavior information encoded in the IR for \p IRP.
8333 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
8334 BitIntegerState &State,
8335 bool IgnoreSubsumingPositions = false) {
8336 // For internal functions we ignore `argmemonly` and
8337 // `inaccessiblememorargmemonly` as we might break it via interprocedural
8338 // constant propagation. It is unclear if this is the best way but it is
8339 // unlikely this will cause real performance problems. If we are deriving
8340 // attributes for the anchor function we even remove the attribute in
8341 // addition to ignoring it.
8342 // TODO: A better way to handle this would be to add ~NO_GLOBAL_MEM /
8343 // MemoryEffects::Other as a possible location.
8344 bool UseArgMemOnly = true;
8345 Function *AnchorFn = IRP.getAnchorScope();
8346 if (AnchorFn && A.isRunOn(*AnchorFn))
8347 UseArgMemOnly = !AnchorFn->hasLocalLinkage();
8348
8350 A.getAttrs(IRP, {Attribute::Memory}, Attrs, IgnoreSubsumingPositions);
8351 for (const Attribute &Attr : Attrs) {
8352 // TODO: We can map MemoryEffects to Attributor locations more precisely.
8353 MemoryEffects ME = Attr.getMemoryEffects();
8354 if (ME.doesNotAccessMemory()) {
8355 State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
8356 continue;
8357 }
8358 if (ME.onlyAccessesInaccessibleMem()) {
8359 State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
8360 continue;
8361 }
8362 if (ME.onlyAccessesArgPointees()) {
8363 if (UseArgMemOnly)
8364 State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
8365 else {
8366 // Remove location information, only keep read/write info.
8367 ME = MemoryEffects(ME.getModRef());
8368 A.manifestAttrs(IRP,
8369 Attribute::getWithMemoryEffects(
8370 IRP.getAnchorValue().getContext(), ME),
8371 /*ForceReplace*/ true);
8372 }
8373 continue;
8374 }
8376 if (UseArgMemOnly)
8377 State.addKnownBits(inverseLocation(
8378 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
8379 else {
8380 // Remove location information, only keep read/write info.
8381 ME = MemoryEffects(ME.getModRef());
8382 A.manifestAttrs(IRP,
8383 Attribute::getWithMemoryEffects(
8384 IRP.getAnchorValue().getContext(), ME),
8385 /*ForceReplace*/ true);
8386 }
8387 continue;
8388 }
8389 }
8390 }
8391
8392 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
8393 SmallVectorImpl<Attribute> &Attrs) const override {
8394 // TODO: We can map Attributor locations to MemoryEffects more precisely.
8395 assert(Attrs.size() == 0);
8396 if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
8397 if (isAssumedReadNone())
8398 Attrs.push_back(
8399 Attribute::getWithMemoryEffects(Ctx, MemoryEffects::none()));
8400 else if (isAssumedInaccessibleMemOnly())
8401 Attrs.push_back(Attribute::getWithMemoryEffects(
8403 else if (isAssumedArgMemOnly())
8404 Attrs.push_back(
8405 Attribute::getWithMemoryEffects(Ctx, MemoryEffects::argMemOnly()));
8406 else if (isAssumedInaccessibleOrArgMemOnly())
8407 Attrs.push_back(Attribute::getWithMemoryEffects(
8409 }
8410 assert(Attrs.size() <= 1);
8411 }
8412
8413 ChangeStatus manifest(Attributor &A) override {
8414 // TODO: If AAMemoryLocation and AAMemoryBehavior are merged, we could
8415 // provide per-location modref information here.
8416 const IRPosition &IRP = getIRPosition();
8417
8418 SmallVector<Attribute, 1> DeducedAttrs;
8419 getDeducedAttributes(A, IRP.getAnchorValue().getContext(), DeducedAttrs);
8420 if (DeducedAttrs.size() != 1)
8421 return ChangeStatus::UNCHANGED;
8422 MemoryEffects ME = DeducedAttrs[0].getMemoryEffects();
8423
8424 // Clear conflicting writable attributes of the function arguments.
8426 !isModSet(ME.getModRef(IRMemLocation::ArgMem))) {
8427 for (Argument &Arg : IRP.getAnchorScope()->args())
8428 A.removeAttrs(IRPosition::argument(Arg), Attribute::Writable);
8429 }
8430
8431 return A.manifestAttrs(IRP, Attribute::getWithMemoryEffects(
8432 IRP.getAnchorValue().getContext(), ME));
8433 }
8434
8435 bool checkForAllAccessesToMemoryKind(
8436 function_ref<bool(const Instruction *, const Value *, AccessKind,
8437 MemoryLocationsKind)>
8438 Pred,
8439 MemoryLocationsKind RequestedMLK) const override {
8440 if (!isValidState())
8441 return false;
8442
8443 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
8444 if (AssumedMLK == NO_LOCATIONS)
8445 return true;
8446
8447 unsigned Idx = 0;
8448 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
8449 CurMLK *= 2, ++Idx) {
8450 if (CurMLK & RequestedMLK)
8451 continue;
8452
8453 if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
8454 for (const AccessInfo &AI : *Accesses)
8455 if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
8456 return false;
8457 }
8458
8459 return true;
8460 }
8461
8462 ChangeStatus indicatePessimisticFixpoint() override {
8463 // If we give up and indicate a pessimistic fixpoint this instruction will
8464 // become an access for all potential access kinds:
8465 // TODO: Add pointers for argmemonly and globals to improve the results of
8466 // checkForAllAccessesToMemoryKind.
8467 bool Changed = false;
8468 MemoryLocationsKind KnownMLK = getKnown();
8469 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
8470 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
8471 if (!(CurMLK & KnownMLK))
8472 updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
8473 getAccessKindFromInst(I));
8474 return AAMemoryLocation::indicatePessimisticFixpoint();
8475 }
8476
8477protected:
8478 /// Helper struct to tie together an instruction that has a read or write
8479 /// effect with the pointer it accesses (if any).
8480 struct AccessInfo {
8481
8482 /// The instruction that caused the access.
8483 const Instruction *I;
8484
8485 /// The base pointer that is accessed, or null if unknown.
8486 const Value *Ptr;
8487
8488 /// The kind of access (read/write/read+write).
8490
8491 bool operator==(const AccessInfo &RHS) const {
8492 return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
8493 }
8494 bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
8495 if (LHS.I != RHS.I)
8496 return LHS.I < RHS.I;
8497 if (LHS.Ptr != RHS.Ptr)
8498 return LHS.Ptr < RHS.Ptr;
8499 if (LHS.Kind != RHS.Kind)
8500 return LHS.Kind < RHS.Kind;
8501 return false;
8502 }
8503 };
8504
8505 /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
8506 /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
8507 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
8508 std::array<AccessSet *, llvm::ConstantLog2<VALID_STATE>()>
8509 AccessKind2Accesses;
8510
8511 /// Categorize the pointer arguments of CB that might access memory in
8512 /// AccessedLoc and update the state and access map accordingly.
8513 void
8514 categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
8515 AAMemoryLocation::StateType &AccessedLocs,
8516 bool &Changed);
8517
8518 /// Return the kind(s) of location that may be accessed by \p V.
8520 categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
8521
8522 /// Return the access kind as determined by \p I.
8523 AccessKind getAccessKindFromInst(const Instruction *I) {
8524 AccessKind AK = READ_WRITE;
8525 if (I) {
8526 AK = I->mayReadFromMemory() ? READ : NONE;
8527 AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
8528 }
8529 return AK;
8530 }
8531
8532 /// Update the state \p State and the AccessKind2Accesses given that \p I is
8533 /// an access of kind \p AK to a \p MLK memory location with the access
8534 /// pointer \p Ptr.
8535 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
8536 MemoryLocationsKind MLK, const Instruction *I,
8537 const Value *Ptr, bool &Changed,
8538 AccessKind AK = READ_WRITE) {
8539
8540 assert(isPowerOf2_32(MLK) && "Expected a single location set!");
8541 auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
8542 if (!Accesses)
8543 Accesses = new (Allocator) AccessSet();
8544 Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
8545 if (MLK == NO_UNKOWN_MEM)
8546 MLK = NO_LOCATIONS;
8547 State.removeAssumedBits(MLK);
8548 }
8549
8550 /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
8551 /// arguments, and update the state and access map accordingly.
8552 void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
8553 AAMemoryLocation::StateType &State, bool &Changed,
8554 unsigned AccessAS = 0);
8555
8556 /// Used to allocate access sets.
8558};
8559
8560void AAMemoryLocationImpl::categorizePtrValue(
8561 Attributor &A, const Instruction &I, const Value &Ptr,
8562 AAMemoryLocation::StateType &State, bool &Changed, unsigned AccessAS) {
8563 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
8564 << Ptr << " ["
8565 << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
8566
8567 auto Pred = [&](Value &Obj) {
8568 unsigned ObjectAS = Obj.getType()->getPointerAddressSpace();
8569 // TODO: recognize the TBAA used for constant accesses.
8570 MemoryLocationsKind MLK = NO_LOCATIONS;
8571
8572 // Filter accesses to constant (GPU) memory if we have an AS at the access
8573 // site or the object is known to actually have the associated AS.
8574 if (AA::isGPU(A.getModule())) {
8575 if (AA::isGPUConstantAddressSpace(A.getModule(), AccessAS) ||
8576 (AA::isGPUConstantAddressSpace(A.getModule(), ObjectAS) &&
8577 isIdentifiedObject(&Obj)))
8578 return true;
8579 }
8580
8581 if (isa<UndefValue>(&Obj))
8582 return true;
8583 if (isa<Argument>(&Obj)) {
8584 // TODO: For now we do not treat byval arguments as local copies performed
8585 // on the call edge, though, we should. To make that happen we need to
8586 // teach various passes, e.g., DSE, about the copy effect of a byval. That
8587 // would also allow us to mark functions only accessing byval arguments as
8588 // readnone again, arguably their accesses have no effect outside of the
8589 // function, like accesses to allocas.
8590 MLK = NO_ARGUMENT_MEM;
8591 } else if (auto *GV = dyn_cast<GlobalValue>(&Obj)) {
8592 // Reading constant memory is not treated as a read "effect" by the
8593 // function attr pass so we won't neither. Constants defined by TBAA are
8594 // similar. (We know we do not write it because it is constant.)
8595 if (auto *GVar = dyn_cast<GlobalVariable>(GV))
8596 if (GVar->isConstant())
8597 return true;
8598
8599 if (GV->hasLocalLinkage())
8600 MLK = NO_GLOBAL_INTERNAL_MEM;
8601 else
8602 MLK = NO_GLOBAL_EXTERNAL_MEM;
8603 } else if (isa<ConstantPointerNull>(&Obj) && ObjectAS == AccessAS &&
8604 !NullPointerIsDefined(getAssociatedFunction(), AccessAS)) {
8605 // Accessing null is undefined, but not accessing a null pointer cast to
8606 // another address space, which may be a valid address there.
8607 return true;
8608 } else if (isa<AllocaInst>(&Obj)) {
8609 MLK = NO_LOCAL_MEM;
8610 } else if (const auto *CB = dyn_cast<CallBase>(&Obj)) {
8611 bool IsKnownNoAlias;
8614 IsKnownNoAlias))
8615 MLK = NO_MALLOCED_MEM;
8616 else
8617 MLK = NO_UNKOWN_MEM;
8618 } else {
8619 MLK = NO_UNKOWN_MEM;
8620 }
8621
8622 assert(MLK != NO_LOCATIONS && "No location specified!");
8623 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: "
8624 << Obj << " -> " << getMemoryLocationsAsStr(MLK) << "\n");
8625 updateStateAndAccessesMap(State, MLK, &I, &Obj, Changed,
8626 getAccessKindFromInst(&I));
8627
8628 return true;
8629 };
8630
8631 const auto *AA = A.getAAFor<AAUnderlyingObjects>(
8633 if (!AA || !AA->forallUnderlyingObjects(Pred, AA::Intraprocedural)) {
8634 LLVM_DEBUG(
8635 dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
8636 updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
8637 getAccessKindFromInst(&I));
8638 return;
8639 }
8640
8641 LLVM_DEBUG(
8642 dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: "
8643 << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
8644}
8645
8646void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
8647 Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
8648 bool &Changed) {
8649 for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) {
8650
8651 // Skip non-pointer arguments.
8652 const Value *ArgOp = CB.getArgOperand(ArgNo);
8653 if (!ArgOp->getType()->isPtrOrPtrVectorTy())
8654 continue;
8655
8656 // Skip readnone arguments.
8657 const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
8658 const auto *ArgOpMemLocationAA =
8659 A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL);
8660
8661 if (ArgOpMemLocationAA && ArgOpMemLocationAA->isAssumedReadNone())
8662 continue;
8663
8664 // Categorize potentially accessed pointer arguments as if there was an
8665 // access instruction with them as pointer.
8666 categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
8667 }
8668}
8669
8671AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
8672 bool &Changed) {
8673 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
8674 << I << "\n");
8675
8676 AAMemoryLocation::StateType AccessedLocs;
8677 AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
8678
8679 if (auto *CB = dyn_cast<CallBase>(&I)) {
8680
8681 // First check if we assume any memory is access is visible.
8682 const auto *CBMemLocationAA = A.getAAFor<AAMemoryLocation>(
8684 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
8685 << " [" << CBMemLocationAA << "]\n");
8686 if (!CBMemLocationAA) {
8687 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr,
8688 Changed, getAccessKindFromInst(&I));
8689 return NO_UNKOWN_MEM;
8690 }
8691
8692 if (CBMemLocationAA->isAssumedReadNone())
8693 return NO_LOCATIONS;
8694
8695 if (CBMemLocationAA->isAssumedInaccessibleMemOnly()) {
8696 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
8697 Changed, getAccessKindFromInst(&I));
8698 return AccessedLocs.getAssumed();
8699 }
8700
8701 uint32_t CBAssumedNotAccessedLocs =
8702 CBMemLocationAA->getAssumedNotAccessedLocation();
8703
8704 // Set the argmemonly and global bit as we handle them separately below.
8705 uint32_t CBAssumedNotAccessedLocsNoArgMem =
8706 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
8707
8708 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
8709 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
8710 continue;
8711 updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
8712 getAccessKindFromInst(&I));
8713 }
8714
8715 // Now handle global memory if it might be accessed. This is slightly tricky
8716 // as NO_GLOBAL_MEM has multiple bits set.
8717 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
8718 if (HasGlobalAccesses) {
8719 auto AccessPred = [&](const Instruction *, const Value *Ptr,
8720 AccessKind Kind, MemoryLocationsKind MLK) {
8721 updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
8722 getAccessKindFromInst(&I));
8723 return true;
8724 };
8725 if (!CBMemLocationAA->checkForAllAccessesToMemoryKind(
8726 AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
8727 return AccessedLocs.getWorstState();
8728 }
8729
8730 LLVM_DEBUG(
8731 dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
8732 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8733
8734 // Now handle argument memory if it might be accessed.
8735 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
8736 if (HasArgAccesses)
8737 categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
8738
8739 LLVM_DEBUG(
8740 dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
8741 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8742
8743 return AccessedLocs.getAssumed();
8744 }
8745
8746 if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
8747 LLVM_DEBUG(
8748 dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
8749 << I << " [" << *Ptr << "]\n");
8750 categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed,
8751 Ptr->getType()->getPointerAddressSpace());
8752 return AccessedLocs.getAssumed();
8753 }
8754
8755 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
8756 << I << "\n");
8757 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
8758 getAccessKindFromInst(&I));
8759 return AccessedLocs.getAssumed();
8760}
8761
8762/// An AA to represent the memory behavior function attributes.
8763struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
8764 AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
8765 : AAMemoryLocationImpl(IRP, A) {}
8766
8767 ChangeStatus updateImpl(Attributor &A) override {
8768
8769 const auto *MemBehaviorAA =
8770 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
8771 if (MemBehaviorAA && MemBehaviorAA->isAssumedReadNone()) {
8772 if (MemBehaviorAA->isKnownReadNone())
8773 return indicateOptimisticFixpoint();
8775 "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
8776 A.recordDependence(*MemBehaviorAA, *this, DepClassTy::OPTIONAL);
8777 return ChangeStatus::UNCHANGED;
8778 }
8779
8780 // The current assumed state used to determine a change.
8781 auto AssumedState = getAssumed();
8782 bool Changed = false;
8783
8784 auto CheckRWInst = [&](Instruction &I) {
8785 MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
8786 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
8787 << ": " << getMemoryLocationsAsStr(MLK) << "\n");
8788 removeAssumedBits(inverseLocation(MLK, false, false));
8789 // Stop once only the valid bit set in the *not assumed location*, thus
8790 // once we don't actually exclude any memory locations in the state.
8791 return getAssumedNotAccessedLocation() != VALID_STATE;
8792 };
8793
8794 bool UsedAssumedInformation = false;
8795 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
8796 UsedAssumedInformation))
8797 return indicatePessimisticFixpoint();
8798
8799 Changed |= AssumedState != getAssumed();
8800 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8801 }
8802
8803 void trackStatistics() const override {
8804 if (isAssumedReadNone())
8805 STATS_DECLTRACK_FN_ATTR(readnone)
8806 else if (isAssumedArgMemOnly())
8807 STATS_DECLTRACK_FN_ATTR(argmemonly)
8808 else if (isAssumedInaccessibleMemOnly())
8809 STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
8810 else if (isAssumedInaccessibleOrArgMemOnly())
8811 STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
8812 }
8813};
8814
8815/// AAMemoryLocation attribute for call sites.
8816struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
8817 AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
8818 : AAMemoryLocationImpl(IRP, A) {}
8819
8820 void initialize(Attributor &A) override {
8821 AAMemoryLocationImpl::initialize(A);
8822
8823 // Volatile calls may also access inaccessible memory, which the callee's
8824 // attributes do not say.
8825 auto &CB = cast<CallBase>(getAnchorValue());
8826 if (CB.isVolatile()) {
8827 bool Changed = false;
8828 removeKnownBits(NO_INACCESSIBLE_MEM);
8829 updateStateAndAccessesMap(getState(), NO_INACCESSIBLE_MEM, &CB, nullptr,
8830 Changed, getAccessKindFromInst(&CB));
8831 }
8832 }
8833
8834 ChangeStatus updateImpl(Attributor &A) override {
8835 // TODO: Once we have call site specific value information we can provide
8836 // call site specific liveness liveness information and then it makes
8837 // sense to specialize attributes for call sites arguments instead of
8838 // redirecting requests to the callee argument.
8839 Function *F = getAssociatedFunction();
8840 const IRPosition &FnPos = IRPosition::function(*F);
8841 auto *FnAA =
8842 A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED);
8843 if (!FnAA)
8844 return indicatePessimisticFixpoint();
8845 bool Changed = false;
8846 auto AccessPred = [&](const Instruction *I, const Value *Ptr,
8847 AccessKind Kind, MemoryLocationsKind MLK) {
8848 updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
8849 getAccessKindFromInst(I));
8850 return true;
8851 };
8852 if (!FnAA->checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
8853 return indicatePessimisticFixpoint();
8854 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8855 }
8856
8857 void trackStatistics() const override {
8858 if (isAssumedReadNone())
8859 STATS_DECLTRACK_CS_ATTR(readnone)
8860 }
8861};
8862} // namespace
8863
8864/// ------------------ denormal-fp-math Attribute -------------------------
8865
8866namespace {
8867struct AADenormalFPMathImpl : public AADenormalFPMath {
8868 AADenormalFPMathImpl(const IRPosition &IRP, Attributor &A)
8869 : AADenormalFPMath(IRP, A) {}
8870
8871 const std::string getAsStr(Attributor *A) const override {
8872 std::string Str("AADenormalFPMath[");
8873 raw_string_ostream OS(Str);
8874
8875 DenormalState Known = getKnown();
8876 if (Known.Mode.isValid())
8877 OS << "denormal-fp-math=" << Known.Mode;
8878 else
8879 OS << "invalid";
8880
8881 if (Known.ModeF32.isValid())
8882 OS << " denormal-fp-math-f32=" << Known.ModeF32;
8883 OS << ']';
8884 return Str;
8885 }
8886};
8887
8888struct AADenormalFPMathFunction final : AADenormalFPMathImpl {
8889 AADenormalFPMathFunction(const IRPosition &IRP, Attributor &A)
8890 : AADenormalFPMathImpl(IRP, A) {}
8891
8892 void initialize(Attributor &A) override {
8893 const Function *F = getAnchorScope();
8894 DenormalFPEnv DenormEnv = F->getDenormalFPEnv();
8895
8896 Known = DenormalState{DenormEnv.DefaultMode, DenormEnv.F32Mode};
8897 if (isModeFixed())
8898 indicateFixpoint();
8899 }
8900
8901 ChangeStatus updateImpl(Attributor &A) override {
8902 ChangeStatus Change = ChangeStatus::UNCHANGED;
8903
8904 auto CheckCallSite = [=, &Change, &A](AbstractCallSite CS) {
8905 Function *Caller = CS.getInstruction()->getFunction();
8906 LLVM_DEBUG(dbgs() << "[AADenormalFPMath] Call " << Caller->getName()
8907 << "->" << getAssociatedFunction()->getName() << '\n');
8908
8909 const auto *CallerInfo = A.getAAFor<AADenormalFPMath>(
8910 *this, IRPosition::function(*Caller), DepClassTy::REQUIRED);
8911 if (!CallerInfo)
8912 return false;
8913
8914 Change = Change | clampStateAndIndicateChange(this->getState(),
8915 CallerInfo->getState());
8916 return true;
8917 };
8918
8919 bool AllCallSitesKnown = true;
8920 if (!A.checkForAllCallSites(CheckCallSite, *this, true, AllCallSitesKnown))
8921 return indicatePessimisticFixpoint();
8922
8923 if (Change == ChangeStatus::CHANGED && isModeFixed())
8924 indicateFixpoint();
8925 return Change;
8926 }
8927
8928 ChangeStatus manifest(Attributor &A) override {
8929 LLVMContext &Ctx = getAssociatedFunction()->getContext();
8930
8931 SmallVector<Attribute, 2> AttrToAdd;
8933
8934 // TODO: Change to use DenormalFPEnv everywhere.
8935 DenormalFPEnv KnownEnv(Known.Mode, Known.ModeF32);
8936
8937 if (KnownEnv == DenormalFPEnv::getDefault()) {
8938 AttrToRemove.push_back(Attribute::DenormalFPEnv);
8939 } else {
8940 AttrToAdd.push_back(Attribute::get(
8941 Ctx, Attribute::DenormalFPEnv,
8942 DenormalFPEnv(Known.Mode, Known.ModeF32).toIntValue()));
8943 }
8944
8945 auto &IRP = getIRPosition();
8946
8947 // TODO: There should be a combined add and remove API.
8948 return A.removeAttrs(IRP, AttrToRemove) |
8949 A.manifestAttrs(IRP, AttrToAdd, /*ForceReplace=*/true);
8950 }
8951
8952 void trackStatistics() const override {
8953 STATS_DECLTRACK_FN_ATTR(denormal_fpenv)
8954 }
8955};
8956} // namespace
8957
8958/// ------------------ Value Constant Range Attribute -------------------------
8959
8960namespace {
8961struct AAValueConstantRangeImpl : AAValueConstantRange {
8962 using StateType = IntegerRangeState;
8963 AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
8964 : AAValueConstantRange(IRP, A) {}
8965
8966 void initialize(Attributor &A) override {
8967 if (A.hasSimplificationCallback(getIRPosition())) {
8968 indicatePessimisticFixpoint();
8969 return;
8970 }
8971
8972 // Intersect a range given by SCEV.
8973 intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
8974
8975 // Intersect a range given by LVI.
8976 intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
8977 }
8978
8979 const std::string getAsStr(Attributor *A) const override {
8980 std::string Str;
8981 llvm::raw_string_ostream OS(Str);
8982 OS << "range(" << getBitWidth() << ")<";
8983 getKnown().print(OS);
8984 OS << " / ";
8985 getAssumed().print(OS);
8986 OS << ">";
8987 return Str;
8988 }
8989
8990 /// Helper function to get a SCEV expr for the associated value at program
8991 /// point \p I.
8992 const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
8993 if (!getAnchorScope())
8994 return nullptr;
8995
8996 ScalarEvolution *SE =
8997 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8998 *getAnchorScope());
8999
9000 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
9001 *getAnchorScope());
9002
9003 if (!SE || !LI)
9004 return nullptr;
9005
9006 const SCEV *S = SE->getSCEV(&getAssociatedValue());
9007 if (!I)
9008 return S;
9009
9010 return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
9011 }
9012
9013 /// Helper function to get a range from SCEV for the associated value at
9014 /// program point \p I.
9015 ConstantRange getConstantRangeFromSCEV(Attributor &A,
9016 const Instruction *I = nullptr) const {
9017 if (!getAnchorScope())
9018 return getWorstState(getBitWidth());
9019
9020 ScalarEvolution *SE =
9021 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
9022 *getAnchorScope());
9023
9024 const SCEV *S = getSCEV(A, I);
9025 if (!SE || !S)
9026 return getWorstState(getBitWidth());
9027
9028 return SE->getUnsignedRange(S);
9029 }
9030
9031 /// Helper function to get a range from LVI for the associated value at
9032 /// program point \p I.
9033 ConstantRange
9034 getConstantRangeFromLVI(Attributor &A,
9035 const Instruction *CtxI = nullptr) const {
9036 if (!getAnchorScope())
9037 return getWorstState(getBitWidth());
9038
9039 LazyValueInfo *LVI =
9040 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
9041 *getAnchorScope());
9042
9043 if (!LVI || !CtxI)
9044 return getWorstState(getBitWidth());
9045 return LVI->getConstantRange(&getAssociatedValue(),
9046 const_cast<Instruction *>(CtxI),
9047 /*UndefAllowed*/ false);
9048 }
9049
9050 /// Return true if \p CtxI is valid for querying outside analyses.
9051 /// This basically makes sure we do not ask intra-procedural analysis
9052 /// about a context in the wrong function or a context that violates
9053 /// dominance assumptions they might have. The \p AllowAACtxI flag indicates
9054 /// if the original context of this AA is OK or should be considered invalid.
9055 bool isValidCtxInstructionForOutsideAnalysis(Attributor &A,
9056 const Instruction *CtxI,
9057 bool AllowAACtxI) const {
9058 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
9059 return false;
9060
9061 // Our context might be in a different function, neither intra-procedural
9062 // analysis (ScalarEvolution nor LazyValueInfo) can handle that.
9063 if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction()))
9064 return false;
9065
9066 // If the context is not dominated by the value there are paths to the
9067 // context that do not define the value. This cannot be handled by
9068 // LazyValueInfo so we need to bail.
9069 if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) {
9070 InformationCache &InfoCache = A.getInfoCache();
9071 const DominatorTree *DT =
9072 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
9073 *I->getFunction());
9074 return DT && DT->dominates(I, CtxI);
9075 }
9076
9077 return true;
9078 }
9079
9080 ConstantRange
9081 getAssumedConstantRange(Attributor &A,
9082 const Instruction *CtxI = nullptr) const override {
9083 // TODO: Make SCEV use Attributor assumption.
9084 // We may be able to bound a variable range via assumptions in
9085 // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
9086 // evolve to x^2 + x, then we can say that y is in [2, 12].
9087 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
9088 /* AllowAACtxI */ false))
9089 return getAssumed();
9090
9091 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
9092 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
9093 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
9094 }
9095
9096 /// Helper function to create MDNode for range metadata.
9097 static MDNode *
9098 getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
9099 const ConstantRange &AssumedConstantRange) {
9100 Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
9101 Ty, AssumedConstantRange.getLower())),
9102 ConstantAsMetadata::get(ConstantInt::get(
9103 Ty, AssumedConstantRange.getUpper()))};
9104 return MDNode::get(Ctx, LowAndHigh);
9105 }
9106
9107 /// Return true if \p Assumed is included in ranges from instruction \p I.
9108 static bool isBetterRange(const ConstantRange &Assumed,
9109 const Instruction &I) {
9110 if (Assumed.isFullSet())
9111 return false;
9112
9113 std::optional<ConstantRange> Known;
9114
9115 if (const auto *CB = dyn_cast<CallBase>(&I)) {
9116 Known = CB->getRange();
9117 } else if (MDNode *KnownRanges = I.getMetadata(LLVMContext::MD_range)) {
9118 // If multiple ranges are annotated in IR, we give up to annotate assumed
9119 // range for now.
9120
9121 // TODO: If there exists a known range which containts assumed range, we
9122 // can say assumed range is better.
9123 if (KnownRanges->getNumOperands() > 2)
9124 return false;
9125
9126 ConstantInt *Lower =
9127 mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
9128 ConstantInt *Upper =
9129 mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
9130
9131 Known.emplace(Lower->getValue(), Upper->getValue());
9132 }
9133 return !Known || (*Known != Assumed && Known->contains(Assumed));
9134 }
9135
9136 /// Helper function to set range metadata.
9137 static bool
9138 setRangeMetadataIfisBetterRange(Instruction *I,
9139 const ConstantRange &AssumedConstantRange) {
9140 if (isBetterRange(AssumedConstantRange, *I)) {
9141 I->setMetadata(LLVMContext::MD_range,
9142 getMDNodeForConstantRange(I->getType(), I->getContext(),
9143 AssumedConstantRange));
9144 return true;
9145 }
9146 return false;
9147 }
9148 /// Helper function to set range return attribute.
9149 static bool
9150 setRangeRetAttrIfisBetterRange(Attributor &A, const IRPosition &IRP,
9151 Instruction *I,
9152 const ConstantRange &AssumedConstantRange) {
9153 if (isBetterRange(AssumedConstantRange, *I)) {
9154 A.manifestAttrs(IRP,
9155 Attribute::get(I->getContext(), Attribute::Range,
9156 AssumedConstantRange),
9157 /*ForceReplace*/ true);
9158 return true;
9159 }
9160 return false;
9161 }
9162
9163 ChangeStatus manifest(Attributor &A) override {
9164 ChangeStatus Changed = ChangeStatus::UNCHANGED;
9165 ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
9166 assert(!AssumedConstantRange.isFullSet() && "Invalid state");
9167
9168 auto &V = getAssociatedValue();
9169 if (!AssumedConstantRange.isEmptySet() &&
9170 !AssumedConstantRange.isSingleElement()) {
9171 if (Instruction *I = dyn_cast<Instruction>(&V)) {
9172 assert(I == getCtxI() && "Should not annotate an instruction which is "
9173 "not the context instruction");
9174 if (isa<LoadInst>(I))
9175 if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
9176 Changed = ChangeStatus::CHANGED;
9177 if (isa<CallInst>(I))
9178 if (setRangeRetAttrIfisBetterRange(A, getIRPosition(), I,
9179 AssumedConstantRange))
9180 Changed = ChangeStatus::CHANGED;
9181 }
9182 }
9183
9184 return Changed;
9185 }
9186};
9187
9188struct AAValueConstantRangeArgument final
9189 : AAArgumentFromCallSiteArguments<
9190 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9191 true /* BridgeCallBaseContext */> {
9192 using Base = AAArgumentFromCallSiteArguments<
9193 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9194 true /* BridgeCallBaseContext */>;
9195 AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
9196 : Base(IRP, A) {}
9197
9198 void trackStatistics() const override {
9199 STATS_DECLTRACK_ARG_ATTR(value_range)
9200 }
9201};
9202
9203struct AAValueConstantRangeReturned
9204 : AAReturnedFromReturnedValues<AAValueConstantRange,
9205 AAValueConstantRangeImpl,
9206 AAValueConstantRangeImpl::StateType,
9207 /* PropagateCallBaseContext */ true> {
9208 using Base =
9209 AAReturnedFromReturnedValues<AAValueConstantRange,
9210 AAValueConstantRangeImpl,
9211 AAValueConstantRangeImpl::StateType,
9212 /* PropagateCallBaseContext */ true>;
9213 AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
9214 : Base(IRP, A) {}
9215
9216 void initialize(Attributor &A) override {
9217 if (!A.isFunctionIPOAmendable(*getAssociatedFunction()))
9218 indicatePessimisticFixpoint();
9219 }
9220
9221 void trackStatistics() const override {
9222 STATS_DECLTRACK_FNRET_ATTR(value_range)
9223 }
9224};
9225
9226struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
9227 AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
9228 : AAValueConstantRangeImpl(IRP, A) {}
9229
9230 void initialize(Attributor &A) override {
9231 AAValueConstantRangeImpl::initialize(A);
9232 if (isAtFixpoint())
9233 return;
9234
9235 Value &V = getAssociatedValue();
9236
9237 if (auto *C = dyn_cast<ConstantInt>(&V)) {
9238 unionAssumed(ConstantRange(C->getValue()));
9239 indicateOptimisticFixpoint();
9240 return;
9241 }
9242
9243 if (isa<UndefValue>(&V)) {
9244 // Collapse the undef state to 0.
9245 unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
9246 indicateOptimisticFixpoint();
9247 return;
9248 }
9249
9250 if (isa<CallBase>(&V))
9251 return;
9252
9254 return;
9255
9256 // If it is a load instruction with range metadata, use it.
9257 if (LoadInst *LI = dyn_cast<LoadInst>(&V))
9258 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
9259 intersectKnown(getConstantRangeFromMetadata(*RangeMD));
9260 return;
9261 }
9262
9263 // We can work with PHI and select instruction as we traverse their operands
9264 // during update.
9266 return;
9267
9268 // Otherwise we give up.
9269 indicatePessimisticFixpoint();
9270
9271 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
9272 << getAssociatedValue() << "\n");
9273 }
9274
9275 bool calculateBinaryOperator(
9276 Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
9277 const Instruction *CtxI,
9278 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9279 Value *LHS = BinOp->getOperand(0);
9280 Value *RHS = BinOp->getOperand(1);
9281
9282 // Simplify the operands first.
9283 bool UsedAssumedInformation = false;
9284 const auto &SimplifiedLHS = A.getAssumedSimplified(
9285 IRPosition::value(*LHS, getCallBaseContext()), *this,
9286 UsedAssumedInformation, AA::Interprocedural);
9287 if (!SimplifiedLHS.has_value())
9288 return true;
9289 if (!*SimplifiedLHS)
9290 return false;
9291 LHS = *SimplifiedLHS;
9292
9293 const auto &SimplifiedRHS = A.getAssumedSimplified(
9294 IRPosition::value(*RHS, getCallBaseContext()), *this,
9295 UsedAssumedInformation, AA::Interprocedural);
9296 if (!SimplifiedRHS.has_value())
9297 return true;
9298 if (!*SimplifiedRHS)
9299 return false;
9300 RHS = *SimplifiedRHS;
9301
9302 // TODO: Allow non integers as well.
9303 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9304 return false;
9305
9306 auto *LHSAA = A.getAAFor<AAValueConstantRange>(
9307 *this, IRPosition::value(*LHS, getCallBaseContext()),
9308 DepClassTy::REQUIRED);
9309 if (!LHSAA)
9310 return false;
9311 QuerriedAAs.push_back(LHSAA);
9312 auto LHSAARange = LHSAA->getAssumedConstantRange(A, CtxI);
9313
9314 auto *RHSAA = A.getAAFor<AAValueConstantRange>(
9315 *this, IRPosition::value(*RHS, getCallBaseContext()),
9316 DepClassTy::REQUIRED);
9317 if (!RHSAA)
9318 return false;
9319 QuerriedAAs.push_back(RHSAA);
9320 auto RHSAARange = RHSAA->getAssumedConstantRange(A, CtxI);
9321
9322 auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
9323
9324 T.unionAssumed(AssumedRange);
9325
9326 // TODO: Track a known state too.
9327
9328 return T.isValidState();
9329 }
9330
9331 bool calculateCastInst(
9332 Attributor &A, CastInst *CastI, IntegerRangeState &T,
9333 const Instruction *CtxI,
9334 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9335 assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
9336 // TODO: Allow non integers as well.
9337 Value *OpV = CastI->getOperand(0);
9338
9339 // Simplify the operand first.
9340 bool UsedAssumedInformation = false;
9341 const auto &SimplifiedOpV = A.getAssumedSimplified(
9342 IRPosition::value(*OpV, getCallBaseContext()), *this,
9343 UsedAssumedInformation, AA::Interprocedural);
9344 if (!SimplifiedOpV.has_value())
9345 return true;
9346 if (!*SimplifiedOpV)
9347 return false;
9348 OpV = *SimplifiedOpV;
9349
9350 if (!OpV->getType()->isIntegerTy())
9351 return false;
9352
9353 auto *OpAA = A.getAAFor<AAValueConstantRange>(
9354 *this, IRPosition::value(*OpV, getCallBaseContext()),
9355 DepClassTy::REQUIRED);
9356 if (!OpAA)
9357 return false;
9358 QuerriedAAs.push_back(OpAA);
9359 T.unionAssumed(OpAA->getAssumed().castOp(CastI->getOpcode(),
9360 getState().getBitWidth()));
9361 return T.isValidState();
9362 }
9363
9364 bool
9365 calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
9366 const Instruction *CtxI,
9367 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9368 Value *LHS = CmpI->getOperand(0);
9369 Value *RHS = CmpI->getOperand(1);
9370
9371 // Simplify the operands first.
9372 bool UsedAssumedInformation = false;
9373 const auto &SimplifiedLHS = A.getAssumedSimplified(
9374 IRPosition::value(*LHS, getCallBaseContext()), *this,
9375 UsedAssumedInformation, AA::Interprocedural);
9376 if (!SimplifiedLHS.has_value())
9377 return true;
9378 if (!*SimplifiedLHS)
9379 return false;
9380 LHS = *SimplifiedLHS;
9381
9382 const auto &SimplifiedRHS = A.getAssumedSimplified(
9383 IRPosition::value(*RHS, getCallBaseContext()), *this,
9384 UsedAssumedInformation, AA::Interprocedural);
9385 if (!SimplifiedRHS.has_value())
9386 return true;
9387 if (!*SimplifiedRHS)
9388 return false;
9389 RHS = *SimplifiedRHS;
9390
9391 // TODO: Allow non integers as well.
9392 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9393 return false;
9394
9395 auto *LHSAA = A.getAAFor<AAValueConstantRange>(
9396 *this, IRPosition::value(*LHS, getCallBaseContext()),
9397 DepClassTy::REQUIRED);
9398 if (!LHSAA)
9399 return false;
9400 QuerriedAAs.push_back(LHSAA);
9401 auto *RHSAA = A.getAAFor<AAValueConstantRange>(
9402 *this, IRPosition::value(*RHS, getCallBaseContext()),
9403 DepClassTy::REQUIRED);
9404 if (!RHSAA)
9405 return false;
9406 QuerriedAAs.push_back(RHSAA);
9407 auto LHSAARange = LHSAA->getAssumedConstantRange(A, CtxI);
9408 auto RHSAARange = RHSAA->getAssumedConstantRange(A, CtxI);
9409
9410 // If one of them is empty set, we can't decide.
9411 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
9412 return true;
9413
9414 bool MustTrue = false, MustFalse = false;
9415
9416 auto AllowedRegion =
9418
9419 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
9420 MustFalse = true;
9421
9422 if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange))
9423 MustTrue = true;
9424
9425 assert((!MustTrue || !MustFalse) &&
9426 "Either MustTrue or MustFalse should be false!");
9427
9428 if (MustTrue)
9429 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
9430 else if (MustFalse)
9431 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
9432 else
9433 T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
9434
9435 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " after "
9436 << (MustTrue ? "true" : (MustFalse ? "false" : "unknown"))
9437 << ": " << T << "\n\t" << *LHSAA << "\t<op>\n\t"
9438 << *RHSAA);
9439
9440 // TODO: Track a known state too.
9441 return T.isValidState();
9442 }
9443
9444 ChangeStatus updateImpl(Attributor &A) override {
9445
9446 IntegerRangeState T(getBitWidth());
9447 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
9449 if (!I || isa<CallBase>(I)) {
9450
9451 // Simplify the operand first.
9452 bool UsedAssumedInformation = false;
9453 const auto &SimplifiedOpV = A.getAssumedSimplified(
9454 IRPosition::value(V, getCallBaseContext()), *this,
9455 UsedAssumedInformation, AA::Interprocedural);
9456 if (!SimplifiedOpV.has_value())
9457 return true;
9458 if (!*SimplifiedOpV)
9459 return false;
9460 Value *VPtr = *SimplifiedOpV;
9461
9462 // If the value is not instruction, we query AA to Attributor.
9463 const auto *AA = A.getAAFor<AAValueConstantRange>(
9464 *this, IRPosition::value(*VPtr, getCallBaseContext()),
9465 DepClassTy::REQUIRED);
9466
9467 // Clamp operator is not used to utilize a program point CtxI.
9468 if (AA)
9469 T.unionAssumed(AA->getAssumedConstantRange(A, CtxI));
9470 else
9471 return false;
9472
9473 return T.isValidState();
9474 }
9475
9477 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
9478 if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
9479 return false;
9480 } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
9481 if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
9482 return false;
9483 } else if (auto *CastI = dyn_cast<CastInst>(I)) {
9484 if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
9485 return false;
9486 } else {
9487 // Give up with other instructions.
9488 // TODO: Add other instructions
9489
9490 T.indicatePessimisticFixpoint();
9491 return false;
9492 }
9493
9494 // Catch circular reasoning in a pessimistic way for now.
9495 // TODO: Check how the range evolves and if we stripped anything, see also
9496 // AADereferenceable or AAAlign for similar situations.
9497 for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
9498 if (QueriedAA != this)
9499 continue;
9500 // If we are in a stady state we do not need to worry.
9501 if (T.getAssumed() == getState().getAssumed())
9502 continue;
9503 T.indicatePessimisticFixpoint();
9504 }
9505
9506 return T.isValidState();
9507 };
9508
9509 if (!VisitValueCB(getAssociatedValue(), getCtxI()))
9510 return indicatePessimisticFixpoint();
9511
9512 // Ensure that long def-use chains can't cause circular reasoning either by
9513 // introducing a cutoff below.
9514 if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED)
9515 return ChangeStatus::UNCHANGED;
9516 if (++NumChanges > MaxNumChanges) {
9517 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges
9518 << " but only " << MaxNumChanges
9519 << " are allowed to avoid cyclic reasoning.");
9520 return indicatePessimisticFixpoint();
9521 }
9522 return ChangeStatus::CHANGED;
9523 }
9524
9525 void trackStatistics() const override {
9527 }
9528
9529 /// Tracker to bail after too many widening steps of the constant range.
9530 int NumChanges = 0;
9531
9532 /// Upper bound for the number of allowed changes (=widening steps) for the
9533 /// constant range before we give up.
9534 static constexpr int MaxNumChanges = 5;
9535};
9536
9537struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
9538 AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
9539 : AAValueConstantRangeImpl(IRP, A) {}
9540
9541 ChangeStatus updateImpl(Attributor &A) override {
9542 llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
9543 "not be called");
9544 }
9545
9546 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
9547};
9548
9549struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
9550 AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
9551 : AAValueConstantRangeFunction(IRP, A) {}
9552
9553 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
9554};
9555
9556struct AAValueConstantRangeCallSiteReturned
9557 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9558 AAValueConstantRangeImpl::StateType,
9559 /* IntroduceCallBaseContext */ true> {
9560 AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
9561 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9562 AAValueConstantRangeImpl::StateType,
9563 /* IntroduceCallBaseContext */ true>(IRP, A) {}
9564
9565 void initialize(Attributor &A) override {
9566 // If it is a call instruction with range attribute, use the range.
9567 if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue())) {
9568 if (std::optional<ConstantRange> Range = CI->getRange())
9569 intersectKnown(*Range);
9570 }
9571
9572 AAValueConstantRangeImpl::initialize(A);
9573 }
9574
9575 void trackStatistics() const override {
9576 STATS_DECLTRACK_CSRET_ATTR(value_range)
9577 }
9578};
9579struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
9580 AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
9581 : AAValueConstantRangeFloating(IRP, A) {}
9582
9583 ChangeStatus manifest(Attributor &A) override {
9584 return ChangeStatus::UNCHANGED;
9585 }
9586
9587 void trackStatistics() const override {
9588 STATS_DECLTRACK_CSARG_ATTR(value_range)
9589 }
9590};
9591} // namespace
9592
9593/// ------------------ Potential Values Attribute -------------------------
9594
9596 Attributor &A)
9597 : Base(IRP, true, A.Opts.attributor_max_potential_values) {}
9598
9599namespace {
9600struct AAPotentialConstantValuesImpl : AAPotentialConstantValues {
9601 using StateType = PotentialConstantIntValuesState;
9602
9603 AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A)
9604 : AAPotentialConstantValues(IRP, A) {}
9605
9606 void initialize(Attributor &A) override {
9607 if (A.hasSimplificationCallback(getIRPosition()))
9608 indicatePessimisticFixpoint();
9609 else
9611 }
9612
9613 bool fillSetWithConstantValues(Attributor &A, const IRPosition &IRP, SetTy &S,
9614 bool &ContainsUndef, bool ForSelf) {
9616 bool UsedAssumedInformation = false;
9617 if (!A.getAssumedSimplifiedValues(IRP, *this, Values, AA::Interprocedural,
9618 UsedAssumedInformation)) {
9619 // Avoid recursion when the caller is computing constant values for this
9620 // IRP itself.
9621 if (ForSelf)
9622 return false;
9623 if (!IRP.getAssociatedType()->isIntegerTy())
9624 return false;
9625 auto *PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>(
9626 *this, IRP, DepClassTy::REQUIRED);
9627 if (!PotentialValuesAA || !PotentialValuesAA->getState().isValidState())
9628 return false;
9629 ContainsUndef = PotentialValuesAA->getState().undefIsContained();
9630 S = PotentialValuesAA->getState().getAssumedSet();
9631 return true;
9632 }
9633
9634 // Copy all the constant values, except UndefValue. ContainsUndef is true
9635 // iff Values contains only UndefValue instances. If there are other known
9636 // constants, then UndefValue is dropped.
9637 ContainsUndef = false;
9638 for (auto &It : Values) {
9639 if (isa<UndefValue>(It.getValue())) {
9640 ContainsUndef = true;
9641 continue;
9642 }
9643 auto *CI = dyn_cast<ConstantInt>(It.getValue());
9644 if (!CI)
9645 return false;
9646 S.insert(CI->getValue());
9647 }
9648 ContainsUndef &= S.empty();
9649
9650 return true;
9651 }
9652
9653 const std::string getAsStr(Attributor *A) const override {
9654 std::string Str;
9655 llvm::raw_string_ostream OS(Str);
9656 OS << getState();
9657 return Str;
9658 }
9659
9660 ChangeStatus updateImpl(Attributor &A) override {
9661 return indicatePessimisticFixpoint();
9662 }
9663};
9664
9665struct AAPotentialConstantValuesArgument final
9666 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9667 AAPotentialConstantValuesImpl,
9668 PotentialConstantIntValuesState> {
9669 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9670 AAPotentialConstantValuesImpl,
9672 AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A)
9673 : Base(IRP, A) {}
9674
9675 void trackStatistics() const override {
9676 STATS_DECLTRACK_ARG_ATTR(potential_values)
9677 }
9678};
9679
9680struct AAPotentialConstantValuesReturned
9681 : AAReturnedFromReturnedValues<AAPotentialConstantValues,
9682 AAPotentialConstantValuesImpl> {
9683 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
9684 AAPotentialConstantValuesImpl>;
9685 AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A)
9686 : Base(IRP, A) {}
9687
9688 void initialize(Attributor &A) override {
9689 if (!A.isFunctionIPOAmendable(*getAssociatedFunction()))
9690 indicatePessimisticFixpoint();
9691 Base::initialize(A);
9692 }
9693
9694 void trackStatistics() const override {
9695 STATS_DECLTRACK_FNRET_ATTR(potential_values)
9696 }
9697};
9698
9699struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
9700 AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A)
9701 : AAPotentialConstantValuesImpl(IRP, A) {}
9702
9703 void initialize(Attributor &A) override {
9704 AAPotentialConstantValuesImpl::initialize(A);
9705 if (isAtFixpoint())
9706 return;
9707
9708 Value &V = getAssociatedValue();
9709
9710 if (auto *C = dyn_cast<ConstantInt>(&V)) {
9711 unionAssumed(C->getValue());
9712 indicateOptimisticFixpoint();
9713 return;
9714 }
9715
9716 if (isa<UndefValue>(&V)) {
9717 unionAssumedWithUndef();
9718 indicateOptimisticFixpoint();
9719 return;
9720 }
9721
9723 return;
9724
9726 return;
9727
9728 indicatePessimisticFixpoint();
9729
9730 LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: "
9731 << getAssociatedValue() << "\n");
9732 }
9733
9734 static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
9735 const APInt &RHS) {
9736 return ICmpInst::compare(LHS, RHS, ICI->getPredicate());
9737 }
9738
9739 static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
9740 uint32_t ResultBitWidth) {
9741 Instruction::CastOps CastOp = CI->getOpcode();
9742 switch (CastOp) {
9743 default:
9744 llvm_unreachable("unsupported or not integer cast");
9745 case Instruction::Trunc:
9746 return Src.trunc(ResultBitWidth);
9747 case Instruction::SExt:
9748 return Src.sext(ResultBitWidth);
9749 case Instruction::ZExt:
9750 return Src.zext(ResultBitWidth);
9751 case Instruction::BitCast:
9752 return Src;
9753 }
9754 }
9755
9756 static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
9757 const APInt &LHS, const APInt &RHS,
9758 bool &SkipOperation, bool &Unsupported) {
9759 Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
9760 // Unsupported is set to true when the binary operator is not supported.
9761 // SkipOperation is set to true when UB occur with the given operand pair
9762 // (LHS, RHS).
9763 // TODO: we should look at nsw and nuw keywords to handle operations
9764 // that create poison or undef value.
9765 switch (BinOpcode) {
9766 default:
9767 Unsupported = true;
9768 return LHS;
9769 case Instruction::Add:
9770 return LHS + RHS;
9771 case Instruction::Sub:
9772 return LHS - RHS;
9773 case Instruction::Mul:
9774 return LHS * RHS;
9775 case Instruction::UDiv:
9776 if (RHS.isZero()) {
9777 SkipOperation = true;
9778 return LHS;
9779 }
9780 return LHS.udiv(RHS);
9781 case Instruction::SDiv:
9782 if (RHS.isZero()) {
9783 SkipOperation = true;
9784 return LHS;
9785 }
9786 return LHS.sdiv(RHS);
9787 case Instruction::URem:
9788 if (RHS.isZero()) {
9789 SkipOperation = true;
9790 return LHS;
9791 }
9792 return LHS.urem(RHS);
9793 case Instruction::SRem:
9794 if (RHS.isZero()) {
9795 SkipOperation = true;
9796 return LHS;
9797 }
9798 return LHS.srem(RHS);
9799 case Instruction::Shl:
9800 return LHS.shl(RHS);
9801 case Instruction::LShr:
9802 return LHS.lshr(RHS);
9803 case Instruction::AShr:
9804 return LHS.ashr(RHS);
9805 case Instruction::And:
9806 return LHS & RHS;
9807 case Instruction::Or:
9808 return LHS | RHS;
9809 case Instruction::Xor:
9810 return LHS ^ RHS;
9811 }
9812 }
9813
9814 bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp,
9815 const APInt &LHS, const APInt &RHS) {
9816 bool SkipOperation = false;
9817 bool Unsupported = false;
9818 APInt Result =
9819 calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported);
9820 if (Unsupported)
9821 return false;
9822 // If SkipOperation is true, we can ignore this operand pair (L, R).
9823 if (!SkipOperation)
9824 unionAssumed(Result);
9825 return isValidState();
9826 }
9827
9828 ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
9829 auto AssumedBefore = getAssumed();
9830 Value *LHS = ICI->getOperand(0);
9831 Value *RHS = ICI->getOperand(1);
9832
9833 bool LHSContainsUndef = false, RHSContainsUndef = false;
9834 SetTy LHSAAPVS, RHSAAPVS;
9835 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9836 LHSContainsUndef, /* ForSelf */ false) ||
9837 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9838 RHSContainsUndef, /* ForSelf */ false))
9839 return indicatePessimisticFixpoint();
9840
9841 // TODO: make use of undef flag to limit potential values aggressively.
9842 bool MaybeTrue = false, MaybeFalse = false;
9843 const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0);
9844 if (LHSContainsUndef && RHSContainsUndef) {
9845 // The result of any comparison between undefs can be soundly replaced
9846 // with undef.
9847 unionAssumedWithUndef();
9848 } else if (LHSContainsUndef) {
9849 for (const APInt &R : RHSAAPVS) {
9850 bool CmpResult = calculateICmpInst(ICI, Zero, R);
9851 MaybeTrue |= CmpResult;
9852 MaybeFalse |= !CmpResult;
9853 if (MaybeTrue & MaybeFalse)
9854 return indicatePessimisticFixpoint();
9855 }
9856 } else if (RHSContainsUndef) {
9857 for (const APInt &L : LHSAAPVS) {
9858 bool CmpResult = calculateICmpInst(ICI, L, Zero);
9859 MaybeTrue |= CmpResult;
9860 MaybeFalse |= !CmpResult;
9861 if (MaybeTrue & MaybeFalse)
9862 return indicatePessimisticFixpoint();
9863 }
9864 } else {
9865 for (const APInt &L : LHSAAPVS) {
9866 for (const APInt &R : RHSAAPVS) {
9867 bool CmpResult = calculateICmpInst(ICI, L, R);
9868 MaybeTrue |= CmpResult;
9869 MaybeFalse |= !CmpResult;
9870 if (MaybeTrue & MaybeFalse)
9871 return indicatePessimisticFixpoint();
9872 }
9873 }
9874 }
9875 if (MaybeTrue)
9876 unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
9877 if (MaybeFalse)
9878 unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
9879 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9880 : ChangeStatus::CHANGED;
9881 }
9882
9883 ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
9884 auto AssumedBefore = getAssumed();
9885 Value *LHS = SI->getTrueValue();
9886 Value *RHS = SI->getFalseValue();
9887
9888 bool UsedAssumedInformation = false;
9889 std::optional<Constant *> C = A.getAssumedConstant(
9890 *SI->getCondition(), *this, UsedAssumedInformation);
9891
9892 // Check if we only need one operand.
9893 bool OnlyLeft = false, OnlyRight = false;
9894 if (C && *C && (*C)->isOneValue())
9895 OnlyLeft = true;
9896 else if (C && *C && (*C)->isNullValue())
9897 OnlyRight = true;
9898
9899 bool LHSContainsUndef = false, RHSContainsUndef = false;
9900 SetTy LHSAAPVS, RHSAAPVS;
9901 if (!OnlyRight &&
9902 !fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9903 LHSContainsUndef, /* ForSelf */ false))
9904 return indicatePessimisticFixpoint();
9905
9906 if (!OnlyLeft &&
9907 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9908 RHSContainsUndef, /* ForSelf */ false))
9909 return indicatePessimisticFixpoint();
9910
9911 if (OnlyLeft || OnlyRight) {
9912 // select (true/false), lhs, rhs
9913 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS;
9914 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef;
9915
9916 if (Undef)
9917 unionAssumedWithUndef();
9918 else {
9919 for (const auto &It : *OpAA)
9920 unionAssumed(It);
9921 }
9922
9923 } else if (LHSContainsUndef && RHSContainsUndef) {
9924 // select i1 *, undef , undef => undef
9925 unionAssumedWithUndef();
9926 } else {
9927 for (const auto &It : LHSAAPVS)
9928 unionAssumed(It);
9929 for (const auto &It : RHSAAPVS)
9930 unionAssumed(It);
9931 }
9932 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9933 : ChangeStatus::CHANGED;
9934 }
9935
9936 ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
9937 auto AssumedBefore = getAssumed();
9938 if (!CI->isIntegerCast())
9939 return indicatePessimisticFixpoint();
9940 assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
9941 uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
9942 Value *Src = CI->getOperand(0);
9943
9944 bool SrcContainsUndef = false;
9945 SetTy SrcPVS;
9946 if (!fillSetWithConstantValues(A, IRPosition::value(*Src), SrcPVS,
9947 SrcContainsUndef, /* ForSelf */ false))
9948 return indicatePessimisticFixpoint();
9949
9950 if (SrcContainsUndef)
9951 unionAssumedWithUndef();
9952 else {
9953 for (const APInt &S : SrcPVS) {
9954 APInt T = calculateCastInst(CI, S, ResultBitWidth);
9955 unionAssumed(T);
9956 }
9957 }
9958 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9959 : ChangeStatus::CHANGED;
9960 }
9961
9962 ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
9963 auto AssumedBefore = getAssumed();
9964 Value *LHS = BinOp->getOperand(0);
9965 Value *RHS = BinOp->getOperand(1);
9966
9967 bool LHSContainsUndef = false, RHSContainsUndef = false;
9968 SetTy LHSAAPVS, RHSAAPVS;
9969 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9970 LHSContainsUndef, /* ForSelf */ false) ||
9971 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9972 RHSContainsUndef, /* ForSelf */ false))
9973 return indicatePessimisticFixpoint();
9974
9975 const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0);
9976
9977 // TODO: make use of undef flag to limit potential values aggressively.
9978 if (LHSContainsUndef && RHSContainsUndef) {
9979 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero))
9980 return indicatePessimisticFixpoint();
9981 } else if (LHSContainsUndef) {
9982 for (const APInt &R : RHSAAPVS) {
9983 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R))
9984 return indicatePessimisticFixpoint();
9985 }
9986 } else if (RHSContainsUndef) {
9987 for (const APInt &L : LHSAAPVS) {
9988 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero))
9989 return indicatePessimisticFixpoint();
9990 }
9991 } else {
9992 for (const APInt &L : LHSAAPVS) {
9993 for (const APInt &R : RHSAAPVS) {
9994 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9995 return indicatePessimisticFixpoint();
9996 }
9997 }
9998 }
9999 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10000 : ChangeStatus::CHANGED;
10001 }
10002
10003 ChangeStatus updateWithInstruction(Attributor &A, Instruction *Inst) {
10004 auto AssumedBefore = getAssumed();
10005 SetTy Incoming;
10006 bool ContainsUndef;
10007 if (!fillSetWithConstantValues(A, IRPosition::value(*Inst), Incoming,
10008 ContainsUndef, /* ForSelf */ true))
10009 return indicatePessimisticFixpoint();
10010 if (ContainsUndef) {
10011 unionAssumedWithUndef();
10012 } else {
10013 for (const auto &It : Incoming)
10014 unionAssumed(It);
10015 }
10016 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10017 : ChangeStatus::CHANGED;
10018 }
10019
10020 ChangeStatus updateImpl(Attributor &A) override {
10021 Value &V = getAssociatedValue();
10023
10024 if (auto *ICI = dyn_cast<ICmpInst>(I))
10025 return updateWithICmpInst(A, ICI);
10026
10027 if (auto *SI = dyn_cast<SelectInst>(I))
10028 return updateWithSelectInst(A, SI);
10029
10030 if (auto *CI = dyn_cast<CastInst>(I))
10031 return updateWithCastInst(A, CI);
10032
10033 if (auto *BinOp = dyn_cast<BinaryOperator>(I))
10034 return updateWithBinaryOperator(A, BinOp);
10035
10036 if (isa<PHINode>(I) || isa<LoadInst>(I))
10037 return updateWithInstruction(A, I);
10038
10039 return indicatePessimisticFixpoint();
10040 }
10041
10042 void trackStatistics() const override {
10043 STATS_DECLTRACK_FLOATING_ATTR(potential_values)
10044 }
10045};
10046
10047struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
10048 AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A)
10049 : AAPotentialConstantValuesImpl(IRP, A) {}
10050
10051 ChangeStatus updateImpl(Attributor &A) override {
10053 "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
10054 "not be called");
10055 }
10056
10057 void trackStatistics() const override {
10058 STATS_DECLTRACK_FN_ATTR(potential_values)
10059 }
10060};
10061
10062struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
10063 AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A)
10064 : AAPotentialConstantValuesFunction(IRP, A) {}
10065
10066 void trackStatistics() const override {
10067 STATS_DECLTRACK_CS_ATTR(potential_values)
10068 }
10069};
10070
10071struct AAPotentialConstantValuesCallSiteReturned
10072 : AACalleeToCallSite<AAPotentialConstantValues,
10073 AAPotentialConstantValuesImpl> {
10074 AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP,
10075 Attributor &A)
10076 : AACalleeToCallSite<AAPotentialConstantValues,
10077 AAPotentialConstantValuesImpl>(IRP, A) {}
10078
10079 void trackStatistics() const override {
10080 STATS_DECLTRACK_CSRET_ATTR(potential_values)
10081 }
10082};
10083
10084struct AAPotentialConstantValuesCallSiteArgument
10085 : AAPotentialConstantValuesFloating {
10086 AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP,
10087 Attributor &A)
10088 : AAPotentialConstantValuesFloating(IRP, A) {}
10089
10090 void initialize(Attributor &A) override {
10091 AAPotentialConstantValuesImpl::initialize(A);
10092 if (isAtFixpoint())
10093 return;
10094
10095 Value &V = getAssociatedValue();
10096
10097 if (auto *C = dyn_cast<ConstantInt>(&V)) {
10098 unionAssumed(C->getValue());
10099 indicateOptimisticFixpoint();
10100 return;
10101 }
10102
10103 if (isa<UndefValue>(&V)) {
10104 unionAssumedWithUndef();
10105 indicateOptimisticFixpoint();
10106 return;
10107 }
10108 }
10109
10110 ChangeStatus updateImpl(Attributor &A) override {
10111 Value &V = getAssociatedValue();
10112 auto AssumedBefore = getAssumed();
10113 auto *AA = A.getAAFor<AAPotentialConstantValues>(
10114 *this, IRPosition::value(V), DepClassTy::REQUIRED);
10115 if (!AA)
10116 return indicatePessimisticFixpoint();
10117 const auto &S = AA->getAssumed();
10118 unionAssumed(S);
10119 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10120 : ChangeStatus::CHANGED;
10121 }
10122
10123 void trackStatistics() const override {
10124 STATS_DECLTRACK_CSARG_ATTR(potential_values)
10125 }
10126};
10127} // namespace
10128
10129/// ------------------------ NoUndef Attribute ---------------------------------
10131 Attribute::AttrKind ImpliedAttributeKind,
10132 bool IgnoreSubsumingPositions) {
10133 assert(ImpliedAttributeKind == Attribute::NoUndef &&
10134 "Unexpected attribute kind");
10135 if (A.hasAttr(IRP, {Attribute::NoUndef}, IgnoreSubsumingPositions,
10136 Attribute::NoUndef))
10137 return true;
10138
10139 Value &Val = IRP.getAssociatedValue();
10142 LLVMContext &Ctx = Val.getContext();
10143 A.manifestAttrs(IRP, Attribute::get(Ctx, Attribute::NoUndef));
10144 return true;
10145 }
10146
10147 return false;
10148}
10149
10150namespace {
10151struct AANoUndefImpl : AANoUndef {
10152 AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
10153
10154 void initialize(Attributor &A) override {
10155 Value &V = getAssociatedValue();
10156 if (isa<UndefValue>(V))
10157 indicatePessimisticFixpoint();
10158 assert(!isImpliedByIR(A, getIRPosition(), Attribute::NoUndef));
10159 }
10160
10161 /// See followUsesInMBEC
10162 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
10163 AANoUndef::StateType &State) {
10164 const Value *UseV = U->get();
10165 const DominatorTree *DT = nullptr;
10166 AssumptionCache *AC = nullptr;
10167 InformationCache &InfoCache = A.getInfoCache();
10168 if (Function *F = getAnchorScope()) {
10169 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
10170 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
10171 }
10172 State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT));
10173 bool TrackUse = false;
10174 // Track use for instructions which must produce undef or poison bits when
10175 // at least one operand contains such bits.
10177 TrackUse = true;
10178 return TrackUse;
10179 }
10180
10181 const std::string getAsStr(Attributor *A) const override {
10182 return getAssumed() ? "noundef" : "may-undef-or-poison";
10183 }
10184
10185 ChangeStatus manifest(Attributor &A) override {
10186 // We don't manifest noundef attribute for dead positions because the
10187 // associated values with dead positions would be replaced with undef
10188 // values.
10189 bool UsedAssumedInformation = false;
10190 if (A.isAssumedDead(getIRPosition(), nullptr, nullptr,
10191 UsedAssumedInformation))
10192 return ChangeStatus::UNCHANGED;
10193 // A position whose simplified value does not have any value is
10194 // considered to be dead. We don't manifest noundef in such positions for
10195 // the same reason above.
10196 if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation,
10198 .has_value())
10199 return ChangeStatus::UNCHANGED;
10200 return AANoUndef::manifest(A);
10201 }
10202};
10203
10204struct AANoUndefFloating : public AANoUndefImpl {
10205 AANoUndefFloating(const IRPosition &IRP, Attributor &A)
10206 : AANoUndefImpl(IRP, A) {}
10207
10208 void initialize(Attributor &A) override {
10209 AANoUndefImpl::initialize(A);
10210 if (!getState().isAtFixpoint() && getAnchorScope() &&
10211 !getAnchorScope()->isDeclaration())
10212 if (Instruction *CtxI = getCtxI())
10213 followUsesInMBEC(*this, A, getState(), *CtxI);
10214 }
10215
10216 ChangeStatus updateImpl(Attributor &A) override {
10217 auto VisitValueCB = [&](const IRPosition &IRP) -> bool {
10218 bool IsKnownNoUndef;
10220 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoUndef);
10221 };
10222
10223 bool Stripped;
10224 bool UsedAssumedInformation = false;
10225 Value *AssociatedValue = &getAssociatedValue();
10227 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
10228 AA::AnyScope, UsedAssumedInformation))
10229 Stripped = false;
10230 else
10231 Stripped =
10232 Values.size() != 1 || Values.front().getValue() != AssociatedValue;
10233
10234 if (!Stripped) {
10235 // If we haven't stripped anything we might still be able to use a
10236 // different AA, but only if the IRP changes. Effectively when we
10237 // interpret this not as a call site value but as a floating/argument
10238 // value.
10239 const IRPosition AVIRP = IRPosition::value(*AssociatedValue);
10240 if (AVIRP == getIRPosition() || !VisitValueCB(AVIRP))
10241 return indicatePessimisticFixpoint();
10242 return ChangeStatus::UNCHANGED;
10243 }
10244
10245 for (const auto &VAC : Values)
10246 if (!VisitValueCB(IRPosition::value(*VAC.getValue())))
10247 return indicatePessimisticFixpoint();
10248
10249 return ChangeStatus::UNCHANGED;
10250 }
10251
10252 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
10253};
10254
10255/// Return true if the poison-generating attributes in \p Attrs are assumed to
10256/// hold for the value at \p Pos.
10257static bool checkPoisonGeneratingAttrsHold(Attributor &A,
10258 const AbstractAttribute &QueryingAA,
10259 AttributeSet Attrs,
10260 const IRPosition &Pos,
10261 const Instruction *CtxI) {
10262 AttributeMask AM = AttributeFuncs::getPoisonGeneratingAttributes();
10263 for (Attribute Attr : Attrs) {
10264 if (!AM.contains(Attr))
10265 continue;
10266
10267 switch (Attr.getKindAsEnum()) {
10268 case Attribute::NonNull: {
10269 bool IsKnown;
10271 A, &QueryingAA, Pos, DepClassTy::REQUIRED, IsKnown))
10272 return false;
10273 break;
10274 }
10275 case Attribute::Alignment: {
10276 const auto *AlignAA =
10277 A.getAAFor<AAAlign>(QueryingAA, Pos, DepClassTy::REQUIRED);
10278 if (!AlignAA || AlignAA->getAssumedAlign() < *Attr.getAlignment())
10279 return false;
10280 break;
10281 }
10282 case Attribute::Range: {
10283 const auto *RangeAA = A.getAAFor<AAValueConstantRange>(
10284 QueryingAA, Pos, DepClassTy::REQUIRED);
10285 if (!RangeAA ||
10286 !Attr.getRange().contains(RangeAA->getAssumedConstantRange(A, CtxI)))
10287 return false;
10288 break;
10289 }
10290 case Attribute::NoFPClass: {
10291 FPClassTest NoFPClass = Attr.getNoFPClass();
10292 const auto *NoFPClassAA =
10293 A.getAAFor<AANoFPClass>(QueryingAA, Pos, DepClassTy::REQUIRED);
10294 if (!NoFPClassAA ||
10295 (NoFPClassAA->getAssumedNoFPClass() & NoFPClass) != NoFPClass)
10296 return false;
10297 break;
10298 }
10299 default:
10300 // Conservatively assume unhandled attributes do not hold.
10301 return false;
10302 }
10303 }
10304
10305 return true;
10306}
10307
10308struct AANoUndefReturned final
10309 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
10310 using Base = AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>;
10311 AANoUndefReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
10312
10313 void initialize(Attributor &A) override {
10314 Base::initialize(A);
10315 RetAttrs = getAssociatedFunction()->getAttributes().getRetAttrs();
10316 }
10317
10318 ChangeStatus updateImpl(Attributor &A) override {
10319 // A returned value that violates a poison-generating return attribute
10320 // becomes poison, so the attributes must hold for every returned value.
10321 if (RetAttrs.hasAttributes()) {
10322 auto AttrsHold = [&](Instruction &I) {
10323 Value &V = *cast<ReturnInst>(I).getReturnValue();
10324 return checkPoisonGeneratingAttrsHold(A, *this, RetAttrs,
10325 IRPosition::value(V), &I);
10326 };
10327 bool UsedAssumedInformation = false;
10328 if (!A.checkForAllInstructions(AttrsHold, *this, {Instruction::Ret},
10329 UsedAssumedInformation))
10330 return indicatePessimisticFixpoint();
10331 }
10332
10333 return Base::updateImpl(A);
10334 }
10335
10336 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
10337
10338private:
10339 /// The function return attributes.
10340 AttributeSet RetAttrs;
10341};
10342
10343struct AANoUndefArgument final
10344 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
10345 AANoUndefArgument(const IRPosition &IRP, Attributor &A)
10346 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
10347
10348 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
10349};
10350
10351struct AANoUndefCallSiteArgument final : AANoUndefFloating {
10352 AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
10353 : AANoUndefFloating(IRP, A) {}
10354
10355 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
10356};
10357
10358struct AANoUndefCallSiteReturned final
10359 : AACalleeToCallSite<AANoUndef, AANoUndefImpl> {
10360 using Base = AACalleeToCallSite<AANoUndef, AANoUndefImpl>;
10361 AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
10362 : Base(IRP, A) {}
10363
10364 void initialize(Attributor &A) override {
10365 Base::initialize(A);
10366 RetAttrs = cast<CallBase>(getAnchorValue()).getRetAttributes();
10367 }
10368
10369 ChangeStatus updateImpl(Attributor &A) override {
10370 // The call returns poison if the callee return value violates a
10371 // poison-generating call site return attribute, so the attributes must
10372 // hold for every callee.
10373 if (RetAttrs.hasAttributes()) {
10374 auto AttrsHold = [&](ArrayRef<const Function *> Callees) {
10375 return all_of(Callees, [&](const Function *Callee) {
10376 return checkPoisonGeneratingAttrsHold(
10377 A, *this, RetAttrs, IRPosition::returned(*Callee), nullptr);
10378 });
10379 };
10380 if (!A.checkForAllCallees(AttrsHold, *this,
10381 cast<CallBase>(getAnchorValue())))
10382 return indicatePessimisticFixpoint();
10383 }
10384
10385 return Base::updateImpl(A);
10386 }
10387
10388 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
10389
10390private:
10391 /// The call site return attributes.
10392 AttributeSet RetAttrs;
10393};
10394
10395/// ------------------------ NoFPClass Attribute -------------------------------
10396
10397struct AANoFPClassImpl : AANoFPClass {
10398 AANoFPClassImpl(const IRPosition &IRP, Attributor &A) : AANoFPClass(IRP, A) {}
10399
10400 void initialize(Attributor &A) override {
10401 const IRPosition &IRP = getIRPosition();
10402
10403 Value &V = IRP.getAssociatedValue();
10404 if (isa<UndefValue>(V)) {
10405 indicateOptimisticFixpoint();
10406 return;
10407 }
10408
10410 A.getAttrs(getIRPosition(), {Attribute::NoFPClass}, Attrs, false);
10411 for (const auto &Attr : Attrs) {
10412 addKnownBits(Attr.getNoFPClass());
10413 }
10414
10415 Instruction *CtxI = getCtxI();
10416
10417 if (getPositionKind() != IRPosition::IRP_RETURNED) {
10418 const DataLayout &DL = A.getDataLayout();
10419 InformationCache &InfoCache = A.getInfoCache();
10420
10421 const DominatorTree *DT = nullptr;
10422 AssumptionCache *AC = nullptr;
10423 const TargetLibraryInfo *TLI = nullptr;
10424 Function *F = getAnchorScope();
10425 if (F) {
10427 if (!F->isDeclaration()) {
10428 DT =
10429 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
10430 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
10431 }
10432 }
10433
10434 SimplifyQuery Q(DL, TLI, DT, AC, CtxI);
10435
10436 KnownFPClass KnownFPClass = computeKnownFPClass(&V, fcAllFlags, Q);
10437 addKnownBits(~KnownFPClass.getKnownFPClasses());
10438 }
10439
10440 if (CtxI)
10441 followUsesInMBEC(*this, A, getState(), *CtxI);
10442 }
10443
10444 /// See followUsesInMBEC
10445 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
10446 AANoFPClass::StateType &State) {
10447 // TODO: Determine what instructions can be looked through.
10448 auto *CB = dyn_cast<CallBase>(I);
10449 if (!CB)
10450 return false;
10451
10452 if (!CB->isArgOperand(U))
10453 return false;
10454
10455 unsigned ArgNo = CB->getArgOperandNo(U);
10456 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
10457 if (auto *NoFPAA = A.getAAFor<AANoFPClass>(*this, IRP, DepClassTy::NONE))
10458 State.addKnownBits(NoFPAA->getState().getKnown());
10459 return false;
10460 }
10461
10462 const std::string getAsStr(Attributor *A) const override {
10463 std::string Result = "nofpclass";
10464 raw_string_ostream OS(Result);
10465 OS << getKnownNoFPClass() << '/' << getAssumedNoFPClass();
10466 return Result;
10467 }
10468
10469 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
10470 SmallVectorImpl<Attribute> &Attrs) const override {
10471 Attrs.emplace_back(Attribute::getWithNoFPClass(Ctx, getAssumedNoFPClass()));
10472 }
10473};
10474
10475struct AANoFPClassFloating : public AANoFPClassImpl {
10476 AANoFPClassFloating(const IRPosition &IRP, Attributor &A)
10477 : AANoFPClassImpl(IRP, A) {}
10478
10479 ChangeStatus updateImpl(Attributor &A) override {
10481 bool UsedAssumedInformation = false;
10482 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
10483 AA::AnyScope, UsedAssumedInformation)) {
10484 Values.push_back({getAssociatedValue(), getCtxI()});
10485 }
10486
10487 StateType T;
10488 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
10489 const auto *AA = A.getAAFor<AANoFPClass>(*this, IRPosition::value(V),
10490 DepClassTy::REQUIRED);
10491 if (!AA || this == AA) {
10492 T.indicatePessimisticFixpoint();
10493 } else {
10494 const AANoFPClass::StateType &S =
10495 static_cast<const AANoFPClass::StateType &>(AA->getState());
10496 T ^= S;
10497 }
10498 return T.isValidState();
10499 };
10500
10501 for (const auto &VAC : Values)
10502 if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI()))
10503 return indicatePessimisticFixpoint();
10504
10505 return clampStateAndIndicateChange(getState(), T);
10506 }
10507
10508 void trackStatistics() const override {
10510 }
10511};
10512
10513struct AANoFPClassReturned final
10514 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10515 AANoFPClassImpl::StateType, false,
10516 Attribute::None, false> {
10517 AANoFPClassReturned(const IRPosition &IRP, Attributor &A)
10518 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10519 AANoFPClassImpl::StateType, false,
10520 Attribute::None, false>(IRP, A) {}
10521
10522 void trackStatistics() const override {
10524 }
10525};
10526
10527struct AANoFPClassArgument final
10528 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl> {
10529 AANoFPClassArgument(const IRPosition &IRP, Attributor &A)
10530 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl>(IRP, A) {}
10531
10532 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofpclass) }
10533};
10534
10535struct AANoFPClassCallSiteArgument final : AANoFPClassFloating {
10536 AANoFPClassCallSiteArgument(const IRPosition &IRP, Attributor &A)
10537 : AANoFPClassFloating(IRP, A) {}
10538
10539 void trackStatistics() const override {
10541 }
10542};
10543
10544struct AANoFPClassCallSiteReturned final
10545 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl> {
10546 AANoFPClassCallSiteReturned(const IRPosition &IRP, Attributor &A)
10547 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl>(IRP, A) {}
10548
10549 void trackStatistics() const override {
10551 }
10552};
10553
10554struct AACallEdgesImpl : public AACallEdges {
10555 AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {}
10556
10557 const SetVector<Function *> &getOptimisticEdges() const override {
10558 return CalledFunctions;
10559 }
10560
10561 bool hasUnknownCallee() const override { return HasUnknownCallee; }
10562
10563 bool hasNonAsmUnknownCallee() const override {
10564 return HasUnknownCalleeNonAsm;
10565 }
10566
10567 const std::string getAsStr(Attributor *A) const override {
10568 return "CallEdges[" + std::to_string(HasUnknownCallee) + "," +
10569 std::to_string(CalledFunctions.size()) + "]";
10570 }
10571
10572 void trackStatistics() const override {}
10573
10574protected:
10575 /// Return the callee of \p CB if it is a direct call whose callee has no
10576 /// callback metadata. Such a call only calls its callee.
10577 static Function *getOnlyCallee(const CallBase &CB) {
10579 if (Callee && !Callee->hasMetadata(LLVMContext::MD_callback))
10580 return Callee;
10581 return nullptr;
10582 }
10583
10584 void addCalledFunction(Function *Fn, ChangeStatus &Change) {
10585 if (CalledFunctions.insert(Fn)) {
10586 Change = ChangeStatus::CHANGED;
10587 LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName()
10588 << "\n");
10589 }
10590 }
10591
10592 void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) {
10593 if (!HasUnknownCallee)
10594 Change = ChangeStatus::CHANGED;
10595 if (NonAsm && !HasUnknownCalleeNonAsm)
10596 Change = ChangeStatus::CHANGED;
10597 HasUnknownCalleeNonAsm |= NonAsm;
10598 HasUnknownCallee = true;
10599 }
10600
10601private:
10602 /// Optimistic set of functions that might be called by this position.
10603 SetVector<Function *> CalledFunctions;
10604
10605 /// Is there any call with a unknown callee.
10606 bool HasUnknownCallee = false;
10607
10608 /// Is there any call with a unknown callee, excluding any inline asm.
10609 bool HasUnknownCalleeNonAsm = false;
10610};
10611
10612struct AACallEdgesCallSite : public AACallEdgesImpl {
10613 AACallEdgesCallSite(const IRPosition &IRP, Attributor &A)
10614 : AACallEdgesImpl(IRP, A) {}
10615
10616 void initialize(Attributor &A) override {
10617 // The only callee of a direct call without callbacks never changes.
10618 if (Function *Callee = getOnlyCallee(cast<CallBase>(getAnchorValue()))) {
10619 ChangeStatus Change = ChangeStatus::UNCHANGED;
10620 addCalledFunction(Callee, Change);
10621 indicateOptimisticFixpoint();
10622 }
10623 }
10624
10625 ChangeStatus updateImpl(Attributor &A) override {
10626 ChangeStatus Change = ChangeStatus::UNCHANGED;
10627
10628 auto VisitValue = [&](Value &V, const Instruction *CtxI) -> bool {
10629 if (Function *Fn = dyn_cast<Function>(&V)) {
10630 addCalledFunction(Fn, Change);
10631 } else {
10632 LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n");
10633 setHasUnknownCallee(true, Change);
10634 }
10635
10636 // Explore all values.
10637 return true;
10638 };
10639
10641 // Process any value that we might call.
10642 auto ProcessCalledOperand = [&](Value *V, Instruction *CtxI) {
10643 if (isa<Constant>(V)) {
10644 VisitValue(*V, CtxI);
10645 return;
10646 }
10647
10648 bool UsedAssumedInformation = false;
10649 Values.clear();
10650 if (!A.getAssumedSimplifiedValues(IRPosition::value(*V), *this, Values,
10651 AA::AnyScope, UsedAssumedInformation)) {
10652 Values.push_back({*V, CtxI});
10653 }
10654 for (auto &VAC : Values)
10655 VisitValue(*VAC.getValue(), VAC.getCtxI());
10656 };
10657
10658 CallBase *CB = cast<CallBase>(getCtxI());
10659
10660 if (auto *IA = dyn_cast<InlineAsm>(CB->getCalledOperand())) {
10661 if (IA->hasSideEffects() &&
10662 !hasAssumption(*CB->getCaller(), "ompx_no_call_asm") &&
10663 !hasAssumption(*CB, "ompx_no_call_asm")) {
10664 setHasUnknownCallee(false, Change);
10665 }
10666 return Change;
10667 }
10668
10669 if (CB->isIndirectCall())
10670 if (auto *IndirectCallAA = A.getAAFor<AAIndirectCallInfo>(
10671 *this, getIRPosition(), DepClassTy::OPTIONAL))
10672 if (IndirectCallAA->foreachCallee(
10673 [&](Function *Fn) { return VisitValue(*Fn, CB); }))
10674 return Change;
10675
10676 // The most simple case.
10677 ProcessCalledOperand(CB->getCalledOperand(), CB);
10678
10679 // Process callback functions.
10680 SmallVector<const Use *, 4u> CallbackUses;
10681 AbstractCallSite::getCallbackUses(*CB, CallbackUses);
10682 for (const Use *U : CallbackUses)
10683 ProcessCalledOperand(U->get(), CB);
10684
10685 return Change;
10686 }
10687};
10688
10689struct AACallEdgesFunction : public AACallEdgesImpl {
10690 AACallEdgesFunction(const IRPosition &IRP, Attributor &A)
10691 : AACallEdgesImpl(IRP, A) {}
10692
10693 ChangeStatus updateImpl(Attributor &A) override {
10694 ChangeStatus Change = ChangeStatus::UNCHANGED;
10695 bool AllCallsDirect = true;
10696
10697 auto ProcessCallInst = [&](Instruction &Inst) {
10698 CallBase &CB = cast<CallBase>(Inst);
10699
10700 // A direct call without callbacks only calls its callee; there is no
10701 // need for a call site attribute.
10702 if (Function *Callee = getOnlyCallee(CB)) {
10703 addCalledFunction(Callee, Change);
10704 return true;
10705 }
10706
10707 AllCallsDirect = false;
10708 auto *CBEdges = A.getAAFor<AACallEdges>(
10709 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
10710 if (!CBEdges)
10711 return false;
10712 if (CBEdges->hasNonAsmUnknownCallee())
10713 setHasUnknownCallee(true, Change);
10714 if (CBEdges->hasUnknownCallee())
10715 setHasUnknownCallee(false, Change);
10716
10717 for (Function *F : CBEdges->getOptimisticEdges())
10718 addCalledFunction(F, Change);
10719
10720 return true;
10721 };
10722
10723 // Visit all callable instructions.
10724 bool UsedAssumedInformation = false;
10725 if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this,
10726 UsedAssumedInformation,
10727 /* CheckBBLivenessOnly */ true)) {
10728 // If we haven't looked at all call like instructions, assume that there
10729 // are unknown callees.
10730 setHasUnknownCallee(true, Change);
10731 }
10732
10733 // The callees of direct calls in code known to be live do not change.
10734 if (AllCallsDirect && !UsedAssumedInformation)
10735 indicateOptimisticFixpoint();
10736
10737 return Change;
10738 }
10739};
10740
10741/// -------------------AAInterFnReachability Attribute--------------------------
10742
10743struct AAInterFnReachabilityFunction
10744 : public CachedReachabilityAA<AAInterFnReachability, Function> {
10745 using Base = CachedReachabilityAA<AAInterFnReachability, Function>;
10746 AAInterFnReachabilityFunction(const IRPosition &IRP, Attributor &A)
10747 : Base(IRP, A) {}
10748
10749 bool instructionCanReach(
10750 Attributor &A, const Instruction &From, const Function &To,
10751 const AA::InstExclusionSetTy *ExclusionSet) const override {
10752 assert(From.getFunction() == getAnchorScope() && "Queried the wrong AA!");
10753 auto *NonConstThis = const_cast<AAInterFnReachabilityFunction *>(this);
10754
10755 RQITy StackRQI(A, From, To, ExclusionSet, false);
10756 RQITy::Reachable Result;
10757 if (!NonConstThis->checkQueryCache(A, StackRQI, Result))
10758 return NonConstThis->isReachableImpl(A, StackRQI,
10759 /*IsTemporaryRQI=*/true);
10760 return Result == RQITy::Reachable::Yes;
10761 }
10762
10763 bool isReachableImpl(Attributor &A, RQITy &RQI,
10764 bool IsTemporaryRQI) override {
10765 const Instruction *EntryI =
10766 &RQI.From->getFunction()->getEntryBlock().front();
10767 if (EntryI != RQI.From &&
10768 !instructionCanReach(A, *EntryI, *RQI.To, nullptr))
10769 return rememberResult(A, RQITy::Reachable::No, RQI, false,
10770 IsTemporaryRQI);
10771
10772 auto CheckReachableCallBase = [&](CallBase *CB) {
10773 auto *CBEdges = A.getAAFor<AACallEdges>(
10774 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
10775 if (!CBEdges || !CBEdges->getState().isValidState())
10776 return false;
10777 // TODO Check To backwards in this case.
10778 if (CBEdges->hasUnknownCallee())
10779 return false;
10780
10781 for (Function *Fn : CBEdges->getOptimisticEdges()) {
10782 if (Fn == RQI.To)
10783 return false;
10784
10785 if (Fn->isDeclaration()) {
10786 if (Fn->hasFnAttribute(Attribute::NoCallback))
10787 continue;
10788 // TODO Check To backwards in this case.
10789 return false;
10790 }
10791
10792 if (Fn == getAnchorScope()) {
10793 if (EntryI == RQI.From)
10794 continue;
10795 return false;
10796 }
10797
10798 const AAInterFnReachability *InterFnReachability =
10799 A.getAAFor<AAInterFnReachability>(*this, IRPosition::function(*Fn),
10800 DepClassTy::OPTIONAL);
10801
10802 const Instruction &FnFirstInst = Fn->getEntryBlock().front();
10803 if (!InterFnReachability ||
10804 InterFnReachability->instructionCanReach(A, FnFirstInst, *RQI.To,
10805 RQI.ExclusionSet))
10806 return false;
10807 }
10808 return true;
10809 };
10810
10811 const auto *IntraFnReachability = A.getAAFor<AAIntraFnReachability>(
10812 *this, IRPosition::function(*RQI.From->getFunction()),
10813 DepClassTy::OPTIONAL);
10814
10815 // Determine call like instructions that we can reach from the inst.
10816 auto CheckCallBase = [&](Instruction &CBInst) {
10817 // There are usually less nodes in the call graph, check inter function
10818 // reachability first.
10819 if (CheckReachableCallBase(cast<CallBase>(&CBInst)))
10820 return true;
10821 return IntraFnReachability && !IntraFnReachability->isAssumedReachable(
10822 A, *RQI.From, CBInst, RQI.ExclusionSet);
10823 };
10824
10825 bool UsedExclusionSet = /* conservative */ true;
10826 bool UsedAssumedInformation = false;
10827 if (!A.checkForAllCallLikeInstructions(CheckCallBase, *this,
10828 UsedAssumedInformation,
10829 /* CheckBBLivenessOnly */ true))
10830 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
10831 IsTemporaryRQI);
10832
10833 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
10834 IsTemporaryRQI);
10835 }
10836
10837 void trackStatistics() const override {}
10838};
10839} // namespace
10840
10841template <typename AAType>
10842static std::optional<Constant *>
10844 const IRPosition &IRP, Type &Ty) {
10845 if (!Ty.isIntegerTy())
10846 return nullptr;
10847
10848 // This will also pass the call base context.
10849 const auto *AA = A.getAAFor<AAType>(QueryingAA, IRP, DepClassTy::NONE);
10850 if (!AA)
10851 return nullptr;
10852
10853 std::optional<Constant *> COpt = AA->getAssumedConstant(A);
10854
10855 if (!COpt.has_value()) {
10856 A.recordDependence(*AA, QueryingAA, DepClassTy::OPTIONAL);
10857 return std::nullopt;
10858 }
10859 if (auto *C = *COpt) {
10860 A.recordDependence(*AA, QueryingAA, DepClassTy::OPTIONAL);
10861 return C;
10862 }
10863 return nullptr;
10864}
10865
10867 Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP,
10869 Type &Ty = *IRP.getAssociatedType();
10870 std::optional<Value *> V;
10871 for (auto &It : Values) {
10872 V = AA::combineOptionalValuesInAAValueLatice(V, It.getValue(), &Ty);
10873 if (V.has_value() && !*V)
10874 break;
10875 }
10876 if (!V.has_value())
10877 return UndefValue::get(&Ty);
10878 return *V;
10879}
10880
10881namespace {
10882struct AAPotentialValuesImpl : AAPotentialValues {
10883 using StateType = PotentialLLVMValuesState;
10884
10885 AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A)
10886 : AAPotentialValues(IRP, A) {}
10887
10888 void initialize(Attributor &A) override {
10889 if (A.hasSimplificationCallback(getIRPosition())) {
10890 indicatePessimisticFixpoint();
10891 return;
10892 }
10893 Value *Stripped = getAssociatedValue().stripPointerCasts();
10894 if (isa<Constant>(Stripped) && !isa<ConstantExpr>(Stripped)) {
10895 addValue(A, getState(), *Stripped, getCtxI(), AA::AnyScope,
10896 getAnchorScope());
10897 indicateOptimisticFixpoint();
10898 return;
10899 }
10900 AAPotentialValues::initialize(A);
10901 }
10902
10903 const std::string getAsStr(Attributor *A) const override {
10904 std::string Str;
10905 llvm::raw_string_ostream OS(Str);
10906 OS << getState();
10907 return Str;
10908 }
10909
10910 template <typename AAType>
10911 static std::optional<Value *> askOtherAA(Attributor &A,
10912 const AbstractAttribute &AA,
10913 const IRPosition &IRP, Type &Ty) {
10915 return &IRP.getAssociatedValue();
10916 std::optional<Constant *> C = askForAssumedConstant<AAType>(A, AA, IRP, Ty);
10917 if (!C)
10918 return std::nullopt;
10919 if (*C)
10920 if (auto *CC = AA::getWithType(**C, Ty))
10921 return CC;
10922 return nullptr;
10923 }
10924
10925 virtual void addValue(Attributor &A, StateType &State, Value &V,
10926 const Instruction *CtxI, AA::ValueScope S,
10927 Function *AnchorScope) const {
10928
10929 IRPosition ValIRP = IRPosition::value(V);
10930 if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) {
10931 for (const auto &U : CB->args()) {
10932 if (U.get() != &V)
10933 continue;
10934 ValIRP = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
10935 break;
10936 }
10937 }
10938
10939 Value *VPtr = &V;
10940 if (ValIRP.getAssociatedType()->isIntegerTy()) {
10941 Type &Ty = *getAssociatedType();
10942 std::optional<Value *> SimpleV =
10943 askOtherAA<AAValueConstantRange>(A, *this, ValIRP, Ty);
10944 if (SimpleV.has_value() && !*SimpleV) {
10945 auto *PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>(
10946 *this, ValIRP, DepClassTy::OPTIONAL);
10947 if (PotentialConstantsAA && PotentialConstantsAA->isValidState()) {
10948 for (const auto &It : PotentialConstantsAA->getAssumedSet())
10949 State.unionAssumed({{*ConstantInt::get(&Ty, It), nullptr}, S});
10950 if (PotentialConstantsAA->undefIsContained())
10951 State.unionAssumed({{*UndefValue::get(&Ty), nullptr}, S});
10952 return;
10953 }
10954 }
10955 if (!SimpleV.has_value())
10956 return;
10957
10958 if (*SimpleV)
10959 VPtr = *SimpleV;
10960 }
10961
10962 if (isa<ConstantInt>(VPtr))
10963 CtxI = nullptr;
10964 if (!AA::isValidInScope(*VPtr, AnchorScope))
10966
10967 State.unionAssumed({{*VPtr, CtxI}, S});
10968 }
10969
10970 /// Helper struct to tie a value+context pair together with the scope for
10971 /// which this is the simplified version.
10972 struct ItemInfo {
10973 AA::ValueAndContext I;
10975
10976 bool operator==(const ItemInfo &II) const {
10977 return II.I == I && II.S == S;
10978 };
10979 bool operator<(const ItemInfo &II) const {
10980 return std::tie(I, S) < std::tie(II.I, II.S);
10981 };
10982 };
10983
10984 bool recurseForValue(Attributor &A, const IRPosition &IRP, AA::ValueScope S) {
10985 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap;
10986 for (auto CS : {AA::Intraprocedural, AA::Interprocedural}) {
10987 if (!(CS & S))
10988 continue;
10989
10990 bool UsedAssumedInformation = false;
10992 if (!A.getAssumedSimplifiedValues(IRP, this, Values, CS,
10993 UsedAssumedInformation))
10994 return false;
10995
10996 for (auto &It : Values)
10997 ValueScopeMap[It] += CS;
10998 }
10999 for (auto &It : ValueScopeMap)
11000 addValue(A, getState(), *It.first.getValue(), It.first.getCtxI(),
11001 AA::ValueScope(It.second), getAnchorScope());
11002
11003 return true;
11004 }
11005
11006 void giveUpOnIntraprocedural(Attributor &A) {
11007 auto NewS = StateType::getBestState(getState());
11008 for (const auto &It : getAssumedSet()) {
11009 if (It.second == AA::Intraprocedural)
11010 continue;
11011 addValue(A, NewS, *It.first.getValue(), It.first.getCtxI(),
11012 AA::Interprocedural, getAnchorScope());
11013 }
11014 assert(!undefIsContained() && "Undef should be an explicit value!");
11015 addValue(A, NewS, getAssociatedValue(), getCtxI(), AA::Intraprocedural,
11016 getAnchorScope());
11017 getState() = NewS;
11018 }
11019
11020 ChangeStatus indicatePessimisticFixpoint() override {
11021 getState() = StateType::getBestState(getState());
11022 getState().unionAssumed({{getAssociatedValue(), getCtxI()}, AA::AnyScope});
11023 AAPotentialValues::indicateOptimisticFixpoint();
11024 return ChangeStatus::CHANGED;
11025 }
11026
11027 ChangeStatus updateImpl(Attributor &A) override {
11028 return indicatePessimisticFixpoint();
11029 }
11030
11031 ChangeStatus manifest(Attributor &A) override {
11034 Values.clear();
11035 if (!getAssumedSimplifiedValues(A, Values, S))
11036 continue;
11037 Value &OldV = getAssociatedValue();
11038 if (isa<UndefValue>(OldV))
11039 continue;
11040 Value *NewV = getSingleValue(A, *this, getIRPosition(), Values);
11041 if (!NewV || NewV == &OldV)
11042 continue;
11043 if (getCtxI() &&
11044 !AA::isValidAtPosition({*NewV, *getCtxI()}, A.getInfoCache()))
11045 continue;
11046 if (A.changeAfterManifest(getIRPosition(), *NewV))
11047 return ChangeStatus::CHANGED;
11048 }
11049 return ChangeStatus::UNCHANGED;
11050 }
11051
11052 bool getAssumedSimplifiedValues(
11053 Attributor &A, SmallVectorImpl<AA::ValueAndContext> &Values,
11054 AA::ValueScope S, bool RecurseForSelectAndPHI = false) const override {
11055 if (!isValidState())
11056 return false;
11057 bool UsedAssumedInformation = false;
11058 for (const auto &It : getAssumedSet())
11059 if (It.second & S) {
11060 if (RecurseForSelectAndPHI && (isa<PHINode>(It.first.getValue()) ||
11061 isa<SelectInst>(It.first.getValue()))) {
11062 if (A.getAssumedSimplifiedValues(
11063 IRPosition::inst(*cast<Instruction>(It.first.getValue())),
11064 this, Values, S, UsedAssumedInformation))
11065 continue;
11066 }
11067 Values.push_back(It.first);
11068 }
11069 assert(!undefIsContained() && "Undef should be an explicit value!");
11070 return true;
11071 }
11072};
11073
11074struct AAPotentialValuesFloating : AAPotentialValuesImpl {
11075 AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A)
11076 : AAPotentialValuesImpl(IRP, A) {}
11077
11078 ChangeStatus updateImpl(Attributor &A) override {
11079 auto AssumedBefore = getAssumed();
11080
11081 genericValueTraversal(A, &getAssociatedValue());
11082
11083 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11084 : ChangeStatus::CHANGED;
11085 }
11086
11087 /// Helper struct to remember which AAIsDead instances we actually used.
11088 struct LivenessInfo {
11089 const AAIsDead *LivenessAA = nullptr;
11090 bool AnyDead = false;
11091 };
11092
11093 /// Check if \p Cmp is a comparison we can simplify.
11094 ///
11095 /// We handle multiple cases, one in which at least one operand is an
11096 /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other
11097 /// operand. Return true if successful, in that case Worklist will be updated.
11098 bool handleCmp(Attributor &A, Value &Cmp, Value *LHS, Value *RHS,
11099 CmpInst::Predicate Pred, ItemInfo II,
11100 SmallVectorImpl<ItemInfo> &Worklist) {
11101
11102 // Simplify the operands first.
11103 bool UsedAssumedInformation = false;
11104 SmallVector<AA::ValueAndContext> LHSValues, RHSValues;
11105 auto GetSimplifiedValues = [&](Value &V,
11107 if (!A.getAssumedSimplifiedValues(
11108 IRPosition::value(V, getCallBaseContext()), this, Values,
11109 AA::Intraprocedural, UsedAssumedInformation)) {
11110 Values.clear();
11111 Values.push_back(AA::ValueAndContext{V, II.I.getCtxI()});
11112 }
11113 return Values.empty();
11114 };
11115 if (GetSimplifiedValues(*LHS, LHSValues))
11116 return true;
11117 if (GetSimplifiedValues(*RHS, RHSValues))
11118 return true;
11119
11120 LLVMContext &Ctx = LHS->getContext();
11121
11122 InformationCache &InfoCache = A.getInfoCache();
11123 Instruction *CmpI = dyn_cast<Instruction>(&Cmp);
11124 Function *F = CmpI ? CmpI->getFunction() : nullptr;
11125 const auto *DT =
11126 F ? InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F)
11127 : nullptr;
11128 const auto *TLI =
11129 F ? A.getInfoCache().getTargetLibraryInfoForFunction(*F) : nullptr;
11130 auto *AC =
11131 F ? InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F)
11132 : nullptr;
11133
11134 const DataLayout &DL = A.getDataLayout();
11135 SimplifyQuery Q(DL, TLI, DT, AC, CmpI);
11136
11137 auto CheckPair = [&](Value &LHSV, Value &RHSV) {
11138 if (isa<UndefValue>(LHSV) || isa<UndefValue>(RHSV)) {
11139 addValue(A, getState(), *UndefValue::get(Cmp.getType()),
11140 /* CtxI */ nullptr, II.S, getAnchorScope());
11141 return true;
11142 }
11143
11144 // Handle the trivial case first in which we don't even need to think
11145 // about null or non-null.
11146 if (&LHSV == &RHSV &&
11148 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx),
11150 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11151 getAnchorScope());
11152 return true;
11153 }
11154
11155 auto *TypedLHS = AA::getWithType(LHSV, *LHS->getType());
11156 auto *TypedRHS = AA::getWithType(RHSV, *RHS->getType());
11157 if (TypedLHS && TypedRHS) {
11158 Value *NewV = simplifyCmpInst(Pred, TypedLHS, TypedRHS, Q);
11159 if (NewV && NewV != &Cmp) {
11160 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11161 getAnchorScope());
11162 return true;
11163 }
11164 }
11165
11166 // From now on we only handle equalities (==, !=).
11168 return false;
11169
11170 bool LHSIsNull = isa<ConstantPointerNull>(LHSV);
11171 bool RHSIsNull = isa<ConstantPointerNull>(RHSV);
11172 if (!LHSIsNull && !RHSIsNull)
11173 return false;
11174
11175 // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
11176 // non-nullptr operand and if we assume it's non-null we can conclude the
11177 // result of the comparison.
11178 assert((LHSIsNull || RHSIsNull) &&
11179 "Expected nullptr versus non-nullptr comparison at this point");
11180
11181 // The index is the operand that we assume is not null.
11182 unsigned PtrIdx = LHSIsNull;
11183 bool IsKnownNonNull;
11184 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
11185 A, this, IRPosition::value(*(PtrIdx ? &RHSV : &LHSV)),
11186 DepClassTy::REQUIRED, IsKnownNonNull);
11187 if (!IsAssumedNonNull)
11188 return false;
11189
11190 // The new value depends on the predicate, true for != and false for ==.
11191 Constant *NewV =
11192 ConstantInt::get(Type::getInt1Ty(Ctx), Pred == CmpInst::ICMP_NE);
11193 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11194 getAnchorScope());
11195 return true;
11196 };
11197
11198 for (auto &LHSValue : LHSValues)
11199 for (auto &RHSValue : RHSValues)
11200 if (!CheckPair(*LHSValue.getValue(), *RHSValue.getValue()))
11201 return false;
11202 return true;
11203 }
11204
11205 bool handleSelectInst(Attributor &A, SelectInst &SI, ItemInfo II,
11206 SmallVectorImpl<ItemInfo> &Worklist) {
11207 const Instruction *CtxI = II.I.getCtxI();
11208 bool UsedAssumedInformation = false;
11209
11210 std::optional<Constant *> C =
11211 A.getAssumedConstant(*SI.getCondition(), *this, UsedAssumedInformation);
11212 bool NoValueYet = !C.has_value();
11213 if (NoValueYet || isa_and_nonnull<UndefValue>(*C))
11214 return true;
11215 if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) {
11216 if (CI->isZero())
11217 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
11218 else
11219 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
11220 } else if (&SI == &getAssociatedValue()) {
11221 // We could not simplify the condition, assume both values.
11222 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
11223 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
11224 } else {
11225 std::optional<Value *> SimpleV = A.getAssumedSimplified(
11226 IRPosition::inst(SI), *this, UsedAssumedInformation, II.S);
11227 if (!SimpleV.has_value())
11228 return true;
11229 if (*SimpleV) {
11230 addValue(A, getState(), **SimpleV, CtxI, II.S, getAnchorScope());
11231 return true;
11232 }
11233 return false;
11234 }
11235 return true;
11236 }
11237
11238 bool handleLoadInst(Attributor &A, LoadInst &LI, ItemInfo II,
11239 SmallVectorImpl<ItemInfo> &Worklist) {
11240 SmallSetVector<Value *, 4> PotentialCopies;
11241 SmallSetVector<Instruction *, 4> PotentialValueOrigins;
11242 bool UsedAssumedInformation = false;
11243 if (!AA::getPotentiallyLoadedValues(A, LI, PotentialCopies,
11244 PotentialValueOrigins, *this,
11245 UsedAssumedInformation,
11246 /* OnlyExact */ true)) {
11247 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Failed to get potentially "
11248 "loaded values for load instruction "
11249 << LI << "\n");
11250 return false;
11251 }
11252
11253 // Do not simplify loads that are only used in llvm.assume if we cannot also
11254 // remove all stores that may feed into the load. The reason is that the
11255 // assume is probably worth something as long as the stores are around.
11256 InformationCache &InfoCache = A.getInfoCache();
11257 if (InfoCache.isOnlyUsedByAssume(LI)) {
11258 if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) {
11259 if (!I || isa<AssumeInst>(I))
11260 return true;
11261 if (auto *SI = dyn_cast<StoreInst>(I))
11262 return A.isAssumedDead(SI->getOperandUse(0), this,
11263 /* LivenessAA */ nullptr,
11264 UsedAssumedInformation,
11265 /* CheckBBLivenessOnly */ false);
11266 return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr,
11267 UsedAssumedInformation,
11268 /* CheckBBLivenessOnly */ false);
11269 })) {
11270 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Load is onl used by assumes "
11271 "and we cannot delete all the stores: "
11272 << LI << "\n");
11273 return false;
11274 }
11275 }
11276
11277 // Values have to be dynamically unique or we loose the fact that a
11278 // single llvm::Value might represent two runtime values (e.g.,
11279 // stack locations in different recursive calls).
11280 const Instruction *CtxI = II.I.getCtxI();
11281 bool ScopeIsLocal = (II.S & AA::Intraprocedural);
11282 bool AllLocal = ScopeIsLocal;
11283 bool DynamicallyUnique = llvm::all_of(PotentialCopies, [&](Value *PC) {
11284 AllLocal &= AA::isValidInScope(*PC, getAnchorScope());
11285 return AA::isDynamicallyUnique(A, *this, *PC);
11286 });
11287 if (!DynamicallyUnique) {
11288 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Not all potentially loaded "
11289 "values are dynamically unique: "
11290 << LI << "\n");
11291 return false;
11292 }
11293
11294 for (auto *PotentialCopy : PotentialCopies) {
11295 if (AllLocal) {
11296 Worklist.push_back({{*PotentialCopy, CtxI}, II.S});
11297 } else {
11298 Worklist.push_back({{*PotentialCopy, CtxI}, AA::Interprocedural});
11299 }
11300 }
11301 if (!AllLocal && ScopeIsLocal)
11302 addValue(A, getState(), LI, CtxI, AA::Intraprocedural, getAnchorScope());
11303 return true;
11304 }
11305
11306 bool handlePHINode(
11307 Attributor &A, PHINode &PHI, ItemInfo II,
11308 SmallVectorImpl<ItemInfo> &Worklist,
11309 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11310 auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & {
11311 LivenessInfo &LI = LivenessAAs[&F];
11312 if (!LI.LivenessAA)
11313 LI.LivenessAA = A.getAAFor<AAIsDead>(*this, IRPosition::function(F),
11314 DepClassTy::NONE);
11315 return LI;
11316 };
11317
11318 if (&PHI == &getAssociatedValue()) {
11319 LivenessInfo &LI = GetLivenessInfo(*PHI.getFunction());
11320 const auto *CI =
11321 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
11322 *PHI.getFunction());
11323
11324 CycleRef C;
11325 bool CyclePHI = mayBeInCycle(CI, &PHI, /* HeaderOnly */ true, &C);
11326 for (unsigned u = 0, e = PHI.getNumIncomingValues(); u < e; u++) {
11327 BasicBlock *IncomingBB = PHI.getIncomingBlock(u);
11328 if (LI.LivenessAA &&
11329 LI.LivenessAA->isEdgeDead(IncomingBB, PHI.getParent())) {
11330 LI.AnyDead = true;
11331 continue;
11332 }
11333 Value *V = PHI.getIncomingValue(u);
11334 if (V == &PHI)
11335 continue;
11336
11337 // If the incoming value is not the PHI but an instruction in the same
11338 // cycle we might have multiple versions of it flying around.
11339 if (CyclePHI && isa<Instruction>(V) &&
11340 (!C || CI->contains(C, cast<Instruction>(V)->getParent())))
11341 return false;
11342
11343 Worklist.push_back({{*V, IncomingBB->getTerminator()}, II.S});
11344 }
11345 return true;
11346 }
11347
11348 bool UsedAssumedInformation = false;
11349 std::optional<Value *> SimpleV = A.getAssumedSimplified(
11350 IRPosition::inst(PHI), *this, UsedAssumedInformation, II.S);
11351 if (!SimpleV.has_value())
11352 return true;
11353 if (!(*SimpleV))
11354 return false;
11355 addValue(A, getState(), **SimpleV, &PHI, II.S, getAnchorScope());
11356 return true;
11357 }
11358
11359 /// Use the generic, non-optimistic InstSimplfy functionality if we managed to
11360 /// simplify any operand of the instruction \p I. Return true if successful,
11361 /// in that case Worklist will be updated.
11362 bool handleGenericInst(Attributor &A, Instruction &I, ItemInfo II,
11363 SmallVectorImpl<ItemInfo> &Worklist) {
11364 bool SomeSimplified = false;
11365 bool UsedAssumedInformation = false;
11366
11367 SmallVector<Value *, 8> NewOps(I.getNumOperands());
11368 int Idx = 0;
11369 for (Value *Op : I.operands()) {
11370 const auto &SimplifiedOp = A.getAssumedSimplified(
11371 IRPosition::value(*Op, getCallBaseContext()), *this,
11372 UsedAssumedInformation, AA::Intraprocedural);
11373 // If we are not sure about any operand we are not sure about the entire
11374 // instruction, we'll wait.
11375 if (!SimplifiedOp.has_value())
11376 return true;
11377
11378 if (*SimplifiedOp)
11379 NewOps[Idx] = *SimplifiedOp;
11380 else
11381 NewOps[Idx] = Op;
11382
11383 SomeSimplified |= (NewOps[Idx] != Op);
11384 ++Idx;
11385 }
11386
11387 // We won't bother with the InstSimplify interface if we didn't simplify any
11388 // operand ourselves.
11389 if (!SomeSimplified)
11390 return false;
11391
11392 InformationCache &InfoCache = A.getInfoCache();
11393 Function *F = I.getFunction();
11394 const auto *DT =
11395 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
11396 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
11397 auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
11398
11399 const DataLayout &DL = I.getDataLayout();
11400 SimplifyQuery Q(DL, TLI, DT, AC, &I);
11401 Value *NewV = simplifyInstructionWithOperands(&I, NewOps, Q);
11402 if (!NewV || NewV == &I)
11403 return false;
11404
11405 LLVM_DEBUG(dbgs() << "Generic inst " << I << " assumed simplified to "
11406 << *NewV << "\n");
11407 Worklist.push_back({{*NewV, II.I.getCtxI()}, II.S});
11408 return true;
11409 }
11410
11412 Attributor &A, Instruction &I, ItemInfo II,
11413 SmallVectorImpl<ItemInfo> &Worklist,
11414 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11415 if (auto *CI = dyn_cast<CmpInst>(&I))
11416 return handleCmp(A, *CI, CI->getOperand(0), CI->getOperand(1),
11417 CI->getPredicate(), II, Worklist);
11418
11419 switch (I.getOpcode()) {
11420 case Instruction::Select:
11421 return handleSelectInst(A, cast<SelectInst>(I), II, Worklist);
11422 case Instruction::PHI:
11423 return handlePHINode(A, cast<PHINode>(I), II, Worklist, LivenessAAs);
11424 case Instruction::Load:
11425 return handleLoadInst(A, cast<LoadInst>(I), II, Worklist);
11426 default:
11427 return handleGenericInst(A, I, II, Worklist);
11428 };
11429 return false;
11430 }
11431
11432 void genericValueTraversal(Attributor &A, Value *InitialV) {
11433 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
11434
11435 SmallSet<ItemInfo, 16> Visited;
11437 Worklist.push_back({{*InitialV, getCtxI()}, AA::AnyScope});
11438
11439 int Iteration = 0;
11440 do {
11441 ItemInfo II = Worklist.pop_back_val();
11442 Value *V = II.I.getValue();
11443 assert(V);
11444 const Instruction *CtxI = II.I.getCtxI();
11445 AA::ValueScope S = II.S;
11446
11447 // Check if we should process the current value. To prevent endless
11448 // recursion keep a record of the values we followed!
11449 if (!Visited.insert(II).second)
11450 continue;
11451
11452 // Make sure we limit the compile time for complex expressions.
11453 if (Iteration++ >= A.Opts.attributor_max_potential_values_iterations) {
11454 LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: "
11455 << Iteration << "!\n");
11456 addValue(A, getState(), *V, CtxI, S, getAnchorScope());
11457 continue;
11458 }
11459
11460 // Explicitly look through calls with a "returned" attribute if we do
11461 // not have a pointer as stripPointerCasts only works on them.
11462 Value *NewV = nullptr;
11463 if (V->getType()->isPointerTy()) {
11464 NewV = AA::getWithType(*V->stripPointerCasts(), *V->getType());
11465 } else {
11466 if (auto *CB = dyn_cast<CallBase>(V))
11467 if (auto *Callee =
11469 for (Argument &Arg : Callee->args())
11470 if (Arg.hasReturnedAttr()) {
11471 NewV = CB->getArgOperand(Arg.getArgNo());
11472 break;
11473 }
11474 }
11475 }
11476 if (NewV && NewV != V) {
11477 Worklist.push_back({{*NewV, CtxI}, S});
11478 continue;
11479 }
11480
11481 if (auto *I = dyn_cast<Instruction>(V)) {
11482 if (simplifyInstruction(A, *I, II, Worklist, LivenessAAs))
11483 continue;
11484 }
11485
11486 if (V != InitialV || isa<Argument>(V))
11487 if (recurseForValue(A, IRPosition::value(*V), II.S))
11488 continue;
11489
11490 // If we haven't stripped anything we give up.
11491 if (V == InitialV && CtxI == getCtxI()) {
11492 indicatePessimisticFixpoint();
11493 return;
11494 }
11495
11496 addValue(A, getState(), *V, CtxI, S, getAnchorScope());
11497 } while (!Worklist.empty());
11498
11499 // If we actually used liveness information so we have to record a
11500 // dependence.
11501 for (auto &It : LivenessAAs)
11502 if (It.second.AnyDead)
11503 A.recordDependence(*It.second.LivenessAA, *this, DepClassTy::OPTIONAL);
11504 }
11505
11506 void trackStatistics() const override {
11507 STATS_DECLTRACK_FLOATING_ATTR(potential_values)
11508 }
11509};
11510
11511struct AAPotentialValuesArgument final : AAPotentialValuesImpl {
11512 using Base = AAPotentialValuesImpl;
11513 AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A)
11514 : Base(IRP, A) {}
11515
11516 void initialize(Attributor &A) override {
11517 auto &Arg = cast<Argument>(getAssociatedValue());
11519 indicatePessimisticFixpoint();
11520 }
11521
11522 ChangeStatus updateImpl(Attributor &A) override {
11523 auto AssumedBefore = getAssumed();
11524
11525 unsigned ArgNo = getCalleeArgNo();
11526
11527 bool UsedAssumedInformation = false;
11529 auto CallSitePred = [&](AbstractCallSite ACS) {
11530 const auto CSArgIRP = IRPosition::callsite_argument(ACS, ArgNo);
11531 if (CSArgIRP.getPositionKind() == IRP_INVALID)
11532 return false;
11533
11534 if (!A.getAssumedSimplifiedValues(CSArgIRP, this, Values,
11536 UsedAssumedInformation))
11537 return false;
11538
11539 return isValidState();
11540 };
11541
11542 if (!A.checkForAllCallSites(CallSitePred, *this,
11543 /* RequireAllCallSites */ true,
11544 UsedAssumedInformation))
11545 return indicatePessimisticFixpoint();
11546
11547 Function *Fn = getAssociatedFunction();
11548 bool AnyNonLocal = false;
11549 for (auto &It : Values) {
11550 if (isa<Constant>(It.getValue())) {
11551 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
11552 getAnchorScope());
11553 continue;
11554 }
11555 if (!AA::isDynamicallyUnique(A, *this, *It.getValue()))
11556 return indicatePessimisticFixpoint();
11557
11558 if (auto *Arg = dyn_cast<Argument>(It.getValue()))
11559 if (Arg->getParent() == Fn) {
11560 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
11561 getAnchorScope());
11562 continue;
11563 }
11564 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::Interprocedural,
11565 getAnchorScope());
11566 AnyNonLocal = true;
11567 }
11568 assert(!undefIsContained() && "Undef should be an explicit value!");
11569 if (AnyNonLocal)
11570 giveUpOnIntraprocedural(A);
11571
11572 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11573 : ChangeStatus::CHANGED;
11574 }
11575
11576 void trackStatistics() const override {
11577 STATS_DECLTRACK_ARG_ATTR(potential_values)
11578 }
11579};
11580
11581struct AAPotentialValuesReturned : public AAPotentialValuesFloating {
11582 using Base = AAPotentialValuesFloating;
11583 AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A)
11584 : Base(IRP, A) {}
11585
11586 void initialize(Attributor &A) override {
11587 Function *F = getAssociatedFunction();
11588 if (!F || F->isDeclaration() || F->getReturnType()->isVoidTy()) {
11589 indicatePessimisticFixpoint();
11590 return;
11591 }
11592
11593 for (Argument &Arg : F->args())
11594 if (Arg.hasReturnedAttr()) {
11595 addValue(A, getState(), Arg, nullptr, AA::AnyScope, F);
11596 ReturnedArg = &Arg;
11597 break;
11598 }
11599 if (!A.isFunctionIPOAmendable(*F) ||
11600 A.hasSimplificationCallback(getIRPosition())) {
11601 if (!ReturnedArg)
11602 indicatePessimisticFixpoint();
11603 else
11604 indicateOptimisticFixpoint();
11605 }
11606 }
11607
11608 ChangeStatus updateImpl(Attributor &A) override {
11609 auto AssumedBefore = getAssumed();
11610 bool UsedAssumedInformation = false;
11611
11613 Function *AnchorScope = getAnchorScope();
11614 auto HandleReturnedValue = [&](Value &V, Instruction *CtxI,
11615 bool AddValues) {
11617 Values.clear();
11618 if (!A.getAssumedSimplifiedValues(IRPosition::value(V), this, Values, S,
11619 UsedAssumedInformation,
11620 /* RecurseForSelectAndPHI */ true))
11621 return false;
11622 if (!AddValues)
11623 continue;
11624
11625 bool AllInterAreIntra = false;
11626 if (S == AA::Interprocedural)
11627 AllInterAreIntra =
11628 llvm::all_of(Values, [&](const AA::ValueAndContext &VAC) {
11629 return AA::isValidInScope(*VAC.getValue(), AnchorScope);
11630 });
11631
11632 for (const AA::ValueAndContext &VAC : Values) {
11633 addValue(A, getState(), *VAC.getValue(),
11634 VAC.getCtxI() ? VAC.getCtxI() : CtxI,
11635 AllInterAreIntra ? AA::AnyScope : S, AnchorScope);
11636 }
11637 if (AllInterAreIntra)
11638 break;
11639 }
11640 return true;
11641 };
11642
11643 if (ReturnedArg) {
11644 HandleReturnedValue(*ReturnedArg, nullptr, true);
11645 } else {
11646 auto RetInstPred = [&](Instruction &RetI) {
11647 bool AddValues = true;
11648 if (isa<PHINode>(RetI.getOperand(0)) ||
11649 isa<SelectInst>(RetI.getOperand(0))) {
11650 addValue(A, getState(), *RetI.getOperand(0), &RetI, AA::AnyScope,
11651 AnchorScope);
11652 AddValues = false;
11653 }
11654 return HandleReturnedValue(*RetI.getOperand(0), &RetI, AddValues);
11655 };
11656
11657 if (!A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
11658 UsedAssumedInformation,
11659 /* CheckBBLivenessOnly */ true))
11660 return indicatePessimisticFixpoint();
11661 }
11662
11663 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11664 : ChangeStatus::CHANGED;
11665 }
11666
11667 ChangeStatus manifest(Attributor &A) override {
11668 if (ReturnedArg)
11669 return ChangeStatus::UNCHANGED;
11671 if (!getAssumedSimplifiedValues(A, Values, AA::ValueScope::Intraprocedural,
11672 /* RecurseForSelectAndPHI */ true))
11673 return ChangeStatus::UNCHANGED;
11674 Value *NewVal = getSingleValue(A, *this, getIRPosition(), Values);
11675 if (!NewVal)
11676 return ChangeStatus::UNCHANGED;
11677
11678 ChangeStatus Changed = ChangeStatus::UNCHANGED;
11679 if (auto *Arg = dyn_cast<Argument>(NewVal)) {
11680 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
11681 "Number of function with unique return");
11682 Changed |= A.manifestAttrs(
11684 {Attribute::get(Arg->getContext(), Attribute::Returned)});
11685 STATS_DECLTRACK_ARG_ATTR(returned);
11686 }
11687
11688 auto RetInstPred = [&](Instruction &RetI) {
11689 Value *RetOp = RetI.getOperand(0);
11690 if (isa<UndefValue>(RetOp) || RetOp == NewVal)
11691 return true;
11692 if (AA::isValidAtPosition({*NewVal, RetI}, A.getInfoCache()))
11693 if (A.changeUseAfterManifest(RetI.getOperandUse(0), *NewVal))
11694 Changed = ChangeStatus::CHANGED;
11695 return true;
11696 };
11697 bool UsedAssumedInformation = false;
11698 (void)A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
11699 UsedAssumedInformation,
11700 /* CheckBBLivenessOnly */ true);
11701 return Changed;
11702 }
11703
11704 ChangeStatus indicatePessimisticFixpoint() override {
11705 return AAPotentialValues::indicatePessimisticFixpoint();
11706 }
11707
11708 void trackStatistics() const override{
11709 STATS_DECLTRACK_FNRET_ATTR(potential_values)}
11710
11711 /// The argumented with an existing `returned` attribute.
11712 Argument *ReturnedArg = nullptr;
11713};
11714
11715struct AAPotentialValuesFunction : AAPotentialValuesImpl {
11716 AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A)
11717 : AAPotentialValuesImpl(IRP, A) {}
11718
11719 ChangeStatus updateImpl(Attributor &A) override {
11720 llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will "
11721 "not be called");
11722 }
11723
11724 void trackStatistics() const override {
11725 STATS_DECLTRACK_FN_ATTR(potential_values)
11726 }
11727};
11728
11729struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
11730 AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A)
11731 : AAPotentialValuesFunction(IRP, A) {}
11732
11733 void trackStatistics() const override {
11734 STATS_DECLTRACK_CS_ATTR(potential_values)
11735 }
11736};
11737
11738struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl {
11739 AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A)
11740 : AAPotentialValuesImpl(IRP, A) {}
11741
11742 ChangeStatus updateImpl(Attributor &A) override {
11743 auto AssumedBefore = getAssumed();
11744
11745 Function *Callee = getAssociatedFunction();
11746 if (!Callee)
11747 return indicatePessimisticFixpoint();
11748
11749 bool UsedAssumedInformation = false;
11750 auto *CB = cast<CallBase>(getCtxI());
11751 if (CB->isMustTailCall() &&
11752 !A.isAssumedDead(IRPosition::inst(*CB), this, nullptr,
11753 UsedAssumedInformation))
11754 return indicatePessimisticFixpoint();
11755
11756 Function *Caller = CB->getCaller();
11757
11758 auto AddScope = [&](AA::ValueScope S) {
11760 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this,
11761 Values, S, UsedAssumedInformation))
11762 return false;
11763
11764 for (auto &It : Values) {
11765 Value *V = It.getValue();
11766 std::optional<Value *> CallerV = A.translateArgumentToCallSiteContent(
11767 V, *CB, *this, UsedAssumedInformation);
11768 if (!CallerV.has_value()) {
11769 // Nothing to do as long as no value was determined.
11770 continue;
11771 }
11772 V = *CallerV ? *CallerV : V;
11773 if (*CallerV && AA::isDynamicallyUnique(A, *this, *V)) {
11774 if (recurseForValue(A, IRPosition::value(*V), S))
11775 continue;
11776 }
11777 if (S == AA::Intraprocedural && !AA::isValidInScope(*V, Caller)) {
11778 giveUpOnIntraprocedural(A);
11779 return true;
11780 }
11781 addValue(A, getState(), *V, CB, S, getAnchorScope());
11782 }
11783 return true;
11784 };
11785 if (!AddScope(AA::Intraprocedural))
11786 return indicatePessimisticFixpoint();
11787 if (!AddScope(AA::Interprocedural))
11788 return indicatePessimisticFixpoint();
11789 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11790 : ChangeStatus::CHANGED;
11791 }
11792
11793 ChangeStatus indicatePessimisticFixpoint() override {
11794 return AAPotentialValues::indicatePessimisticFixpoint();
11795 }
11796
11797 void trackStatistics() const override {
11798 STATS_DECLTRACK_CSRET_ATTR(potential_values)
11799 }
11800};
11801
11802struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
11803 AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A)
11804 : AAPotentialValuesFloating(IRP, A) {}
11805
11806 void trackStatistics() const override {
11807 STATS_DECLTRACK_CSARG_ATTR(potential_values)
11808 }
11809};
11810} // namespace
11811
11812/// ---------------------- Assumption Propagation ------------------------------
11813namespace {
11814struct AAAssumptionInfoImpl : public AAAssumptionInfo {
11815 AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A,
11816 const DenseSet<StringRef> &Known)
11817 : AAAssumptionInfo(IRP, A, Known) {}
11818
11819 ChangeStatus manifest(Attributor &A) override {
11820 // Don't manifest a universal set if it somehow made it here.
11821 if (getKnown().isUniversal())
11822 return ChangeStatus::UNCHANGED;
11823
11824 const IRPosition &IRP = getIRPosition();
11825 SmallVector<StringRef, 0> Set(getAssumed().getSet().begin(),
11826 getAssumed().getSet().end());
11827 llvm::sort(Set);
11828 return A.manifestAttrs(IRP,
11829 Attribute::get(IRP.getAnchorValue().getContext(),
11831 llvm::join(Set, ",")),
11832 /*ForceReplace=*/true);
11833 }
11834
11835 bool hasAssumption(const StringRef Assumption) const override {
11836 return isValidState() && setContains(Assumption);
11837 }
11838
11839 const std::string getAsStr(Attributor *A) const override {
11840 const SetContents &Known = getKnown();
11841 const SetContents &Assumed = getAssumed();
11842
11843 SmallVector<StringRef, 0> Set(Known.getSet().begin(), Known.getSet().end());
11844 llvm::sort(Set);
11845 const std::string KnownStr = llvm::join(Set, ",");
11846
11847 std::string AssumedStr = "Universal";
11848 if (!Assumed.isUniversal()) {
11849 Set.assign(Assumed.getSet().begin(), Assumed.getSet().end());
11850 AssumedStr = llvm::join(Set, ",");
11851 }
11852 return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]";
11853 }
11854};
11855
11856/// Propagates assumption information from parent functions to all of their
11857/// successors. An assumption can be propagated if the containing function
11858/// dominates the called function.
11859///
11860/// We start with a "known" set of assumptions already valid for the associated
11861/// function and an "assumed" set that initially contains all possible
11862/// assumptions. The assumed set is inter-procedurally updated by narrowing its
11863/// contents as concrete values are known. The concrete values are seeded by the
11864/// first nodes that are either entries into the call graph, or contains no
11865/// assumptions. Each node is updated as the intersection of the assumed state
11866/// with all of its predecessors.
11867struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
11868 AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A)
11869 : AAAssumptionInfoImpl(IRP, A,
11870 getAssumptions(*IRP.getAssociatedFunction())) {}
11871
11872 ChangeStatus updateImpl(Attributor &A) override {
11873 bool Changed = false;
11874
11875 auto CallSitePred = [&](AbstractCallSite ACS) {
11876 const auto *AssumptionAA = A.getAAFor<AAAssumptionInfo>(
11877 *this, IRPosition::callsite_function(*ACS.getInstruction()),
11878 DepClassTy::REQUIRED);
11879 if (!AssumptionAA)
11880 return false;
11881 // Get the set of assumptions shared by all of this function's callers.
11882 Changed |= getIntersection(AssumptionAA->getAssumed());
11883 return !getAssumed().empty() || !getKnown().empty();
11884 };
11885
11886 bool UsedAssumedInformation = false;
11887 // Get the intersection of all assumptions held by this node's predecessors.
11888 // If we don't know all the call sites then this is either an entry into the
11889 // call graph or an empty node. This node is known to only contain its own
11890 // assumptions and can be propagated to its successors.
11891 if (!A.checkForAllCallSites(CallSitePred, *this, true,
11892 UsedAssumedInformation))
11893 return indicatePessimisticFixpoint();
11894
11895 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11896 }
11897
11898 void trackStatistics() const override {}
11899};
11900
11901/// Assumption Info defined for call sites.
11902struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
11903
11904 AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A)
11905 : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {}
11906
11907 void initialize(Attributor &A) override {
11908 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
11909 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
11910 }
11911
11912 ChangeStatus updateImpl(Attributor &A) override {
11913 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
11914 auto *AssumptionAA =
11915 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
11916 if (!AssumptionAA)
11917 return indicatePessimisticFixpoint();
11918 bool Changed = getIntersection(AssumptionAA->getAssumed());
11919 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11920 }
11921
11922 void trackStatistics() const override {}
11923
11924private:
11925 /// Helper to initialized the known set as all the assumptions this call and
11926 /// the callee contain.
11927 DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) {
11928 const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue());
11929 auto Assumptions = getAssumptions(CB);
11930 if (const Function *F = CB.getCaller())
11931 set_union(Assumptions, getAssumptions(*F));
11932 if (Function *F = IRP.getAssociatedFunction())
11933 set_union(Assumptions, getAssumptions(*F));
11934 return Assumptions;
11935 }
11936};
11937} // namespace
11938
11940 return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>(
11941 A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I))));
11942}
11943
11945
11946/// ------------------------ UnderlyingObjects ---------------------------------
11947
11948namespace {
11949struct AAUnderlyingObjectsImpl
11950 : StateWrapper<BooleanState, AAUnderlyingObjects> {
11952 AAUnderlyingObjectsImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {}
11953
11954 const std::string getAsStr(Attributor *A) const override {
11955 if (!isValidState())
11956 return "<invalid>";
11957 std::string Str;
11959 OS << "underlying objects: inter " << InterAssumedUnderlyingObjects.size()
11960 << " objects, intra " << IntraAssumedUnderlyingObjects.size()
11961 << " objects.\n";
11962 if (!InterAssumedUnderlyingObjects.empty()) {
11963 OS << "inter objects:\n";
11964 for (auto *Obj : InterAssumedUnderlyingObjects)
11965 OS << *Obj << '\n';
11966 }
11967 if (!IntraAssumedUnderlyingObjects.empty()) {
11968 OS << "intra objects:\n";
11969 for (auto *Obj : IntraAssumedUnderlyingObjects)
11970 OS << *Obj << '\n';
11971 }
11972 return Str;
11973 }
11974
11975 void trackStatistics() const override {}
11976
11977 ChangeStatus updateImpl(Attributor &A) override {
11978 auto &Ptr = getAssociatedValue();
11979
11980 bool UsedAssumedInformation = false;
11981 auto DoUpdate = [&](SmallSetVector<Value *, 8> &UnderlyingObjects,
11983 SmallPtrSet<Value *, 8> SeenObjects;
11985
11986 if (!A.getAssumedSimplifiedValues(IRPosition::value(Ptr), *this, Values,
11987 Scope, UsedAssumedInformation))
11988 return UnderlyingObjects.insert(&Ptr);
11989
11990 bool Changed = false;
11991
11992 for (unsigned I = 0; I < Values.size(); ++I) {
11993 auto &VAC = Values[I];
11994 auto *Obj = VAC.getValue();
11995 Value *UO = getUnderlyingObject(Obj);
11996 if (!SeenObjects.insert(UO ? UO : Obj).second)
11997 continue;
11998 if (UO && UO != Obj) {
11999 if (isa<AllocaInst>(UO) || isa<GlobalValue>(UO)) {
12000 Changed |= UnderlyingObjects.insert(UO);
12001 continue;
12002 }
12003
12004 const auto *OtherAA = A.getAAFor<AAUnderlyingObjects>(
12005 *this, IRPosition::value(*UO), DepClassTy::OPTIONAL);
12006 auto Pred = [&](Value &V) {
12007 if (&V == UO)
12008 Changed |= UnderlyingObjects.insert(UO);
12009 else
12010 Values.emplace_back(V, nullptr);
12011 return true;
12012 };
12013
12014 if (!OtherAA || !OtherAA->forallUnderlyingObjects(Pred, Scope))
12016 "The forall call should not return false at this position");
12017 UsedAssumedInformation |= !OtherAA->getState().isAtFixpoint();
12018 continue;
12019 }
12020
12021 if (isa<SelectInst>(Obj)) {
12022 Changed |= handleIndirect(A, *Obj, UnderlyingObjects, Scope,
12023 UsedAssumedInformation);
12024 continue;
12025 }
12026 if (auto *PHI = dyn_cast<PHINode>(Obj)) {
12027 // Explicitly look through PHIs as we do not care about dynamically
12028 // uniqueness.
12029 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
12030 Changed |=
12031 handleIndirect(A, *PHI->getIncomingValue(u), UnderlyingObjects,
12032 Scope, UsedAssumedInformation);
12033 }
12034 continue;
12035 }
12036
12037 Changed |= UnderlyingObjects.insert(Obj);
12038 }
12039
12040 return Changed;
12041 };
12042
12043 bool Changed = false;
12044 Changed |= DoUpdate(IntraAssumedUnderlyingObjects, AA::Intraprocedural);
12045 Changed |= DoUpdate(InterAssumedUnderlyingObjects, AA::Interprocedural);
12046 if (!UsedAssumedInformation)
12047 indicateOptimisticFixpoint();
12048 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
12049 }
12050
12051 bool forallUnderlyingObjects(
12052 function_ref<bool(Value &)> Pred,
12053 AA::ValueScope Scope = AA::Interprocedural) const override {
12054 if (!isValidState())
12055 return Pred(getAssociatedValue());
12056
12057 auto &AssumedUnderlyingObjects = Scope == AA::Intraprocedural
12058 ? IntraAssumedUnderlyingObjects
12059 : InterAssumedUnderlyingObjects;
12060 for (Value *Obj : AssumedUnderlyingObjects)
12061 if (!Pred(*Obj))
12062 return false;
12063
12064 return true;
12065 }
12066
12067private:
12068 /// Handle the case where the value is not the actual underlying value, such
12069 /// as a phi node or a select instruction.
12070 bool handleIndirect(Attributor &A, Value &V,
12071 SmallSetVector<Value *, 8> &UnderlyingObjects,
12072 AA::ValueScope Scope, bool &UsedAssumedInformation) {
12073 bool Changed = false;
12074 const auto *AA = A.getAAFor<AAUnderlyingObjects>(
12075 *this, IRPosition::value(V), DepClassTy::OPTIONAL);
12076 auto Pred = [&](Value &V) {
12077 Changed |= UnderlyingObjects.insert(&V);
12078 return true;
12079 };
12080 if (!AA || !AA->forallUnderlyingObjects(Pred, Scope))
12082 "The forall call should not return false at this position");
12083 UsedAssumedInformation |= !AA->getState().isAtFixpoint();
12084 return Changed;
12085 }
12086
12087 /// All the underlying objects collected so far via intra procedural scope.
12088 SmallSetVector<Value *, 8> IntraAssumedUnderlyingObjects;
12089 /// All the underlying objects collected so far via inter procedural scope.
12090 SmallSetVector<Value *, 8> InterAssumedUnderlyingObjects;
12091};
12092
12093struct AAUnderlyingObjectsFloating final : AAUnderlyingObjectsImpl {
12094 AAUnderlyingObjectsFloating(const IRPosition &IRP, Attributor &A)
12095 : AAUnderlyingObjectsImpl(IRP, A) {}
12096};
12097
12098struct AAUnderlyingObjectsArgument final : AAUnderlyingObjectsImpl {
12099 AAUnderlyingObjectsArgument(const IRPosition &IRP, Attributor &A)
12100 : AAUnderlyingObjectsImpl(IRP, A) {}
12101};
12102
12103struct AAUnderlyingObjectsCallSite final : AAUnderlyingObjectsImpl {
12104 AAUnderlyingObjectsCallSite(const IRPosition &IRP, Attributor &A)
12105 : AAUnderlyingObjectsImpl(IRP, A) {}
12106};
12107
12108struct AAUnderlyingObjectsCallSiteArgument final : AAUnderlyingObjectsImpl {
12109 AAUnderlyingObjectsCallSiteArgument(const IRPosition &IRP, Attributor &A)
12110 : AAUnderlyingObjectsImpl(IRP, A) {}
12111};
12112
12113struct AAUnderlyingObjectsReturned final : AAUnderlyingObjectsImpl {
12114 AAUnderlyingObjectsReturned(const IRPosition &IRP, Attributor &A)
12115 : AAUnderlyingObjectsImpl(IRP, A) {}
12116};
12117
12118struct AAUnderlyingObjectsCallSiteReturned final : AAUnderlyingObjectsImpl {
12119 AAUnderlyingObjectsCallSiteReturned(const IRPosition &IRP, Attributor &A)
12120 : AAUnderlyingObjectsImpl(IRP, A) {}
12121};
12122
12123struct AAUnderlyingObjectsFunction final : AAUnderlyingObjectsImpl {
12124 AAUnderlyingObjectsFunction(const IRPosition &IRP, Attributor &A)
12125 : AAUnderlyingObjectsImpl(IRP, A) {}
12126};
12127} // namespace
12128
12129/// ------------------------ Global Value Info -------------------------------
12130namespace {
12131struct AAGlobalValueInfoFloating : public AAGlobalValueInfo {
12132 AAGlobalValueInfoFloating(const IRPosition &IRP, Attributor &A)
12133 : AAGlobalValueInfo(IRP, A) {}
12134
12135 void initialize(Attributor &A) override {}
12136
12137 bool checkUse(Attributor &A, const Use &U, bool &Follow,
12138 SmallVectorImpl<const Value *> &Worklist) {
12139 Instruction *UInst = dyn_cast<Instruction>(U.getUser());
12140 if (!UInst) {
12141 // Outside a closed world, code outside the module can read an
12142 // externally visible global, so the value escapes through it.
12143 if (auto *GV = dyn_cast<GlobalValue>(U.getUser()))
12144 if (!GV->hasLocalLinkage() && !A.isClosedWorldModule())
12145 return false;
12146 Follow = true;
12147 return true;
12148 }
12149
12150 LLVM_DEBUG(dbgs() << "[AAGlobalValueInfo] Check use: " << *U.get() << " in "
12151 << *UInst << "\n");
12152
12153 if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
12154 int Idx = &Cmp->getOperandUse(0) == &U;
12155 if (isa<Constant>(Cmp->getOperand(Idx)))
12156 return true;
12157 return U == &getAnchorValue();
12158 }
12159
12160 // Explicitly catch return instructions.
12161 if (isa<ReturnInst>(UInst)) {
12162 auto CallSitePred = [&](AbstractCallSite ACS) {
12163 Worklist.push_back(ACS.getInstruction());
12164 return true;
12165 };
12166 bool UsedAssumedInformation = false;
12167 // TODO: We should traverse the uses or add a "non-call-site" CB.
12168 if (!A.checkForAllCallSites(CallSitePred, *UInst->getFunction(),
12169 /*RequireAllCallSites=*/true, this,
12170 UsedAssumedInformation))
12171 return false;
12172 return true;
12173 }
12174
12175 // For now we only use special logic for call sites. However, the tracker
12176 // itself knows about a lot of other non-capturing cases already.
12177 auto *CB = dyn_cast<CallBase>(UInst);
12178 if (!CB)
12179 return false;
12180 // Direct calls are OK uses.
12181 if (CB->isCallee(&U))
12182 return true;
12183 // Non-argument uses are scary.
12184 if (!CB->isArgOperand(&U))
12185 return false;
12186 // TODO: Iterate callees.
12187 auto *Fn = dyn_cast<Function>(CB->getCalledOperand());
12188 if (!Fn || !A.isFunctionIPOAmendable(*Fn))
12189 return false;
12190
12191 unsigned ArgNo = CB->getArgOperandNo(&U);
12192 Worklist.push_back(Fn->getArg(ArgNo));
12193 return true;
12194 }
12195
12196 ChangeStatus updateImpl(Attributor &A) override {
12197 unsigned NumUsesBefore = Uses.size();
12198
12199 SmallPtrSet<const Value *, 8> Visited;
12201 Worklist.push_back(&getAnchorValue());
12202
12203 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
12204 Uses.insert(&U);
12205 // TODO(captures): Make this more precise.
12206 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
12207 if (CI.isPassthrough()) {
12208 Follow = true;
12209 return true;
12210 }
12211 return checkUse(A, U, Follow, Worklist);
12212 };
12213 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
12214 Uses.insert(&OldU);
12215 return true;
12216 };
12217
12218 while (!Worklist.empty()) {
12219 const Value *V = Worklist.pop_back_val();
12220 if (!Visited.insert(V).second)
12221 continue;
12222 if (!A.checkForAllUses(UsePred, *this, *V,
12223 /* CheckBBLivenessOnly */ true,
12224 DepClassTy::OPTIONAL,
12225 /* IgnoreDroppableUses */ true, EquivalentUseCB)) {
12226 return indicatePessimisticFixpoint();
12227 }
12228 }
12229
12230 return Uses.size() == NumUsesBefore ? ChangeStatus::UNCHANGED
12231 : ChangeStatus::CHANGED;
12232 }
12233
12234 bool isPotentialUse(const Use &U) const override {
12235 return !isValidState() || Uses.contains(&U);
12236 }
12237
12238 ChangeStatus manifest(Attributor &A) override {
12239 return ChangeStatus::UNCHANGED;
12240 }
12241
12242 const std::string getAsStr(Attributor *A) const override {
12243 return "[" + std::to_string(Uses.size()) + " uses]";
12244 }
12245
12246 void trackStatistics() const override {
12247 STATS_DECLTRACK_FLOATING_ATTR(GlobalValuesTracked);
12248 }
12249
12250private:
12251 /// Set of (transitive) uses of this GlobalValue.
12252 SmallPtrSet<const Use *, 8> Uses;
12253};
12254} // namespace
12255
12256/// ------------------------ Indirect Call Info -------------------------------
12257namespace {
12258struct AAIndirectCallInfoCallSite : public AAIndirectCallInfo {
12259 AAIndirectCallInfoCallSite(const IRPosition &IRP, Attributor &A)
12260 : AAIndirectCallInfo(IRP, A) {}
12261
12262 void initialize(Attributor &A) override {
12263 auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees);
12264 if (!MD && !A.isClosedWorldModule())
12265 return;
12266
12267 if (MD) {
12268 for (const auto &Op : MD->operands())
12270 PotentialCallees.insert(Callee);
12271 } else if (A.isClosedWorldModule()) {
12272 ArrayRef<Function *> IndirectlyCallableFunctions =
12273 A.getInfoCache().getIndirectlyCallableFunctions(A);
12274 PotentialCallees.insert_range(IndirectlyCallableFunctions);
12275 }
12276
12277 if (PotentialCallees.empty())
12278 indicateOptimisticFixpoint();
12279 }
12280
12281 ChangeStatus updateImpl(Attributor &A) override {
12282 CallBase *CB = cast<CallBase>(getCtxI());
12283 const Use &CalleeUse = CB->getCalledOperandUse();
12284 Value *FP = CB->getCalledOperand();
12285
12286 SmallSetVector<Function *, 4> AssumedCalleesNow;
12287 bool AllCalleesKnownNow = AllCalleesKnown;
12288
12289 auto CheckPotentialCalleeUse = [&](Function &PotentialCallee,
12290 bool &UsedAssumedInformation) {
12291 const auto *GIAA = A.getAAFor<AAGlobalValueInfo>(
12292 *this, IRPosition::value(PotentialCallee), DepClassTy::OPTIONAL);
12293 if (!GIAA || GIAA->isPotentialUse(CalleeUse))
12294 return true;
12295 UsedAssumedInformation = !GIAA->isAtFixpoint();
12296 return false;
12297 };
12298
12299 auto AddPotentialCallees = [&]() {
12300 for (auto *PotentialCallee : PotentialCallees) {
12301 bool UsedAssumedInformation = false;
12302 if (CheckPotentialCalleeUse(*PotentialCallee, UsedAssumedInformation))
12303 AssumedCalleesNow.insert(PotentialCallee);
12304 }
12305 };
12306
12307 // Use simplification to find potential callees, if !callees was present,
12308 // fallback to that set if necessary.
12309 bool UsedAssumedInformation = false;
12311 if (!A.getAssumedSimplifiedValues(IRPosition::value(*FP), this, Values,
12312 AA::ValueScope::AnyScope,
12313 UsedAssumedInformation)) {
12314 if (PotentialCallees.empty())
12315 return indicatePessimisticFixpoint();
12316 AddPotentialCallees();
12317 }
12318
12319 // Try to find a reason for \p Fn not to be a potential callee. If none was
12320 // found, add it to the assumed callees set.
12321 auto CheckPotentialCallee = [&](Function &Fn) {
12322 if (!PotentialCallees.empty() && !PotentialCallees.count(&Fn))
12323 return false;
12324
12325 auto &CachedResult = FilterResults[&Fn];
12326 if (CachedResult.has_value())
12327 return CachedResult.value();
12328
12329 bool UsedAssumedInformation = false;
12330 if (!CheckPotentialCalleeUse(Fn, UsedAssumedInformation)) {
12331 if (!UsedAssumedInformation)
12332 CachedResult = false;
12333 return false;
12334 }
12335
12336 int NumFnArgs = Fn.arg_size();
12337 int NumCBArgs = CB->arg_size();
12338
12339 // Check if any excess argument (which we fill up with poison) is known to
12340 // be UB on undef.
12341 for (int I = NumCBArgs; I < NumFnArgs; ++I) {
12342 bool IsKnown = false;
12344 A, this, IRPosition::argument(*Fn.getArg(I)),
12345 DepClassTy::OPTIONAL, IsKnown)) {
12346 if (IsKnown)
12347 CachedResult = false;
12348 return false;
12349 }
12350 }
12351
12352 CachedResult = true;
12353 return true;
12354 };
12355
12356 // Check simplification result, prune known UB callees, also restrict it to
12357 // the !callees set, if present.
12358 for (auto &VAC : Values) {
12359 if (isa<UndefValue>(VAC.getValue()))
12360 continue;
12362 VAC.getValue()->getType()->getPointerAddressSpace() == 0)
12363 continue;
12364 // TODO: Check for known UB, e.g., poison + noundef.
12365 if (auto *VACFn = dyn_cast<Function>(VAC.getValue())) {
12366 if (CheckPotentialCallee(*VACFn))
12367 AssumedCalleesNow.insert(VACFn);
12368 continue;
12369 }
12370 if (!PotentialCallees.empty()) {
12371 AddPotentialCallees();
12372 break;
12373 }
12374 AllCalleesKnownNow = false;
12375 }
12376
12377 if (AssumedCalleesNow == AssumedCallees &&
12378 AllCalleesKnown == AllCalleesKnownNow)
12379 return ChangeStatus::UNCHANGED;
12380
12381 std::swap(AssumedCallees, AssumedCalleesNow);
12382 AllCalleesKnown = AllCalleesKnownNow;
12383 return ChangeStatus::CHANGED;
12384 }
12385
12386 ChangeStatus manifest(Attributor &A) override {
12387 // If we can't specialize at all, give up now.
12388 if (!AllCalleesKnown && AssumedCallees.empty())
12389 return ChangeStatus::UNCHANGED;
12390
12391 CallBase *CB = cast<CallBase>(getCtxI());
12392 bool UsedAssumedInformation = false;
12393 if (A.isAssumedDead(*CB, this, /*LivenessAA=*/nullptr,
12394 UsedAssumedInformation))
12395 return ChangeStatus::UNCHANGED;
12396
12397 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12398 unsigned ProgramAS = CB->getDataLayout().getProgramAddressSpace();
12399 Value *FP = CB->getCalledOperand();
12400 if (FP->getType()->getPointerAddressSpace() != ProgramAS)
12401 FP = new AddrSpaceCastInst(
12402 FP, PointerType::get(FP->getContext(), ProgramAS),
12403 FP->getName() + ".as" + Twine(ProgramAS), CB->getIterator());
12404
12405 bool CBIsVoid = CB->getType()->isVoidTy();
12407 FunctionType *CSFT = CB->getFunctionType();
12408 SmallVector<Value *> CSArgs(CB->args());
12409
12410 // If we know all callees and there are none, the call site is (effectively)
12411 // dead (or UB).
12412 if (AssumedCallees.empty()) {
12413 assert(AllCalleesKnown &&
12414 "Expected all callees to be known if there are none.");
12415 A.changeToUnreachableAfterManifest(CB);
12416 return ChangeStatus::CHANGED;
12417 }
12418
12419 // Special handling for the single callee case.
12420 if (AllCalleesKnown && AssumedCallees.size() == 1) {
12421 auto *NewCallee = AssumedCallees.front();
12422 if (isLegalToPromote(*CB, NewCallee)) {
12423 promoteCall(*CB, NewCallee, nullptr);
12424 NumIndirectCallsPromoted++;
12425 return ChangeStatus::CHANGED;
12426 }
12427 Instruction *NewCall =
12428 CallInst::Create(FunctionCallee(CSFT, NewCallee), CSArgs,
12429 CB->getName(), CB->getIterator());
12430 NewCall->setDebugLoc(CB->getDebugLoc());
12431 if (!CBIsVoid)
12432 A.changeAfterManifest(IRPosition::callsite_returned(*CB), *NewCall);
12433 A.deleteAfterManifest(*CB);
12434 return ChangeStatus::CHANGED;
12435 }
12436
12437 // For each potential value we create a conditional
12438 //
12439 // ```
12440 // if (ptr == value) value(args);
12441 // else ...
12442 // ```
12443 //
12444 bool SpecializedForAnyCallees = false;
12445 bool SpecializedForAllCallees = AllCalleesKnown;
12446 ICmpInst *LastCmp = nullptr;
12447 SmallVector<Function *, 8> SkippedAssumedCallees;
12449 for (Function *NewCallee : AssumedCallees) {
12450 if (!A.shouldSpecializeCallSiteForCallee(*this, *CB, *NewCallee,
12451 AssumedCallees.size())) {
12452 SkippedAssumedCallees.push_back(NewCallee);
12453 SpecializedForAllCallees = false;
12454 continue;
12455 }
12456 SpecializedForAnyCallees = true;
12457
12458 LastCmp = new ICmpInst(IP, llvm::CmpInst::ICMP_EQ, FP, NewCallee);
12459 Instruction *ThenTI =
12460 SplitBlockAndInsertIfThen(LastCmp, IP, /* Unreachable */ false);
12461 BasicBlock *CBBB = CB->getParent();
12462 A.registerManifestAddedBasicBlock(*ThenTI->getParent());
12463 A.registerManifestAddedBasicBlock(*IP->getParent());
12464 auto *SplitTI = cast<CondBrInst>(LastCmp->getNextNode());
12465 BasicBlock *ElseBB;
12466 if (&*IP == CB) {
12467 ElseBB = BasicBlock::Create(ThenTI->getContext(), "",
12468 ThenTI->getFunction(), CBBB);
12469 A.registerManifestAddedBasicBlock(*ElseBB);
12470 IP = UncondBrInst::Create(CBBB, ElseBB)->getIterator();
12471 SplitTI->replaceUsesOfWith(CBBB, ElseBB);
12472 } else {
12473 ElseBB = IP->getParent();
12474 ThenTI->replaceUsesOfWith(ElseBB, CBBB);
12475 }
12476 CastInst *RetBC = nullptr;
12477 CallInst *NewCall = nullptr;
12478 if (isLegalToPromote(*CB, NewCallee)) {
12479 auto *CBClone = cast<CallBase>(CB->clone());
12480 CBClone->insertBefore(ThenTI->getIterator());
12481 NewCall = &cast<CallInst>(promoteCall(*CBClone, NewCallee, &RetBC));
12482 NumIndirectCallsPromoted++;
12483 } else {
12484 NewCall = CallInst::Create(FunctionCallee(CSFT, NewCallee), CSArgs,
12485 CB->getName(), ThenTI->getIterator());
12486 NewCall->setDebugLoc(CB->getDebugLoc());
12487 }
12488 NewCalls.push_back({NewCall, RetBC});
12489 }
12490
12491 auto AttachCalleeMetadata = [&](CallBase &IndirectCB) {
12492 if (!AllCalleesKnown)
12493 return ChangeStatus::UNCHANGED;
12494 MDBuilder MDB(IndirectCB.getContext());
12495 MDNode *Callees = MDB.createCallees(SkippedAssumedCallees);
12496 IndirectCB.setMetadata(LLVMContext::MD_callees, Callees);
12497 return ChangeStatus::CHANGED;
12498 };
12499
12500 if (!SpecializedForAnyCallees)
12501 return AttachCalleeMetadata(*CB);
12502
12503 // Check if we need the fallback indirect call still.
12504 if (SpecializedForAllCallees) {
12506 LastCmp->eraseFromParent();
12507 new UnreachableInst(IP->getContext(), IP);
12508 IP->eraseFromParent();
12509 } else {
12510 auto *CBClone = cast<CallInst>(CB->clone());
12511 CBClone->setName(CB->getName());
12512 CBClone->insertBefore(*IP->getParent(), IP);
12513 NewCalls.push_back({CBClone, nullptr});
12514 AttachCalleeMetadata(*CBClone);
12515 }
12516
12517 // Check if we need a PHI to merge the results.
12518 if (!CBIsVoid) {
12519 auto *PHI = PHINode::Create(CB->getType(), NewCalls.size(),
12520 CB->getName() + ".phi",
12521 CB->getParent()->getFirstInsertionPt());
12522 for (auto &It : NewCalls) {
12523 CallBase *NewCall = It.first;
12524 Instruction *CallRet = It.second ? It.second : It.first;
12525 if (CallRet->getType() == CB->getType())
12526 PHI->addIncoming(CallRet, CallRet->getParent());
12527 else if (NewCall->getType()->isVoidTy())
12528 PHI->addIncoming(PoisonValue::get(CB->getType()),
12529 NewCall->getParent());
12530 else
12531 llvm_unreachable("Call return should match or be void!");
12532 }
12533 A.changeAfterManifest(IRPosition::callsite_returned(*CB), *PHI);
12534 }
12535
12536 A.deleteAfterManifest(*CB);
12537 Changed = ChangeStatus::CHANGED;
12538
12539 return Changed;
12540 }
12541
12542 const std::string getAsStr(Attributor *A) const override {
12543 return std::string(AllCalleesKnown ? "eliminate" : "specialize") +
12544 " indirect call site with " + std::to_string(AssumedCallees.size()) +
12545 " functions";
12546 }
12547
12548 void trackStatistics() const override {
12549 if (AllCalleesKnown) {
12551 Eliminated, CallSites,
12552 "Number of indirect call sites eliminated via specialization")
12553 } else {
12554 STATS_DECLTRACK(Specialized, CallSites,
12555 "Number of indirect call sites specialized")
12556 }
12557 }
12558
12559 bool foreachCallee(function_ref<bool(Function *)> CB) const override {
12560 return isValidState() && AllCalleesKnown && all_of(AssumedCallees, CB);
12561 }
12562
12563private:
12564 /// Map to remember filter results.
12565 DenseMap<Function *, std::optional<bool>> FilterResults;
12566
12567 /// If the !callee metadata was present, this set will contain all potential
12568 /// callees (superset).
12569 SmallSetVector<Function *, 4> PotentialCallees;
12570
12571 /// This set contains all currently assumed calllees, which might grow over
12572 /// time.
12573 SmallSetVector<Function *, 4> AssumedCallees;
12574
12575 /// Flag to indicate if all possible callees are in the AssumedCallees set or
12576 /// if there could be others.
12577 bool AllCalleesKnown = true;
12578};
12579} // namespace
12580
12581/// --------------------- Invariant Load Pointer -------------------------------
12582namespace {
12583
12584struct AAInvariantLoadPointerImpl
12585 : public StateWrapper<BitIntegerState<uint8_t, 15>,
12586 AAInvariantLoadPointer> {
12587
12588 enum {
12589 // pointer does not alias within the bounds of the function
12590 IS_NOALIAS = 1 << 0,
12591 // pointer is not involved in any effectful instructions within the bounds
12592 // of the function
12593 IS_NOEFFECT = 1 << 1,
12594 // loads are invariant within the bounds of the function
12595 IS_LOCALLY_INVARIANT = 1 << 2,
12596 // memory lifetime is constrained within the bounds of the function
12597 IS_LOCALLY_CONSTRAINED = 1 << 3,
12598
12599 IS_BEST_STATE = IS_NOALIAS | IS_NOEFFECT | IS_LOCALLY_INVARIANT |
12600 IS_LOCALLY_CONSTRAINED,
12601 };
12602 static_assert(getBestState() == IS_BEST_STATE, "Unexpected best state");
12603
12604 using Base =
12605 StateWrapper<BitIntegerState<uint8_t, 15>, AAInvariantLoadPointer>;
12606
12607 // the BitIntegerState is optimistic about IS_NOALIAS and IS_NOEFFECT, but
12608 // pessimistic about IS_KNOWN_INVARIANT
12609 AAInvariantLoadPointerImpl(const IRPosition &IRP, Attributor &A)
12610 : Base(IRP) {}
12611
12612 bool isKnownInvariant() const final {
12613 return isKnownLocallyInvariant() && isKnown(IS_LOCALLY_CONSTRAINED);
12614 }
12615
12616 bool isKnownLocallyInvariant() const final {
12617 if (isKnown(IS_LOCALLY_INVARIANT))
12618 return true;
12619 return isKnown(IS_NOALIAS | IS_NOEFFECT);
12620 }
12621
12622 bool isAssumedInvariant() const final {
12623 return isAssumedLocallyInvariant() && isAssumed(IS_LOCALLY_CONSTRAINED);
12624 }
12625
12626 bool isAssumedLocallyInvariant() const final {
12627 if (isAssumed(IS_LOCALLY_INVARIANT))
12628 return true;
12629 return isAssumed(IS_NOALIAS | IS_NOEFFECT);
12630 }
12631
12632 ChangeStatus updateImpl(Attributor &A) override {
12633 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12634
12635 Changed |= updateNoAlias(A);
12636 if (requiresNoAlias() && !isAssumed(IS_NOALIAS))
12637 return indicatePessimisticFixpoint();
12638
12639 Changed |= updateNoEffect(A);
12640
12641 Changed |= updateLocalInvariance(A);
12642
12643 return Changed;
12644 }
12645
12646 ChangeStatus manifest(Attributor &A) override {
12647 if (!isKnownInvariant())
12648 return ChangeStatus::UNCHANGED;
12649
12650 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12651 const Value *Ptr = &getAssociatedValue();
12652 const auto TagInvariantLoads = [&](const Use &U, bool &) {
12653 if (U.get() != Ptr)
12654 return true;
12655 auto *I = dyn_cast<Instruction>(U.getUser());
12656 if (!I)
12657 return true;
12658
12659 // Ensure that we are only changing uses from the corresponding callgraph
12660 // SSC in the case that the AA isn't run on the entire module
12661 if (!A.isRunOn(I->getFunction()))
12662 return true;
12663
12664 if (I->hasMetadata(LLVMContext::MD_invariant_load))
12665 return true;
12666
12667 if (auto *LI = dyn_cast<LoadInst>(I)) {
12668 LI->setMetadata(LLVMContext::MD_invariant_load,
12669 MDNode::get(LI->getContext(), {}));
12670 Changed = ChangeStatus::CHANGED;
12671 }
12672 return true;
12673 };
12674
12675 (void)A.checkForAllUses(TagInvariantLoads, *this, *Ptr);
12676 return Changed;
12677 }
12678
12679 const std::string getAsStr(Attributor *) const override {
12680 if (isKnownInvariant())
12681 return "load-invariant pointer";
12682 return "non-invariant pointer";
12683 }
12684
12685 void trackStatistics() const override {}
12686
12687private:
12688 /// Indicate that noalias is required for the pointer to be invariant.
12689 bool requiresNoAlias() const {
12690 switch (getPositionKind()) {
12691 default:
12692 // Conservatively default to require noalias.
12693 return true;
12694 case IRP_FLOAT:
12695 case IRP_RETURNED:
12696 case IRP_CALL_SITE:
12697 return false;
12698 case IRP_CALL_SITE_RETURNED: {
12699 const auto &CB = cast<CallBase>(getAnchorValue());
12701 &CB, /*MustPreserveOffset=*/false);
12702 }
12703 case IRP_ARGUMENT: {
12704 const Function *F = getAssociatedFunction();
12705 assert(F && "no associated function for argument");
12706 return !isCallableCC(F->getCallingConv());
12707 }
12708 }
12709 }
12710
12711 bool isExternal() const {
12712 const Function *F = getAssociatedFunction();
12713 if (!F)
12714 return true;
12715 return isCallableCC(F->getCallingConv()) &&
12716 getPositionKind() != IRP_CALL_SITE_RETURNED;
12717 }
12718
12719 ChangeStatus updateNoAlias(Attributor &A) {
12720 if (isKnown(IS_NOALIAS) || !isAssumed(IS_NOALIAS))
12721 return ChangeStatus::UNCHANGED;
12722
12723 // Try to use AANoAlias.
12724 if (const auto *ANoAlias = A.getOrCreateAAFor<AANoAlias>(
12725 getIRPosition(), this, DepClassTy::REQUIRED)) {
12726 if (ANoAlias->isKnownNoAlias()) {
12727 addKnownBits(IS_NOALIAS);
12728 return ChangeStatus::CHANGED;
12729 }
12730
12731 if (!ANoAlias->isAssumedNoAlias()) {
12732 removeAssumedBits(IS_NOALIAS);
12733 return ChangeStatus::CHANGED;
12734 }
12735
12736 return ChangeStatus::UNCHANGED;
12737 }
12738
12739 // Try to infer noalias from argument attribute, since it is applicable for
12740 // the duration of the function.
12741 if (const Argument *Arg = getAssociatedArgument()) {
12742 if (Arg->hasNoAliasAttr()) {
12743 addKnownBits(IS_NOALIAS);
12744 return ChangeStatus::UNCHANGED;
12745 }
12746
12747 // Noalias information is not provided, and cannot be inferred,
12748 // so we conservatively assume the pointer aliases.
12749 removeAssumedBits(IS_NOALIAS);
12750 return ChangeStatus::CHANGED;
12751 }
12752
12753 return ChangeStatus::UNCHANGED;
12754 }
12755
12756 ChangeStatus updateNoEffect(Attributor &A) {
12757 if (isKnown(IS_NOEFFECT) || !isAssumed(IS_NOEFFECT))
12758 return ChangeStatus::UNCHANGED;
12759
12760 if (!getAssociatedFunction())
12761 return indicatePessimisticFixpoint();
12762
12763 if (isa<AllocaInst>(&getAssociatedValue()))
12764 return indicatePessimisticFixpoint();
12765
12766 const auto HasNoEffectLoads = [&](const Use &U, bool &) {
12767 const auto *LI = dyn_cast<LoadInst>(U.getUser());
12768 return !LI || !LI->mayHaveSideEffects();
12769 };
12770 if (!A.checkForAllUses(HasNoEffectLoads, *this, getAssociatedValue()))
12771 return indicatePessimisticFixpoint();
12772
12773 if (const auto *AMemoryBehavior = A.getOrCreateAAFor<AAMemoryBehavior>(
12774 getIRPosition(), this, DepClassTy::REQUIRED)) {
12775 // For non-instructions, try to use AAMemoryBehavior to infer the readonly
12776 // attribute
12777 if (!AMemoryBehavior->isAssumedReadOnly())
12778 return indicatePessimisticFixpoint();
12779
12780 if (AMemoryBehavior->isKnownReadOnly()) {
12781 addKnownBits(IS_NOEFFECT);
12782 return ChangeStatus::UNCHANGED;
12783 }
12784
12785 return ChangeStatus::UNCHANGED;
12786 }
12787
12788 if (const Argument *Arg = getAssociatedArgument()) {
12789 if (Arg->onlyReadsMemory()) {
12790 addKnownBits(IS_NOEFFECT);
12791 return ChangeStatus::UNCHANGED;
12792 }
12793
12794 // Readonly information is not provided, and cannot be inferred from
12795 // AAMemoryBehavior.
12796 return indicatePessimisticFixpoint();
12797 }
12798
12799 return ChangeStatus::UNCHANGED;
12800 }
12801
12802 ChangeStatus updateLocalInvariance(Attributor &A) {
12803 if (isKnown(IS_LOCALLY_INVARIANT) || !isAssumed(IS_LOCALLY_INVARIANT))
12804 return ChangeStatus::UNCHANGED;
12805
12806 // try to infer invariance from underlying objects
12807 const auto *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(
12808 getIRPosition(), this, DepClassTy::REQUIRED);
12809 if (!AUO)
12810 return ChangeStatus::UNCHANGED;
12811
12812 bool UsedAssumedInformation = false;
12813 const auto IsLocallyInvariantLoadIfPointer = [&](const Value &V) {
12814 if (!V.getType()->isPointerTy())
12815 return true;
12816 const auto *IsInvariantLoadPointer =
12817 A.getOrCreateAAFor<AAInvariantLoadPointer>(IRPosition::value(V), this,
12818 DepClassTy::REQUIRED);
12819 // Conservatively fail if invariance cannot be inferred.
12820 if (!IsInvariantLoadPointer)
12821 return false;
12822
12823 if (IsInvariantLoadPointer->isKnownLocallyInvariant())
12824 return true;
12825 if (!IsInvariantLoadPointer->isAssumedLocallyInvariant())
12826 return false;
12827
12828 UsedAssumedInformation = true;
12829 return true;
12830 };
12831 if (!AUO->forallUnderlyingObjects(IsLocallyInvariantLoadIfPointer))
12832 return indicatePessimisticFixpoint();
12833
12834 if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue())) {
12836 CB, /*MustPreserveOffset=*/false)) {
12837 for (const Value *Arg : CB->args()) {
12838 if (!IsLocallyInvariantLoadIfPointer(*Arg))
12839 return indicatePessimisticFixpoint();
12840 }
12841 }
12842 }
12843
12844 if (!UsedAssumedInformation) {
12845 // Pointer is known and not just assumed to be locally invariant.
12846 addKnownBits(IS_LOCALLY_INVARIANT);
12847 return ChangeStatus::CHANGED;
12848 }
12849
12850 return ChangeStatus::UNCHANGED;
12851 }
12852};
12853
12854struct AAInvariantLoadPointerFloating final : AAInvariantLoadPointerImpl {
12855 AAInvariantLoadPointerFloating(const IRPosition &IRP, Attributor &A)
12856 : AAInvariantLoadPointerImpl(IRP, A) {}
12857};
12858
12859struct AAInvariantLoadPointerReturned final : AAInvariantLoadPointerImpl {
12860 AAInvariantLoadPointerReturned(const IRPosition &IRP, Attributor &A)
12861 : AAInvariantLoadPointerImpl(IRP, A) {}
12862
12863 void initialize(Attributor &) override {
12864 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12865 }
12866};
12867
12868struct AAInvariantLoadPointerCallSiteReturned final
12869 : AAInvariantLoadPointerImpl {
12870 AAInvariantLoadPointerCallSiteReturned(const IRPosition &IRP, Attributor &A)
12871 : AAInvariantLoadPointerImpl(IRP, A) {}
12872
12873 void initialize(Attributor &A) override {
12874 // Nothing is known about the result of an indirect call.
12875 const Function *F = getAssociatedFunction();
12876 if (!F) {
12877 indicatePessimisticFixpoint();
12878 return;
12879 }
12880
12881 if (!F->isDeclaration() && !F->isIntrinsic())
12882 return AAInvariantLoadPointerImpl::initialize(A);
12883
12884 const auto &CB = cast<CallBase>(getAnchorValue());
12886 &CB, /*MustPreserveOffset=*/false))
12887 return AAInvariantLoadPointerImpl::initialize(A);
12888
12889 if (F->onlyReadsMemory() && F->hasNoSync())
12890 return AAInvariantLoadPointerImpl::initialize(A);
12891
12892 // At this point, the function is opaque, so we conservatively assume
12893 // non-invariance.
12894 indicatePessimisticFixpoint();
12895 }
12896};
12897
12898struct AAInvariantLoadPointerArgument final : AAInvariantLoadPointerImpl {
12899 AAInvariantLoadPointerArgument(const IRPosition &IRP, Attributor &A)
12900 : AAInvariantLoadPointerImpl(IRP, A) {}
12901
12902 void initialize(Attributor &) override {
12903 const Function *F = getAssociatedFunction();
12904 assert(F && "no associated function for argument");
12905
12906 if (!isCallableCC(F->getCallingConv())) {
12907 addKnownBits(IS_LOCALLY_CONSTRAINED);
12908 return;
12909 }
12910
12911 if (!F->hasLocalLinkage())
12912 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12913 }
12914};
12915
12916struct AAInvariantLoadPointerCallSiteArgument final
12917 : AAInvariantLoadPointerImpl {
12918 AAInvariantLoadPointerCallSiteArgument(const IRPosition &IRP, Attributor &A)
12919 : AAInvariantLoadPointerImpl(IRP, A) {}
12920};
12921} // namespace
12922
12923/// ------------------------ Address Space ------------------------------------
12924namespace {
12925
12926template <typename InstType>
12927static bool makeChange(Attributor &A, InstType *MemInst, const Use &U,
12928 Value *OriginalValue, PointerType *NewPtrTy,
12929 bool UseOriginalValue) {
12930 if (U.getOperandNo() != InstType::getPointerOperandIndex())
12931 return false;
12932
12933 if (MemInst->isVolatile()) {
12934 auto *TTI = A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(
12935 *MemInst->getFunction());
12936 unsigned NewAS = NewPtrTy->getPointerAddressSpace();
12937 if (!TTI || !TTI->hasVolatileVariant(MemInst, NewAS))
12938 return false;
12939 }
12940
12941 if (UseOriginalValue) {
12942 A.changeUseAfterManifest(const_cast<Use &>(U), *OriginalValue);
12943 return true;
12944 }
12945
12946 Instruction *CastInst = new AddrSpaceCastInst(OriginalValue, NewPtrTy);
12947 CastInst->insertBefore(MemInst->getIterator());
12948 A.changeUseAfterManifest(const_cast<Use &>(U), *CastInst);
12949 return true;
12950}
12951
12952struct AAAddressSpaceImpl : public AAAddressSpace {
12953 AAAddressSpaceImpl(const IRPosition &IRP, Attributor &A)
12954 : AAAddressSpace(IRP, A) {}
12955
12956 uint32_t getAddressSpace() const override {
12957 assert(isValidState() && "the AA is invalid");
12958 return AssumedAddressSpace;
12959 }
12960
12961 void initialize(Attributor &A) override {
12962 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
12963 "Associated value is not a pointer");
12964
12965 if (!A.getInfoCache().getFlatAddressSpace().has_value()) {
12966 indicatePessimisticFixpoint();
12967 return;
12968 }
12969
12970 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
12971 unsigned AS = getAssociatedType()->getPointerAddressSpace();
12972 if (AS != FlatAS) {
12973 [[maybe_unused]] bool R = takeAddressSpace(AS);
12974 assert(R && "The take should happen");
12975 indicateOptimisticFixpoint();
12976 }
12977 }
12978
12979 ChangeStatus updateImpl(Attributor &A) override {
12980 uint32_t OldAddressSpace = AssumedAddressSpace;
12981 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
12982
12983 auto CheckAddressSpace = [&](Value &Obj) {
12984 // Ignore undef.
12985 if (isa<UndefValue>(&Obj))
12986 return true;
12987
12988 // If the object already has a non-flat address space, we simply take it.
12989 unsigned ObjAS = Obj.getType()->getPointerAddressSpace();
12990 if (ObjAS != FlatAS)
12991 return takeAddressSpace(ObjAS);
12992
12993 // At this point, we know Obj is in the flat address space. For a final
12994 // attempt, we want to use getAssumedAddrSpace, but first we must get the
12995 // associated function, if possible.
12996 Function *F = nullptr;
12997 if (auto *Arg = dyn_cast<Argument>(&Obj))
12998 F = Arg->getParent();
12999 else if (auto *I = dyn_cast<Instruction>(&Obj))
13000 F = I->getFunction();
13001
13002 // Use getAssumedAddrSpace if the associated function exists.
13003 if (F) {
13004 auto *TTI =
13005 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(*F);
13006 unsigned AssumedAS = TTI->getAssumedAddrSpace(&Obj);
13007 if (AssumedAS != ~0U)
13008 return takeAddressSpace(AssumedAS);
13009 }
13010
13011 // Now we can't do anything else but to take the flat AS.
13012 return takeAddressSpace(FlatAS);
13013 };
13014
13015 auto *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(getIRPosition(), this,
13016 DepClassTy::REQUIRED);
13017 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13018 return indicatePessimisticFixpoint();
13019
13020 return OldAddressSpace == AssumedAddressSpace ? ChangeStatus::UNCHANGED
13021 : ChangeStatus::CHANGED;
13022 }
13023
13024 ChangeStatus manifest(Attributor &A) override {
13025 unsigned NewAS = getAddressSpace();
13026
13027 if (NewAS == InvalidAddressSpace ||
13028 NewAS == getAssociatedType()->getPointerAddressSpace())
13029 return ChangeStatus::UNCHANGED;
13030
13031 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13032
13033 Value *AssociatedValue = &getAssociatedValue();
13034 Value *OriginalValue = peelAddrspacecast(AssociatedValue, FlatAS);
13035
13036 PointerType *NewPtrTy =
13037 PointerType::get(getAssociatedType()->getContext(), NewAS);
13038 bool UseOriginalValue =
13039 OriginalValue->getType()->getPointerAddressSpace() == NewAS;
13040
13041 bool Changed = false;
13042
13043 auto Pred = [&](const Use &U, bool &) {
13044 if (U.get() != AssociatedValue)
13045 return true;
13046 auto *Inst = dyn_cast<Instruction>(U.getUser());
13047 if (!Inst)
13048 return true;
13049 // This is a WA to make sure we only change uses from the corresponding
13050 // CGSCC if the AA is run on CGSCC instead of the entire module.
13051 if (!A.isRunOn(Inst->getFunction()))
13052 return true;
13053 if (auto *LI = dyn_cast<LoadInst>(Inst)) {
13054 Changed |=
13055 makeChange(A, LI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13056 } else if (auto *SI = dyn_cast<StoreInst>(Inst)) {
13057 Changed |=
13058 makeChange(A, SI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13059 } else if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
13060 Changed |=
13061 makeChange(A, RMW, U, OriginalValue, NewPtrTy, UseOriginalValue);
13062 } else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
13063 Changed |=
13064 makeChange(A, CmpX, U, OriginalValue, NewPtrTy, UseOriginalValue);
13065 }
13066 return true;
13067 };
13068
13069 // It doesn't matter if we can't check all uses as we can simply
13070 // conservatively ignore those that can not be visited.
13071 (void)A.checkForAllUses(Pred, *this, getAssociatedValue(),
13072 /* CheckBBLivenessOnly */ true);
13073
13074 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13075 }
13076
13077 const std::string getAsStr(Attributor *A) const override {
13078 if (!isValidState())
13079 return "addrspace(<invalid>)";
13080 return "addrspace(" +
13081 (AssumedAddressSpace == InvalidAddressSpace
13082 ? "none"
13083 : std::to_string(AssumedAddressSpace)) +
13084 ")";
13085 }
13086
13087private:
13088 uint32_t AssumedAddressSpace = InvalidAddressSpace;
13089
13090 bool takeAddressSpace(uint32_t AS) {
13091 if (AssumedAddressSpace == InvalidAddressSpace) {
13092 AssumedAddressSpace = AS;
13093 return true;
13094 }
13095 return AssumedAddressSpace == AS;
13096 }
13097
13098 static Value *peelAddrspacecast(Value *V, unsigned FlatAS) {
13099 if (auto *I = dyn_cast<AddrSpaceCastInst>(V)) {
13100 assert(I->getSrcAddressSpace() != FlatAS &&
13101 "there should not be flat AS -> non-flat AS");
13102 return I->getPointerOperand();
13103 }
13104 if (auto *C = dyn_cast<ConstantExpr>(V))
13105 if (C->getOpcode() == Instruction::AddrSpaceCast) {
13106 assert(C->getOperand(0)->getType()->getPointerAddressSpace() !=
13107 FlatAS &&
13108 "there should not be flat AS -> non-flat AS X");
13109 return C->getOperand(0);
13110 }
13111 return V;
13112 }
13113};
13114
13115struct AAAddressSpaceFloating final : AAAddressSpaceImpl {
13116 AAAddressSpaceFloating(const IRPosition &IRP, Attributor &A)
13117 : AAAddressSpaceImpl(IRP, A) {}
13118
13119 void trackStatistics() const override {
13121 }
13122};
13123
13124struct AAAddressSpaceReturned final : AAAddressSpaceImpl {
13125 AAAddressSpaceReturned(const IRPosition &IRP, Attributor &A)
13126 : AAAddressSpaceImpl(IRP, A) {}
13127
13128 void initialize(Attributor &A) override {
13129 // TODO: we don't rewrite function argument for now because it will need to
13130 // rewrite the function signature and all call sites.
13131 (void)indicatePessimisticFixpoint();
13132 }
13133
13134 void trackStatistics() const override {
13135 STATS_DECLTRACK_FNRET_ATTR(addrspace);
13136 }
13137};
13138
13139struct AAAddressSpaceCallSiteReturned final : AAAddressSpaceImpl {
13140 AAAddressSpaceCallSiteReturned(const IRPosition &IRP, Attributor &A)
13141 : AAAddressSpaceImpl(IRP, A) {}
13142
13143 void trackStatistics() const override {
13144 STATS_DECLTRACK_CSRET_ATTR(addrspace);
13145 }
13146};
13147
13148struct AAAddressSpaceArgument final : AAAddressSpaceImpl {
13149 AAAddressSpaceArgument(const IRPosition &IRP, Attributor &A)
13150 : AAAddressSpaceImpl(IRP, A) {}
13151
13152 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(addrspace); }
13153};
13154
13155struct AAAddressSpaceCallSiteArgument final : AAAddressSpaceImpl {
13156 AAAddressSpaceCallSiteArgument(const IRPosition &IRP, Attributor &A)
13157 : AAAddressSpaceImpl(IRP, A) {}
13158
13159 void initialize(Attributor &A) override {
13160 // TODO: we don't rewrite call site argument for now because it will need to
13161 // rewrite the function signature of the callee.
13162 (void)indicatePessimisticFixpoint();
13163 }
13164
13165 void trackStatistics() const override {
13166 STATS_DECLTRACK_CSARG_ATTR(addrspace);
13167 }
13168};
13169} // namespace
13170
13171/// ------------------------ No Alias Address Space ---------------------------
13172// This attribute assumes flat address space can alias all other address space
13173
13174// TODO: this is similar to AAAddressSpace, most of the code should be merged.
13175// But merging it created failing cased on gateway test that cannot be
13176// reproduced locally. So should open a separated PR to handle the merge of
13177// AANoAliasAddrSpace and AAAddressSpace attribute
13178
13179namespace {
13180struct AANoAliasAddrSpaceImpl : public AANoAliasAddrSpace {
13181 AANoAliasAddrSpaceImpl(const IRPosition &IRP, Attributor &A)
13182 : AANoAliasAddrSpace(IRP, A) {}
13183
13184 void initialize(Attributor &A) override {
13185 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
13186 "Associated value is not a pointer");
13187
13188 resetASRanges(A);
13189
13190 std::optional<unsigned> FlatAS = A.getInfoCache().getFlatAddressSpace();
13191 if (!FlatAS.has_value()) {
13192 indicatePessimisticFixpoint();
13193 return;
13194 }
13195
13196 removeAS(*FlatAS);
13197
13198 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13199 if (AS != *FlatAS) {
13200 removeAS(AS);
13201 indicateOptimisticFixpoint();
13202 }
13203 }
13204
13205 ChangeStatus updateImpl(Attributor &A) override {
13206 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13207 uint32_t OldAssumed = getAssumed();
13208
13209 auto CheckAddressSpace = [&](Value &Obj) {
13210 if (isa<PoisonValue>(&Obj))
13211 return true;
13212
13213 unsigned AS = Obj.getType()->getPointerAddressSpace();
13214 if (AS == FlatAS)
13215 return false;
13216
13217 removeAS(Obj.getType()->getPointerAddressSpace());
13218 return true;
13219 };
13220
13221 const AAUnderlyingObjects *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(
13222 getIRPosition(), this, DepClassTy::REQUIRED);
13223 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13224 return indicatePessimisticFixpoint();
13225
13226 return OldAssumed == getAssumed() ? ChangeStatus::UNCHANGED
13227 : ChangeStatus::CHANGED;
13228 }
13229
13230 ChangeStatus manifest(Attributor &A) override {
13231 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13232
13233 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13234 if (AS != FlatAS || Map.empty())
13235 return ChangeStatus::UNCHANGED;
13236
13237 LLVMContext &Ctx = getAssociatedValue().getContext();
13238 MDNode *NoAliasASNode = nullptr;
13239 MDBuilder MDB(Ctx);
13240 // Has to use iterator to get the range info.
13241 for (RangeMap::const_iterator I = Map.begin(); I != Map.end(); I++) {
13242 if (!I.value())
13243 continue;
13244 unsigned Upper = I.stop();
13245 unsigned Lower = I.start();
13246 if (!NoAliasASNode) {
13247 NoAliasASNode = MDB.createRange(APInt(32, Lower), APInt(32, Upper + 1));
13248 continue;
13249 }
13250 MDNode *ASRange = MDB.createRange(APInt(32, Lower), APInt(32, Upper + 1));
13251 NoAliasASNode = MDNode::getMostGenericRange(NoAliasASNode, ASRange);
13252 }
13253
13254 Value *AssociatedValue = &getAssociatedValue();
13255 bool Changed = false;
13256
13257 auto AddNoAliasAttr = [&](const Use &U, bool &) {
13258 if (U.get() != AssociatedValue)
13259 return true;
13260 Instruction *Inst = dyn_cast<Instruction>(U.getUser());
13261 if (!Inst || Inst->hasMetadata(LLVMContext::MD_noalias_addrspace))
13262 return true;
13263 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst) &&
13265 return true;
13266 if (!A.isRunOn(Inst->getFunction()))
13267 return true;
13268 Inst->setMetadata(LLVMContext::MD_noalias_addrspace, NoAliasASNode);
13269 Changed = true;
13270 return true;
13271 };
13272 (void)A.checkForAllUses(AddNoAliasAttr, *this, *AssociatedValue,
13273 /*CheckBBLivenessOnly=*/true);
13274 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13275 }
13276
13277 const std::string getAsStr(Attributor *A) const override {
13278 if (!isValidState())
13279 return "<invalid>";
13280 std::string Str;
13281 raw_string_ostream OS(Str);
13282 OS << "CanNotBeAddrSpace(";
13283 for (RangeMap::const_iterator I = Map.begin(); I != Map.end(); I++) {
13284 unsigned Upper = I.stop();
13285 unsigned Lower = I.start();
13286 OS << ' ' << '[' << Upper << ',' << Lower + 1 << ')';
13287 }
13288 OS << " )";
13289 return OS.str();
13290 }
13291
13292private:
13293 void removeAS(unsigned AS) {
13294 RangeMap::iterator I = Map.find(AS);
13295
13296 if (I != Map.end()) {
13297 unsigned Upper = I.stop();
13298 unsigned Lower = I.start();
13299 I.erase();
13300 if (Upper == Lower)
13301 return;
13302 if (AS != ~((unsigned)0) && AS + 1 <= Upper)
13303 Map.insert(AS + 1, Upper, /*what ever this variable name is=*/true);
13304 if (AS != 0 && Lower <= AS - 1)
13305 Map.insert(Lower, AS - 1, true);
13306 }
13307 }
13308
13309 void resetASRanges(Attributor &A) {
13310 Map.clear();
13311 Map.insert(0, A.getInfoCache().getMaxAddrSpace(), true);
13312 }
13313};
13314
13315struct AANoAliasAddrSpaceFloating final : AANoAliasAddrSpaceImpl {
13316 AANoAliasAddrSpaceFloating(const IRPosition &IRP, Attributor &A)
13317 : AANoAliasAddrSpaceImpl(IRP, A) {}
13318
13319 void trackStatistics() const override {
13320 STATS_DECLTRACK_FLOATING_ATTR(noaliasaddrspace);
13321 }
13322};
13323
13324struct AANoAliasAddrSpaceReturned final : AANoAliasAddrSpaceImpl {
13325 AANoAliasAddrSpaceReturned(const IRPosition &IRP, Attributor &A)
13326 : AANoAliasAddrSpaceImpl(IRP, A) {}
13327
13328 void trackStatistics() const override {
13329 STATS_DECLTRACK_FNRET_ATTR(noaliasaddrspace);
13330 }
13331};
13332
13333struct AANoAliasAddrSpaceCallSiteReturned final : AANoAliasAddrSpaceImpl {
13334 AANoAliasAddrSpaceCallSiteReturned(const IRPosition &IRP, Attributor &A)
13335 : AANoAliasAddrSpaceImpl(IRP, A) {}
13336
13337 void trackStatistics() const override {
13338 STATS_DECLTRACK_CSRET_ATTR(noaliasaddrspace);
13339 }
13340};
13341
13342struct AANoAliasAddrSpaceArgument final : AANoAliasAddrSpaceImpl {
13343 AANoAliasAddrSpaceArgument(const IRPosition &IRP, Attributor &A)
13344 : AANoAliasAddrSpaceImpl(IRP, A) {}
13345
13346 void trackStatistics() const override {
13347 STATS_DECLTRACK_ARG_ATTR(noaliasaddrspace);
13348 }
13349};
13350
13351struct AANoAliasAddrSpaceCallSiteArgument final : AANoAliasAddrSpaceImpl {
13352 AANoAliasAddrSpaceCallSiteArgument(const IRPosition &IRP, Attributor &A)
13353 : AANoAliasAddrSpaceImpl(IRP, A) {}
13354
13355 void trackStatistics() const override {
13356 STATS_DECLTRACK_CSARG_ATTR(noaliasaddrspace);
13357 }
13358};
13359} // namespace
13360/// ----------- Allocation Info ----------
13361namespace {
13362struct AAAllocationInfoImpl : public AAAllocationInfo {
13363 AAAllocationInfoImpl(const IRPosition &IRP, Attributor &A)
13364 : AAAllocationInfo(IRP, A) {}
13365
13366 std::optional<TypeSize> getAllocatedSize() const override {
13367 assert(isValidState() && "the AA is invalid");
13368 return AssumedAllocatedSize;
13369 }
13370
13371 std::optional<TypeSize> findInitialAllocationSize(Instruction *I,
13372 const DataLayout &DL) {
13373
13374 // TODO: implement case for malloc like instructions
13375 switch (I->getOpcode()) {
13376 case Instruction::Alloca: {
13377 AllocaInst *AI = cast<AllocaInst>(I);
13378 return AI->getAllocationSize(DL);
13379 }
13380 default:
13381 return std::nullopt;
13382 }
13383 }
13384
13385 ChangeStatus updateImpl(Attributor &A) override {
13386
13387 const IRPosition &IRP = getIRPosition();
13388 Instruction *I = IRP.getCtxI();
13389
13390 // TODO: update check for malloc like calls
13391 if (!isa<AllocaInst>(I))
13392 return indicatePessimisticFixpoint();
13393
13394 bool IsKnownNoCapture;
13396 A, this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture))
13397 return indicatePessimisticFixpoint();
13398
13399 const AAPointerInfo *PI =
13400 A.getOrCreateAAFor<AAPointerInfo>(IRP, *this, DepClassTy::REQUIRED);
13401
13402 if (!PI)
13403 return indicatePessimisticFixpoint();
13404
13405 if (!PI->getState().isValidState() || PI->reachesReturn())
13406 return indicatePessimisticFixpoint();
13407
13408 const DataLayout &DL = A.getDataLayout();
13409 const auto AllocationSize = findInitialAllocationSize(I, DL);
13410
13411 // If allocation size is nullopt, we give up.
13412 if (!AllocationSize)
13413 return indicatePessimisticFixpoint();
13414
13415 // For zero sized allocations, we give up.
13416 // Since we can't reduce further
13417 if (*AllocationSize == 0)
13418 return indicatePessimisticFixpoint();
13419
13420 int64_t BinSize = PI->numOffsetBins();
13421
13422 // TODO: implement for multiple bins
13423 if (BinSize > 1)
13424 return indicatePessimisticFixpoint();
13425
13426 if (BinSize == 0) {
13427 auto NewAllocationSize = std::make_optional<TypeSize>(0, false);
13428 if (!changeAllocationSize(NewAllocationSize))
13429 return ChangeStatus::UNCHANGED;
13430 return ChangeStatus::CHANGED;
13431 }
13432
13433 // TODO: refactor this to be part of multiple bin case
13434 const auto &It = PI->begin();
13435
13436 // TODO: handle if Offset is not zero
13437 if (It->first.Offset != 0)
13438 return indicatePessimisticFixpoint();
13439
13440 uint64_t SizeOfBin = It->first.Offset + It->first.Size;
13441
13442 if (SizeOfBin >= *AllocationSize)
13443 return indicatePessimisticFixpoint();
13444
13445 auto NewAllocationSize = std::make_optional<TypeSize>(SizeOfBin * 8, false);
13446
13447 if (!changeAllocationSize(NewAllocationSize))
13448 return ChangeStatus::UNCHANGED;
13449
13450 return ChangeStatus::CHANGED;
13451 }
13452
13453 ChangeStatus manifest(Attributor &A) override {
13454
13455 assert(isValidState() &&
13456 "Manifest should only be called if the state is valid.");
13457
13458 Instruction *I = getIRPosition().getCtxI();
13459
13460 auto FixedAllocatedSizeInBits = getAllocatedSize()->getFixedValue();
13461
13462 unsigned long NumBytesToAllocate = (FixedAllocatedSizeInBits + 7) / 8;
13463
13464 switch (I->getOpcode()) {
13465 // TODO: add case for malloc like calls
13466 case Instruction::Alloca: {
13467
13468 AllocaInst *AI = cast<AllocaInst>(I);
13469
13470 Type *CharType = Type::getInt8Ty(I->getContext());
13471
13472 auto *NumBytesToValue =
13473 ConstantInt::get(I->getContext(), APInt(32, NumBytesToAllocate));
13474
13475 BasicBlock::iterator insertPt = AI->getIterator();
13476 insertPt = std::next(insertPt);
13477 AllocaInst *NewAllocaInst =
13478 new AllocaInst(CharType, AI->getAddressSpace(), NumBytesToValue,
13479 AI->getAlign(), AI->getName(), insertPt);
13480
13481 if (A.changeAfterManifest(IRPosition::inst(*AI), *NewAllocaInst))
13482 return ChangeStatus::CHANGED;
13483
13484 break;
13485 }
13486 default:
13487 break;
13488 }
13489
13490 return ChangeStatus::UNCHANGED;
13491 }
13492
13493 const std::string getAsStr(Attributor *A) const override {
13494 if (!isValidState())
13495 return "allocationinfo(<invalid>)";
13496 return "allocationinfo(" +
13497 (AssumedAllocatedSize == HasNoAllocationSize
13498 ? "none"
13499 : std::to_string(AssumedAllocatedSize->getFixedValue())) +
13500 ")";
13501 }
13502
13503private:
13504 std::optional<TypeSize> AssumedAllocatedSize = HasNoAllocationSize;
13505
13506 // Maintain the computed allocation size of the object.
13507 // Returns (bool) weather the size of the allocation was modified or not.
13508 bool changeAllocationSize(std::optional<TypeSize> Size) {
13509 if (AssumedAllocatedSize == HasNoAllocationSize ||
13510 AssumedAllocatedSize != Size) {
13511 AssumedAllocatedSize = Size;
13512 return true;
13513 }
13514 return false;
13515 }
13516};
13517
13518struct AAAllocationInfoFloating : AAAllocationInfoImpl {
13519 AAAllocationInfoFloating(const IRPosition &IRP, Attributor &A)
13520 : AAAllocationInfoImpl(IRP, A) {}
13521
13522 void trackStatistics() const override {
13523 STATS_DECLTRACK_FLOATING_ATTR(allocationinfo);
13524 }
13525};
13526
13527struct AAAllocationInfoReturned : AAAllocationInfoImpl {
13528 AAAllocationInfoReturned(const IRPosition &IRP, Attributor &A)
13529 : AAAllocationInfoImpl(IRP, A) {}
13530
13531 void initialize(Attributor &A) override {
13532 // TODO: we don't rewrite function argument for now because it will need to
13533 // rewrite the function signature and all call sites
13534 (void)indicatePessimisticFixpoint();
13535 }
13536
13537 void trackStatistics() const override {
13538 STATS_DECLTRACK_FNRET_ATTR(allocationinfo);
13539 }
13540};
13541
13542struct AAAllocationInfoCallSiteReturned : AAAllocationInfoImpl {
13543 AAAllocationInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
13544 : AAAllocationInfoImpl(IRP, A) {}
13545
13546 void trackStatistics() const override {
13547 STATS_DECLTRACK_CSRET_ATTR(allocationinfo);
13548 }
13549};
13550
13551struct AAAllocationInfoArgument : AAAllocationInfoImpl {
13552 AAAllocationInfoArgument(const IRPosition &IRP, Attributor &A)
13553 : AAAllocationInfoImpl(IRP, A) {}
13554
13555 void trackStatistics() const override {
13556 STATS_DECLTRACK_ARG_ATTR(allocationinfo);
13557 }
13558};
13559
13560struct AAAllocationInfoCallSiteArgument : AAAllocationInfoImpl {
13561 AAAllocationInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
13562 : AAAllocationInfoImpl(IRP, A) {}
13563
13564 void initialize(Attributor &A) override {
13565
13566 (void)indicatePessimisticFixpoint();
13567 }
13568
13569 void trackStatistics() const override {
13570 STATS_DECLTRACK_CSARG_ATTR(allocationinfo);
13571 }
13572};
13573} // namespace
13574
13575const char AANoUnwind::ID = 0;
13576const char AANoSync::ID = 0;
13577const char AANoFree::ID = 0;
13578const char AANonNull::ID = 0;
13579const char AAMustProgress::ID = 0;
13580const char AANoRecurse::ID = 0;
13581const char AANonConvergent::ID = 0;
13582const char AAWillReturn::ID = 0;
13583const char AAUndefinedBehavior::ID = 0;
13584const char AANoAlias::ID = 0;
13585const char AAIntraFnReachability::ID = 0;
13586const char AANoReturn::ID = 0;
13587const char AAIsDead::ID = 0;
13588const char AADereferenceable::ID = 0;
13589const char AAAlign::ID = 0;
13590const char AAInstanceInfo::ID = 0;
13591const char AANoCapture::ID = 0;
13592const char AAValueSimplify::ID = 0;
13593const char AAHeapToStack::ID = 0;
13594const char AAPrivatizablePtr::ID = 0;
13595const char AAMemoryBehavior::ID = 0;
13596const char AAMemoryLocation::ID = 0;
13597const char AAValueConstantRange::ID = 0;
13598const char AAPotentialConstantValues::ID = 0;
13599const char AAPotentialValues::ID = 0;
13600const char AANoUndef::ID = 0;
13601const char AANoFPClass::ID = 0;
13602const char AACallEdges::ID = 0;
13603const char AAInterFnReachability::ID = 0;
13604const char AAPointerInfo::ID = 0;
13605const char AAAssumptionInfo::ID = 0;
13606const char AAUnderlyingObjects::ID = 0;
13607const char AAInvariantLoadPointer::ID = 0;
13608const char AAAddressSpace::ID = 0;
13609const char AANoAliasAddrSpace::ID = 0;
13610const char AAAllocationInfo::ID = 0;
13611const char AAIndirectCallInfo::ID = 0;
13612const char AAGlobalValueInfo::ID = 0;
13613const char AADenormalFPMath::ID = 0;
13614
13615// Macro magic to create the static generator function for attributes that
13616// follow the naming scheme.
13617
13618#define SWITCH_PK_INV(CLASS, PK, POS_NAME) \
13619 case IRPosition::PK: \
13620 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
13621
13622#define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \
13623 case IRPosition::PK: \
13624 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \
13625 ++NumAAs; \
13626 break;
13627
13628#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13629 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13630 CLASS *AA = nullptr; \
13631 switch (IRP.getPositionKind()) { \
13632 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13633 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13634 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13635 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13636 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13637 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13638 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13639 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13640 } \
13641 return *AA; \
13642 }
13643
13644#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13645 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13646 CLASS *AA = nullptr; \
13647 switch (IRP.getPositionKind()) { \
13648 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13649 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \
13650 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13651 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13652 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13653 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13654 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13655 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13656 } \
13657 return *AA; \
13658 }
13659
13660#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS) \
13661 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13662 CLASS *AA = nullptr; \
13663 switch (IRP.getPositionKind()) { \
13664 SWITCH_PK_CREATE(CLASS, IRP, POS, SUFFIX) \
13665 default: \
13666 llvm_unreachable("Cannot create " #CLASS " for position otherthan " #POS \
13667 " position!"); \
13668 } \
13669 return *AA; \
13670 }
13671
13672#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13673 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13674 CLASS *AA = nullptr; \
13675 switch (IRP.getPositionKind()) { \
13676 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13677 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13678 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13679 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13680 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13681 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13682 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13683 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13684 } \
13685 return *AA; \
13686 }
13687
13688#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13689 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13690 CLASS *AA = nullptr; \
13691 switch (IRP.getPositionKind()) { \
13692 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13693 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13694 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13695 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13696 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13697 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13698 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13699 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13700 } \
13701 return *AA; \
13702 }
13703
13704#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13705 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13706 CLASS *AA = nullptr; \
13707 switch (IRP.getPositionKind()) { \
13708 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13709 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13710 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13711 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13712 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13713 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13714 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13715 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13716 } \
13717 return *AA; \
13718 }
13719
13729
13747
13752
13757
13764
13766
13767#undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
13768#undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
13769#undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
13770#undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
13771#undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
13772#undef CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION
13773#undef SWITCH_PK_CREATE
13774#undef SWITCH_PK_INV
#define Success
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
#define STATS_DECLTRACK(NAME, TYPE, MSG)
static std::optional< Constant * > askForAssumedConstant(Attributor &A, const AbstractAttribute &QueryingAA, const IRPosition &IRP, Type &Ty)
static bool collectTailCalls(Attributor &A, const AbstractAttribute &QueryingAA, SmallVectorImpl< CallInst * > &TailCalls)
Collect the non-musttail tail calls in the function of QueryingAA.
static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA, StateType &S, const IRPosition::CallBaseContext *CBContext=nullptr)
Clamp the information known for all returned values of a function (identified by QueryingAA) into S.
#define STATS_DECLTRACK_FN_ATTR(NAME)
#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define STATS_DECLTRACK_CS_ATTR(NAME)
#define PIPE_OPERATOR(CLASS)
#define STATS_DECLTRACK_ARG_ATTR(NAME)
static const Value * stripAndAccumulateOffsets(Attributor &A, const AbstractAttribute &QueryingAA, const Value *Val, const DataLayout &DL, APInt &Offset, bool GetMinOffset, bool AllowNonInbounds, bool UseAssumed=false)
#define STATS_DECLTRACK_CSRET_ATTR(NAME)
static Value * constructPointer(Value *Ptr, int64_t Offset, IRBuilder< NoFolder > &IRB)
Helper function to create a pointer based on Ptr, and advanced by Offset bytes.
#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define BUILD_STAT_NAME(NAME, TYPE)
static bool isDenselyPacked(Type *Ty, const DataLayout &DL)
Checks if a type could have padding bytes.
#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
static const Value * getMinimalBaseOfPointer(Attributor &A, const AbstractAttribute &QueryingAA, const Value *Ptr, int64_t &BytesOffset, const DataLayout &DL, bool AllowNonInbounds=false)
static bool mayBeInCycle(const CycleInfo *CI, const Instruction *I, bool HeaderOnly, CycleRef *CPtr=nullptr)
#define STATS_DECLTRACK_FNRET_ATTR(NAME)
#define STATS_DECLTRACK_CSARG_ATTR(NAME)
#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS)
#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define STATS_DECLTRACK_FLOATING_ATTR(NAME)
#define STATS_DECL(NAME, TYPE, MSG)
bpf unwind BPF Unwind Lower
basic Basic Alias true
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isReachableImpl(SmallVectorImpl< BasicBlock * > &Worklist, const StopSetT &StopSet, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT, const LoopInfo *LI, const CycleInfo *CI)
Definition CFG.cpp:145
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
static uint64_t align(uint64_t Size)
DXIL Forward Handle Accesses
DXIL Resource Access
dxil translate DXIL Translate Metadata
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
#define Check(C,...)
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
#define T
#define T1
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
RISCVCC::CondCode CC
Basic Register Allocator
dot regions Print regions of function to dot true view regions View regions of function(with no function bodies)"
Remove Loads Into Fake Uses
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
bool IsDead
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
static unsigned getSize(unsigned Kind)
LLVM_ABI AACallGraphNode * operator*() const
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are no-alias.
Class for arbitrary precision integers.
Definition APInt.h:78
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
CallBase * getInstruction() const
Return the underlying instruction.
bool isCallbackCall() const
Return true if this ACS represents a callback call.
bool isDirectCall() const
Return true if this ACS represents a direct call.
static LLVM_ABI void getCallbackUses(const CallBase &CB, SmallVectorImpl< const Use * > &CallbackUses)
Add operand uses of CB that represent callback uses into CallbackUses.
int getCallArgOperandNo(Argument &Arg) const
Return the operand index of the underlying instruction associated with Arg.
This class represents a conversion between pointers from one address space to another.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
Definition Function.cpp:266
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Definition Function.cpp:302
LLVM_ABI bool hasPointeeInMemoryValueAttr() const
Return true if this argument has the byval, sret, inalloca, preallocated, or byref attribute.
Definition Function.cpp:169
LLVM_ABI bool hasReturnedAttr() const
Return true if this argument has the returned attribute.
Definition Function.cpp:290
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:126
const Function * getParent() const
Definition Argument.h:44
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI FPClassTest getNoFPClass() const
Return the FPClassTest for nofpclass.
LLVM_ABI Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
LLVM_ABI MemoryEffects getMemoryEffects() const
Returns memory effects.
static LLVM_ABI Attribute getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
static bool isEnumAttrKind(AttrKind Kind)
Definition Attributes.h:140
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
LLVM_ABI MaybeAlign getAlignment() const
Returns the alignment field of an attribute as a byte alignment value.
LLVM_ABI CaptureInfo getCaptureInfo() const
Returns information from captures attribute.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI MemoryEffects getMemoryEffects() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
Value * getCalledOperand() const
const Use & getCalledOperandUse() const
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
const Use & getArgOperandUse(unsigned i) const
Wrappers for getting the Use of a call argument.
LLVM_ABI bool isVolatile() const
Return true if this is a call to an intrinsic with a volatile flag that is set, e....
OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const
Return the operand bundle for the operand at index OpIdx.
LLVM_ABI std::optional< ConstantRange > getRange() const
If this return value has a range attribute, return the value range of the argument.
Value * getArgOperand(unsigned i) const
bool isBundleOperand(unsigned Idx) const
Return true if the operand at index Idx is a bundle operand.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
unsigned arg_size() const
bool isArgOperand(const Use *U) const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
LLVM_ABI bool isIntegerCast() const
There are several places where we need to know if a cast instruction only deals with integer source a...
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_NE
not equal
Definition InstrTypes.h:762
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
bool isSingleElement() const
Return true if this set contains exactly one member.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned getProgramAddressSpace() const
Definition DataLayout.h:272
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
Definition Function.h:803
Argument * arg_iterator
Definition Function.h:73
iterator_range< arg_iterator > args()
Definition Function.h:886
const Function & getFunction() const
Definition Function.h:167
size_t arg_size() const
Definition Function.h:895
Argument * getArg(unsigned i) const
Definition Function.h:880
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
BlockT * getHeader(CycleRef C) const
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
bool hasLocalLinkage() const
PointerType * getType() const
Global values are always pointers.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Value * CreatePtrAddWithSignedOffset(Value *Ptr, int64_t Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd with a signed constant offset.
Definition IRBuilder.h:2123
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool mayReadOrWriteMemory() const LLVM_READONLY
Return true if this instruction may read or write memory.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI ConstantRange getConstantRange(Value *V, Instruction *CtxI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool empty() const
Definition MapVector.h:80
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
Definition ModRef.h:265
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
Definition ModRef.h:219
bool onlyAccessesArgPointees() const
Whether this function only (at most) accesses argument memory.
Definition ModRef.h:255
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
bool onlyAccessesInaccessibleOrArgMem() const
Whether this function only (at most) accesses argument and inaccessible memory.
Definition ModRef.h:305
static MemoryEffectsBase unknown()
Definition ModRef.h:123
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static SizeOffsetValue unknown()
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Class to represent pointers.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:746
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:777
TypeSize getSizeInBits() const
Definition DataLayout.h:757
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition DataLayout.h:782
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Analysis pass providing the TargetTransformInfo.
LLVM_ABI bool areTypesABICompatible(const Function *Caller, const Function *Callee, ArrayRef< Type * > Types) const
LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * get() const
Definition Use.h:55
const Use & getOperandUse(unsigned i) const
Definition User.h:220
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition User.cpp:113
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
bool use_empty() const
Definition Value.h:348
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition Value.h:800
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI bool isAssumedReadNone(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readnone.
LLVM_ABI bool isAssumedReadOnly(Attributor &A, const IRPosition &IRP, const AbstractAttribute &QueryingAA, bool &IsKnown)
Return true if IRP is readonly.
raw_ostream & operator<<(raw_ostream &OS, const RangeTy &R)
Definition Attributor.h:328
LLVM_ABI std::optional< Value * > combineOptionalValuesInAAValueLatice(const std::optional< Value * > &A, const std::optional< Value * > &B, Type *Ty)
Return the combination of A and B such that the result is a possible value of both.
LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC, InformationCache &InfoCache)
Return true if the value of VAC is a valid at the position of VAC, that is a constant,...
LLVM_ABI bool isAssumedThreadLocalObject(Attributor &A, Value &Obj, const AbstractAttribute &QueryingAA)
Return true if Obj is assumed to be a thread local object.
LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU constant address space for the target triple...
LLVM_ABI bool isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA, const Value &V, bool ForAnalysisOnly=true)
Return true if V is dynamically unique, that is, there are no two "instances" of V at runtime with di...
LLVM_ABI bool getPotentialCopiesOfStoredValue(Attributor &A, StoreInst &SI, SmallSetVector< Value *, 4 > &PotentialCopies, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values of the one stored by SI into PotentialCopies.
LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU shared address space for the target triple i...
LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU local/private address space for the target t...
SmallPtrSet< Instruction *, 4 > InstExclusionSetTy
Definition Attributor.h:167
LLVM_ABI bool isGPU(const Module &M)
Return true iff M target a GPU (and we can use GPU AS reasoning).
ValueScope
Flags to distinguish intra-procedural queries from potentially inter-procedural queries.
Definition Attributor.h:187
@ Intraprocedural
Definition Attributor.h:188
@ Interprocedural
Definition Attributor.h:189
LLVM_ABI bool isValidInScope(const Value &V, const Function *Scope)
Return true if V is a valid value in Scope, that is a constant or an instruction/argument of Scope.
LLVM_ABI bool isPotentiallyReachable(Attributor &A, const Instruction &FromI, const Instruction &ToI, const AbstractAttribute &QueryingAA, const AA::InstExclusionSetTy *ExclusionSet=nullptr, std::function< bool(const Function &F)> GoBackwardsCB=nullptr)
Return true if ToI is potentially reachable from FromI without running into any instruction in Exclus...
LLVM_ABI bool isNoSyncInst(Attributor &A, const Instruction &I, const AbstractAttribute &QueryingAA)
Return true if I is a nosync instruction.
bool hasAssumedIRAttr(Attributor &A, const AbstractAttribute *QueryingAA, const IRPosition &IRP, DepClassTy DepClass, bool &IsKnown, bool IgnoreSubsumingPositions=false, const AAType **AAPtr=nullptr)
Helper to avoid creating an AA for IR Attributes that might already be set.
LLVM_ABI bool getPotentiallyLoadedValues(Attributor &A, LoadInst &LI, SmallSetVector< Value *, 4 > &PotentialValues, SmallSetVector< Instruction *, 4 > &PotentialValueOrigins, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values LI could read into PotentialValues.
LLVM_ABI Value * getWithType(Value &V, Type &Ty)
Try to convert V to type Ty without introducing new instructions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ Unsupported
This operation is completely unsupported on the target.
Offsets
Offsets in bytes from the start of the input buffer.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:63
@ Valid
The data is already valid.
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
auto pred_end(const MachineBasicBlock *BB)
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:381
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1769
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
LLVM_ABI Value * getAllocAlignment(const CallBase *V, const TargetLibraryInfo *TLI)
Gets the alignment argument for an aligned_alloc-like function, using either built-in knowledge based...
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
PotentialValuesState< std::pair< AA::ValueAndContext, AA::ValueScope > > PotentialLLVMValuesState
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:369
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:415
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CallBase & promoteCall(CallBase &CB, Function *Callee, CastInst **RetBitCast=nullptr)
Promote the given indirect call site to unconditionally call Callee.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool hasAssumption(const Function &F, const KnownAssumptionString &AssumptionStr)
Return true if F has the assumption AssumptionStr attached.
@ Success
The lock was released successfully.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Other
Any other memory.
Definition ModRef.h:68
PotentialValuesState< APInt > PotentialConstantIntValuesState
TargetTransformInfo TTI
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
InterleavedRange< Range > interleaved_array(const Range &R, StringRef Separator=", ")
Output range R as an array of interleaved elements.
ChangeStatus clampStateAndIndicateChange< DerefState >(DerefState &S, const DerefState &R)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R)
Helper function to clamp a state S of type StateType with the information in R and indicate/return if...
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
ChangeStatus
{
Definition Attributor.h:474
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
LLVM_ABI DenseSet< StringRef > getAssumptions(const Function &F)
Return the set of all assumptions for the function F.
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
Definition Alignment.h:105
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
@ OPTIONAL
The target may be valid if the source is not.
Definition Attributor.h:486
@ NONE
Do not track a dependence between source and target.
Definition Attributor.h:487
@ REQUIRED
The target cannot be valid if the source is not.
Definition Attributor.h:485
LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U, const Value *Base)
Determine what kind of capture behaviour U may exhibit.
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
LLVM_ABI bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
Definition ModRef.h:400
constexpr StringRef AssumptionAttrKey
The key we use for assumption attributes.
Definition Assumptions.h:29
constexpr bool isCallableCC(CallingConv::ID CC)
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
A type to track pointer/struct usage and accesses for AAPointerInfo.
bool forallInterferingAccesses(AA::RangeTy Range, F CB) const
See AAPointerInfo::forallInterferingAccesses.
AAPointerInfo::const_bin_iterator end() const
ChangeStatus addAccess(Attributor &A, const AAPointerInfo::RangeList &Ranges, Instruction &I, std::optional< Value * > Content, AAPointerInfo::AccessKind Kind, Type *Ty, Instruction *RemoteI=nullptr)
Add a new Access to the state at offset Offset and with size Size.
DenseMap< const Instruction *, SmallVector< unsigned > > RemoteIMap
AAPointerInfo::const_bin_iterator begin() const
AAPointerInfo::OffsetInfo ReturnedOffsets
Flag to determine if the underlying pointer is reaching a return statement in the associated function...
State(State &&SIS)=default
const AAPointerInfo::Access & getAccess(unsigned Index) const
SmallVector< AAPointerInfo::Access > AccessList
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
bool forallInterferingAccesses(Instruction &I, F CB, AA::RangeTy &Range) const
See AAPointerInfo::forallInterferingAccesses.
static State getWorstState(const State &SIS)
Return the worst possible representable state.
AAPointerInfo::OffsetBinsTy OffsetBins
ChangeStatus indicateOptimisticFixpoint() override
Indicate that the abstract state should converge to the optimistic state.
ChangeStatus indicatePessimisticFixpoint() override
Indicate that the abstract state should converge to the pessimistic state.
static State getBestState(const State &SIS)
Return the best possible representable state.
bool isValidState() const override
Return if this abstract state is in a valid state.
----------------—AAIntraFnReachability Attribute-----------------------—
ReachabilityQueryInfo(const ReachabilityQueryInfo &RQI)
unsigned Hash
Precomputed hash for this RQI.
const Instruction * From
Start here,.
Reachable Result
and remember if it worked:
ReachabilityQueryInfo(const Instruction *From, const ToTy *To)
ReachabilityQueryInfo(Attributor &A, const Instruction &From, const ToTy &To, const AA::InstExclusionSetTy *ES, bool MakeUnique)
Constructor replacement to ensure unique and stable sets are used for the cache.
const ToTy * To
reach this place,
const AA::InstExclusionSetTy * ExclusionSet
without going through any of these instructions,
An abstract interface for address space information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all align attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
Align getKnownAlign() const
Return known alignment.
static LLVM_ABI const char ID
An abstract attribute for getting assumption information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract state for querying live call edges.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for specializing "dynamic" components of denormal_fpenv to a known denormal mod...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all dereferenceable attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for llvm::GlobalValue information interference.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for indirect call information interference.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface to track if a value leaves it's defining function instance.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for computing reachability between functions.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool canReach(Attributor &A, const Function &Fn) const
If the function represented by this possition can reach Fn.
virtual bool instructionCanReach(Attributor &A, const Instruction &Inst, const Function &Fn, const AA::InstExclusionSetTy *ExclusionSet=nullptr) const =0
Can Inst reach Fn.
An abstract interface to determine reachability of point A to B.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for identifying pointers from which loads can be marked invariant.
static LLVM_ABI const char ID
Unique ID (due to the unique address).
An abstract interface for liveness abstract attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for memory access kind related attributes (readnone/readonly/writeonly).
bool isAssumedReadOnly() const
Return true if we assume that the underlying value is not accessed (=written) in its respective scope...
bool isKnownReadNone() const
Return true if we know that the underlying value is not read or accessed in its respective scope.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedReadNone() const
Return true if we assume that the underlying value is not read or accessed in its respective scope.
An abstract interface for all memory location attributes (readnone/argmemonly/inaccessiblememonly/ina...
static LLVM_ABI std::string getMemoryLocationsAsStr(MemoryLocationsKind MLK)
Return the locations encoded by MLK as a readable string.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StateType::base_t MemoryLocationsKind
An abstract interface for all nonnull attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for potential address space information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all noalias attributes.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoAlias Argument Attribute ---------------------—
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all nocapture attributes.
@ NO_CAPTURE_MAYBE_RETURNED
If we do not capture the value in memory or through integers we can only communicate it back as a der...
@ NO_CAPTURE
If we do not capture the value in memory, through integers, or as a derived pointer we know it is not...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedNoCaptureMaybeReturned() const
Return true if we assume that the underlying value is not captured in its respective scope but we all...
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
--------------------— Variable Capturing ------------------------------—
static LLVM_ABI void determineFunctionCaptureCapabilities(const IRPosition &IRP, const Function &F, BitIntegerState &State)
Update State according to the capture capabilities of F for position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An AbstractAttribute for nofree.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for norecurse.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An AbstractAttribute for noreturn.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isAlignedBarrier(const CallBase &CB, bool ExecutedAligned)
Helper function to determine if CB is an aligned (GPU) barrier.
static LLVM_ABI bool isNonRelaxedAtomic(const Instruction *I)
Helper function used to determine whether an instruction is non-relaxed atomic.
An abstract interface for all noundef attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoUndef Attribute ------------------------------—
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for determining the necessity of the convergent attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all nonnull attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NonNull Argument Attribute ---------------------—
An access description.
A helper containing a list of offsets computed for a Use.
A container for a list of ranges.
static void set_difference(const RangeList &L, const RangeList &R, RangeList &D)
Copy ranges from L that are not in R, into D.
An abstract interface for struct information.
virtual bool reachesReturn() const =0
OffsetBinsTy::const_iterator const_bin_iterator
virtual const_bin_iterator begin() const =0
DenseMap< AA::RangeTy, SmallSet< unsigned, 4 > > OffsetBinsTy
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual int64_t numOffsetBins() const =0
An abstract interface for potential values analysis.
StateWrapper< PotentialConstantIntValuesState, AbstractAttribute, bool, unsigned > Base
static LLVM_ABI const char ID
Unique ID (due to the unique address)
LLVM_ABI AAPotentialConstantValues(const IRPosition &IRP, Attributor &A)
---------------— Potential Values Attribute ----------------------—
friend struct Attributor
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI Value * getSingleValue(Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP, SmallVectorImpl< AA::ValueAndContext > &Values)
Extract the single value in Values if any.
An abstract interface for privatizability.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for undefined behavior.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for getting all assumption underlying objects.
virtual bool forallUnderlyingObjects(function_ref< bool(Value &)> Pred, AA::ValueScope Scope=AA::Interprocedural) const =0
Check Pred on all underlying objects in Scope collected so far.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for range value analysis.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for value simplify abstract attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for willreturn.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
Helper to represent an access offset and size, with logic to deal with uncertainty and check for over...
Definition Attributor.h:246
static constexpr int64_t Unknown
Definition Attributor.h:325
static RangeTy getUnknown()
Definition Attributor.h:252
Value * getValue() const
Definition Attributor.h:199
const Instruction * getCtxI() const
Definition Attributor.h:200
Base struct for all "concrete attribute" deductions.
void print(raw_ostream &OS) const
Helper functions, for debug purposes only.
virtual StateType & getState()=0
Return the internal abstract state for inspection.
virtual void initialize(Attributor &A)
Initialize the state with the information in the Attributor A.
AbstractState StateType
An interface to query the internal state of an abstract attribute.
virtual bool isAtFixpoint() const =0
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
virtual bool isValidState() const =0
Return if this abstract state is in a valid state.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
std::function< void( const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
const Argument & getReplacedArg() const
std::function< void(const ArgumentReplacementInfo &, AbstractCallSite, SmallVectorImpl< Value * > &)> ACSRepairCBTy
Abstract call site (ACS) repair callback type.
The fixpoint analysis framework that orchestrates the attribute deduction.
std::function< std::optional< Value * >( const IRPosition &, const AbstractAttribute *, bool &)> SimplifictionCallbackTy
Register CB as a simplification callback.
Specialization of the integer state for a bit-wise encoding.
BitIntegerState & addKnownBits(base_t Bits)
Add the bits in BitsEncoding to the "known bits".
Simple wrapper for a single bit (boolean) state.
static constexpr DenormalFPEnv getDefault()
static unsigned getHashValue(const Access &A)
static bool isEqual(const Access &LHS, const Access &RHS)
static bool isEqual(const AA::RangeTy &A, const AA::RangeTy B)
static unsigned getHashValue(const AA::RangeTy &Range)
DenseMapInfo< std::pair< const Instruction *, const ToTy * > > PairDMI
static bool isEqual(const ReachabilityQueryInfo< ToTy > *LHS, const ReachabilityQueryInfo< ToTy > *RHS)
DenseMapInfo< const AA::InstExclusionSetTy * > InstSetDMI
static unsigned getHashValue(const ReachabilityQueryInfo< ToTy > *RQI)
An information struct used to provide DenseMap with the various necessary components for a given valu...
State for dereferenceable attribute.
IncIntegerState DerefBytesState
State representing for dereferenceable bytes.
ChangeStatus manifest(Attributor &A) override
Helper to describe and deal with positions in the LLVM-IR.
Definition Attributor.h:570
Function * getAssociatedFunction() const
Return the associated function, if any.
Definition Attributor.h:701
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
Definition Attributor.h:638
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
Definition Attributor.h:620
LLVM_ABI Argument * getAssociatedArgument() const
Return the associated argument, if any.
static const IRPosition value(const Value &V, const CallBaseContext *CBContext=nullptr)
Create a position describing the value of V.
Definition Attributor.h:594
CallBase CallBaseContext
Definition Attributor.h:573
int getCalleeArgNo() const
Return the callee argument number of the associated value if it is an argument or call site argument,...
Definition Attributor.h:787
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
Definition Attributor.h:606
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Definition Attributor.h:643
Kind
The positions we distinguish in the IR.
Definition Attributor.h:576
@ IRP_ARGUMENT
An attribute for a function argument.
Definition Attributor.h:584
@ IRP_RETURNED
An attribute for the function return value.
Definition Attributor.h:580
@ IRP_CALL_SITE
An attribute for a call site (function scope).
Definition Attributor.h:583
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
Definition Attributor.h:581
@ IRP_FUNCTION
An attribute for a function (scope).
Definition Attributor.h:582
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
Definition Attributor.h:585
@ IRP_INVALID
An invalid position.
Definition Attributor.h:577
Instruction * getCtxI() const
Return the context instruction, if any.
Definition Attributor.h:754
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
Definition Attributor.h:627
Type * getAssociatedType() const
Return the type this abstract attribute is associated with.
Definition Attributor.h:776
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
Definition Attributor.h:613
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Definition Attributor.h:893
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Definition Attributor.h:768
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
Definition Attributor.h:687
int getCallSiteArgNo() const
Return the call site argument number of the associated value if it is an argument or call site argume...
Definition Attributor.h:796
static const IRPosition function_scope(const IRPosition &IRP, const CallBaseContext *CBContext=nullptr)
Create a position with function scope matching the "context" of IRP.
Definition Attributor.h:666
Kind getPositionKind() const
Return the associated position kind.
Definition Attributor.h:843
bool isArgumentPosition() const
Return true if the position is an argument or call site argument.
Definition Attributor.h:875
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Definition Attributor.h:633
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
Definition Attributor.h:742
Data structure to hold cached (LLVM-IR) information.
bool isOnlyUsedByAssume(const Instruction &I)
TargetLibraryInfo * getTargetLibraryInfoForFunction(const Function &F)
Return TargetLibraryInfo for function F.
AP::Result * getAnalysisResultForFunction(const Function &F, bool CachedOnly=false)
Return the analysis result from a pass AP for function F.
ConstantRange getKnown() const
Return the known state encoding.
ConstantRange getAssumed() const
Return the assumed state encoding.
base_t getAssumed() const
Return the assumed state encoding.
Helper that allows to insert a new assumption string in the known assumption set by creating a (stati...
Definition Assumptions.h:37
A "must be executed context" for a given program point PP is the set of instructions,...
LLVM_ABI bool checkForAllTerminatorsInContext(const Instruction *PP, function_ref< bool(const Instruction *)> Pred)
Check Pred on all terminators in the context of PP and return true if it holds for all of them.
LLVM_ABI bool isInContextOf(const Instruction *I, const Instruction *PP)
}
Helper to tie a abstract state implementation to an abstract attribute.
StateType & getState() override
CaptureComponents ResultCC
Components captured by the return value of the user of this Use.
LLVM_ABI bool unionAssumed(std::optional< Value * > Other)
Merge Other into the currently assumed simplified value.
std::optional< Value * > SimplifiedAssociatedValue
An assumed simplified value.
Type * Ty
The type of the original value.