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 (Instruction *CmpUser : CmpI->users()) {
1757 if (auto *IntrI = dyn_cast<IntrinsicInst>(CmpUser)) {
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 if (getFreedOperand(CB) == U)
1832 return true;
1833 if (CB->isArgOperand(&U)) {
1834 unsigned ArgNo = CB->getArgOperandNo(&U);
1835 const auto *CSArgPI = A.getAAFor<AAPointerInfo>(
1836 *this, IRPosition::callsite_argument(*CB, ArgNo),
1838 if (!CSArgPI)
1839 return false;
1840 bool IsArgMustAcc = (getUnderlyingObject(CurPtr) == &AssociatedValue);
1841 Changed = translateAndAddState(A, *CSArgPI, OffsetInfoMap[CurPtr], *CB,
1842 IsArgMustAcc) |
1843 Changed;
1844 if (!CSArgPI->reachesReturn())
1845 return isValidState();
1846
1848 if (!Callee || Callee->arg_size() <= ArgNo)
1849 return false;
1850 bool UsedAssumedInformation = false;
1851 auto ReturnedValue = A.getAssumedSimplified(
1852 IRPosition::returned(*Callee), *this, UsedAssumedInformation,
1854 auto *ReturnedArg =
1855 dyn_cast_or_null<Argument>(ReturnedValue.value_or(nullptr));
1856 auto *Arg = Callee->getArg(ArgNo);
1857 if (ReturnedArg && Arg != ReturnedArg)
1858 return true;
1859 bool IsRetMustAcc = IsArgMustAcc && (ReturnedArg == Arg);
1860 const auto *CSRetPI = A.getAAFor<AAPointerInfo>(
1862 if (!CSRetPI)
1863 return false;
1864 OffsetInfo OI = OffsetInfoMap[CurPtr];
1865 CSArgPI->addReturnedOffsetsTo(OI);
1866 Changed =
1867 translateAndAddState(A, *CSRetPI, OI, *CB, IsRetMustAcc) | Changed;
1868 return isValidState();
1869 }
1870 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Call user not handled " << *CB
1871 << "\n");
1872 return false;
1873 }
1874
1875 LLVM_DEBUG(dbgs() << "[AAPointerInfo] User not handled " << *Usr << "\n");
1876 return false;
1877 };
1878 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
1879 assert(OffsetInfoMap.count(OldU) && "Old use should be known already!");
1880 assert(!OffsetInfoMap[OldU].isUnassigned() && "Old use should be assinged");
1881 if (OffsetInfoMap.count(NewU)) {
1882 LLVM_DEBUG({
1883 if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) {
1884 dbgs() << "[AAPointerInfo] Equivalent use callback failed: "
1885 << OffsetInfoMap[NewU] << " vs " << OffsetInfoMap[OldU]
1886 << "\n";
1887 }
1888 });
1889 return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1890 }
1891 bool Unused;
1892 return HandlePassthroughUser(NewU.get(), OldU.get(), Unused);
1893 };
1894 if (!A.checkForAllUses(UsePred, *this, AssociatedValue,
1895 /* CheckBBLivenessOnly */ true, DepClassTy::OPTIONAL,
1896 /* IgnoreDroppableUses */ true, EquivalentUseCB)) {
1897 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Check for all uses failed, abort!\n");
1898 return indicatePessimisticFixpoint();
1899 }
1900
1901 LLVM_DEBUG({
1902 dbgs() << "Accesses by bin after update:\n";
1903 dumpState(dbgs());
1904 });
1905
1906 return Changed;
1907}
1908
1909struct AAPointerInfoReturned final : AAPointerInfoImpl {
1910 AAPointerInfoReturned(const IRPosition &IRP, Attributor &A)
1911 : AAPointerInfoImpl(IRP, A) {}
1912
1913 ChangeStatus updateImpl(Attributor &A) override {
1914 return indicatePessimisticFixpoint();
1915 }
1916
1917 void trackStatistics() const override {
1918 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1919 }
1920};
1921
1922struct AAPointerInfoArgument final : AAPointerInfoFloating {
1923 AAPointerInfoArgument(const IRPosition &IRP, Attributor &A)
1924 : AAPointerInfoFloating(IRP, A) {}
1925
1926 void trackStatistics() const override {
1927 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1928 }
1929};
1930
1931struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1932 AAPointerInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
1933 : AAPointerInfoFloating(IRP, A) {}
1934
1935 ChangeStatus updateImpl(Attributor &A) override {
1936 using namespace AA::PointerInfo;
1937 // We handle memory intrinsics explicitly, at least the first (=
1938 // destination) and second (=source) arguments as we know how they are
1939 // accessed.
1940 if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) {
1941 int64_t LengthVal = AA::RangeTy::Unknown;
1942 if (auto Length = MI->getLengthInBytes())
1943 LengthVal = Length->getSExtValue();
1944 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1945 ChangeStatus Changed = ChangeStatus::UNCHANGED;
1946 if (ArgNo > 1) {
1947 LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled memory intrinsic "
1948 << *MI << "\n");
1949 return indicatePessimisticFixpoint();
1950 } else {
1951 auto Kind =
1952 ArgNo == 0 ? AccessKind::AK_MUST_WRITE : AccessKind::AK_MUST_READ;
1953 Changed =
1954 Changed | addAccess(A, {0, LengthVal}, *MI, nullptr, Kind, nullptr);
1955 }
1956 LLVM_DEBUG({
1957 dbgs() << "Accesses by bin after update:\n";
1958 dumpState(dbgs());
1959 });
1960
1961 return Changed;
1962 }
1963
1964 // TODO: Once we have call site specific value information we can provide
1965 // call site specific liveness information and then it makes
1966 // sense to specialize attributes for call sites arguments instead of
1967 // redirecting requests to the callee argument.
1968 Argument *Arg = getAssociatedArgument();
1969 if (Arg) {
1970 const IRPosition &ArgPos = IRPosition::argument(*Arg);
1971 auto *ArgAA =
1972 A.getAAFor<AAPointerInfo>(*this, ArgPos, DepClassTy::REQUIRED);
1973 if (ArgAA && ArgAA->getState().isValidState())
1974 return translateAndAddStateFromCallee(A, *ArgAA,
1975 *cast<CallBase>(getCtxI()));
1976 if (!Arg->getParent()->isDeclaration())
1977 return indicatePessimisticFixpoint();
1978 }
1979
1980 bool IsKnownNoCapture;
1982 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoCapture))
1983 return indicatePessimisticFixpoint();
1984
1985 bool IsKnown = false;
1986 if (AA::isAssumedReadNone(A, getIRPosition(), *this, IsKnown))
1987 return ChangeStatus::UNCHANGED;
1988 bool ReadOnly = AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown);
1989 auto Kind =
1990 ReadOnly ? AccessKind::AK_MAY_READ : AccessKind::AK_MAY_READ_WRITE;
1991 return addAccess(A, AA::RangeTy::getUnknown(), *getCtxI(), nullptr, Kind,
1992 nullptr);
1993 }
1994
1995 void trackStatistics() const override {
1996 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1997 }
1998};
1999
2000struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
2001 AAPointerInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
2002 : AAPointerInfoFloating(IRP, A) {}
2003
2004 void trackStatistics() const override {
2005 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2006 }
2007};
2008} // namespace
2009
2010/// -----------------------NoUnwind Function Attribute--------------------------
2011
2012namespace {
2013struct AANoUnwindImpl : AANoUnwind {
2014 AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
2015
2016 void initialize(Attributor &A) override {
2017 bool IsKnown;
2019 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2020 (void)IsKnown;
2021 }
2022
2023 const std::string getAsStr(Attributor *A) const override {
2024 return getAssumed() ? "nounwind" : "may-unwind";
2025 }
2026
2027 ChangeStatus updateImpl(Attributor &A) override {
2028 auto Opcodes = {
2029 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
2030 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet,
2031 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
2032
2033 auto CheckForNoUnwind = [&](Instruction &I) {
2034 if (!I.mayThrow(/* IncludePhaseOneUnwind */ true))
2035 return true;
2036
2037 if (const auto *CB = dyn_cast<CallBase>(&I)) {
2038 bool IsKnownNoUnwind;
2040 A, this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED,
2041 IsKnownNoUnwind);
2042 }
2043 return false;
2044 };
2045
2046 bool UsedAssumedInformation = false;
2047 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes,
2048 UsedAssumedInformation))
2049 return indicatePessimisticFixpoint();
2050
2051 return ChangeStatus::UNCHANGED;
2052 }
2053};
2054
2055struct AANoUnwindFunction final : public AANoUnwindImpl {
2056 AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
2057 : AANoUnwindImpl(IRP, A) {}
2058
2059 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
2060};
2061
2062/// NoUnwind attribute deduction for a call sites.
2063struct AANoUnwindCallSite final
2064 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl> {
2065 AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
2066 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl>(IRP, A) {}
2067
2068 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
2069};
2070} // namespace
2071
2072/// ------------------------ NoSync Function Attribute -------------------------
2073
2074bool AANoSync::isAlignedBarrier(const CallBase &CB, bool ExecutedAligned) {
2075 switch (CB.getIntrinsicID()) {
2076 case Intrinsic::nvvm_barrier_cta_sync_aligned_all:
2077 case Intrinsic::nvvm_barrier_cta_sync_aligned_count:
2078 case Intrinsic::nvvm_barrier_cta_red_and_aligned_all:
2079 case Intrinsic::nvvm_barrier_cta_red_and_aligned_count:
2080 case Intrinsic::nvvm_barrier_cta_red_or_aligned_all:
2081 case Intrinsic::nvvm_barrier_cta_red_or_aligned_count:
2082 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_all:
2083 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_count:
2084 return true;
2085 case Intrinsic::amdgcn_s_barrier:
2086 if (ExecutedAligned)
2087 return true;
2088 break;
2089 default:
2090 break;
2091 }
2092 return hasAssumption(CB, KnownAssumptionString("ompx_aligned_barrier"));
2093}
2094
2096 if (!I->isAtomic())
2097 return false;
2098
2099 if (auto *FI = dyn_cast<FenceInst>(I))
2100 // All legal orderings for fence are stronger than monotonic.
2101 return FI->getSyncScopeID() != SyncScope::SingleThread;
2102 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
2103 // Unordered is not a legal ordering for cmpxchg.
2104 return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic ||
2105 AI->getFailureOrdering() != AtomicOrdering::Monotonic);
2106 }
2107
2108 AtomicOrdering Ordering;
2109 switch (I->getOpcode()) {
2110 case Instruction::AtomicRMW:
2111 Ordering = cast<AtomicRMWInst>(I)->getOrdering();
2112 break;
2113 case Instruction::Store:
2114 Ordering = cast<StoreInst>(I)->getOrdering();
2115 break;
2116 case Instruction::Load:
2117 Ordering = cast<LoadInst>(I)->getOrdering();
2118 break;
2119 default:
2121 "New atomic operations need to be known in the attributor.");
2122 }
2123
2124 return (Ordering != AtomicOrdering::Unordered &&
2125 Ordering != AtomicOrdering::Monotonic);
2126}
2127
2128namespace {
2129struct AANoSyncImpl : AANoSync {
2130 AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
2131
2132 void initialize(Attributor &A) override {
2133 bool IsKnown;
2134 assert(!AA::hasAssumedIRAttr<Attribute::NoSync>(A, nullptr, getIRPosition(),
2135 DepClassTy::NONE, IsKnown));
2136 (void)IsKnown;
2137 }
2138
2139 const std::string getAsStr(Attributor *A) const override {
2140 return getAssumed() ? "nosync" : "may-sync";
2141 }
2142
2143 ChangeStatus updateImpl(Attributor &A) override;
2144};
2145
2146ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
2147
2148 auto CheckRWInstForNoSync = [&](Instruction &I) {
2149 return AA::isNoSyncInst(A, I, *this);
2150 };
2151
2152 auto CheckForNoSync = [&](Instruction &I) {
2153 // At this point we handled all read/write effects and they are all
2154 // nosync, so they can be skipped.
2155 if (I.mayReadOrWriteMemory())
2156 return true;
2157
2158 bool IsKnown;
2159 CallBase &CB = cast<CallBase>(I);
2162 IsKnown))
2163 return true;
2164
2165 // non-convergent and readnone imply nosync.
2166 return !CB.isConvergent();
2167 };
2168
2169 bool UsedAssumedInformation = false;
2170 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this,
2171 UsedAssumedInformation) ||
2172 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this,
2173 UsedAssumedInformation))
2174 return indicatePessimisticFixpoint();
2175
2177}
2178
2179struct AANoSyncFunction final : public AANoSyncImpl {
2180 AANoSyncFunction(const IRPosition &IRP, Attributor &A)
2181 : AANoSyncImpl(IRP, A) {}
2182
2183 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
2184};
2185
2186/// NoSync attribute deduction for a call sites.
2187struct AANoSyncCallSite final : AACalleeToCallSite<AANoSync, AANoSyncImpl> {
2188 AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
2189 : AACalleeToCallSite<AANoSync, AANoSyncImpl>(IRP, A) {}
2190
2191 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
2192};
2193} // namespace
2194
2195/// ------------------------ No-Free Attributes ----------------------------
2196
2197namespace {
2198struct AANoFreeImpl : public AANoFree {
2199 AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
2200
2201 void initialize(Attributor &A) override {
2202 bool IsKnown;
2203 assert(!AA::hasAssumedIRAttr<Attribute::NoFree>(A, nullptr, getIRPosition(),
2204 DepClassTy::NONE, IsKnown));
2205 (void)IsKnown;
2206 }
2207
2208 ChangeStatus updateImpl(Attributor &A) override {
2209 auto CheckForNoFree = [&](Instruction &I) {
2210 if (auto *CB = dyn_cast<CallBase>(&I)) {
2211 bool IsKnown;
2213 A, this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED,
2214 IsKnown);
2215 }
2216 // Make sure that synchronization cannot establish happens-before with a
2217 // free on another thread.
2218 return AA::isNoSyncInst(A, I, *this);
2219 };
2220
2221 bool UsedAssumedInformation = false;
2222 if (!A.checkForAllReadWriteInstructions(CheckForNoFree, *this,
2223 UsedAssumedInformation) ||
2224 !A.checkForAllCallLikeInstructions(CheckForNoFree, *this,
2225 UsedAssumedInformation))
2226 return indicatePessimisticFixpoint();
2227
2228 return ChangeStatus::UNCHANGED;
2229 }
2230
2231 const std::string getAsStr(Attributor *A) const override {
2232 return getAssumed() ? "nofree" : "may-free";
2233 }
2234};
2235
2236struct AANoFreeFunction final : public AANoFreeImpl {
2237 AANoFreeFunction(const IRPosition &IRP, Attributor &A)
2238 : AANoFreeImpl(IRP, A) {}
2239
2240 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
2241};
2242
2243/// NoFree attribute deduction for a call sites.
2244struct AANoFreeCallSite final : AACalleeToCallSite<AANoFree, AANoFreeImpl> {
2245 AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
2246 : AACalleeToCallSite<AANoFree, AANoFreeImpl>(IRP, A) {}
2247
2248 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
2249};
2250
2251/// NoFree attribute for floating values.
2252struct AANoFreeFloating : AANoFreeImpl {
2253 AANoFreeFloating(const IRPosition &IRP, Attributor &A)
2254 : AANoFreeImpl(IRP, A) {}
2255
2256 void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
2257
2258 /// See Abstract Attribute::updateImpl(...).
2259 ChangeStatus updateImpl(Attributor &A) override {
2260 const IRPosition &IRP = getIRPosition();
2261
2262 bool IsKnown;
2265 DepClassTy::OPTIONAL, IsKnown))
2266 return ChangeStatus::UNCHANGED;
2267
2268 Value &AssociatedValue = getIRPosition().getAssociatedValue();
2269 auto Pred = [&](const Use &U, bool &Follow) -> bool {
2270 Instruction *UserI = cast<Instruction>(U.getUser());
2271 if (auto *CB = dyn_cast<CallBase>(UserI)) {
2272 if (CB->isBundleOperand(&U))
2273 return false;
2274 if (!CB->isArgOperand(&U))
2275 return true;
2276 unsigned ArgNo = CB->getArgOperandNo(&U);
2277
2278 // Even if the argument is nofree, we still need to check for nocapture,
2279 // as the call may capture the argument without freeing it, and the
2280 // captured argument is freed later.
2281 bool IsKnown;
2283 A, this, IRPosition::callsite_argument(*CB, ArgNo),
2284 DepClassTy::REQUIRED, IsKnown))
2285 return false;
2286
2287 const AANoCapture *NoCaptureAA = nullptr;
2289 A, this, IRPosition::callsite_argument(*CB, ArgNo),
2290 DepClassTy::REQUIRED, IsKnown,
2291 /*IgnoreSubsumingPositions=*/false, &NoCaptureAA)) {
2292 if (NoCaptureAA && NoCaptureAA->isAssumedNoCaptureMaybeReturned()) {
2293 Follow = true;
2294 return true;
2295 }
2296 return false;
2297 }
2298
2299 return true;
2300 }
2301
2302 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
2303 if (!capturesAnyProvenance(CI))
2304 return true;
2306 Follow = true;
2307 return true;
2308 }
2309
2310 if (isa<ReturnInst>(UserI) && getIRPosition().isArgumentPosition())
2311 return true;
2312
2313 // Capturing user.
2314 return false;
2315 };
2316 if (!A.checkForAllUses(Pred, *this, AssociatedValue))
2317 return indicatePessimisticFixpoint();
2318
2319 return ChangeStatus::UNCHANGED;
2320 }
2321};
2322
2323/// NoFree attribute for a call site argument.
2324struct AANoFreeArgument final : AANoFreeFloating {
2325 AANoFreeArgument(const IRPosition &IRP, Attributor &A)
2326 : AANoFreeFloating(IRP, A) {}
2327
2328 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
2329};
2330
2331/// NoFree attribute for call site arguments.
2332struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2333 AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
2334 : AANoFreeFloating(IRP, A) {}
2335
2336 ChangeStatus updateImpl(Attributor &A) override {
2337 // TODO: Once we have call site specific value information we can provide
2338 // call site specific liveness information and then it makes
2339 // sense to specialize attributes for call sites arguments instead of
2340 // redirecting requests to the callee argument.
2341 Argument *Arg = getAssociatedArgument();
2342 if (!Arg)
2343 return indicatePessimisticFixpoint();
2344 const IRPosition &ArgPos = IRPosition::argument(*Arg);
2345 bool IsKnown;
2347 DepClassTy::REQUIRED, IsKnown))
2348 return ChangeStatus::UNCHANGED;
2349 return indicatePessimisticFixpoint();
2350 }
2351
2352 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nofree) };
2353};
2354
2355/// NoFree attribute for function return value.
2356struct AANoFreeReturned final : AANoFreeFloating {
2357 AANoFreeReturned(const IRPosition &IRP, Attributor &A)
2358 : AANoFreeFloating(IRP, A) {
2359 llvm_unreachable("NoFree is not applicable to function returns!");
2360 }
2361
2362 void initialize(Attributor &A) override {
2363 llvm_unreachable("NoFree is not applicable to function returns!");
2364 }
2365
2366 ChangeStatus updateImpl(Attributor &A) override {
2367 llvm_unreachable("NoFree is not applicable to function returns!");
2368 }
2369
2370 void trackStatistics() const override {}
2371};
2372
2373/// NoFree attribute deduction for a call site return value.
2374struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2375 AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
2376 : AANoFreeFloating(IRP, A) {}
2377
2378 ChangeStatus manifest(Attributor &A) override {
2379 return ChangeStatus::UNCHANGED;
2380 }
2381 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
2382};
2383} // namespace
2384
2385/// ------------------------ NonNull Argument Attribute ------------------------
2386
2388 Attribute::AttrKind ImpliedAttributeKind,
2389 bool IgnoreSubsumingPositions) {
2391 AttrKinds.push_back(Attribute::NonNull);
2394 AttrKinds.push_back(Attribute::Dereferenceable);
2395 if (A.hasAttr(IRP, AttrKinds, IgnoreSubsumingPositions, Attribute::NonNull))
2396 return true;
2397
2398 if (!A.canUseBodyFor(IRP))
2399 return false;
2400
2401 DominatorTree *DT = nullptr;
2402 AssumptionCache *AC = nullptr;
2403 InformationCache &InfoCache = A.getInfoCache();
2404 if (const Function *Fn = IRP.getAnchorScope()) {
2405 if (!Fn->isDeclaration()) {
2408 }
2409 }
2410
2412 if (IRP.getPositionKind() != IRP_RETURNED) {
2413 Worklist.push_back({IRP.getAssociatedValue(), IRP.getCtxI()});
2414 } else {
2415 bool UsedAssumedInformation = false;
2416 if (!A.checkForAllInstructions(
2417 [&](Instruction &I) {
2418 Worklist.push_back({*cast<ReturnInst>(I).getReturnValue(), &I});
2419 return true;
2420 },
2421 IRP.getAssociatedFunction(), nullptr, {Instruction::Ret},
2422 UsedAssumedInformation, false, /*CheckPotentiallyDead=*/true))
2423 return false;
2424 }
2425
2426 if (llvm::any_of(Worklist, [&](AA::ValueAndContext VAC) {
2427 return !isKnownNonZero(
2428 VAC.getValue(),
2429 SimplifyQuery(A.getDataLayout(), DT, AC, VAC.getCtxI()));
2430 }))
2431 return false;
2432
2433 A.manifestAttrs(IRP, {Attribute::get(IRP.getAnchorValue().getContext(),
2434 Attribute::NonNull)});
2435 return true;
2436}
2437
2438namespace {
2439static int64_t getKnownNonNullAndDerefBytesForUse(
2440 Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
2441 const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
2442 TrackUse = false;
2443
2444 const Value *UseV = U->get();
2445 if (!UseV->getType()->isPointerTy())
2446 return 0;
2447
2448 // We need to follow common pointer manipulation uses to the accesses they
2449 // feed into. We can try to be smart to avoid looking through things we do not
2450 // like for now, e.g., non-inbounds GEPs.
2451 if (isa<CastInst>(I)) {
2452 TrackUse = true;
2453 return 0;
2454 }
2455
2457 TrackUse = true;
2458 return 0;
2459 }
2460
2461 Type *PtrTy = UseV->getType();
2462 const Function *F = I->getFunction();
2465 const DataLayout &DL = A.getInfoCache().getDL();
2466 if (const auto *CB = dyn_cast<CallBase>(I)) {
2467 if (CB->isBundleOperand(U)) {
2468 auto OBU = CB->getOperandBundleForOperand(U->getOperandNo());
2469 switch (getBundleAttrFromOBU(OBU)) {
2470 case BundleAttr::NonNull:
2471 IsNonNull = true;
2472 break;
2473 case BundleAttr::Dereferenceable: {
2474 IsNonNull |= !NullPointerIsDefined;
2476 if (auto *CI = dyn_cast<ConstantInt>(Count))
2477 return CI->getZExtValue();
2478 } break;
2479 default:
2480 break;
2481 }
2482 return 0;
2483 }
2484
2485 if (CB->isCallee(U)) {
2486 IsNonNull |= !NullPointerIsDefined;
2487 return 0;
2488 }
2489
2490 unsigned ArgNo = CB->getArgOperandNo(U);
2491 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
2492 // As long as we only use known information there is no need to track
2493 // dependences here.
2494 bool IsKnownNonNull;
2496 DepClassTy::NONE, IsKnownNonNull);
2497 IsNonNull |= IsKnownNonNull;
2498 auto *DerefAA =
2499 A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE);
2500 return DerefAA ? DerefAA->getKnownDereferenceableBytes() : 0;
2501 }
2502
2503 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
2504 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
2505 Loc->Size.isScalable() || I->isVolatile())
2506 return 0;
2507
2508 int64_t Offset;
2509 const Value *Base =
2510 getMinimalBaseOfPointer(A, QueryingAA, Loc->Ptr, Offset, DL);
2511 if (Base && Base == &AssociatedValue) {
2512 int64_t DerefBytes = Loc->Size.getValue() + Offset;
2513 IsNonNull |= !NullPointerIsDefined;
2514 return std::max(int64_t(0), DerefBytes);
2515 }
2516
2517 /// Corner case when an offset is 0.
2519 /*AllowNonInbounds*/ true);
2520 if (Base && Base == &AssociatedValue && Offset == 0) {
2521 int64_t DerefBytes = Loc->Size.getValue();
2522 IsNonNull |= !NullPointerIsDefined;
2523 return std::max(int64_t(0), DerefBytes);
2524 }
2525
2526 return 0;
2527}
2528
2529struct AANonNullImpl : AANonNull {
2530 AANonNullImpl(const IRPosition &IRP, Attributor &A) : AANonNull(IRP, A) {}
2531
2532 void initialize(Attributor &A) override {
2533 Value &V = *getAssociatedValue().stripPointerCasts();
2535 indicatePessimisticFixpoint();
2536 return;
2537 }
2538
2539 if (Instruction *CtxI = getCtxI())
2540 followUsesInMBEC(*this, A, getState(), *CtxI);
2541 }
2542
2543 /// See followUsesInMBEC
2544 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
2545 AANonNull::StateType &State) {
2546 bool IsNonNull = false;
2547 bool TrackUse = false;
2548 getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
2549 IsNonNull, TrackUse);
2550 State.setKnown(IsNonNull);
2551 return TrackUse;
2552 }
2553
2554 const std::string getAsStr(Attributor *A) const override {
2555 return getAssumed() ? "nonnull" : "may-null";
2556 }
2557};
2558
2559/// NonNull attribute for a floating value.
2560struct AANonNullFloating : public AANonNullImpl {
2561 AANonNullFloating(const IRPosition &IRP, Attributor &A)
2562 : AANonNullImpl(IRP, A) {}
2563
2564 ChangeStatus updateImpl(Attributor &A) override {
2565 auto CheckIRP = [&](const IRPosition &IRP) {
2566 bool IsKnownNonNull;
2568 A, *this, IRP, DepClassTy::OPTIONAL, IsKnownNonNull);
2569 };
2570
2571 bool Stripped;
2572 bool UsedAssumedInformation = false;
2573 Value *AssociatedValue = &getAssociatedValue();
2575 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
2576 AA::AnyScope, UsedAssumedInformation))
2577 Stripped = false;
2578 else
2579 Stripped =
2580 Values.size() != 1 || Values.front().getValue() != AssociatedValue;
2581
2582 if (!Stripped) {
2583 bool IsKnown;
2584 if (auto *PHI = dyn_cast<PHINode>(AssociatedValue))
2585 if (llvm::all_of(PHI->incoming_values(), [&](Value *Op) {
2586 return AA::hasAssumedIRAttr<Attribute::NonNull>(
2587 A, this, IRPosition::value(*Op), DepClassTy::OPTIONAL,
2588 IsKnown);
2589 }))
2590 return ChangeStatus::UNCHANGED;
2591 if (auto *Select = dyn_cast<SelectInst>(AssociatedValue))
2593 A, this, IRPosition::value(*Select->getFalseValue()),
2594 DepClassTy::OPTIONAL, IsKnown) &&
2596 A, this, IRPosition::value(*Select->getTrueValue()),
2597 DepClassTy::OPTIONAL, IsKnown))
2598 return ChangeStatus::UNCHANGED;
2599
2600 // If we haven't stripped anything we might still be able to use a
2601 // different AA, but only if the IRP changes. Effectively when we
2602 // interpret this not as a call site value but as a floating/argument
2603 // value.
2604 const IRPosition AVIRP = IRPosition::value(*AssociatedValue);
2605 if (AVIRP == getIRPosition() || !CheckIRP(AVIRP))
2606 return indicatePessimisticFixpoint();
2607 return ChangeStatus::UNCHANGED;
2608 }
2609
2610 for (const auto &VAC : Values)
2611 if (!CheckIRP(IRPosition::value(*VAC.getValue())))
2612 return indicatePessimisticFixpoint();
2613
2614 return ChangeStatus::UNCHANGED;
2615 }
2616
2617 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2618};
2619
2620/// NonNull attribute for function return value.
2621struct AANonNullReturned final
2622 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2623 false, AANonNull::IRAttributeKind, false> {
2624 AANonNullReturned(const IRPosition &IRP, Attributor &A)
2625 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2626 false, Attribute::NonNull, false>(IRP, A) {
2627 }
2628
2629 const std::string getAsStr(Attributor *A) const override {
2630 return getAssumed() ? "nonnull" : "may-null";
2631 }
2632
2633 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2634};
2635
2636/// NonNull attribute for function argument.
2637struct AANonNullArgument final
2638 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2639 AANonNullArgument(const IRPosition &IRP, Attributor &A)
2640 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {}
2641
2642 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
2643};
2644
2645struct AANonNullCallSiteArgument final : AANonNullFloating {
2646 AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
2647 : AANonNullFloating(IRP, A) {}
2648
2649 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
2650};
2651
2652/// NonNull attribute for a call site return position.
2653struct AANonNullCallSiteReturned final
2654 : AACalleeToCallSite<AANonNull, AANonNullImpl> {
2655 AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
2656 : AACalleeToCallSite<AANonNull, AANonNullImpl>(IRP, A) {}
2657
2658 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
2659};
2660} // namespace
2661
2662/// ------------------------ Must-Progress Attributes --------------------------
2663namespace {
2664struct AAMustProgressImpl : public AAMustProgress {
2665 AAMustProgressImpl(const IRPosition &IRP, Attributor &A)
2666 : AAMustProgress(IRP, A) {}
2667
2668 void initialize(Attributor &A) override {
2669 bool IsKnown;
2671 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2672 (void)IsKnown;
2673 }
2674
2675 const std::string getAsStr(Attributor *A) const override {
2676 return getAssumed() ? "mustprogress" : "may-not-progress";
2677 }
2678};
2679
2680struct AAMustProgressFunction final : AAMustProgressImpl {
2681 AAMustProgressFunction(const IRPosition &IRP, Attributor &A)
2682 : AAMustProgressImpl(IRP, A) {}
2683
2684 ChangeStatus updateImpl(Attributor &A) override {
2685 bool IsKnown;
2687 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnown)) {
2688 if (IsKnown)
2689 return indicateOptimisticFixpoint();
2690 return ChangeStatus::UNCHANGED;
2691 }
2692
2693 auto CheckForMustProgress = [&](AbstractCallSite ACS) {
2694 IRPosition IPos = IRPosition::callsite_function(*ACS.getInstruction());
2695 bool IsKnownMustProgress;
2697 A, this, IPos, DepClassTy::REQUIRED, IsKnownMustProgress,
2698 /* IgnoreSubsumingPositions */ true);
2699 };
2700
2701 bool AllCallSitesKnown = true;
2702 if (!A.checkForAllCallSites(CheckForMustProgress, *this,
2703 /* RequireAllCallSites */ true,
2704 AllCallSitesKnown))
2705 return indicatePessimisticFixpoint();
2706
2707 return ChangeStatus::UNCHANGED;
2708 }
2709
2710 void trackStatistics() const override {
2711 STATS_DECLTRACK_FN_ATTR(mustprogress)
2712 }
2713};
2714
2715/// MustProgress attribute deduction for a call sites.
2716struct AAMustProgressCallSite final : AAMustProgressImpl {
2717 AAMustProgressCallSite(const IRPosition &IRP, Attributor &A)
2718 : AAMustProgressImpl(IRP, A) {}
2719
2720 ChangeStatus updateImpl(Attributor &A) override {
2721 // TODO: Once we have call site specific value information we can provide
2722 // call site specific liveness information and then it makes
2723 // sense to specialize attributes for call sites arguments instead of
2724 // redirecting requests to the callee argument.
2725 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
2726 bool IsKnownMustProgress;
2728 A, this, FnPos, DepClassTy::REQUIRED, IsKnownMustProgress))
2729 return indicatePessimisticFixpoint();
2730 return ChangeStatus::UNCHANGED;
2731 }
2732
2733 void trackStatistics() const override {
2734 STATS_DECLTRACK_CS_ATTR(mustprogress);
2735 }
2736};
2737} // namespace
2738
2739/// ------------------------ No-Recurse Attributes ----------------------------
2740
2741namespace {
2742struct AANoRecurseImpl : public AANoRecurse {
2743 AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
2744
2745 void initialize(Attributor &A) override {
2746 bool IsKnown;
2748 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2749 (void)IsKnown;
2750 }
2751
2752 const std::string getAsStr(Attributor *A) const override {
2753 return getAssumed() ? "norecurse" : "may-recurse";
2754 }
2755};
2756
2757struct AANoRecurseFunction final : AANoRecurseImpl {
2758 AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
2759 : AANoRecurseImpl(IRP, A) {}
2760
2761 ChangeStatus updateImpl(Attributor &A) override {
2762
2763 // If all live call sites are known to be no-recurse, we are as well.
2764 auto CallSitePred = [&](AbstractCallSite ACS) {
2765 bool IsKnownNoRecurse;
2767 A, this,
2768 IRPosition::function(*ACS.getInstruction()->getFunction()),
2769 DepClassTy::NONE, IsKnownNoRecurse))
2770 return false;
2771 return IsKnownNoRecurse;
2772 };
2773 bool UsedAssumedInformation = false;
2774 if (A.checkForAllCallSites(CallSitePred, *this, true,
2775 UsedAssumedInformation)) {
2776 // If we know all call sites and all are known no-recurse, we are done.
2777 // If all known call sites, which might not be all that exist, are known
2778 // to be no-recurse, we are not done but we can continue to assume
2779 // no-recurse. If one of the call sites we have not visited will become
2780 // live, another update is triggered.
2781 if (!UsedAssumedInformation)
2782 indicateOptimisticFixpoint();
2783 return ChangeStatus::UNCHANGED;
2784 }
2785
2786 const AAInterFnReachability *EdgeReachability =
2787 A.getAAFor<AAInterFnReachability>(*this, getIRPosition(),
2788 DepClassTy::REQUIRED);
2789 if (EdgeReachability && EdgeReachability->canReach(A, *getAnchorScope()))
2790 return indicatePessimisticFixpoint();
2791 return ChangeStatus::UNCHANGED;
2792 }
2793
2794 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
2795};
2796
2797/// NoRecurse attribute deduction for a call sites.
2798struct AANoRecurseCallSite final
2799 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl> {
2800 AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
2801 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl>(IRP, A) {}
2802
2803 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
2804};
2805} // namespace
2806
2807/// ------------------------ No-Convergent Attribute --------------------------
2808
2809namespace {
2810struct AANonConvergentImpl : public AANonConvergent {
2811 AANonConvergentImpl(const IRPosition &IRP, Attributor &A)
2812 : AANonConvergent(IRP, A) {}
2813
2814 const std::string getAsStr(Attributor *A) const override {
2815 return getAssumed() ? "non-convergent" : "may-be-convergent";
2816 }
2817};
2818
2819struct AANonConvergentFunction final : AANonConvergentImpl {
2820 AANonConvergentFunction(const IRPosition &IRP, Attributor &A)
2821 : AANonConvergentImpl(IRP, A) {}
2822
2823 ChangeStatus updateImpl(Attributor &A) override {
2824 // If all function calls are known to not be convergent, we are not
2825 // convergent.
2826 auto CalleeIsNotConvergent = [&](Instruction &Inst) {
2827 CallBase &CB = cast<CallBase>(Inst);
2829 if (!Callee || Callee->isIntrinsic()) {
2830 return false;
2831 }
2832 if (Callee->isDeclaration()) {
2833 return !Callee->hasFnAttribute(Attribute::Convergent);
2834 }
2835 const auto *ConvergentAA = A.getAAFor<AANonConvergent>(
2836 *this, IRPosition::function(*Callee), DepClassTy::REQUIRED);
2837 return ConvergentAA && ConvergentAA->isAssumedNotConvergent();
2838 };
2839
2840 bool UsedAssumedInformation = false;
2841 if (!A.checkForAllCallLikeInstructions(CalleeIsNotConvergent, *this,
2842 UsedAssumedInformation)) {
2843 return indicatePessimisticFixpoint();
2844 }
2845 return ChangeStatus::UNCHANGED;
2846 }
2847
2848 ChangeStatus manifest(Attributor &A) override {
2849 if (isKnownNotConvergent() &&
2850 A.hasAttr(getIRPosition(), Attribute::Convergent)) {
2851 A.removeAttrs(getIRPosition(), {Attribute::Convergent});
2852 return ChangeStatus::CHANGED;
2853 }
2854 return ChangeStatus::UNCHANGED;
2855 }
2856
2857 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(convergent) }
2858};
2859} // namespace
2860
2861/// -------------------- Undefined-Behavior Attributes ------------------------
2862
2863namespace {
2864struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
2865 AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
2866 : AAUndefinedBehavior(IRP, A) {}
2867
2868 struct UBInfo {
2869 enum Kind {
2870 NullPtrAccess,
2871 UndefPtrAccess,
2872 UndefBranchCondition,
2873 UndefReturnValue,
2874 NullReturnViolatesNonNull,
2875 UndefCallArgument,
2876 NullArgViolatesNonNull,
2877 };
2878
2879 Kind K;
2880 std::optional<unsigned> ArgNo;
2881
2882 UBInfo(Kind K) : K(K), ArgNo(std::nullopt) {}
2883
2884 UBInfo(Kind K, std::optional<unsigned> ArgNo) : K(K), ArgNo(ArgNo) {}
2885 };
2886
2887 ChangeStatus updateImpl(Attributor &A) override {
2888 const size_t UBPrevSize = KnownUBInsts.size();
2889 const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2890
2891 auto InspectMemAccessInstForUB = [&](Instruction &I) {
2892 // Volatile accesses on null are not necessarily UB.
2893 if (I.isVolatile())
2894 return true;
2895
2896 // Skip instructions that are already saved.
2897 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2898 return true;
2899
2900 // If we reach here, we know we have an instruction
2901 // that accesses memory through a pointer operand,
2902 // for which getPointerOperand() should give it to us.
2903 Value *PtrOp =
2904 const_cast<Value *>(getPointerOperand(&I, /* AllowVolatile */ true));
2905 assert(PtrOp &&
2906 "Expected pointer operand of memory accessing instruction");
2907
2908 // Either we stopped and the appropriate action was taken,
2909 // or we got back a simplified value to continue.
2910 std::optional<Value *> SimplifiedPtrOp =
2911 stopOnUndefOrAssumed(A, PtrOp, &I, UBInfo::UndefPtrAccess);
2912 if (!SimplifiedPtrOp || !*SimplifiedPtrOp)
2913 return true;
2914 const Value *PtrOpVal = *SimplifiedPtrOp;
2915
2916 // A memory access through a pointer is considered UB
2917 // only if the pointer has constant null value.
2918 // TODO: Expand it to not only check constant values.
2919 if (!isa<ConstantPointerNull>(PtrOpVal)) {
2920 AssumedNoUBInsts.insert(&I);
2921 return true;
2922 }
2923 const Type *PtrTy = PtrOpVal->getType();
2924
2925 // Because we only consider instructions inside functions,
2926 // assume that a parent function exists.
2927 const Function *F = I.getFunction();
2928
2929 // A memory access using constant null pointer is only considered UB
2930 // if null pointer is _not_ defined for the target platform.
2932 AssumedNoUBInsts.insert(&I);
2933 else
2934 KnownUBInsts.try_emplace(&I, UBInfo::NullPtrAccess);
2935 return true;
2936 };
2937
2938 auto InspectBrInstForUB = [&](Instruction &I) {
2939 // A conditional branch instruction is considered UB if it has `undef`
2940 // condition.
2941
2942 // Skip instructions that are already saved.
2943 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2944 return true;
2945
2946 // We know we have a branch instruction.
2947 auto *BrInst = cast<CondBrInst>(&I);
2948
2949 // Either we stopped and the appropriate action was taken,
2950 // or we got back a simplified value to continue.
2951 std::optional<Value *> SimplifiedCond = stopOnUndefOrAssumed(
2952 A, BrInst->getCondition(), BrInst, UBInfo::UndefBranchCondition);
2953 if (!SimplifiedCond || !*SimplifiedCond)
2954 return true;
2955 AssumedNoUBInsts.insert(&I);
2956 return true;
2957 };
2958
2959 auto InspectCallSiteForUB = [&](Instruction &I) {
2960 // Check whether a callsite always cause UB or not
2961
2962 // Skip instructions that are already saved.
2963 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2964 return true;
2965
2966 // Check nonnull and noundef argument attribute violation for each
2967 // callsite.
2968 CallBase &CB = cast<CallBase>(I);
2970 if (!Callee)
2971 return true;
2972 for (unsigned idx = 0; idx < CB.arg_size(); idx++) {
2973 // If current argument is known to be simplified to null pointer and the
2974 // corresponding argument position is known to have nonnull attribute,
2975 // the argument is poison. Furthermore, if the argument is poison and
2976 // the position is known to have noundef attriubte, this callsite is
2977 // considered UB.
2978 if (idx >= Callee->arg_size())
2979 break;
2980 Value *ArgVal = CB.getArgOperand(idx);
2981 if (!ArgVal)
2982 continue;
2983 // Here, we handle three cases.
2984 // (1) Not having a value means it is dead. (we can replace the value
2985 // with undef)
2986 // (2) Simplified to undef. The argument violate noundef attriubte.
2987 // (3) Simplified to null pointer where known to be nonnull.
2988 // The argument is a poison value and violate noundef attribute.
2989 IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
2990 bool IsKnownNoUndef;
2992 A, this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNoUndef);
2993 if (!IsKnownNoUndef)
2994 continue;
2995 bool UsedAssumedInformation = false;
2996 std::optional<Value *> SimplifiedVal =
2997 A.getAssumedSimplified(IRPosition::value(*ArgVal), *this,
2998 UsedAssumedInformation, AA::Interprocedural);
2999 if (UsedAssumedInformation)
3000 continue;
3001 if (SimplifiedVal && !*SimplifiedVal)
3002 return true;
3003 if (!SimplifiedVal || isa<UndefValue>(**SimplifiedVal)) {
3004 KnownUBInsts.try_emplace(&I, UBInfo(UBInfo::UndefCallArgument, idx));
3005 continue;
3006 }
3007 if (!ArgVal->getType()->isPointerTy() ||
3008 !isa<ConstantPointerNull>(**SimplifiedVal))
3009 continue;
3010 bool IsKnownNonNull;
3012 A, this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNonNull);
3013 if (IsKnownNonNull)
3014 KnownUBInsts.try_emplace(&I,
3015 UBInfo(UBInfo::NullArgViolatesNonNull, idx));
3016 }
3017 return true;
3018 };
3019
3020 auto InspectReturnInstForUB = [&](Instruction &I) {
3021 auto &RI = cast<ReturnInst>(I);
3022 // Either we stopped and the appropriate action was taken,
3023 // or we got back a simplified return value to continue.
3024 std::optional<Value *> SimplifiedRetValue = stopOnUndefOrAssumed(
3025 A, RI.getReturnValue(), &I, UBInfo::UndefReturnValue);
3026 if (!SimplifiedRetValue || !*SimplifiedRetValue)
3027 return true;
3028
3029 // Check if a return instruction always cause UB or not
3030 // Note: It is guaranteed that the returned position of the anchor
3031 // scope has noundef attribute when this is called.
3032 // We also ensure the return position is not "assumed dead"
3033 // because the returned value was then potentially simplified to
3034 // `undef` in AAReturnedValues without removing the `noundef`
3035 // attribute yet.
3036
3037 // When the returned position has noundef attriubte, UB occurs in the
3038 // following cases.
3039 // (1) Returned value is known to be undef.
3040 // (2) The value is known to be a null pointer and the returned
3041 // position has nonnull attribute (because the returned value is
3042 // poison).
3043 if (isa<ConstantPointerNull>(*SimplifiedRetValue)) {
3044 bool IsKnownNonNull;
3046 A, this, IRPosition::returned(*getAnchorScope()), DepClassTy::NONE,
3047 IsKnownNonNull);
3048 if (IsKnownNonNull)
3049 KnownUBInsts.try_emplace(&I, UBInfo::NullReturnViolatesNonNull);
3050 }
3051
3052 return true;
3053 };
3054
3055 bool UsedAssumedInformation = false;
3056 A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
3057 {Instruction::Load, Instruction::Store,
3058 Instruction::AtomicCmpXchg,
3059 Instruction::AtomicRMW},
3060 UsedAssumedInformation,
3061 /* CheckBBLivenessOnly */ true);
3062 A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::CondBr},
3063 UsedAssumedInformation,
3064 /* CheckBBLivenessOnly */ true);
3065 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this,
3066 UsedAssumedInformation);
3067
3068 // If the returned position of the anchor scope has noundef attriubte, check
3069 // all returned instructions.
3070 if (!getAnchorScope()->getReturnType()->isVoidTy()) {
3071 const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope());
3072 if (!A.isAssumedDead(ReturnIRP, this, nullptr, UsedAssumedInformation)) {
3073 bool IsKnownNoUndef;
3075 A, this, ReturnIRP, DepClassTy::NONE, IsKnownNoUndef);
3076 if (IsKnownNoUndef)
3077 A.checkForAllInstructions(InspectReturnInstForUB, *this,
3078 {Instruction::Ret}, UsedAssumedInformation,
3079 /* CheckBBLivenessOnly */ true);
3080 }
3081 }
3082
3083 if (NoUBPrevSize != AssumedNoUBInsts.size() ||
3084 UBPrevSize != KnownUBInsts.size())
3085 return ChangeStatus::CHANGED;
3086 return ChangeStatus::UNCHANGED;
3087 }
3088
3089 bool isKnownToCauseUB(Instruction *I) const override {
3090 return KnownUBInsts.count(I);
3091 }
3092
3093 bool isAssumedToCauseUB(Instruction *I) const override {
3094 // In simple words, if an instruction is not in the assumed to _not_
3095 // cause UB, then it is assumed UB (that includes those
3096 // in the KnownUBInsts set). The rest is boilerplate
3097 // is to ensure that it is one of the instructions we test
3098 // for UB.
3099
3100 switch (I->getOpcode()) {
3101 case Instruction::Load:
3102 case Instruction::Store:
3103 case Instruction::AtomicCmpXchg:
3104 case Instruction::AtomicRMW:
3105 case Instruction::CondBr:
3106 return !AssumedNoUBInsts.count(I);
3107 default:
3108 return false;
3109 }
3110 return false;
3111 }
3112
3113 /// Emit an optimization remark explaining why \p I is known to cause UB,
3114 /// per \p Info, right before it is replaced with 'unreachable'.
3115 static void emitUBRemark(Attributor &A, Instruction *I, const UBInfo &Info) {
3116 auto Remark = [&](OptimizationRemark OR) {
3117 switch (Info.K) {
3118 case UBInfo::NullPtrAccess:
3119 case UBInfo::UndefPtrAccess: {
3120 return OR << "Memory access through a pointer known to be "
3121 << ore::NV("Pointer",
3122 getPointerOperand(I, /*AllowVolatile*/ true))
3123 << " is undefined behavior; replacing with 'unreachable'.";
3124 }
3125 case UBInfo::UndefBranchCondition:
3126 return OR << "Branch condition known to be "
3127 << ore::NV("Condition", cast<CondBrInst>(I)->getCondition())
3128 << " is undefined behavior; replacing with 'unreachable'.";
3129 case UBInfo::UndefReturnValue:
3130 case UBInfo::NullReturnViolatesNonNull:
3131 return OR << "Value returned known to be "
3132 << ore::NV("ReturnValue",
3133 cast<ReturnInst>(I)->getReturnValue())
3134 << " is undefined behavior; replacing with 'unreachable'.";
3135 case UBInfo::UndefCallArgument:
3136 case UBInfo::NullArgViolatesNonNull: {
3137 bool IsUndef = Info.K == UBInfo::UndefCallArgument;
3138 CallBase &CB = *cast<CallBase>(I);
3139 OR << "Argument " << ore::NV("ArgNo", *Info.ArgNo)
3140 << " passed to parameter of ";
3141 if (auto *Callee = dyn_cast_if_present<Function>(CB.getCalledOperand()))
3142 OR << ore::NV("Callee", Callee);
3143 else
3144 OR << "the callee";
3145 return OR << " known to be "
3146 << ore::NV("Argument", IsUndef ? "undef" : "null")
3147 << " is undefined behavior; replacing with 'unreachable'.";
3148 }
3149 }
3150 llvm_unreachable("Unknown UBInfo::Kind");
3151 };
3152 A.emitRemark<OptimizationRemark>(I, "UndefinedBehavior", Remark);
3153 }
3154
3155 ChangeStatus manifest(Attributor &A) override {
3156 if (KnownUBInsts.empty())
3157 return ChangeStatus::UNCHANGED;
3158 for (const auto &[I, Info] : KnownUBInsts) {
3159 emitUBRemark(A, I, Info);
3160 A.changeToUnreachableAfterManifest(I);
3161 }
3162 return ChangeStatus::CHANGED;
3163 }
3164
3165 const std::string getAsStr(Attributor *A) const override {
3166 return getAssumed() ? "undefined-behavior" : "no-ub";
3167 }
3168
3169 /// Note: The correctness of this analysis depends on the fact that the
3170 /// following 2 sets will stop changing after some point.
3171 /// "Change" here means that their size changes.
3172 /// The size of each set is monotonically increasing
3173 /// (we only add items to them) and it is upper bounded by the number of
3174 /// instructions in the processed function (we can never save more
3175 /// elements in either set than this number). Hence, at some point,
3176 /// they will stop increasing.
3177 /// Consequently, at some point, both sets will have stopped
3178 /// changing, effectively making the analysis reach a fixpoint.
3179
3180 /// Note: These 2 sets are disjoint and an instruction can be considered
3181 /// one of 3 things:
3182 /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
3183 /// the KnownUBInsts set.
3184 /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
3185 /// has a reason to assume it).
3186 /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
3187 /// could not find a reason to assume or prove that it can cause UB,
3188 /// hence it assumes it doesn't. We have a set for these instructions
3189 /// so that we don't reprocess them in every update.
3190 /// Note however that instructions in this set may cause UB.
3191
3192protected:
3193 /// A map from all live instructions _known_ to cause UB to the reason why,
3194 /// used to build actionable optimization remarks in manifest().
3195 MapVector<Instruction *, UBInfo> KnownUBInsts;
3196
3197private:
3198 /// A set of all the (live) instructions that are assumed to _not_ cause UB.
3199 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
3200
3201 // Should be called on updates in which if we're processing an instruction
3202 // \p I that depends on a value \p V, one of the following has to happen:
3203 // - If the value is assumed, then stop.
3204 // - If the value is known but undef, then consider it UB for \p K.
3205 // - Otherwise, do specific processing with the simplified value.
3206 // We return std::nullopt in the first 2 cases to signify that an appropriate
3207 // action was taken and the caller should stop.
3208 // Otherwise, we return the simplified value that the caller should
3209 // use for specific processing.
3210 std::optional<Value *> stopOnUndefOrAssumed(Attributor &A, Value *V,
3211 Instruction *I, UBInfo::Kind K) {
3212 bool UsedAssumedInformation = false;
3213 std::optional<Value *> SimplifiedV =
3214 A.getAssumedSimplified(IRPosition::value(*V), *this,
3215 UsedAssumedInformation, AA::Interprocedural);
3216 if (!UsedAssumedInformation) {
3217 // Don't depend on assumed values.
3218 if (!SimplifiedV) {
3219 // If it is known (which we tested above) but it doesn't have a value,
3220 // then we can assume `undef` and hence the instruction is UB.
3221 KnownUBInsts.try_emplace(I, K);
3222 return std::nullopt;
3223 }
3224 if (!*SimplifiedV)
3225 return nullptr;
3226 V = *SimplifiedV;
3227 }
3228 if (isa<UndefValue>(V)) {
3229 KnownUBInsts.try_emplace(I, K);
3230 return std::nullopt;
3231 }
3232 return V;
3233 }
3234};
3235
3236struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
3237 AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
3238 : AAUndefinedBehaviorImpl(IRP, A) {}
3239
3240 void trackStatistics() const override {
3241 STATS_DECL(UndefinedBehaviorInstruction, Instruction,
3242 "Number of instructions known to have UB");
3243 BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
3244 KnownUBInsts.size();
3245 }
3246};
3247} // namespace
3248
3249/// ------------------------ Will-Return Attributes ----------------------------
3250
3251namespace {
3252// Helper function that checks whether a function has any cycle which we don't
3253// know if it is bounded or not.
3254// Loops with maximum trip count are considered bounded, any other cycle not.
3255static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
3256 ScalarEvolution *SE =
3257 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
3258 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
3259 // If either SCEV or LoopInfo is not available for the function then we assume
3260 // any cycle to be unbounded cycle.
3261 // We use scc_iterator which uses Tarjan algorithm to find all the maximal
3262 // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
3263 if (!SE || !LI) {
3264 for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
3265 if (SCCI.hasCycle())
3266 return true;
3267 return false;
3268 }
3269
3270 // If there's irreducible control, the function may contain non-loop cycles.
3272 return true;
3273
3274 // Any loop that does not have a max trip count is considered unbounded cycle.
3275 for (auto *L : LI->getLoopsInPreorder()) {
3276 if (!SE->getSmallConstantMaxTripCount(L))
3277 return true;
3278 }
3279 return false;
3280}
3281
3282struct AAWillReturnImpl : public AAWillReturn {
3283 AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
3284 : AAWillReturn(IRP, A) {}
3285
3286 void initialize(Attributor &A) override {
3287 bool IsKnown;
3289 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
3290 (void)IsKnown;
3291 }
3292
3293 /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
3294 bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) {
3295 if (!A.hasAttr(getIRPosition(), {Attribute::MustProgress}))
3296 return false;
3297
3298 bool IsKnown;
3299 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3300 return IsKnown || !KnownOnly;
3301 return false;
3302 }
3303
3304 ChangeStatus updateImpl(Attributor &A) override {
3305 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
3306 return ChangeStatus::UNCHANGED;
3307
3308 auto CheckForWillReturn = [&](Instruction &I) {
3310 bool IsKnown;
3312 A, this, IPos, DepClassTy::REQUIRED, IsKnown)) {
3313 if (IsKnown)
3314 return true;
3315 } else {
3316 return false;
3317 }
3318 bool IsKnownNoRecurse;
3320 A, this, IPos, DepClassTy::REQUIRED, IsKnownNoRecurse);
3321 };
3322
3323 bool UsedAssumedInformation = false;
3324 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this,
3325 UsedAssumedInformation))
3326 return indicatePessimisticFixpoint();
3327
3328 auto CheckForVolatile = [&](Instruction &I) {
3329 // Volatile operations are not willreturn.
3330 return !I.isVolatile();
3331 };
3332 if (!A.checkForAllInstructions(CheckForVolatile, *this,
3333 {Instruction::Load, Instruction::Store,
3334 Instruction::AtomicCmpXchg,
3335 Instruction::AtomicRMW},
3336 UsedAssumedInformation))
3337 return indicatePessimisticFixpoint();
3338
3339 return ChangeStatus::UNCHANGED;
3340 }
3341
3342 const std::string getAsStr(Attributor *A) const override {
3343 return getAssumed() ? "willreturn" : "may-noreturn";
3344 }
3345};
3346
3347struct AAWillReturnFunction final : AAWillReturnImpl {
3348 AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
3349 : AAWillReturnImpl(IRP, A) {}
3350
3351 void initialize(Attributor &A) override {
3352 AAWillReturnImpl::initialize(A);
3353
3354 Function *F = getAnchorScope();
3355 assert(F && "Did expect an anchor function");
3356 if (F->isDeclaration() || mayContainUnboundedCycle(*F, A))
3357 indicatePessimisticFixpoint();
3358 }
3359
3360 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
3361};
3362
3363/// WillReturn attribute deduction for a call sites.
3364struct AAWillReturnCallSite final
3365 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl> {
3366 AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
3367 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl>(IRP, A) {}
3368
3369 ChangeStatus updateImpl(Attributor &A) override {
3370 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
3371 return ChangeStatus::UNCHANGED;
3372
3373 return AACalleeToCallSite::updateImpl(A);
3374 }
3375
3376 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
3377};
3378} // namespace
3379
3380/// -------------------AAIntraFnReachability Attribute--------------------------
3381
3382/// All information associated with a reachability query. This boilerplate code
3383/// is used by both AAIntraFnReachability and AAInterFnReachability, with
3384/// different \p ToTy values.
3385template <typename ToTy> struct ReachabilityQueryInfo {
3386 enum class Reachable {
3389 };
3390
3391 /// Start here,
3392 const Instruction *From = nullptr;
3393 /// reach this place,
3394 const ToTy *To = nullptr;
3395 /// without going through any of these instructions,
3397 /// and remember if it worked:
3399
3400 /// Precomputed hash for this RQI.
3401 unsigned Hash = 0;
3402
3403 unsigned computeHashValue() const {
3404 assert(Hash == 0 && "Computed hash twice!");
3407 return const_cast<ReachabilityQueryInfo<ToTy> *>(this)->Hash =
3408 detail::combineHashValue(PairDMI ::getHashValue({From, To}),
3409 InstSetDMI::getHashValue(ExclusionSet));
3410 }
3411
3413 : From(From), To(To) {}
3414
3415 /// Constructor replacement to ensure unique and stable sets are used for the
3416 /// cache.
3418 const AA::InstExclusionSetTy *ES, bool MakeUnique)
3419 : From(&From), To(&To), ExclusionSet(ES) {
3420
3421 if (!ES || ES->empty()) {
3422 ExclusionSet = nullptr;
3423 } else if (MakeUnique) {
3424 ExclusionSet = A.getInfoCache().getOrCreateUniqueBlockExecutionSet(ES);
3425 }
3426 }
3427
3430};
3431
3432namespace llvm {
3433template <typename ToTy> struct DenseMapInfo<ReachabilityQueryInfo<ToTy> *> {
3436
3437 static unsigned getHashValue(const ReachabilityQueryInfo<ToTy> *RQI) {
3438 return RQI->Hash ? RQI->Hash : RQI->computeHashValue();
3439 }
3440 static bool isEqual(const ReachabilityQueryInfo<ToTy> *LHS,
3441 const ReachabilityQueryInfo<ToTy> *RHS) {
3442 if (!PairDMI::isEqual({LHS->From, LHS->To}, {RHS->From, RHS->To}))
3443 return false;
3444 return InstSetDMI::isEqual(LHS->ExclusionSet, RHS->ExclusionSet);
3445 }
3446};
3447
3448} // namespace llvm
3449
3450namespace {
3451
3452template <typename BaseTy, typename ToTy>
3453struct CachedReachabilityAA : public BaseTy {
3454 using RQITy = ReachabilityQueryInfo<ToTy>;
3455
3456 CachedReachabilityAA(const IRPosition &IRP, Attributor &A) : BaseTy(IRP, A) {}
3457
3458 bool isQueryAA() const override { return true; }
3459
3460 ChangeStatus updateImpl(Attributor &A) override {
3461 ChangeStatus Changed = ChangeStatus::UNCHANGED;
3462 for (unsigned u = 0, e = QueryVector.size(); u < e; ++u) {
3463 RQITy *RQI = QueryVector[u];
3464 if (RQI->Result == RQITy::Reachable::No &&
3465 isReachableImpl(A, *RQI, /*IsTemporaryRQI=*/false))
3466 Changed = ChangeStatus::CHANGED;
3467 }
3468 return Changed;
3469 }
3470
3471 virtual bool isReachableImpl(Attributor &A, RQITy &RQI,
3472 bool IsTemporaryRQI) = 0;
3473
3474 bool rememberResult(Attributor &A, typename RQITy::Reachable Result,
3475 RQITy &RQI, bool UsedExclusionSet, bool IsTemporaryRQI) {
3476 RQI.Result = Result;
3477
3478 // Remove the temporary RQI from the cache.
3479 if (IsTemporaryRQI)
3480 QueryCache.erase(&RQI);
3481
3482 // Insert a plain RQI (w/o exclusion set) if that makes sense. Two options:
3483 // 1) If it is reachable, it doesn't matter if we have an exclusion set for
3484 // this query. 2) We did not use the exclusion set, potentially because
3485 // there is none.
3486 if (Result == RQITy::Reachable::Yes || !UsedExclusionSet) {
3487 RQITy PlainRQI(RQI.From, RQI.To);
3488 if (!QueryCache.count(&PlainRQI)) {
3489 RQITy *RQIPtr = new (A.Allocator) RQITy(RQI.From, RQI.To);
3490 RQIPtr->Result = Result;
3491 QueryVector.push_back(RQIPtr);
3492 QueryCache.insert(RQIPtr);
3493 }
3494 }
3495
3496 // Check if we need to insert a new permanent RQI with the exclusion set.
3497 if (IsTemporaryRQI && Result != RQITy::Reachable::Yes && UsedExclusionSet) {
3498 assert((!RQI.ExclusionSet || !RQI.ExclusionSet->empty()) &&
3499 "Did not expect empty set!");
3500 RQITy *RQIPtr = new (A.Allocator)
3501 RQITy(A, *RQI.From, *RQI.To, RQI.ExclusionSet, true);
3502 assert(RQIPtr->Result == RQITy::Reachable::No && "Already reachable?");
3503 RQIPtr->Result = Result;
3504 assert(!QueryCache.count(RQIPtr));
3505 QueryVector.push_back(RQIPtr);
3506 QueryCache.insert(RQIPtr);
3507 }
3508
3509 if (Result == RQITy::Reachable::No && IsTemporaryRQI)
3510 A.registerForUpdate(*this);
3511 return Result == RQITy::Reachable::Yes;
3512 }
3513
3514 const std::string getAsStr(Attributor *A) const override {
3515 // TODO: Return the number of reachable queries.
3516 return "#queries(" + std::to_string(QueryVector.size()) + ")";
3517 }
3518
3519 bool checkQueryCache(Attributor &A, RQITy &StackRQI,
3520 typename RQITy::Reachable &Result) {
3521 if (!this->getState().isValidState()) {
3522 Result = RQITy::Reachable::Yes;
3523 return true;
3524 }
3525
3526 // If we have an exclusion set we might be able to find our answer by
3527 // ignoring it first.
3528 if (StackRQI.ExclusionSet) {
3529 RQITy PlainRQI(StackRQI.From, StackRQI.To);
3530 auto It = QueryCache.find(&PlainRQI);
3531 if (It != QueryCache.end() && (*It)->Result == RQITy::Reachable::No) {
3532 Result = RQITy::Reachable::No;
3533 return true;
3534 }
3535 }
3536
3537 auto It = QueryCache.find(&StackRQI);
3538 if (It != QueryCache.end()) {
3539 Result = (*It)->Result;
3540 return true;
3541 }
3542
3543 // Insert a temporary for recursive queries. We will replace it with a
3544 // permanent entry later.
3545 QueryCache.insert(&StackRQI);
3546 return false;
3547 }
3548
3549private:
3550 SmallVector<RQITy *> QueryVector;
3551 DenseSet<RQITy *> QueryCache;
3552};
3553
3554struct AAIntraFnReachabilityFunction final
3555 : public CachedReachabilityAA<AAIntraFnReachability, Instruction> {
3556 using Base = CachedReachabilityAA<AAIntraFnReachability, Instruction>;
3557 AAIntraFnReachabilityFunction(const IRPosition &IRP, Attributor &A)
3558 : Base(IRP, A) {
3559 DT = A.getInfoCache().getAnalysisResultForFunction<DominatorTreeAnalysis>(
3560 *IRP.getAssociatedFunction());
3561 }
3562
3563 bool isAssumedReachable(
3564 Attributor &A, const Instruction &From, const Instruction &To,
3565 const AA::InstExclusionSetTy *ExclusionSet) const override {
3566 auto *NonConstThis = const_cast<AAIntraFnReachabilityFunction *>(this);
3567 if (&From == &To)
3568 return true;
3569
3570 RQITy StackRQI(A, From, To, ExclusionSet, false);
3571 RQITy::Reachable Result;
3572 if (!NonConstThis->checkQueryCache(A, StackRQI, Result))
3573 return NonConstThis->isReachableImpl(A, StackRQI,
3574 /*IsTemporaryRQI=*/true);
3575 return Result == RQITy::Reachable::Yes;
3576 }
3577
3578 ChangeStatus updateImpl(Attributor &A) override {
3579 // We only depend on liveness. DeadEdges is all we care about, check if any
3580 // of them changed.
3581 auto *LivenessAA =
3582 A.getAAFor<AAIsDead>(*this, getIRPosition(), DepClassTy::OPTIONAL);
3583 if (LivenessAA &&
3584 llvm::all_of(DeadEdges,
3585 [&](const auto &DeadEdge) {
3586 return LivenessAA->isEdgeDead(DeadEdge.first,
3587 DeadEdge.second);
3588 }) &&
3589 llvm::all_of(DeadBlocks, [&](const BasicBlock *BB) {
3590 return LivenessAA->isAssumedDead(BB);
3591 })) {
3592 return ChangeStatus::UNCHANGED;
3593 }
3594 DeadEdges.clear();
3595 DeadBlocks.clear();
3596 return Base::updateImpl(A);
3597 }
3598
3599 bool isReachableImpl(Attributor &A, RQITy &RQI,
3600 bool IsTemporaryRQI) override {
3601 const Instruction *Origin = RQI.From;
3602 bool UsedExclusionSet = false;
3603
3604 auto WillReachInBlock = [&](const Instruction &From, const Instruction &To,
3605 const AA::InstExclusionSetTy *ExclusionSet) {
3606 const Instruction *IP = &From;
3607 while (IP && IP != &To) {
3608 if (ExclusionSet && IP != Origin && ExclusionSet->count(IP)) {
3609 UsedExclusionSet = true;
3610 break;
3611 }
3612 IP = IP->getNextNode();
3613 }
3614 return IP == &To;
3615 };
3616
3617 const BasicBlock *FromBB = RQI.From->getParent();
3618 const BasicBlock *ToBB = RQI.To->getParent();
3619 assert(FromBB->getParent() == ToBB->getParent() &&
3620 "Not an intra-procedural query!");
3621
3622 // Check intra-block reachability, however, other reaching paths are still
3623 // possible.
3624 if (FromBB == ToBB &&
3625 WillReachInBlock(*RQI.From, *RQI.To, RQI.ExclusionSet))
3626 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3627 IsTemporaryRQI);
3628
3629 // Check if reaching the ToBB block is sufficient or if even that would not
3630 // ensure reaching the target. In the latter case we are done.
3631 if (!WillReachInBlock(ToBB->front(), *RQI.To, RQI.ExclusionSet))
3632 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3633 IsTemporaryRQI);
3634
3635 const Function *Fn = FromBB->getParent();
3636 SmallPtrSet<const BasicBlock *, 16> ExclusionBlocks;
3637 if (RQI.ExclusionSet)
3638 for (auto *I : *RQI.ExclusionSet)
3639 if (I->getFunction() == Fn)
3640 ExclusionBlocks.insert(I->getParent());
3641
3642 // Check if we make it out of the FromBB block at all.
3643 if (ExclusionBlocks.count(FromBB) &&
3644 !WillReachInBlock(*RQI.From, *FromBB->getTerminator(),
3645 RQI.ExclusionSet))
3646 return rememberResult(A, RQITy::Reachable::No, RQI, true, IsTemporaryRQI);
3647
3648 auto *LivenessAA =
3649 A.getAAFor<AAIsDead>(*this, getIRPosition(), DepClassTy::OPTIONAL);
3650 if (LivenessAA && LivenessAA->isAssumedDead(ToBB)) {
3651 DeadBlocks.insert(ToBB);
3652 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3653 IsTemporaryRQI);
3654 }
3655
3656 SmallPtrSet<const BasicBlock *, 16> Visited;
3658 Worklist.push_back(FromBB);
3659
3660 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> LocalDeadEdges;
3661 while (!Worklist.empty()) {
3662 const BasicBlock *BB = Worklist.pop_back_val();
3663 if (!Visited.insert(BB).second)
3664 continue;
3665 for (const BasicBlock *SuccBB : successors(BB)) {
3666 if (LivenessAA && LivenessAA->isEdgeDead(BB, SuccBB)) {
3667 LocalDeadEdges.insert({BB, SuccBB});
3668 continue;
3669 }
3670 // We checked before if we just need to reach the ToBB block.
3671 if (SuccBB == ToBB)
3672 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3673 IsTemporaryRQI);
3674 if (DT && ExclusionBlocks.empty() && DT->dominates(BB, ToBB))
3675 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3676 IsTemporaryRQI);
3677
3678 if (ExclusionBlocks.count(SuccBB)) {
3679 UsedExclusionSet = true;
3680 continue;
3681 }
3682 Worklist.push_back(SuccBB);
3683 }
3684 }
3685
3686 DeadEdges.insert_range(LocalDeadEdges);
3687 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3688 IsTemporaryRQI);
3689 }
3690
3691 void trackStatistics() const override {}
3692
3693private:
3694 // Set of assumed dead blocks we used in the last query. If any changes we
3695 // update the state.
3696 DenseSet<const BasicBlock *> DeadBlocks;
3697
3698 // Set of assumed dead edges we used in the last query. If any changes we
3699 // update the state.
3700 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> DeadEdges;
3701
3702 /// The dominator tree of the function to short-circuit reasoning.
3703 const DominatorTree *DT = nullptr;
3704};
3705} // namespace
3706
3707/// ------------------------ NoAlias Argument Attribute ------------------------
3708
3710 Attribute::AttrKind ImpliedAttributeKind,
3711 bool IgnoreSubsumingPositions) {
3712 assert(ImpliedAttributeKind == Attribute::NoAlias &&
3713 "Unexpected attribute kind");
3714 Value *Val = &IRP.getAssociatedValue();
3716 if (isa<AllocaInst>(Val))
3717 return true;
3718 } else {
3719 IgnoreSubsumingPositions = true;
3720 }
3721
3722 if (isa<UndefValue>(Val))
3723 return true;
3724
3725 if (isa<ConstantPointerNull>(Val) &&
3728 return true;
3729
3730 if (A.hasAttr(IRP, {Attribute::ByVal, Attribute::NoAlias},
3731 IgnoreSubsumingPositions, Attribute::NoAlias))
3732 return true;
3733
3734 return false;
3735}
3736
3737namespace {
3738struct AANoAliasImpl : AANoAlias {
3739 AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
3740 assert(getAssociatedType()->isPointerTy() &&
3741 "Noalias is a pointer attribute");
3742 }
3743
3744 const std::string getAsStr(Attributor *A) const override {
3745 return getAssumed() ? "noalias" : "may-alias";
3746 }
3747};
3748
3749/// NoAlias attribute for a floating value.
3750struct AANoAliasFloating final : AANoAliasImpl {
3751 AANoAliasFloating(const IRPosition &IRP, Attributor &A)
3752 : AANoAliasImpl(IRP, A) {}
3753
3754 ChangeStatus updateImpl(Attributor &A) override {
3755 // TODO: Implement this.
3756 return indicatePessimisticFixpoint();
3757 }
3758
3759 void trackStatistics() const override {
3761 }
3762};
3763
3764/// NoAlias attribute for an argument.
3765struct AANoAliasArgument final
3766 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3767 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3768 AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3769
3770 ChangeStatus updateImpl(Attributor &A) override {
3771 // We have to make sure no-alias on the argument does not break
3772 // synchronization when this is a callback argument, see also [1] below.
3773 // If synchronization cannot be affected, we delegate to the base updateImpl
3774 // function, otherwise we give up for now.
3775
3776 // If the function is no-sync, no-alias cannot break synchronization.
3777 bool IsKnownNoSycn;
3779 A, this, IRPosition::function_scope(getIRPosition()),
3780 DepClassTy::OPTIONAL, IsKnownNoSycn))
3781 return Base::updateImpl(A);
3782
3783 // If the argument is read-only, no-alias cannot break synchronization.
3784 bool IsKnown;
3785 if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3786 return Base::updateImpl(A);
3787
3788 // If the argument is never passed through callbacks, no-alias cannot break
3789 // synchronization.
3790 bool UsedAssumedInformation = false;
3791 if (A.checkForAllCallSites(
3792 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
3793 true, UsedAssumedInformation))
3794 return Base::updateImpl(A);
3795
3796 // TODO: add no-alias but make sure it doesn't break synchronization by
3797 // introducing fake uses. See:
3798 // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
3799 // International Workshop on OpenMP 2018,
3800 // http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
3801
3802 return indicatePessimisticFixpoint();
3803 }
3804
3805 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
3806};
3807
3808struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3809 AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
3810 : AANoAliasImpl(IRP, A) {}
3811
3812 /// Determine if the underlying value may alias with the call site argument
3813 /// \p OtherArgNo of \p ICS (= the underlying call site).
3814 bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
3815 const AAMemoryBehavior &MemBehaviorAA,
3816 const CallBase &CB, unsigned OtherArgNo) {
3817 // We do not need to worry about aliasing with the underlying IRP.
3818 if (this->getCallSiteArgNo() == (int)OtherArgNo)
3819 return false;
3820
3821 // If it is not a pointer or pointer vector we do not alias.
3822 const Value *ArgOp = CB.getArgOperand(OtherArgNo);
3823 if (!ArgOp->getType()->isPtrOrPtrVectorTy())
3824 return false;
3825
3826 auto *CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
3827 *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE);
3828
3829 // If the argument is readnone, there is no read-write aliasing.
3830 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadNone()) {
3831 A.recordDependence(*CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3832 return false;
3833 }
3834
3835 // If the argument is readonly and the underlying value is readonly, there
3836 // is no read-write aliasing.
3837 bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
3838 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadOnly() &&
3839 IsReadOnly) {
3840 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3841 A.recordDependence(*CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3842 return false;
3843 }
3844
3845 // We have to utilize actual alias analysis queries so we need the object.
3846 if (!AAR)
3847 AAR = A.getInfoCache().getAnalysisResultForFunction<AAManager>(
3848 *getAnchorScope());
3849
3850 // Try to rule it out at the call site.
3851 bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
3852 LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
3853 "callsite arguments: "
3854 << getAssociatedValue() << " " << *ArgOp << " => "
3855 << (IsAliasing ? "" : "no-") << "alias \n");
3856
3857 return IsAliasing;
3858 }
3859
3860 bool isKnownNoAliasDueToNoAliasPreservation(
3861 Attributor &A, AAResults *&AAR, const AAMemoryBehavior &MemBehaviorAA) {
3862 // We can deduce "noalias" if the following conditions hold.
3863 // (i) Associated value is assumed to be noalias in the definition.
3864 // (ii) Associated value is assumed to be no-capture in all the uses
3865 // possibly executed before this callsite.
3866 // (iii) There is no other pointer argument which could alias with the
3867 // value.
3868
3869 const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3870 const Function *ScopeFn = VIRP.getAnchorScope();
3871 // Check whether the value is captured in the scope using AANoCapture.
3872 // Look at CFG and check only uses possibly executed before this
3873 // callsite.
3874 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
3875 Instruction *UserI = cast<Instruction>(U.getUser());
3876
3877 // If UserI is the curr instruction and there is a single potential use of
3878 // the value in UserI we allow the use.
3879 // TODO: We should inspect the operands and allow those that cannot alias
3880 // with the value.
3881 if (UserI == getCtxI() && UserI->getNumOperands() == 1)
3882 return true;
3883
3884 if (ScopeFn) {
3885 if (auto *CB = dyn_cast<CallBase>(UserI)) {
3886 if (CB->isArgOperand(&U)) {
3887
3888 unsigned ArgNo = CB->getArgOperandNo(&U);
3889
3890 bool IsKnownNoCapture;
3892 A, this, IRPosition::callsite_argument(*CB, ArgNo),
3893 DepClassTy::OPTIONAL, IsKnownNoCapture))
3894 return true;
3895 }
3896 }
3897
3899 A, *UserI, *getCtxI(), *this, /* ExclusionSet */ nullptr,
3900 [ScopeFn](const Function &Fn) { return &Fn != ScopeFn; }))
3901 return true;
3902 }
3903
3904 // TODO: We should track the capturing uses in AANoCapture but the problem
3905 // is CGSCC runs. For those we would need to "allow" AANoCapture for
3906 // a value in the module slice.
3907 // TODO(captures): Make this more precise.
3908 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
3909 if (capturesNothing(CI))
3910 return true;
3911 if (CI.isPassthrough()) {
3912 Follow = true;
3913 return true;
3914 }
3915 LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *UserI << "\n");
3916 return false;
3917 };
3918
3919 bool IsKnownNoCapture;
3920 const AANoCapture *NoCaptureAA = nullptr;
3921 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
3922 A, this, VIRP, DepClassTy::NONE, IsKnownNoCapture, false, &NoCaptureAA);
3923 if (!IsAssumedNoCapture &&
3924 (!NoCaptureAA || !NoCaptureAA->isAssumedNoCaptureMaybeReturned())) {
3925 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
3926 LLVM_DEBUG(
3927 dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
3928 << " cannot be noalias as it is potentially captured\n");
3929 return false;
3930 }
3931 }
3932 if (NoCaptureAA)
3933 A.recordDependence(*NoCaptureAA, *this, DepClassTy::OPTIONAL);
3934
3935 // Check there is no other pointer argument which could alias with the
3936 // value passed at this call site.
3937 // TODO: AbstractCallSite
3938 const auto &CB = cast<CallBase>(getAnchorValue());
3939 for (unsigned OtherArgNo = 0; OtherArgNo < CB.arg_size(); OtherArgNo++)
3940 if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
3941 return false;
3942
3943 return true;
3944 }
3945
3946 ChangeStatus updateImpl(Attributor &A) override {
3947 // If the argument is readnone we are done as there are no accesses via the
3948 // argument.
3949 auto *MemBehaviorAA =
3950 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
3951 if (MemBehaviorAA && MemBehaviorAA->isAssumedReadNone()) {
3952 A.recordDependence(*MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3953 return ChangeStatus::UNCHANGED;
3954 }
3955
3956 bool IsKnownNoAlias;
3957 const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3959 A, this, VIRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
3960 LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
3961 << " is not no-alias at the definition\n");
3962 return indicatePessimisticFixpoint();
3963 }
3964
3965 AAResults *AAR = nullptr;
3966 if (MemBehaviorAA &&
3967 isKnownNoAliasDueToNoAliasPreservation(A, AAR, *MemBehaviorAA)) {
3968 LLVM_DEBUG(
3969 dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
3970 return ChangeStatus::UNCHANGED;
3971 }
3972
3973 return indicatePessimisticFixpoint();
3974 }
3975
3976 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
3977};
3978
3979/// NoAlias attribute for function return value.
3980struct AANoAliasReturned final : AANoAliasImpl {
3981 AANoAliasReturned(const IRPosition &IRP, Attributor &A)
3982 : AANoAliasImpl(IRP, A) {}
3983
3984 ChangeStatus updateImpl(Attributor &A) override {
3985
3986 auto CheckReturnValue = [&](Value &RV) -> bool {
3987 if (Constant *C = dyn_cast<Constant>(&RV))
3988 if (C->isNullValue() || isa<UndefValue>(C))
3989 return true;
3990
3991 /// For now, we can only deduce noalias if we have call sites.
3992 /// FIXME: add more support.
3993 if (!isa<CallBase>(&RV))
3994 return false;
3995
3996 const IRPosition &RVPos = IRPosition::value(RV);
3997 bool IsKnownNoAlias;
3999 A, this, RVPos, DepClassTy::REQUIRED, IsKnownNoAlias))
4000 return false;
4001
4002 bool IsKnownNoCapture;
4003 const AANoCapture *NoCaptureAA = nullptr;
4004 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
4005 A, this, RVPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
4006 &NoCaptureAA);
4007 return IsAssumedNoCapture ||
4008 (NoCaptureAA && NoCaptureAA->isAssumedNoCaptureMaybeReturned());
4009 };
4010
4011 if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
4012 return indicatePessimisticFixpoint();
4013
4014 return ChangeStatus::UNCHANGED;
4015 }
4016
4017 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
4018};
4019
4020/// NoAlias attribute deduction for a call site return value.
4021struct AANoAliasCallSiteReturned final
4022 : AACalleeToCallSite<AANoAlias, AANoAliasImpl> {
4023 AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
4024 : AACalleeToCallSite<AANoAlias, AANoAliasImpl>(IRP, A) {}
4025
4026 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
4027};
4028} // namespace
4029
4030/// -------------------AAIsDead Function Attribute-----------------------
4031
4032namespace {
4033struct AAIsDeadValueImpl : public AAIsDead {
4034 AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
4035
4036 bool isAssumedDead() const override { return isAssumed(IS_DEAD); }
4037
4038 bool isKnownDead() const override { return isKnown(IS_DEAD); }
4039
4040 bool isAssumedDead(const BasicBlock *BB) const override { return false; }
4041
4042 bool isKnownDead(const BasicBlock *BB) const override { return false; }
4043
4044 bool isAssumedDead(const Instruction *I) const override {
4045 return I == getCtxI() && isAssumedDead();
4046 }
4047
4048 bool isKnownDead(const Instruction *I) const override {
4049 return isAssumedDead(I) && isKnownDead();
4050 }
4051
4052 const std::string getAsStr(Attributor *A) const override {
4053 return isAssumedDead() ? "assumed-dead" : "assumed-live";
4054 }
4055
4056 /// Check if all uses are assumed dead.
4057 bool areAllUsesAssumedDead(Attributor &A, Value &V) {
4058 // Callers might not check the type, void has no uses.
4059 if (V.getType()->isVoidTy() || V.use_empty())
4060 return true;
4061
4062 // If we replace a value with a constant there are no uses left afterwards.
4063 if (!isa<Constant>(V)) {
4064 if (auto *I = dyn_cast<Instruction>(&V))
4065 if (!A.isRunOn(*I->getFunction()))
4066 return false;
4067 bool UsedAssumedInformation = false;
4068 std::optional<Constant *> C =
4069 A.getAssumedConstant(V, *this, UsedAssumedInformation);
4070 if (!C || *C)
4071 return true;
4072 }
4073
4074 auto UsePred = [&](const Use &U, bool &Follow) { return false; };
4075 // Explicitly set the dependence class to required because we want a long
4076 // chain of N dependent instructions to be considered live as soon as one is
4077 // without going through N update cycles. This is not required for
4078 // correctness.
4079 return A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ false,
4080 DepClassTy::REQUIRED,
4081 /* IgnoreDroppableUses */ false);
4082 }
4083
4084 /// Determine if \p I is assumed to be side-effect free.
4085 bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
4087 return true;
4088
4089 if (!I->isTerminator() && !I->mayHaveSideEffects())
4090 return true;
4091
4092 auto *CB = dyn_cast<CallBase>(I);
4093 if (!CB || isa<IntrinsicInst>(CB))
4094 return false;
4095
4096 const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
4097
4098 bool IsKnownNoUnwind;
4100 A, this, CallIRP, DepClassTy::OPTIONAL, IsKnownNoUnwind))
4101 return false;
4102
4103 bool IsKnown;
4104 return AA::isAssumedReadOnly(A, CallIRP, *this, IsKnown);
4105 }
4106};
4107
4108struct AAIsDeadFloating : public AAIsDeadValueImpl {
4109 AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
4110 : AAIsDeadValueImpl(IRP, A) {}
4111
4112 void initialize(Attributor &A) override {
4113 AAIsDeadValueImpl::initialize(A);
4114
4115 if (isa<UndefValue>(getAssociatedValue())) {
4116 indicatePessimisticFixpoint();
4117 return;
4118 }
4119
4120 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4121 if (!isAssumedSideEffectFree(A, I)) {
4123 indicatePessimisticFixpoint();
4124 else
4125 removeAssumedBits(HAS_NO_EFFECT);
4126 }
4127 }
4128
4129 bool isDeadFence(Attributor &A, FenceInst &FI) {
4130 const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>(
4131 IRPosition::function(*FI.getFunction()), *this, DepClassTy::NONE);
4132 if (!ExecDomainAA || !ExecDomainAA->isNoOpFence(FI))
4133 return false;
4134 A.recordDependence(*ExecDomainAA, *this, DepClassTy::OPTIONAL);
4135 return true;
4136 }
4137
4138 bool isDeadStore(Attributor &A, StoreInst &SI,
4139 SmallSetVector<Instruction *, 8> *AssumeOnlyInst = nullptr) {
4140 // Lang ref now states volatile store is not UB/dead, let's skip them.
4141 if (SI.isVolatile())
4142 return false;
4143
4144 // If we are collecting assumes to be deleted we are in the manifest stage.
4145 // It's problematic to collect the potential copies again now so we use the
4146 // cached ones.
4147 bool UsedAssumedInformation = false;
4148 if (!AssumeOnlyInst) {
4149 PotentialCopies.clear();
4150 if (!AA::getPotentialCopiesOfStoredValue(A, SI, PotentialCopies, *this,
4151 UsedAssumedInformation)) {
4152 LLVM_DEBUG(
4153 dbgs()
4154 << "[AAIsDead] Could not determine potential copies of store!\n");
4155 return false;
4156 }
4157 }
4158 LLVM_DEBUG(dbgs() << "[AAIsDead] Store has " << PotentialCopies.size()
4159 << " potential copies.\n");
4160
4161 InformationCache &InfoCache = A.getInfoCache();
4162 return llvm::all_of(PotentialCopies, [&](Value *V) {
4163 if (A.isAssumedDead(IRPosition::value(*V), this, nullptr,
4164 UsedAssumedInformation))
4165 return true;
4166 if (auto *LI = dyn_cast<LoadInst>(V)) {
4167 if (llvm::all_of(LI->uses(), [&](const Use &U) {
4168 auto &UserI = cast<Instruction>(*U.getUser());
4169 if (InfoCache.isOnlyUsedByAssume(UserI)) {
4170 if (AssumeOnlyInst)
4171 AssumeOnlyInst->insert(&UserI);
4172 return true;
4173 }
4174 return A.isAssumedDead(U, this, nullptr, UsedAssumedInformation);
4175 })) {
4176 return true;
4177 }
4178 }
4179 LLVM_DEBUG(dbgs() << "[AAIsDead] Potential copy " << *V
4180 << " is assumed live!\n");
4181 return false;
4182 });
4183 }
4184
4185 const std::string getAsStr(Attributor *A) const override {
4186 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4188 if (isValidState())
4189 return "assumed-dead-store";
4191 if (isValidState())
4192 return "assumed-dead-fence";
4193 return AAIsDeadValueImpl::getAsStr(A);
4194 }
4195
4196 ChangeStatus updateImpl(Attributor &A) override {
4197 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
4198 if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
4199 if (!isDeadStore(A, *SI))
4200 return indicatePessimisticFixpoint();
4201 } else if (auto *FI = dyn_cast_or_null<FenceInst>(I)) {
4202 if (!isDeadFence(A, *FI))
4203 return indicatePessimisticFixpoint();
4204 } else {
4205 if (!isAssumedSideEffectFree(A, I))
4206 return indicatePessimisticFixpoint();
4207 if (!areAllUsesAssumedDead(A, getAssociatedValue()))
4208 return indicatePessimisticFixpoint();
4209 }
4211 }
4212
4213 bool isRemovableStore() const override {
4214 return isAssumed(IS_REMOVABLE) && isa<StoreInst>(&getAssociatedValue());
4215 }
4216
4217 ChangeStatus manifest(Attributor &A) override {
4218 Value &V = getAssociatedValue();
4219 if (auto *I = dyn_cast<Instruction>(&V)) {
4220 // If we get here we basically know the users are all dead. We check if
4221 // isAssumedSideEffectFree returns true here again because it might not be
4222 // the case and only the users are dead but the instruction (=call) is
4223 // still needed.
4224 if (auto *SI = dyn_cast<StoreInst>(I)) {
4225 SmallSetVector<Instruction *, 8> AssumeOnlyInst;
4226 bool IsDead = isDeadStore(A, *SI, &AssumeOnlyInst);
4227 (void)IsDead;
4228 assert(IsDead && "Store was assumed to be dead!");
4229 A.deleteAfterManifest(*I);
4230 for (size_t i = 0; i < AssumeOnlyInst.size(); ++i) {
4231 Instruction *AOI = AssumeOnlyInst[i];
4232 for (Instruction *Usr : AOI->users())
4233 AssumeOnlyInst.insert(Usr);
4234 A.deleteAfterManifest(*AOI);
4235 }
4236 return ChangeStatus::CHANGED;
4237 }
4238 if (auto *FI = dyn_cast<FenceInst>(I)) {
4239 assert(isDeadFence(A, *FI));
4240 A.deleteAfterManifest(*FI);
4241 return ChangeStatus::CHANGED;
4242 }
4243 if (isAssumedSideEffectFree(A, I) && !I->isTerminator()) {
4244 A.deleteAfterManifest(*I);
4245 return ChangeStatus::CHANGED;
4246 }
4247 }
4249 }
4250
4251 void trackStatistics() const override {
4253 }
4254
4255private:
4256 // The potential copies of a dead store, used for deletion during manifest.
4257 SmallSetVector<Value *, 4> PotentialCopies;
4258};
4259
4260struct AAIsDeadArgument : public AAIsDeadFloating {
4261 AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
4262 : AAIsDeadFloating(IRP, A) {}
4263
4264 ChangeStatus manifest(Attributor &A) override {
4265 Argument &Arg = *getAssociatedArgument();
4266 if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
4267 if (A.registerFunctionSignatureRewrite(
4268 Arg, /* ReplacementTypes */ {},
4271 return ChangeStatus::CHANGED;
4272 }
4273 return ChangeStatus::UNCHANGED;
4274 }
4275
4276 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
4277};
4278
4279struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
4280 AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
4281 : AAIsDeadValueImpl(IRP, A) {}
4282
4283 void initialize(Attributor &A) override {
4284 AAIsDeadValueImpl::initialize(A);
4285 if (isa<UndefValue>(getAssociatedValue()))
4286 indicatePessimisticFixpoint();
4287 }
4288
4289 ChangeStatus updateImpl(Attributor &A) override {
4290 // TODO: Once we have call site specific value information we can provide
4291 // call site specific liveness information and then it makes
4292 // sense to specialize attributes for call sites arguments instead of
4293 // redirecting requests to the callee argument.
4294 Argument *Arg = getAssociatedArgument();
4295 if (!Arg)
4296 return indicatePessimisticFixpoint();
4297 const IRPosition &ArgPos = IRPosition::argument(*Arg);
4298 auto *ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED);
4299 if (!ArgAA)
4300 return indicatePessimisticFixpoint();
4301 return clampStateAndIndicateChange(getState(), ArgAA->getState());
4302 }
4303
4304 ChangeStatus manifest(Attributor &A) override {
4305 CallBase &CB = cast<CallBase>(getAnchorValue());
4306 Use &U = CB.getArgOperandUse(getCallSiteArgNo());
4307 assert(!isa<UndefValue>(U.get()) &&
4308 "Expected undef values to be filtered out!");
4309 UndefValue &UV = *UndefValue::get(U->getType());
4310 if (A.changeUseAfterManifest(U, UV))
4311 return ChangeStatus::CHANGED;
4312 return ChangeStatus::UNCHANGED;
4313 }
4314
4315 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
4316};
4317
4318struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
4319 AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
4320 : AAIsDeadFloating(IRP, A) {}
4321
4322 bool isAssumedDead() const override {
4323 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
4324 }
4325
4326 void initialize(Attributor &A) override {
4327 AAIsDeadFloating::initialize(A);
4328 if (isa<UndefValue>(getAssociatedValue())) {
4329 indicatePessimisticFixpoint();
4330 return;
4331 }
4332
4333 // We track this separately as a secondary state.
4334 IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
4335 }
4336
4337 ChangeStatus updateImpl(Attributor &A) override {
4338 ChangeStatus Changed = ChangeStatus::UNCHANGED;
4339 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
4340 IsAssumedSideEffectFree = false;
4341 Changed = ChangeStatus::CHANGED;
4342 }
4343 if (!areAllUsesAssumedDead(A, getAssociatedValue()))
4344 return indicatePessimisticFixpoint();
4345 return Changed;
4346 }
4347
4348 void trackStatistics() const override {
4349 if (IsAssumedSideEffectFree)
4351 else
4352 STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
4353 }
4354
4355 const std::string getAsStr(Attributor *A) const override {
4356 return isAssumedDead()
4357 ? "assumed-dead"
4358 : (getAssumed() ? "assumed-dead-users" : "assumed-live");
4359 }
4360
4361private:
4362 bool IsAssumedSideEffectFree = true;
4363};
4364
4365struct AAIsDeadReturned : public AAIsDeadValueImpl {
4366 AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
4367 : AAIsDeadValueImpl(IRP, A) {}
4368
4369 ChangeStatus updateImpl(Attributor &A) override {
4370
4371 bool UsedAssumedInformation = false;
4372 A.checkForAllInstructions([](Instruction &) { return true; }, *this,
4373 {Instruction::Ret}, UsedAssumedInformation);
4374
4375 auto PredForCallSite = [&](AbstractCallSite ACS) {
4376 if (ACS.isCallbackCall() || !ACS.getInstruction())
4377 return false;
4378 return areAllUsesAssumedDead(A, *ACS.getInstruction());
4379 };
4380
4381 if (!A.checkForAllCallSites(PredForCallSite, *this, true,
4382 UsedAssumedInformation))
4383 return indicatePessimisticFixpoint();
4384
4385 return ChangeStatus::UNCHANGED;
4386 }
4387
4388 ChangeStatus manifest(Attributor &A) override {
4389 // TODO: Rewrite the signature to return void?
4390 bool AnyChange = false;
4391 UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
4392 auto RetInstPred = [&](Instruction &I) {
4393 ReturnInst &RI = cast<ReturnInst>(I);
4395 AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
4396 return true;
4397 };
4398 bool UsedAssumedInformation = false;
4399 A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
4400 UsedAssumedInformation);
4401 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
4402 }
4403
4404 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
4405};
4406
4407struct AAIsDeadFunction : public AAIsDead {
4408 AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
4409
4410 void initialize(Attributor &A) override {
4411 Function *F = getAnchorScope();
4412 assert(F && "Did expect an anchor function");
4413 if (!isAssumedDeadInternalFunction(A)) {
4414 ToBeExploredFrom.insert(&F->getEntryBlock().front());
4415 assumeLive(A, F->getEntryBlock());
4416 }
4417 }
4418
4419 bool isAssumedDeadInternalFunction(Attributor &A) {
4420 if (!getAnchorScope()->hasLocalLinkage())
4421 return false;
4422 // An AA that will not be updated is fixed pessimistically right after
4423 // initialization, so an assumed-dead result would be discarded. Checking
4424 // the call sites recursively initializes the liveness of every internal
4425 // caller, which in CGSCC cleanup repeats for each callee SCC.
4426 if (!A.shouldUpdateAA<AAIsDead>(getIRPosition()))
4427 return false;
4428 bool UsedAssumedInformation = false;
4429 return A.checkForAllCallSites([](AbstractCallSite) { return false; }, *this,
4430 true, UsedAssumedInformation);
4431 }
4432
4433 const std::string getAsStr(Attributor *A) const override {
4434 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
4435 std::to_string(getAnchorScope()->size()) + "][#TBEP " +
4436 std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
4437 std::to_string(KnownDeadEnds.size()) + "]";
4438 }
4439
4440 ChangeStatus manifest(Attributor &A) override {
4441 assert(getState().isValidState() &&
4442 "Attempted to manifest an invalid state!");
4443
4444 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
4445 Function &F = *getAnchorScope();
4446
4447 if (AssumedLiveBlocks.empty()) {
4448 A.deleteAfterManifest(F);
4449 return ChangeStatus::CHANGED;
4450 }
4451
4452 // Flag to determine if we can change an invoke to a call assuming the
4453 // callee is nounwind. This is not possible if the personality of the
4454 // function allows to catch asynchronous exceptions.
4455 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
4456
4457 KnownDeadEnds.set_union(ToBeExploredFrom);
4458 for (const Instruction *DeadEndI : KnownDeadEnds) {
4459 auto *CB = dyn_cast<CallBase>(DeadEndI);
4460 if (!CB)
4461 continue;
4462 bool IsKnownNoReturn;
4464 A, this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL,
4465 IsKnownNoReturn);
4466 if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
4467 continue;
4468
4469 if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
4470 A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
4471 else
4472 A.changeToUnreachableAfterManifest(
4473 const_cast<Instruction *>(DeadEndI->getNextNode()));
4474 HasChanged = ChangeStatus::CHANGED;
4475 }
4476
4477 STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
4478 for (BasicBlock &BB : F)
4479 if (!AssumedLiveBlocks.count(&BB)) {
4480 A.deleteAfterManifest(BB);
4481 ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
4482 HasChanged = ChangeStatus::CHANGED;
4483 }
4484
4485 return HasChanged;
4486 }
4487
4488 ChangeStatus updateImpl(Attributor &A) override;
4489
4490 bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override {
4491 assert(From->getParent() == getAnchorScope() &&
4492 To->getParent() == getAnchorScope() &&
4493 "Used AAIsDead of the wrong function");
4494 return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
4495 }
4496
4497 void trackStatistics() const override {}
4498
4499 /// Returns true if the function is assumed dead.
4500 bool isAssumedDead() const override { return false; }
4501
4502 bool isKnownDead() const override { return false; }
4503
4504 bool isAssumedDead(const BasicBlock *BB) const override {
4505 assert(BB->getParent() == getAnchorScope() &&
4506 "BB must be in the same anchor scope function.");
4507
4508 if (!getAssumed())
4509 return false;
4510 return !AssumedLiveBlocks.count(BB);
4511 }
4512
4513 bool isKnownDead(const BasicBlock *BB) const override {
4514 return getKnown() && isAssumedDead(BB);
4515 }
4516
4517 bool isAssumedDead(const Instruction *I) const override {
4518 assert(I->getParent()->getParent() == getAnchorScope() &&
4519 "Instruction must be in the same anchor scope function.");
4520
4521 if (!getAssumed())
4522 return false;
4523
4524 // If it is not in AssumedLiveBlocks then it for sure dead.
4525 // Otherwise, it can still be after noreturn call in a live block.
4526 if (!AssumedLiveBlocks.count(I->getParent()))
4527 return true;
4528
4529 // If it is not after a liveness barrier it is live.
4530 const Instruction *PrevI = I->getPrevNode();
4531 while (PrevI) {
4532 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
4533 return true;
4534 PrevI = PrevI->getPrevNode();
4535 }
4536 return false;
4537 }
4538
4539 bool isKnownDead(const Instruction *I) const override {
4540 return getKnown() && isAssumedDead(I);
4541 }
4542
4543 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
4544 /// that internal function called from \p BB should now be looked at.
4545 bool assumeLive(Attributor &A, const BasicBlock &BB) {
4546 if (!AssumedLiveBlocks.insert(&BB).second)
4547 return false;
4548
4549 if (!A.isDuringDeduction())
4550 return true;
4551
4552 // We assume that all of BB is (probably) live now and if there are calls to
4553 // internal functions we will assume that those are now live as well. This
4554 // is a performance optimization for blocks with calls to a lot of internal
4555 // functions. It can however cause dead functions to be treated as live.
4556 for (const Instruction &I : BB)
4557 if (const auto *CB = dyn_cast<CallBase>(&I))
4559 if (F->hasLocalLinkage()) {
4560 LLVM_DEBUG({
4561 dbgs() << "[AAIsDead] Seeding live internal callee ";
4562 F->printAsOperand(dbgs(), /*PrintType=*/false);
4563 dbgs() << " from ";
4564 BB.getParent()->printAsOperand(dbgs(), /*PrintType=*/false);
4565 dbgs() << "\n";
4566 });
4567 A.markLiveInternalFunction(*F);
4568 }
4569 return true;
4570 }
4571
4572 /// Collection of instructions that need to be explored again, e.g., we
4573 /// did assume they do not transfer control to (one of their) successors.
4574 SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
4575
4576 /// Collection of instructions that are known to not transfer control.
4577 SmallSetVector<const Instruction *, 8> KnownDeadEnds;
4578
4579 /// Collection of all assumed live edges
4580 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
4581
4582 /// Collection of all assumed live BasicBlocks.
4583 DenseSet<const BasicBlock *> AssumedLiveBlocks;
4584};
4585
4586static bool
4587identifyAliveSuccessors(Attributor &A, const CallBase &CB,
4588 AbstractAttribute &AA,
4589 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4590 const IRPosition &IPos = IRPosition::callsite_function(CB);
4591
4592 bool IsKnownNoReturn;
4594 A, &AA, IPos, DepClassTy::OPTIONAL, IsKnownNoReturn))
4595 return !IsKnownNoReturn;
4596 if (CB.isTerminator())
4597 AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
4598 else
4599 AliveSuccessors.push_back(CB.getNextNode());
4600 return false;
4601}
4602
4603static bool
4604identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
4605 AbstractAttribute &AA,
4606 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4607 bool UsedAssumedInformation =
4608 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
4609
4610 // First, determine if we can change an invoke to a call assuming the
4611 // callee is nounwind. This is not possible if the personality of the
4612 // function allows to catch asynchronous exceptions.
4613 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
4614 AliveSuccessors.push_back(&II.getUnwindDest()->front());
4615 } else {
4616 const IRPosition &IPos = IRPosition::callsite_function(II);
4617
4618 bool IsKnownNoUnwind;
4620 A, &AA, IPos, DepClassTy::OPTIONAL, IsKnownNoUnwind)) {
4621 UsedAssumedInformation |= !IsKnownNoUnwind;
4622 } else {
4623 AliveSuccessors.push_back(&II.getUnwindDest()->front());
4624 }
4625 }
4626 return UsedAssumedInformation;
4627}
4628
4629static bool
4630identifyAliveSuccessors(Attributor &, const UncondBrInst &BI,
4631 AbstractAttribute &,
4632 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4633 AliveSuccessors.push_back(&BI.getSuccessor()->front());
4634 return false;
4635}
4636
4637static bool
4638identifyAliveSuccessors(Attributor &A, const CondBrInst &BI,
4639 AbstractAttribute &AA,
4640 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4641 bool UsedAssumedInformation = false;
4642 std::optional<Constant *> C =
4643 A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation);
4644 if (!C || isa_and_nonnull<UndefValue>(*C)) {
4645 // No value yet, assume both edges are dead.
4646 } else if (isa_and_nonnull<ConstantInt>(*C)) {
4647 const BasicBlock *SuccBB =
4648 BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue());
4649 AliveSuccessors.push_back(&SuccBB->front());
4650 } else {
4651 AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
4652 AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
4653 UsedAssumedInformation = false;
4654 }
4655 return UsedAssumedInformation;
4656}
4657
4658static bool
4659identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
4660 AbstractAttribute &AA,
4661 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4662 bool UsedAssumedInformation = false;
4664 if (!A.getAssumedSimplifiedValues(IRPosition::value(*SI.getCondition()), &AA,
4666 UsedAssumedInformation)) {
4667 // Something went wrong, assume all successors are live.
4668 for (const BasicBlock *SuccBB : successors(SI.getParent()))
4669 AliveSuccessors.push_back(&SuccBB->front());
4670 return false;
4671 }
4672
4673 if (Values.empty() ||
4674 (Values.size() == 1 &&
4675 isa_and_nonnull<UndefValue>(Values.front().getValue()))) {
4676 // No valid value yet, assume all edges are dead.
4677 return UsedAssumedInformation;
4678 }
4679
4680 Type &Ty = *SI.getCondition()->getType();
4681 SmallPtrSet<ConstantInt *, 8> Constants;
4682 auto CheckForConstantInt = [&](Value *V) {
4683 if (auto *CI = dyn_cast_if_present<ConstantInt>(AA::getWithType(*V, Ty))) {
4684 Constants.insert(CI);
4685 return true;
4686 }
4687 return false;
4688 };
4689
4690 if (!all_of(Values, [&](AA::ValueAndContext &VAC) {
4691 return CheckForConstantInt(VAC.getValue());
4692 })) {
4693 for (const BasicBlock *SuccBB : successors(SI.getParent()))
4694 AliveSuccessors.push_back(&SuccBB->front());
4695 return UsedAssumedInformation;
4696 }
4697
4698 unsigned MatchedCases = 0;
4699 for (const auto &CaseIt : SI.cases()) {
4700 if (Constants.count(CaseIt.getCaseValue())) {
4701 ++MatchedCases;
4702 AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
4703 }
4704 }
4705
4706 // If all potential values have been matched, we will not visit the default
4707 // case.
4708 if (MatchedCases < Constants.size())
4709 AliveSuccessors.push_back(&SI.getDefaultDest()->front());
4710 return UsedAssumedInformation;
4711}
4712
4713ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
4715
4716 if (AssumedLiveBlocks.empty()) {
4717 if (isAssumedDeadInternalFunction(A))
4719
4720 Function *F = getAnchorScope();
4721 ToBeExploredFrom.insert(&F->getEntryBlock().front());
4722 assumeLive(A, F->getEntryBlock());
4723 Change = ChangeStatus::CHANGED;
4724 }
4725
4726 LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
4727 << getAnchorScope()->size() << "] BBs and "
4728 << ToBeExploredFrom.size() << " exploration points and "
4729 << KnownDeadEnds.size() << " known dead ends\n");
4730
4731 // Copy and clear the list of instructions we need to explore from. It is
4732 // refilled with instructions the next update has to look at.
4733 SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
4734 ToBeExploredFrom.end());
4735 decltype(ToBeExploredFrom) NewToBeExploredFrom;
4736
4738 while (!Worklist.empty()) {
4739 const Instruction *I = Worklist.pop_back_val();
4740 LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
4741
4742 // Fast forward for uninteresting instructions. We could look for UB here
4743 // though.
4744 while (!I->isTerminator() && !isa<CallBase>(I))
4745 I = I->getNextNode();
4746
4747 AliveSuccessors.clear();
4748
4749 bool UsedAssumedInformation = false;
4750 switch (I->getOpcode()) {
4751 // TODO: look for (assumed) UB to backwards propagate "deadness".
4752 default:
4753 assert(I->isTerminator() &&
4754 "Expected non-terminators to be handled already!");
4755 for (const BasicBlock *SuccBB : successors(I->getParent()))
4756 AliveSuccessors.push_back(&SuccBB->front());
4757 break;
4758 case Instruction::Call:
4759 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
4760 *this, AliveSuccessors);
4761 break;
4762 case Instruction::Invoke:
4763 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
4764 *this, AliveSuccessors);
4765 break;
4766 case Instruction::UncondBr:
4767 UsedAssumedInformation = identifyAliveSuccessors(
4768 A, cast<UncondBrInst>(*I), *this, AliveSuccessors);
4769 break;
4770 case Instruction::CondBr:
4771 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CondBrInst>(*I),
4772 *this, AliveSuccessors);
4773 break;
4774 case Instruction::Switch:
4775 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
4776 *this, AliveSuccessors);
4777 break;
4778 }
4779
4780 if (UsedAssumedInformation) {
4781 NewToBeExploredFrom.insert(I);
4782 } else if (AliveSuccessors.empty() ||
4783 (I->isTerminator() &&
4784 AliveSuccessors.size() < I->getNumSuccessors())) {
4785 if (KnownDeadEnds.insert(I))
4786 Change = ChangeStatus::CHANGED;
4787 }
4788
4789 LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
4790 << AliveSuccessors.size() << " UsedAssumedInformation: "
4791 << UsedAssumedInformation << "\n");
4792
4793 for (const Instruction *AliveSuccessor : AliveSuccessors) {
4794 if (!I->isTerminator()) {
4795 assert(AliveSuccessors.size() == 1 &&
4796 "Non-terminator expected to have a single successor!");
4797 Worklist.push_back(AliveSuccessor);
4798 } else {
4799 // record the assumed live edge
4800 auto Edge = std::make_pair(I->getParent(), AliveSuccessor->getParent());
4801 if (AssumedLiveEdges.insert(Edge).second)
4802 Change = ChangeStatus::CHANGED;
4803 if (assumeLive(A, *AliveSuccessor->getParent()))
4804 Worklist.push_back(AliveSuccessor);
4805 }
4806 }
4807 }
4808
4809 // Check if the content of ToBeExploredFrom changed, ignore the order.
4810 if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4811 llvm::any_of(NewToBeExploredFrom, [&](const Instruction *I) {
4812 return !ToBeExploredFrom.count(I);
4813 })) {
4814 Change = ChangeStatus::CHANGED;
4815 ToBeExploredFrom = std::move(NewToBeExploredFrom);
4816 }
4817
4818 // If we know everything is live there is no need to query for liveness.
4819 // Instead, indicating a pessimistic fixpoint will cause the state to be
4820 // "invalid" and all queries to be answered conservatively without lookups.
4821 // To be in this state we have to (1) finished the exploration and (3) not
4822 // discovered any non-trivial dead end and (2) not ruled unreachable code
4823 // dead.
4824 if (ToBeExploredFrom.empty() &&
4825 getAnchorScope()->size() == AssumedLiveBlocks.size() &&
4826 llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
4827 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4828 }))
4829 return indicatePessimisticFixpoint();
4830 return Change;
4831}
4832
4833/// Liveness information for a call sites.
4834struct AAIsDeadCallSite final : AAIsDeadFunction {
4835 AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
4836 : AAIsDeadFunction(IRP, A) {}
4837
4838 void initialize(Attributor &A) override {
4839 // TODO: Once we have call site specific value information we can provide
4840 // call site specific liveness information and then it makes
4841 // sense to specialize attributes for call sites instead of
4842 // redirecting requests to the callee.
4843 llvm_unreachable("Abstract attributes for liveness are not "
4844 "supported for call sites yet!");
4845 }
4846
4847 ChangeStatus updateImpl(Attributor &A) override {
4848 return indicatePessimisticFixpoint();
4849 }
4850
4851 void trackStatistics() const override {}
4852};
4853} // namespace
4854
4855/// -------------------- Dereferenceable Argument Attribute --------------------
4856
4857namespace {
4858struct AADereferenceableImpl : AADereferenceable {
4859 AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
4860 : AADereferenceable(IRP, A) {}
4861 using StateType = DerefState;
4862
4863 void initialize(Attributor &A) override {
4864 Value &V = *getAssociatedValue().stripPointerCasts();
4866 A.getAttrs(getIRPosition(),
4867 {Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4868 Attrs, /* IgnoreSubsumingPositions */ false);
4869 for (const Attribute &Attr : Attrs)
4870 takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4871
4872 // Ensure we initialize the non-null AA (if necessary).
4873 bool IsKnownNonNull;
4875 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNonNull);
4876
4877 bool CanBeNull;
4878 takeKnownDerefBytesMaximum(V.getPointerDereferenceableBytes(
4879 A.getDataLayout(), CanBeNull, /*CanBeFreed=*/nullptr));
4880
4881 if (Instruction *CtxI = getCtxI())
4882 followUsesInMBEC(*this, A, getState(), *CtxI);
4883 }
4884
4885 StateType &getState() override { return *this; }
4886 const StateType &getState() const override { return *this; }
4887
4888 /// Helper function for collecting accessed bytes in must-be-executed-context
4889 void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
4890 DerefState &State) {
4891 const Value *UseV = U->get();
4892 if (!UseV->getType()->isPointerTy())
4893 return;
4894
4895 std::optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
4896 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
4897 return;
4898
4899 int64_t Offset;
4901 Loc->Ptr, Offset, A.getDataLayout(), /*AllowNonInbounds*/ true);
4902 if (Base && Base == &getAssociatedValue())
4903 State.addAccessedBytes(Offset, Loc->Size.getValue());
4904 }
4905
4906 /// See followUsesInMBEC
4907 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4908 AADereferenceable::StateType &State) {
4909 bool IsNonNull = false;
4910 bool TrackUse = false;
4911 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4912 A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
4913 LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
4914 << " for instruction " << *I << "\n");
4915
4916 addAccessedBytesForUse(A, U, I, State);
4917 State.takeKnownDerefBytesMaximum(DerefBytes);
4918 return TrackUse;
4919 }
4920
4921 ChangeStatus manifest(Attributor &A) override {
4922 ChangeStatus Change = AADereferenceable::manifest(A);
4923 bool IsKnownNonNull;
4924 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
4925 A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4926 if (IsAssumedNonNull &&
4927 A.hasAttr(getIRPosition(), Attribute::DereferenceableOrNull)) {
4928 A.removeAttrs(getIRPosition(), {Attribute::DereferenceableOrNull});
4929 return ChangeStatus::CHANGED;
4930 }
4931 return Change;
4932 }
4933
4934 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
4935 SmallVectorImpl<Attribute> &Attrs) const override {
4936 // TODO: Add *_globally support
4937 bool IsKnownNonNull;
4938 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
4939 A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4940 if (IsAssumedNonNull)
4941 Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4942 Ctx, getAssumedDereferenceableBytes()));
4943 else
4944 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4945 Ctx, getAssumedDereferenceableBytes()));
4946 }
4947
4948 const std::string getAsStr(Attributor *A) const override {
4949 if (!getAssumedDereferenceableBytes())
4950 return "unknown-dereferenceable";
4951 bool IsKnownNonNull;
4952 bool IsAssumedNonNull = false;
4953 if (A)
4955 *A, this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4956 return std::string("dereferenceable") +
4957 (IsAssumedNonNull ? "" : "_or_null") +
4958 (isAssumedGlobal() ? "_globally" : "") + "<" +
4959 std::to_string(getKnownDereferenceableBytes()) + "-" +
4960 std::to_string(getAssumedDereferenceableBytes()) + ">" +
4961 (!A ? " [non-null is unknown]" : "");
4962 }
4963};
4964
4965/// Dereferenceable attribute for a floating value.
4966struct AADereferenceableFloating : AADereferenceableImpl {
4967 AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
4968 : AADereferenceableImpl(IRP, A) {}
4969
4970 ChangeStatus updateImpl(Attributor &A) override {
4971 bool Stripped;
4972 bool UsedAssumedInformation = false;
4974 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
4975 AA::AnyScope, UsedAssumedInformation)) {
4976 Values.push_back({getAssociatedValue(), getCtxI()});
4977 Stripped = false;
4978 } else {
4979 Stripped = Values.size() != 1 ||
4980 Values.front().getValue() != &getAssociatedValue();
4981 }
4982
4983 const DataLayout &DL = A.getDataLayout();
4984 DerefState T;
4985
4986 auto VisitValueCB = [&](const Value &V) -> bool {
4987 unsigned IdxWidth =
4988 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
4989 APInt Offset(IdxWidth, 0);
4991 A, *this, &V, DL, Offset, /* GetMinOffset */ false,
4992 /* AllowNonInbounds */ true);
4993
4994 const auto *AA = A.getAAFor<AADereferenceable>(
4995 *this, IRPosition::value(*Base), DepClassTy::REQUIRED);
4996 int64_t DerefBytes = 0;
4997 if (!AA || (!Stripped && this == AA)) {
4998 // Use IR information if we did not strip anything.
4999 // TODO: track globally.
5000 bool CanBeNull;
5001 DerefBytes = Base->getPointerDereferenceableBytes(
5002 DL, CanBeNull, /*CanBeFreed=*/nullptr);
5003 T.GlobalState.indicatePessimisticFixpoint();
5004 } else {
5005 const DerefState &DS = AA->getState();
5006 DerefBytes = DS.DerefBytesState.getAssumed();
5007 T.GlobalState &= DS.GlobalState;
5008 }
5009
5010 // For now we do not try to "increase" dereferenceability due to negative
5011 // indices as we first have to come up with code to deal with loops and
5012 // for overflows of the dereferenceable bytes.
5013 int64_t OffsetSExt = Offset.getSExtValue();
5014 if (OffsetSExt < 0)
5015 OffsetSExt = 0;
5016
5017 T.takeAssumedDerefBytesMinimum(
5018 std::max(int64_t(0), DerefBytes - OffsetSExt));
5019
5020 if (this == AA) {
5021 if (!Stripped) {
5022 // If nothing was stripped IR information is all we got.
5023 T.takeKnownDerefBytesMaximum(
5024 std::max(int64_t(0), DerefBytes - OffsetSExt));
5025 T.indicatePessimisticFixpoint();
5026 } else if (OffsetSExt > 0) {
5027 // If something was stripped but there is circular reasoning we look
5028 // for the offset. If it is positive we basically decrease the
5029 // dereferenceable bytes in a circular loop now, which will simply
5030 // drive them down to the known value in a very slow way which we
5031 // can accelerate.
5032 T.indicatePessimisticFixpoint();
5033 }
5034 }
5035
5036 return T.isValidState();
5037 };
5038
5039 for (const auto &VAC : Values)
5040 if (!VisitValueCB(*VAC.getValue()))
5041 return indicatePessimisticFixpoint();
5042
5043 return clampStateAndIndicateChange(getState(), T);
5044 }
5045
5046 void trackStatistics() const override {
5047 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
5048 }
5049};
5050
5051/// Dereferenceable attribute for a return value.
5052struct AADereferenceableReturned final
5053 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
5054 using Base =
5055 AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>;
5056 AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
5057 : Base(IRP, A) {}
5058
5059 void trackStatistics() const override {
5060 STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
5061 }
5062};
5063
5064/// Dereferenceable attribute for an argument
5065struct AADereferenceableArgument final
5066 : AAArgumentFromCallSiteArguments<AADereferenceable,
5067 AADereferenceableImpl> {
5068 using Base =
5069 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
5070 AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
5071 : Base(IRP, A) {}
5072
5073 void trackStatistics() const override {
5074 STATS_DECLTRACK_ARG_ATTR(dereferenceable)
5075 }
5076};
5077
5078/// Dereferenceable attribute for a call site argument.
5079struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
5080 AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
5081 : AADereferenceableFloating(IRP, A) {}
5082
5083 void trackStatistics() const override {
5084 STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
5085 }
5086};
5087
5088/// Dereferenceable attribute deduction for a call site return value.
5089struct AADereferenceableCallSiteReturned final
5090 : AACalleeToCallSite<AADereferenceable, AADereferenceableImpl> {
5091 using Base = AACalleeToCallSite<AADereferenceable, AADereferenceableImpl>;
5092 AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
5093 : Base(IRP, A) {}
5094
5095 void trackStatistics() const override {
5096 STATS_DECLTRACK_CS_ATTR(dereferenceable);
5097 }
5098};
5099} // namespace
5100
5101// ------------------------ Align Argument Attribute ------------------------
5102
5103namespace {
5104
5105static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA,
5106 Value &AssociatedValue, const Use *U,
5107 const Instruction *I, bool &TrackUse) {
5108 // We need to follow common pointer manipulation uses to the accesses they
5109 // feed into.
5110 if (isa<CastInst>(I)) {
5111 // Follow all but ptr2int casts.
5112 TrackUse = !isa<PtrToIntInst>(I);
5113 return 0;
5114 }
5115 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
5116 if (GEP->hasAllConstantIndices())
5117 TrackUse = true;
5118 return 0;
5119 }
5120 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
5121 switch (II->getIntrinsicID()) {
5122 case Intrinsic::ptrmask: {
5123 // Is it appropriate to pull attribute in initialization?
5124 const auto *ConstVals = A.getAAFor<AAPotentialConstantValues>(
5125 QueryingAA, IRPosition::value(*II->getOperand(1)), DepClassTy::NONE);
5126 const auto *AlignAA = A.getAAFor<AAAlign>(
5127 QueryingAA, IRPosition::value(*II), DepClassTy::NONE);
5128 if (ConstVals && ConstVals->isValidState() && ConstVals->isAtFixpoint()) {
5129 unsigned ShiftValue = std::min(ConstVals->getAssumedMinTrailingZeros(),
5131 Align ConstAlign = Align::fromLog2(ShiftValue);
5132 if (ConstAlign >= AlignAA->getKnownAlign())
5133 return Align(1).value();
5134 }
5135 if (AlignAA)
5136 return AlignAA->getKnownAlign().value();
5137 break;
5138 }
5139 case Intrinsic::amdgcn_make_buffer_rsrc: {
5140 const auto *AlignAA = A.getAAFor<AAAlign>(
5141 QueryingAA, IRPosition::value(*II), DepClassTy::NONE);
5142 if (AlignAA)
5143 return AlignAA->getKnownAlign().value();
5144 break;
5145 }
5146 default:
5147 break;
5148 }
5149
5150 MaybeAlign MA;
5151 if (const auto *CB = dyn_cast<CallBase>(I)) {
5152 if (CB->isBundleOperand(U) || CB->isCallee(U))
5153 return 0;
5154
5155 unsigned ArgNo = CB->getArgOperandNo(U);
5156 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
5157 // As long as we only use known information there is no need to track
5158 // dependences here.
5159 auto *AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE);
5160 if (AlignAA)
5161 MA = MaybeAlign(AlignAA->getKnownAlign());
5162 }
5163
5164 const DataLayout &DL = A.getDataLayout();
5165 const Value *UseV = U->get();
5166 if (auto *SI = dyn_cast<StoreInst>(I)) {
5167 if (SI->getPointerOperand() == UseV)
5168 MA = SI->getAlign();
5169 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
5170 if (LI->getPointerOperand() == UseV)
5171 MA = LI->getAlign();
5172 } else if (auto *AI = dyn_cast<AtomicRMWInst>(I)) {
5173 if (AI->getPointerOperand() == UseV)
5174 MA = AI->getAlign();
5175 } else if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
5176 if (AI->getPointerOperand() == UseV)
5177 MA = AI->getAlign();
5178 }
5179
5180 if (!MA || *MA <= QueryingAA.getKnownAlign())
5181 return 0;
5182
5183 unsigned Alignment = MA->value();
5184 int64_t Offset;
5185
5186 if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
5187 if (Base == &AssociatedValue) {
5188 // BasePointerAddr + Offset = Alignment * Q for some integer Q.
5189 // So we can say that the maximum power of two which is a divisor of
5190 // gcd(Offset, Alignment) is an alignment.
5191
5192 uint32_t gcd = std::gcd(uint32_t(abs((int32_t)Offset)), Alignment);
5194 }
5195 }
5196
5197 return Alignment;
5198}
5199
5200struct AAAlignImpl : AAAlign {
5201 AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
5202
5203 void initialize(Attributor &A) override {
5205 A.getAttrs(getIRPosition(), {Attribute::Alignment}, Attrs);
5206 for (const Attribute &Attr : Attrs)
5207 takeKnownMaximum(Attr.getValueAsInt());
5208
5209 Value &V = *getAssociatedValue().stripPointerCasts();
5210 takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
5211
5212 if (Instruction *CtxI = getCtxI())
5213 followUsesInMBEC(*this, A, getState(), *CtxI);
5214 }
5215
5216 ChangeStatus manifest(Attributor &A) override {
5217 ChangeStatus InstrChanged = ChangeStatus::UNCHANGED;
5218
5219 // Check for users that allow alignment annotations.
5220 Value &AssociatedValue = getAssociatedValue();
5221 if (isa<ConstantData>(AssociatedValue))
5222 return ChangeStatus::UNCHANGED;
5223
5224 for (const Use &U : AssociatedValue.uses()) {
5225 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
5226 if (SI->getPointerOperand() == &AssociatedValue)
5227 if (SI->getAlign() < getAssumedAlign()) {
5228 STATS_DECLTRACK(AAAlign, Store,
5229 "Number of times alignment added to a store");
5230 SI->setAlignment(getAssumedAlign());
5231 InstrChanged = ChangeStatus::CHANGED;
5232 }
5233 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
5234 if (LI->getPointerOperand() == &AssociatedValue)
5235 if (LI->getAlign() < getAssumedAlign()) {
5236 LI->setAlignment(getAssumedAlign());
5237 STATS_DECLTRACK(AAAlign, Load,
5238 "Number of times alignment added to a load");
5239 InstrChanged = ChangeStatus::CHANGED;
5240 }
5241 } else if (auto *RMW = dyn_cast<AtomicRMWInst>(U.getUser())) {
5242 if (RMW->getPointerOperand() == &AssociatedValue) {
5243 if (RMW->getAlign() < getAssumedAlign()) {
5244 STATS_DECLTRACK(AAAlign, AtomicRMW,
5245 "Number of times alignment added to atomicrmw");
5246
5247 RMW->setAlignment(getAssumedAlign());
5248 InstrChanged = ChangeStatus::CHANGED;
5249 }
5250 }
5251 } else if (auto *CAS = dyn_cast<AtomicCmpXchgInst>(U.getUser())) {
5252 if (CAS->getPointerOperand() == &AssociatedValue) {
5253 if (CAS->getAlign() < getAssumedAlign()) {
5254 STATS_DECLTRACK(AAAlign, AtomicCmpXchg,
5255 "Number of times alignment added to cmpxchg");
5256 CAS->setAlignment(getAssumedAlign());
5257 InstrChanged = ChangeStatus::CHANGED;
5258 }
5259 }
5260 }
5261 }
5262
5263 ChangeStatus Changed = AAAlign::manifest(A);
5264
5265 Align InheritAlign =
5266 getAssociatedValue().getPointerAlignment(A.getDataLayout());
5267 if (InheritAlign >= getAssumedAlign())
5268 return InstrChanged;
5269 return Changed | InstrChanged;
5270 }
5271
5272 // TODO: Provide a helper to determine the implied ABI alignment and check in
5273 // the existing manifest method and a new one for AAAlignImpl that value
5274 // to avoid making the alignment explicit if it did not improve.
5275
5276 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
5277 SmallVectorImpl<Attribute> &Attrs) const override {
5278 if (getAssumedAlign() > 1)
5279 Attrs.emplace_back(
5280 Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
5281 }
5282
5283 /// See followUsesInMBEC
5284 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
5285 AAAlign::StateType &State) {
5286 bool TrackUse = false;
5287
5288 unsigned int KnownAlign =
5289 getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
5290 State.takeKnownMaximum(KnownAlign);
5291
5292 return TrackUse;
5293 }
5294
5295 const std::string getAsStr(Attributor *A) const override {
5296 return "align<" + std::to_string(getKnownAlign().value()) + "-" +
5297 std::to_string(getAssumedAlign().value()) + ">";
5298 }
5299};
5300
5301/// Align attribute for a floating value.
5302struct AAAlignFloating : AAAlignImpl {
5303 AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
5304
5305 ChangeStatus updateImpl(Attributor &A) override {
5306 const DataLayout &DL = A.getDataLayout();
5307
5308 bool Stripped;
5309 bool UsedAssumedInformation = false;
5311 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
5312 AA::AnyScope, UsedAssumedInformation)) {
5313 Values.push_back({getAssociatedValue(), getCtxI()});
5314 Stripped = false;
5315 } else {
5316 Stripped = Values.size() != 1 ||
5317 Values.front().getValue() != &getAssociatedValue();
5318 }
5319
5320 StateType T;
5321 auto VisitValueCB = [&](Value &V) -> bool {
5323 return true;
5324 const auto *AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V),
5325 DepClassTy::REQUIRED);
5326 if (!AA || (!Stripped && this == AA)) {
5327 int64_t Offset;
5328 unsigned Alignment = 1;
5329 if (const Value *Base =
5331 // TODO: Use AAAlign for the base too.
5332 Align PA = Base->getPointerAlignment(DL);
5333 // BasePointerAddr + Offset = Alignment * Q for some integer Q.
5334 // So we can say that the maximum power of two which is a divisor of
5335 // gcd(Offset, Alignment) is an alignment.
5336
5337 uint32_t gcd =
5338 std::gcd(uint32_t(abs((int32_t)Offset)), uint32_t(PA.value()));
5340 } else {
5341 Alignment = V.getPointerAlignment(DL).value();
5342 }
5343 // Use only IR information if we did not strip anything.
5344 T.takeKnownMaximum(Alignment);
5345 T.indicatePessimisticFixpoint();
5346 } else {
5347 // Use abstract attribute information.
5348 const AAAlign::StateType &DS = AA->getState();
5349 T ^= DS;
5350 }
5351 return T.isValidState();
5352 };
5353
5354 for (const auto &VAC : Values) {
5355 if (!VisitValueCB(*VAC.getValue()))
5356 return indicatePessimisticFixpoint();
5357 }
5358
5359 // TODO: If we know we visited all incoming values, thus no are assumed
5360 // dead, we can take the known information from the state T.
5361 return clampStateAndIndicateChange(getState(), T);
5362 }
5363
5364 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
5365};
5366
5367/// Align attribute for function return value.
5368struct AAAlignReturned final
5369 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
5370 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
5371 AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
5372
5373 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
5374};
5375
5376/// Align attribute for function argument.
5377struct AAAlignArgument final
5378 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
5379 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
5380 AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
5381
5382 ChangeStatus manifest(Attributor &A) override {
5383 // If the associated argument is involved in a must-tail call we give up
5384 // because we would need to keep the argument alignments of caller and
5385 // callee in-sync. Just does not seem worth the trouble right now.
5386 if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
5387 return ChangeStatus::UNCHANGED;
5388 return Base::manifest(A);
5389 }
5390
5391 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
5392};
5393
5394struct AAAlignCallSiteArgument final : AAAlignFloating {
5395 AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
5396 : AAAlignFloating(IRP, A) {}
5397
5398 ChangeStatus manifest(Attributor &A) override {
5399 // If the associated argument is involved in a must-tail call we give up
5400 // because we would need to keep the argument alignments of caller and
5401 // callee in-sync. Just does not seem worth the trouble right now.
5402 if (Argument *Arg = getAssociatedArgument())
5403 if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
5404 return ChangeStatus::UNCHANGED;
5405 ChangeStatus Changed = AAAlignImpl::manifest(A);
5406 Align InheritAlign =
5407 getAssociatedValue().getPointerAlignment(A.getDataLayout());
5408 if (InheritAlign >= getAssumedAlign())
5409 Changed = ChangeStatus::UNCHANGED;
5410 return Changed;
5411 }
5412
5413 ChangeStatus updateImpl(Attributor &A) override {
5414 ChangeStatus Changed = AAAlignFloating::updateImpl(A);
5415 if (Argument *Arg = getAssociatedArgument()) {
5416 // We only take known information from the argument
5417 // so we do not need to track a dependence.
5418 const auto *ArgAlignAA = A.getAAFor<AAAlign>(
5419 *this, IRPosition::argument(*Arg), DepClassTy::NONE);
5420 if (ArgAlignAA)
5421 takeKnownMaximum(ArgAlignAA->getKnownAlign().value());
5422 }
5423 return Changed;
5424 }
5425
5426 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
5427};
5428
5429/// Align attribute deduction for a call site return value.
5430struct AAAlignCallSiteReturned final
5431 : AACalleeToCallSite<AAAlign, AAAlignImpl> {
5432 using Base = AACalleeToCallSite<AAAlign, AAAlignImpl>;
5433 AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
5434 : Base(IRP, A) {}
5435
5436 ChangeStatus updateImpl(Attributor &A) override {
5437 Instruction *I = getIRPosition().getCtxI();
5438 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
5439 switch (II->getIntrinsicID()) {
5440 case Intrinsic::ptrmask: {
5442 bool Valid = false;
5443
5444 const auto *ConstVals = A.getAAFor<AAPotentialConstantValues>(
5445 *this, IRPosition::value(*II->getOperand(1)), DepClassTy::REQUIRED);
5446 if (ConstVals && ConstVals->isValidState()) {
5447 unsigned ShiftValue =
5448 std::min(ConstVals->getAssumedMinTrailingZeros(),
5449 Value::MaxAlignmentExponent);
5450 Alignment = Align::fromLog2(ShiftValue);
5451 Valid = true;
5452 }
5453
5454 const auto *AlignAA =
5455 A.getAAFor<AAAlign>(*this, IRPosition::value(*(II->getOperand(0))),
5456 DepClassTy::REQUIRED);
5457 if (AlignAA) {
5458 Alignment = std::max(AlignAA->getAssumedAlign(), Alignment);
5459 Valid = true;
5460 }
5461
5462 if (Valid)
5464 this->getState(),
5465 std::min(this->getAssumedAlign(), Alignment).value());
5466 break;
5467 }
5468 // FIXME: Should introduce target specific sub-attributes and letting
5469 // getAAfor<AAAlign> lead to create sub-attribute to handle target
5470 // specific intrinsics.
5471 case Intrinsic::amdgcn_make_buffer_rsrc: {
5472 const auto *AlignAA =
5473 A.getAAFor<AAAlign>(*this, IRPosition::value(*(II->getOperand(0))),
5474 DepClassTy::REQUIRED);
5475 if (AlignAA)
5477 this->getState(), AlignAA->getAssumedAlign().value());
5478 break;
5479 }
5480 default:
5481 break;
5482 }
5483 }
5484 return Base::updateImpl(A);
5485 };
5486 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
5487};
5488} // namespace
5489
5490/// ------------------ Function No-Return Attribute ----------------------------
5491namespace {
5492struct AANoReturnImpl : public AANoReturn {
5493 AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
5494
5495 void initialize(Attributor &A) override {
5496 bool IsKnown;
5498 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5499 (void)IsKnown;
5500 }
5501
5502 const std::string getAsStr(Attributor *A) const override {
5503 return getAssumed() ? "noreturn" : "may-return";
5504 }
5505
5506 ChangeStatus updateImpl(Attributor &A) override {
5507 auto CheckForNoReturn = [](Instruction &) { return false; };
5508 bool UsedAssumedInformation = false;
5509 if (!A.checkForAllInstructions(CheckForNoReturn, *this,
5510 {(unsigned)Instruction::Ret},
5511 UsedAssumedInformation))
5512 return indicatePessimisticFixpoint();
5513 return ChangeStatus::UNCHANGED;
5514 }
5515};
5516
5517struct AANoReturnFunction final : AANoReturnImpl {
5518 AANoReturnFunction(const IRPosition &IRP, Attributor &A)
5519 : AANoReturnImpl(IRP, A) {}
5520
5521 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
5522};
5523
5524/// NoReturn attribute deduction for a call sites.
5525struct AANoReturnCallSite final
5526 : AACalleeToCallSite<AANoReturn, AANoReturnImpl> {
5527 AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
5528 : AACalleeToCallSite<AANoReturn, AANoReturnImpl>(IRP, A) {}
5529
5530 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
5531};
5532} // namespace
5533
5534/// ----------------------- Instance Info ---------------------------------
5535
5536namespace {
5537/// A class to hold the state of for no-capture attributes.
5538struct AAInstanceInfoImpl : public AAInstanceInfo {
5539 AAInstanceInfoImpl(const IRPosition &IRP, Attributor &A)
5540 : AAInstanceInfo(IRP, A) {}
5541
5542 void initialize(Attributor &A) override {
5543 Value &V = getAssociatedValue();
5544 if (auto *C = dyn_cast<Constant>(&V)) {
5545 if (C->isThreadDependent())
5546 indicatePessimisticFixpoint();
5547 else
5548 indicateOptimisticFixpoint();
5549 return;
5550 }
5551 if (auto *CB = dyn_cast<CallBase>(&V))
5552 if (CB->arg_size() == 0 && !CB->mayHaveSideEffects() &&
5553 !CB->mayReadFromMemory()) {
5554 indicateOptimisticFixpoint();
5555 return;
5556 }
5557 if (auto *I = dyn_cast<Instruction>(&V)) {
5558 const auto *CI =
5559 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
5560 *I->getFunction());
5561 if (mayBeInCycle(CI, I, /* HeaderOnly */ false)) {
5562 indicatePessimisticFixpoint();
5563 return;
5564 }
5565 }
5566 }
5567
5568 ChangeStatus updateImpl(Attributor &A) override {
5569 ChangeStatus Changed = ChangeStatus::UNCHANGED;
5570
5571 Value &V = getAssociatedValue();
5572 const Function *Scope = nullptr;
5573 if (auto *I = dyn_cast<Instruction>(&V))
5574 Scope = I->getFunction();
5575 if (auto *A = dyn_cast<Argument>(&V)) {
5576 Scope = A->getParent();
5577 if (!Scope->hasLocalLinkage())
5578 return Changed;
5579 }
5580 if (!Scope)
5581 return indicateOptimisticFixpoint();
5582
5583 bool IsKnownNoRecurse;
5585 A, this, IRPosition::function(*Scope), DepClassTy::OPTIONAL,
5586 IsKnownNoRecurse))
5587 return Changed;
5588
5589 auto UsePred = [&](const Use &U, bool &Follow) {
5590 const Instruction *UserI = dyn_cast<Instruction>(U.getUser());
5591 if (!UserI || isa<GetElementPtrInst>(UserI) || isa<CastInst>(UserI) ||
5592 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
5593 Follow = true;
5594 return true;
5595 }
5596 if (isa<LoadInst>(UserI) || isa<CmpInst>(UserI) ||
5597 (isa<StoreInst>(UserI) &&
5598 cast<StoreInst>(UserI)->getValueOperand() != U.get()))
5599 return true;
5600 if (auto *CB = dyn_cast<CallBase>(UserI)) {
5601 // This check is not guaranteeing uniqueness but for now that we cannot
5602 // end up with two versions of \p U thinking it was one.
5604 if (!Callee || !Callee->hasLocalLinkage())
5605 return true;
5606 if (!CB->isArgOperand(&U))
5607 return false;
5608 const auto *ArgInstanceInfoAA = A.getAAFor<AAInstanceInfo>(
5610 DepClassTy::OPTIONAL);
5611 if (!ArgInstanceInfoAA ||
5612 !ArgInstanceInfoAA->isAssumedUniqueForAnalysis())
5613 return false;
5614 // If this call base might reach the scope again we might forward the
5615 // argument back here. This is very conservative.
5617 A, *CB, *Scope, *this, /* ExclusionSet */ nullptr,
5618 [Scope](const Function &Fn) { return &Fn != Scope; }))
5619 return false;
5620 return true;
5621 }
5622 return false;
5623 };
5624
5625 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
5626 if (auto *SI = dyn_cast<StoreInst>(OldU.getUser())) {
5627 auto *Ptr = SI->getPointerOperand()->stripPointerCasts();
5628 if ((isa<AllocaInst>(Ptr) || isNoAliasCall(Ptr)) &&
5629 AA::isDynamicallyUnique(A, *this, *Ptr))
5630 return true;
5631 }
5632 return false;
5633 };
5634
5635 if (!A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ true,
5636 DepClassTy::OPTIONAL,
5637 /* IgnoreDroppableUses */ true, EquivalentUseCB))
5638 return indicatePessimisticFixpoint();
5639
5640 return Changed;
5641 }
5642
5643 const std::string getAsStr(Attributor *A) const override {
5644 return isAssumedUniqueForAnalysis() ? "<unique [fAa]>" : "<unknown>";
5645 }
5646
5647 void trackStatistics() const override {}
5648};
5649
5650/// InstanceInfo attribute for floating values.
5651struct AAInstanceInfoFloating : AAInstanceInfoImpl {
5652 AAInstanceInfoFloating(const IRPosition &IRP, Attributor &A)
5653 : AAInstanceInfoImpl(IRP, A) {}
5654};
5655
5656/// NoCapture attribute for function arguments.
5657struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
5658 AAInstanceInfoArgument(const IRPosition &IRP, Attributor &A)
5659 : AAInstanceInfoFloating(IRP, A) {}
5660};
5661
5662/// InstanceInfo attribute for call site arguments.
5663struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
5664 AAInstanceInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
5665 : AAInstanceInfoImpl(IRP, A) {}
5666
5667 ChangeStatus updateImpl(Attributor &A) override {
5668 // TODO: Once we have call site specific value information we can provide
5669 // call site specific liveness information and then it makes
5670 // sense to specialize attributes for call sites arguments instead of
5671 // redirecting requests to the callee argument.
5672 Argument *Arg = getAssociatedArgument();
5673 if (!Arg)
5674 return indicatePessimisticFixpoint();
5675 const IRPosition &ArgPos = IRPosition::argument(*Arg);
5676 auto *ArgAA =
5677 A.getAAFor<AAInstanceInfo>(*this, ArgPos, DepClassTy::REQUIRED);
5678 if (!ArgAA)
5679 return indicatePessimisticFixpoint();
5680 return clampStateAndIndicateChange(getState(), ArgAA->getState());
5681 }
5682};
5683
5684/// InstanceInfo attribute for function return value.
5685struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
5686 AAInstanceInfoReturned(const IRPosition &IRP, Attributor &A)
5687 : AAInstanceInfoImpl(IRP, A) {
5688 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5689 }
5690
5691 void initialize(Attributor &A) override {
5692 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5693 }
5694
5695 ChangeStatus updateImpl(Attributor &A) override {
5696 llvm_unreachable("InstanceInfo is not applicable to function returns!");
5697 }
5698};
5699
5700/// InstanceInfo attribute deduction for a call site return value.
5701struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
5702 AAInstanceInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
5703 : AAInstanceInfoFloating(IRP, A) {}
5704};
5705} // namespace
5706
5707/// ----------------------- Variable Capturing ---------------------------------
5709 Attribute::AttrKind ImpliedAttributeKind,
5710 bool IgnoreSubsumingPositions) {
5711 assert(ImpliedAttributeKind == Attribute::Captures &&
5712 "Unexpected attribute kind");
5713 Value &V = IRP.getAssociatedValue();
5714 if (!isa<Constant>(V) && !IRP.isArgumentPosition())
5715 return V.use_empty();
5716
5717 // You cannot "capture" null if it is not a valid pointer.
5718 if (isa<UndefValue>(V) ||
5722 return true;
5723 }
5724
5726 A.getAttrs(IRP, {Attribute::Captures}, Attrs,
5727 /* IgnoreSubsumingPositions */ true);
5728 for (const Attribute &Attr : Attrs)
5729 if (capturesNothing(Attr.getCaptureInfo()))
5730 return true;
5731
5733 if (Argument *Arg = IRP.getAssociatedArgument()) {
5735 A.getAttrs(IRPosition::argument(*Arg),
5736 {Attribute::Captures, Attribute::ByVal}, Attrs,
5737 /* IgnoreSubsumingPositions */ true);
5738 bool ArgNoCapture = any_of(Attrs, [](Attribute Attr) {
5739 return Attr.getKindAsEnum() == Attribute::ByVal ||
5741 });
5742 if (ArgNoCapture) {
5743 A.manifestAttrs(IRP, Attribute::getWithCaptureInfo(
5744 V.getContext(), CaptureInfo::none()));
5745 return true;
5746 }
5747 }
5748
5749 if (const Function *F = IRP.getAssociatedFunction()) {
5750 // Check what state the associated function can actually capture.
5753 if (State.isKnown(NO_CAPTURE)) {
5754 A.manifestAttrs(IRP, Attribute::getWithCaptureInfo(V.getContext(),
5756 return true;
5757 }
5758 }
5759
5760 return false;
5761}
5762
5763/// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
5764/// depending on the ability of the function associated with \p IRP to capture
5765/// state in memory and through "returning/throwing", respectively.
5767 const Function &F,
5768 BitIntegerState &State) {
5769 // TODO: Once we have memory behavior attributes we should use them here.
5770
5771 // If we know we cannot communicate or write to memory, we do not care about
5772 // ptr2int anymore. The value can still be captured by whether the function
5773 // returns.
5774 bool ReadOnly = F.onlyReadsMemory();
5775 bool NoThrow = F.doesNotThrow();
5776 bool WillReturn = F.willReturn();
5777 bool IsVoidReturn = F.getReturnType()->isVoidTy();
5778 if (ReadOnly && NoThrow && WillReturn && IsVoidReturn) {
5779 State.addKnownBits(NO_CAPTURE);
5780 return;
5781 }
5782
5783 // A function cannot capture state in memory if it only reads memory, it can
5784 // however return/throw state and the state might be influenced by the
5785 // pointer value, e.g., loading from a returned pointer might reveal a bit.
5786 if (ReadOnly)
5787 State.addKnownBits(NOT_CAPTURED_IN_MEM);
5788
5789 // A function cannot communicate state back if it does not through
5790 // exceptions and doesn not return values.
5791 if (NoThrow && IsVoidReturn)
5792 State.addKnownBits(NOT_CAPTURED_IN_RET);
5793
5794 // Check existing "returned" attributes.
5795 int ArgNo = IRP.getCalleeArgNo();
5796 if (!NoThrow || ArgNo < 0 ||
5797 !F.getAttributes().hasAttrSomewhere(Attribute::Returned))
5798 return;
5799
5800 for (unsigned U = 0, E = F.arg_size(); U < E; ++U)
5801 if (F.hasParamAttribute(U, Attribute::Returned)) {
5802 if (U == unsigned(ArgNo))
5803 State.removeAssumedBits(NOT_CAPTURED_IN_RET);
5804 else if (ReadOnly && WillReturn)
5805 State.addKnownBits(NO_CAPTURE);
5806 else
5807 State.addKnownBits(NOT_CAPTURED_IN_RET);
5808 break;
5809 }
5810}
5811
5812namespace {
5813/// A class to hold the state of for no-capture attributes.
5814struct AANoCaptureImpl : public AANoCapture {
5815 AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
5816
5817 void initialize(Attributor &A) override {
5818 bool IsKnown;
5820 A, nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5821 (void)IsKnown;
5822 }
5823
5824 ChangeStatus updateImpl(Attributor &A) override;
5825
5826 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
5827 SmallVectorImpl<Attribute> &Attrs) const override {
5828 if (!isAssumedNoCaptureMaybeReturned())
5829 return;
5830
5831 if (isArgumentPosition()) {
5832 if (isAssumedNoCapture())
5833 Attrs.emplace_back(Attribute::get(Ctx, Attribute::Captures));
5834 else if (A.Opts.attributor_manifest_internal)
5835 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
5836 }
5837 }
5838
5839 const std::string getAsStr(Attributor *A) const override {
5840 if (isKnownNoCapture())
5841 return "known not-captured";
5842 if (isAssumedNoCapture())
5843 return "assumed not-captured";
5844 if (isKnownNoCaptureMaybeReturned())
5845 return "known not-captured-maybe-returned";
5846 if (isAssumedNoCaptureMaybeReturned())
5847 return "assumed not-captured-maybe-returned";
5848 return "assumed-captured";
5849 }
5850
5851 /// Check the use \p U and update \p State accordingly. Return true if we
5852 /// should continue to update the state.
5853 bool checkUse(Attributor &A, AANoCapture::StateType &State, const Use &U,
5854 bool &Follow) {
5855 Instruction *UInst = cast<Instruction>(U.getUser());
5856 LLVM_DEBUG(dbgs() << "[AANoCapture] Check use: " << *U.get() << " in "
5857 << *UInst << "\n");
5858
5859 // Deal with ptr2int by following uses.
5860 if (isa<PtrToIntInst>(UInst)) {
5861 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
5862 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5863 /* Return */ true);
5864 }
5865
5866 // For stores we already checked if we can follow them, if they make it
5867 // here we give up.
5868 if (isa<StoreInst>(UInst))
5869 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5870 /* Return */ true);
5871
5872 // Explicitly catch return instructions.
5873 if (isa<ReturnInst>(UInst)) {
5874 if (UInst->getFunction() == getAnchorScope())
5875 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5876 /* Return */ true);
5877 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5878 /* Return */ true);
5879 }
5880
5881 // For now we only use special logic for call sites. However, the tracker
5882 // itself knows about a lot of other non-capturing cases already.
5883 auto *CB = dyn_cast<CallBase>(UInst);
5884 if (!CB || !CB->isArgOperand(&U))
5885 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5886 /* Return */ true);
5887
5888 unsigned ArgNo = CB->getArgOperandNo(&U);
5889 const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
5890 // If we have a abstract no-capture attribute for the argument we can use
5891 // it to justify a non-capture attribute here. This allows recursion!
5892 bool IsKnownNoCapture;
5893 const AANoCapture *ArgNoCaptureAA = nullptr;
5894 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
5895 A, this, CSArgPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
5896 &ArgNoCaptureAA);
5897 if (IsAssumedNoCapture)
5898 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5899 /* Return */ false);
5900 if (ArgNoCaptureAA && ArgNoCaptureAA->isAssumedNoCaptureMaybeReturned()) {
5901 Follow = true;
5902 return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5903 /* Return */ false);
5904 }
5905
5906 // Lastly, we could not find a reason no-capture can be assumed so we don't.
5907 return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5908 /* Return */ true);
5909 }
5910
5911 /// Update \p State according to \p CapturedInMem, \p CapturedInInt, and
5912 /// \p CapturedInRet, then return true if we should continue updating the
5913 /// state.
5914 static bool isCapturedIn(AANoCapture::StateType &State, bool CapturedInMem,
5915 bool CapturedInInt, bool CapturedInRet) {
5916 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
5917 << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
5918 if (CapturedInMem)
5919 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
5920 if (CapturedInInt)
5921 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
5922 if (CapturedInRet)
5923 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
5924 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
5925 }
5926};
5927
5928ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
5929 const IRPosition &IRP = getIRPosition();
5930 Value *V = isArgumentPosition() ? IRP.getAssociatedArgument()
5931 : &IRP.getAssociatedValue();
5932 if (!V)
5933 return indicatePessimisticFixpoint();
5934
5935 const Function *F =
5936 isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
5937
5938 // TODO: Is the checkForAllUses below useful for constants?
5939 if (!F)
5940 return indicatePessimisticFixpoint();
5941
5943 const IRPosition &FnPos = IRPosition::function(*F);
5944
5945 // Readonly means we cannot capture through memory.
5946 bool IsKnown;
5947 if (AA::isAssumedReadOnly(A, FnPos, *this, IsKnown)) {
5948 T.addKnownBits(NOT_CAPTURED_IN_MEM);
5949 if (IsKnown)
5950 addKnownBits(NOT_CAPTURED_IN_MEM);
5951 }
5952
5953 // Make sure all returned values are different than the underlying value.
5954 // TODO: we could do this in a more sophisticated way inside
5955 // AAReturnedValues, e.g., track all values that escape through returns
5956 // directly somehow.
5957 auto CheckReturnedArgs = [&](bool &UsedAssumedInformation) {
5959 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*F), this, Values,
5961 UsedAssumedInformation))
5962 return false;
5963 bool SeenConstant = false;
5964 for (const AA::ValueAndContext &VAC : Values) {
5965 if (isa<Constant>(VAC.getValue())) {
5966 if (SeenConstant)
5967 return false;
5968 SeenConstant = true;
5969 } else if (!isa<Argument>(VAC.getValue()) ||
5970 VAC.getValue() == getAssociatedArgument())
5971 return false;
5972 }
5973 return true;
5974 };
5975
5976 bool IsKnownNoUnwind;
5978 A, this, FnPos, DepClassTy::OPTIONAL, IsKnownNoUnwind)) {
5979 bool IsVoidTy = F->getReturnType()->isVoidTy();
5980 bool UsedAssumedInformation = false;
5981 if (IsVoidTy || CheckReturnedArgs(UsedAssumedInformation)) {
5982 T.addKnownBits(NOT_CAPTURED_IN_RET);
5983 // If the function only reads memory and does not return the value, the
5984 // value can still be captured by whether the function returns.
5985 bool IsKnownWillReturn;
5986 bool IsAssumedWillReturn = AA::hasAssumedIRAttr<Attribute::WillReturn>(
5987 A, this, FnPos, DepClassTy::OPTIONAL, IsKnownWillReturn);
5988 if (IsAssumedWillReturn && T.isKnown(NOT_CAPTURED_IN_MEM))
5990 if (IsKnownNoUnwind && (IsVoidTy || !UsedAssumedInformation)) {
5991 addKnownBits(NOT_CAPTURED_IN_RET);
5992 if (IsKnownWillReturn && isKnown(NOT_CAPTURED_IN_MEM))
5993 return indicateOptimisticFixpoint();
5994 }
5995 }
5996 }
5997
5998 auto UseCheck = [&](const Use &U, bool &Follow) -> bool {
5999 // TODO(captures): Make this more precise.
6000 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
6001 if (capturesNothing(CI))
6002 return true;
6003 if (CI.isPassthrough()) {
6004 Follow = true;
6005 return true;
6006 }
6007 return checkUse(A, T, U, Follow);
6008 };
6009
6010 if (!A.checkForAllUses(UseCheck, *this, *V))
6011 return indicatePessimisticFixpoint();
6012
6013 AANoCapture::StateType &S = getState();
6014 auto Assumed = S.getAssumed();
6015 S.intersectAssumedBits(T.getAssumed());
6016 if (!isAssumedNoCaptureMaybeReturned())
6017 return indicatePessimisticFixpoint();
6018 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
6020}
6021
6022/// NoCapture attribute for function arguments.
6023struct AANoCaptureArgument final : AANoCaptureImpl {
6024 AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
6025 : AANoCaptureImpl(IRP, A) {}
6026
6027 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
6028};
6029
6030/// NoCapture attribute for call site arguments.
6031struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
6032 AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
6033 : AANoCaptureImpl(IRP, A) {}
6034
6035 ChangeStatus updateImpl(Attributor &A) override {
6036 // TODO: Once we have call site specific value information we can provide
6037 // call site specific liveness information and then it makes
6038 // sense to specialize attributes for call sites arguments instead of
6039 // redirecting requests to the callee argument.
6040 Argument *Arg = getAssociatedArgument();
6041 if (!Arg)
6042 return indicatePessimisticFixpoint();
6043 const IRPosition &ArgPos = IRPosition::argument(*Arg);
6044 bool IsKnownNoCapture;
6045 const AANoCapture *ArgAA = nullptr;
6047 A, this, ArgPos, DepClassTy::REQUIRED, IsKnownNoCapture, false,
6048 &ArgAA))
6049 return ChangeStatus::UNCHANGED;
6050 if (!ArgAA || !ArgAA->isAssumedNoCaptureMaybeReturned())
6051 return indicatePessimisticFixpoint();
6052 return clampStateAndIndicateChange(getState(), ArgAA->getState());
6053 }
6054
6055 void trackStatistics() const override {
6057 };
6058};
6059
6060/// NoCapture attribute for floating values.
6061struct AANoCaptureFloating final : AANoCaptureImpl {
6062 AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
6063 : AANoCaptureImpl(IRP, A) {}
6064
6065 void trackStatistics() const override {
6067 }
6068};
6069
6070/// NoCapture attribute for function return value.
6071struct AANoCaptureReturned final : AANoCaptureImpl {
6072 AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
6073 : AANoCaptureImpl(IRP, A) {
6074 llvm_unreachable("NoCapture is not applicable to function returns!");
6075 }
6076
6077 void initialize(Attributor &A) override {
6078 llvm_unreachable("NoCapture is not applicable to function returns!");
6079 }
6080
6081 ChangeStatus updateImpl(Attributor &A) override {
6082 llvm_unreachable("NoCapture is not applicable to function returns!");
6083 }
6084
6085 void trackStatistics() const override {}
6086};
6087
6088/// NoCapture attribute deduction for a call site return value.
6089struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
6090 AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
6091 : AANoCaptureImpl(IRP, A) {}
6092
6093 void initialize(Attributor &A) override {
6094 const Function *F = getAnchorScope();
6095 // Check what state the associated function can actually capture.
6096 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
6097 }
6098
6099 void trackStatistics() const override {
6101 }
6102};
6103} // namespace
6104
6105/// ------------------ Value Simplify Attribute ----------------------------
6106
6107bool ValueSimplifyStateType::unionAssumed(std::optional<Value *> Other) {
6108 // FIXME: Add a typecast support.
6111 if (SimplifiedAssociatedValue == std::optional<Value *>(nullptr))
6112 return false;
6113
6114 LLVM_DEBUG({
6116 dbgs() << "[ValueSimplify] is assumed to be "
6117 << **SimplifiedAssociatedValue << "\n";
6118 else
6119 dbgs() << "[ValueSimplify] is assumed to be <none>\n";
6120 });
6121 return true;
6122}
6123
6124namespace {
6125struct AAValueSimplifyImpl : AAValueSimplify {
6126 AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
6127 : AAValueSimplify(IRP, A) {}
6128
6129 void initialize(Attributor &A) override {
6130 if (getAssociatedValue().getType()->isVoidTy())
6131 indicatePessimisticFixpoint();
6132 if (A.hasSimplificationCallback(getIRPosition()))
6133 indicatePessimisticFixpoint();
6134 }
6135
6136 const std::string getAsStr(Attributor *A) const override {
6137 LLVM_DEBUG({
6138 dbgs() << "SAV: " << (bool)SimplifiedAssociatedValue << " ";
6139 if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
6140 dbgs() << "SAV: " << **SimplifiedAssociatedValue << " ";
6141 });
6142 return isValidState() ? (isAtFixpoint() ? "simplified" : "maybe-simple")
6143 : "not-simple";
6144 }
6145
6146 void trackStatistics() const override {}
6147
6148 std::optional<Value *>
6149 getAssumedSimplifiedValue(Attributor &A) const override {
6150 return SimplifiedAssociatedValue;
6151 }
6152
6153 /// Ensure the return value is \p V with type \p Ty, if not possible return
6154 /// nullptr. If \p Check is true we will only verify such an operation would
6155 /// suceed and return a non-nullptr value if that is the case. No IR is
6156 /// generated or modified.
6157 static Value *ensureType(Attributor &A, Value &V, Type &Ty, Instruction *CtxI,
6158 bool Check) {
6159 if (auto *TypedV = AA::getWithType(V, Ty))
6160 return TypedV;
6161 if (CtxI && V.getType()->canLosslesslyBitCastTo(&Ty))
6162 return Check ? &V
6163 : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6164 &V, &Ty, "", CtxI->getIterator());
6165 return nullptr;
6166 }
6167
6168 /// Reproduce \p I with type \p Ty or return nullptr if that is not posisble.
6169 /// If \p Check is true we will only verify such an operation would suceed and
6170 /// return a non-nullptr value if that is the case. No IR is generated or
6171 /// modified.
6172 static Value *reproduceInst(Attributor &A,
6173 const AbstractAttribute &QueryingAA,
6174 Instruction &I, Type &Ty, Instruction *CtxI,
6175 bool Check, ValueToValueMapTy &VMap) {
6176 assert(CtxI && "Cannot reproduce an instruction without context!");
6177 if (Check && (I.mayReadFromMemory() ||
6178 !isSafeToSpeculativelyExecute(&I, CtxI, /* DT */ nullptr,
6179 /* TLI */ nullptr)))
6180 return nullptr;
6181 for (Value *Op : I.operands()) {
6182 Value *NewOp = reproduceValue(A, QueryingAA, *Op, Ty, CtxI, Check, VMap);
6183 if (!NewOp) {
6184 assert(Check && "Manifest of new value unexpectedly failed!");
6185 return nullptr;
6186 }
6187 if (!Check)
6188 VMap[Op] = NewOp;
6189 }
6190 if (Check)
6191 return &I;
6192
6193 Instruction *CloneI = I.clone();
6194 // TODO: Try to salvage debug information here.
6195 CloneI->setDebugLoc(DebugLoc());
6196 VMap[&I] = CloneI;
6197 CloneI->insertBefore(CtxI->getIterator());
6198 RemapInstruction(CloneI, VMap);
6199 return CloneI;
6200 }
6201
6202 /// Reproduce \p V with type \p Ty or return nullptr if that is not posisble.
6203 /// If \p Check is true we will only verify such an operation would suceed and
6204 /// return a non-nullptr value if that is the case. No IR is generated or
6205 /// modified.
6206 static Value *reproduceValue(Attributor &A,
6207 const AbstractAttribute &QueryingAA, Value &V,
6208 Type &Ty, Instruction *CtxI, bool Check,
6209 ValueToValueMapTy &VMap) {
6210 if (const auto &NewV = VMap.lookup(&V))
6211 return NewV;
6212 bool UsedAssumedInformation = false;
6213 std::optional<Value *> SimpleV = A.getAssumedSimplified(
6214 V, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
6215 if (!SimpleV.has_value())
6216 return PoisonValue::get(&Ty);
6217 Value *EffectiveV = &V;
6218 if (*SimpleV)
6219 EffectiveV = *SimpleV;
6220 if (auto *C = dyn_cast<Constant>(EffectiveV))
6221 return C;
6222 if (CtxI && AA::isValidAtPosition(AA::ValueAndContext(*EffectiveV, *CtxI),
6223 A.getInfoCache()))
6224 return ensureType(A, *EffectiveV, Ty, CtxI, Check);
6225 if (auto *I = dyn_cast<Instruction>(EffectiveV))
6226 if (Value *NewV = reproduceInst(A, QueryingAA, *I, Ty, CtxI, Check, VMap))
6227 return ensureType(A, *NewV, Ty, CtxI, Check);
6228 return nullptr;
6229 }
6230
6231 /// Return a value we can use as replacement for the associated one, or
6232 /// nullptr if we don't have one that makes sense.
6233 Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const {
6234 Value *NewV = SimplifiedAssociatedValue
6235 ? *SimplifiedAssociatedValue
6236 : UndefValue::get(getAssociatedType());
6237 if (NewV && NewV != &getAssociatedValue()) {
6238 ValueToValueMapTy VMap;
6239 // First verify we can reprduce the value with the required type at the
6240 // context location before we actually start modifying the IR.
6241 if (reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
6242 /* CheckOnly */ true, VMap))
6243 return reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
6244 /* CheckOnly */ false, VMap);
6245 }
6246 return nullptr;
6247 }
6248
6249 /// Helper function for querying AAValueSimplify and updating candidate.
6250 /// \param IRP The value position we are trying to unify with SimplifiedValue
6251 bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
6252 const IRPosition &IRP, bool Simplify = true) {
6253 bool UsedAssumedInformation = false;
6254 std::optional<Value *> QueryingValueSimplified = &IRP.getAssociatedValue();
6255 if (Simplify)
6256 QueryingValueSimplified = A.getAssumedSimplified(
6257 IRP, QueryingAA, UsedAssumedInformation, AA::Interprocedural);
6258 return unionAssumed(QueryingValueSimplified);
6259 }
6260
6261 /// Returns a candidate is found or not
6262 template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
6263 if (!getAssociatedValue().getType()->isIntegerTy())
6264 return false;
6265
6266 // This will also pass the call base context.
6267 const auto *AA =
6268 A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE);
6269 if (!AA)
6270 return false;
6271
6272 std::optional<Constant *> COpt = AA->getAssumedConstant(A);
6273
6274 if (!COpt) {
6275 SimplifiedAssociatedValue = std::nullopt;
6276 A.recordDependence(*AA, *this, DepClassTy::OPTIONAL);
6277 return true;
6278 }
6279 if (auto *C = *COpt) {
6280 SimplifiedAssociatedValue = C;
6281 A.recordDependence(*AA, *this, DepClassTy::OPTIONAL);
6282 return true;
6283 }
6284 return false;
6285 }
6286
6287 bool askSimplifiedValueForOtherAAs(Attributor &A) {
6288 if (askSimplifiedValueFor<AAValueConstantRange>(A))
6289 return true;
6290 if (askSimplifiedValueFor<AAPotentialConstantValues>(A))
6291 return true;
6292 return false;
6293 }
6294
6295 ChangeStatus manifest(Attributor &A) override {
6296 ChangeStatus Changed = ChangeStatus::UNCHANGED;
6297 for (auto &U : getAssociatedValue().uses()) {
6298 // Check if we need to adjust the insertion point to make sure the IR is
6299 // valid.
6300 Instruction *IP = dyn_cast<Instruction>(U.getUser());
6301 if (auto *PHI = dyn_cast_or_null<PHINode>(IP))
6302 IP = PHI->getIncomingBlock(U)->getTerminator();
6303 if (auto *NewV = manifestReplacementValue(A, IP)) {
6304 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue()
6305 << " -> " << *NewV << " :: " << *this << "\n");
6306 if (A.changeUseAfterManifest(U, *NewV))
6307 Changed = ChangeStatus::CHANGED;
6308 }
6309 }
6310
6311 return Changed | AAValueSimplify::manifest(A);
6312 }
6313
6314 ChangeStatus indicatePessimisticFixpoint() override {
6315 SimplifiedAssociatedValue = &getAssociatedValue();
6316 return AAValueSimplify::indicatePessimisticFixpoint();
6317 }
6318};
6319
6320struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
6321 AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
6322 : AAValueSimplifyImpl(IRP, A) {}
6323
6324 void initialize(Attributor &A) override {
6325 AAValueSimplifyImpl::initialize(A);
6326 if (A.hasAttr(getIRPosition(),
6327 {Attribute::InAlloca, Attribute::Preallocated,
6328 Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
6329 /* IgnoreSubsumingPositions */ true))
6330 indicatePessimisticFixpoint();
6331 }
6332
6333 ChangeStatus updateImpl(Attributor &A) override {
6334 // Byval is only replacable if it is readonly otherwise we would write into
6335 // the replaced value and not the copy that byval creates implicitly.
6336 Argument *Arg = getAssociatedArgument();
6337 if (Arg->hasByValAttr()) {
6338 // TODO: We probably need to verify synchronization is not an issue, e.g.,
6339 // there is no race by not copying a constant byval.
6340 bool IsKnown;
6341 if (!AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
6342 return indicatePessimisticFixpoint();
6343 }
6344
6345 auto Before = SimplifiedAssociatedValue;
6346
6347 auto PredForCallSite = [&](AbstractCallSite ACS) {
6348 const IRPosition &ACSArgPos =
6349 IRPosition::callsite_argument(ACS, getCallSiteArgNo());
6350 // Check if a coresponding argument was found or if it is on not
6351 // associated (which can happen for callback calls).
6352 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
6353 return false;
6354
6355 // Simplify the argument operand explicitly and check if the result is
6356 // valid in the current scope. This avoids refering to simplified values
6357 // in other functions, e.g., we don't want to say a an argument in a
6358 // static function is actually an argument in a different function.
6359 bool UsedAssumedInformation = false;
6360 std::optional<Constant *> SimpleArgOp =
6361 A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation);
6362 if (!SimpleArgOp)
6363 return true;
6364 if (!*SimpleArgOp)
6365 return false;
6366 if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp))
6367 return false;
6368 return unionAssumed(*SimpleArgOp);
6369 };
6370
6371 // Generate a answer specific to a call site context.
6372 bool Success;
6373 bool UsedAssumedInformation = false;
6374 if (hasCallBaseContext() &&
6375 getCallBaseContext()->getCalledOperand() == Arg->getParent())
6376 Success = PredForCallSite(
6377 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
6378 else
6379 Success = A.checkForAllCallSites(PredForCallSite, *this, true,
6380 UsedAssumedInformation);
6381
6382 if (!Success)
6383 if (!askSimplifiedValueForOtherAAs(A))
6384 return indicatePessimisticFixpoint();
6385
6386 // If a candidate was found in this update, return CHANGED.
6387 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6388 : ChangeStatus ::CHANGED;
6389 }
6390
6391 void trackStatistics() const override {
6392 STATS_DECLTRACK_ARG_ATTR(value_simplify)
6393 }
6394};
6395
6396struct AAValueSimplifyReturned : AAValueSimplifyImpl {
6397 AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
6398 : AAValueSimplifyImpl(IRP, A) {}
6399
6400 std::optional<Value *>
6401 getAssumedSimplifiedValue(Attributor &A) const override {
6402 if (!isValidState())
6403 return nullptr;
6404 return SimplifiedAssociatedValue;
6405 }
6406
6407 ChangeStatus updateImpl(Attributor &A) override {
6408 auto Before = SimplifiedAssociatedValue;
6409
6410 auto ReturnInstCB = [&](Instruction &I) {
6411 auto &RI = cast<ReturnInst>(I);
6412 return checkAndUpdate(
6413 A, *this,
6414 IRPosition::value(*RI.getReturnValue(), getCallBaseContext()));
6415 };
6416
6417 bool UsedAssumedInformation = false;
6418 if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
6419 UsedAssumedInformation))
6420 if (!askSimplifiedValueForOtherAAs(A))
6421 return indicatePessimisticFixpoint();
6422
6423 // If a candidate was found in this update, return CHANGED.
6424 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6425 : ChangeStatus ::CHANGED;
6426 }
6427
6428 ChangeStatus manifest(Attributor &A) override {
6429 // We queried AAValueSimplify for the returned values so they will be
6430 // replaced if a simplified form was found. Nothing to do here.
6431 return ChangeStatus::UNCHANGED;
6432 }
6433
6434 void trackStatistics() const override {
6435 STATS_DECLTRACK_FNRET_ATTR(value_simplify)
6436 }
6437};
6438
6439struct AAValueSimplifyFloating : AAValueSimplifyImpl {
6440 AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
6441 : AAValueSimplifyImpl(IRP, A) {}
6442
6443 void initialize(Attributor &A) override {
6444 AAValueSimplifyImpl::initialize(A);
6445 Value &V = getAnchorValue();
6446
6447 // TODO: add other stuffs
6448 if (isa<Constant>(V))
6449 indicatePessimisticFixpoint();
6450 }
6451
6452 ChangeStatus updateImpl(Attributor &A) override {
6453 auto Before = SimplifiedAssociatedValue;
6454 if (!askSimplifiedValueForOtherAAs(A))
6455 return indicatePessimisticFixpoint();
6456
6457 // If a candidate was found in this update, return CHANGED.
6458 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6459 : ChangeStatus ::CHANGED;
6460 }
6461
6462 void trackStatistics() const override {
6463 STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
6464 }
6465};
6466
6467struct AAValueSimplifyFunction : AAValueSimplifyImpl {
6468 AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
6469 : AAValueSimplifyImpl(IRP, A) {}
6470
6471 void initialize(Attributor &A) override {
6472 SimplifiedAssociatedValue = nullptr;
6473 indicateOptimisticFixpoint();
6474 }
6475 ChangeStatus updateImpl(Attributor &A) override {
6477 "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
6478 }
6479 void trackStatistics() const override {
6480 STATS_DECLTRACK_FN_ATTR(value_simplify)
6481 }
6482};
6483
6484struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
6485 AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
6486 : AAValueSimplifyFunction(IRP, A) {}
6487 void trackStatistics() const override {
6488 STATS_DECLTRACK_CS_ATTR(value_simplify)
6489 }
6490};
6491
6492struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
6493 AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
6494 : AAValueSimplifyImpl(IRP, A) {}
6495
6496 void initialize(Attributor &A) override {
6497 AAValueSimplifyImpl::initialize(A);
6498 Function *Fn = getAssociatedFunction();
6499 assert(Fn && "Did expect an associted function");
6500 for (Argument &Arg : Fn->args()) {
6501 if (Arg.hasReturnedAttr()) {
6502 auto IRP = IRPosition::callsite_argument(*cast<CallBase>(getCtxI()),
6503 Arg.getArgNo());
6505 checkAndUpdate(A, *this, IRP))
6506 indicateOptimisticFixpoint();
6507 else
6508 indicatePessimisticFixpoint();
6509 return;
6510 }
6511 }
6512 }
6513
6514 ChangeStatus updateImpl(Attributor &A) override {
6515 return indicatePessimisticFixpoint();
6516 }
6517
6518 void trackStatistics() const override {
6519 STATS_DECLTRACK_CSRET_ATTR(value_simplify)
6520 }
6521};
6522
6523struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
6524 AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
6525 : AAValueSimplifyFloating(IRP, A) {}
6526
6527 ChangeStatus manifest(Attributor &A) override {
6528 ChangeStatus Changed = ChangeStatus::UNCHANGED;
6529 // TODO: We should avoid simplification duplication to begin with.
6530 auto *FloatAA = A.lookupAAFor<AAValueSimplify>(
6531 IRPosition::value(getAssociatedValue()), this, DepClassTy::NONE);
6532 if (FloatAA && FloatAA->getState().isValidState())
6533 return Changed;
6534
6535 if (auto *NewV = manifestReplacementValue(A, getCtxI())) {
6536 Use &U = cast<CallBase>(&getAnchorValue())
6537 ->getArgOperandUse(getCallSiteArgNo());
6538 if (A.changeUseAfterManifest(U, *NewV))
6539 Changed = ChangeStatus::CHANGED;
6540 }
6541
6542 return Changed | AAValueSimplify::manifest(A);
6543 }
6544
6545 void trackStatistics() const override {
6546 STATS_DECLTRACK_CSARG_ATTR(value_simplify)
6547 }
6548};
6549} // namespace
6550
6551/// Collect the non-musttail tail calls in the function of \p QueryingAA. Tail
6552/// calls cannot access allocas of the caller.
6553/// TODO: Be smarter about new allocas escaping into tail calls.
6554static bool collectTailCalls(Attributor &A, const AbstractAttribute &QueryingAA,
6555 SmallVectorImpl<CallInst *> &TailCalls) {
6556 bool UsedAssumedInformation = false;
6557 return A.checkForAllInstructions(
6558 [&](Instruction &I) {
6559 auto &CI = cast<CallInst>(I);
6560 if (CI.isTailCall() && !CI.isMustTailCall())
6561 TailCalls.push_back(&CI);
6562 return true;
6563 },
6564 QueryingAA, {Instruction::Call}, UsedAssumedInformation);
6565}
6566
6567/// ----------------------- Heap-To-Stack Conversion ---------------------------
6568namespace {
6569struct AAHeapToStackFunction final : public AAHeapToStack {
6570
6571 static bool isGlobalizedLocal(const CallBase &CB) {
6572 Attribute A = CB.getFnAttr("alloc-family");
6573 return A.isValid() && A.getValueAsString() == "__kmpc_alloc_shared";
6574 }
6575
6576 struct AllocationInfo {
6577 /// The call that allocates the memory.
6578 CallBase *const CB;
6579
6580 /// Whether this allocation is an OpenMP globalized local variable.
6581 bool IsGlobalizedLocal = false;
6582
6583 /// The status wrt. a rewrite.
6584 enum {
6585 STACK_DUE_TO_USE,
6586 STACK_DUE_TO_FREE,
6587 INVALID,
6588 } Status = STACK_DUE_TO_USE;
6589
6590 /// Flag to indicate if we encountered a use that might free this allocation
6591 /// but which is not in the deallocation infos.
6592 bool HasPotentiallyFreeingUnknownUses = false;
6593
6594 /// Flag to indicate that we should place the new alloca in the function
6595 /// entry block rather than where the call site (CB) is.
6596 bool MoveAllocaIntoEntry = true;
6597
6598 /// The set of free calls that use this allocation.
6599 SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
6600 };
6601
6602 struct DeallocationInfo {
6603 /// The call that deallocates the memory.
6604 CallBase *const CB;
6605 /// The value freed by the call.
6606 Value *FreedOp;
6607
6608 /// Flag to indicate if we don't know all objects this deallocation might
6609 /// free.
6610 bool MightFreeUnknownObjects = false;
6611
6612 /// The set of allocation calls that are potentially freed.
6613 SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
6614 };
6615
6616 AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
6617 : AAHeapToStack(IRP, A) {}
6618
6619 ~AAHeapToStackFunction() override {
6620 // Ensure we call the destructor so we release any memory allocated in the
6621 // sets.
6622 for (auto &It : AllocationInfos)
6623 It.second->~AllocationInfo();
6624 for (auto &It : DeallocationInfos)
6625 It.second->~DeallocationInfo();
6626 }
6627
6628 void initialize(Attributor &A) override {
6629 AAHeapToStack::initialize(A);
6630
6631 auto AllocationIdentifierCB = [&](Instruction &I) {
6632 CallBase *CB = dyn_cast<CallBase>(&I);
6633 if (!CB)
6634 return true;
6635 if (Value *FreedOp = getFreedOperand(CB)) {
6636 DeallocationInfos[CB] = new (A.Allocator) DeallocationInfo{CB, FreedOp};
6637 return true;
6638 }
6639 // To do heap to stack, we need to know that the allocation itself is
6640 // removable once uses are rewritten, and that we can initialize the
6641 // alloca to the same pattern as the original allocation result.
6642 if (isRemovableAlloc(CB)) {
6643 auto *I8Ty = Type::getInt8Ty(CB->getParent()->getContext());
6644 if (nullptr != getInitialValueOfAllocation(CB, I8Ty)) {
6645 AllocationInfo *AI = new (A.Allocator) AllocationInfo{CB};
6646 AllocationInfos[CB] = AI;
6647 AI->IsGlobalizedLocal = isGlobalizedLocal(*CB);
6648 }
6649 }
6650 return true;
6651 };
6652
6653 bool UsedAssumedInformation = false;
6654 bool Success = A.checkForAllCallLikeInstructions(
6655 AllocationIdentifierCB, *this, UsedAssumedInformation,
6656 /* CheckBBLivenessOnly */ false,
6657 /* CheckPotentiallyDead */ true);
6658 (void)Success;
6659 assert(Success && "Did not expect the call base visit callback to fail!");
6660
6662 [](const IRPosition &, const AbstractAttribute *,
6663 bool &) -> std::optional<Value *> { return nullptr; };
6664 for (const auto &It : AllocationInfos)
6665 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6666 SCB);
6667 for (const auto &It : DeallocationInfos)
6668 A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6669 SCB);
6670 }
6671
6672 const std::string getAsStr(Attributor *A) const override {
6673 unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
6674 for (const auto &It : AllocationInfos) {
6675 if (It.second->Status == AllocationInfo::INVALID)
6676 ++NumInvalidMallocs;
6677 else
6678 ++NumH2SMallocs;
6679 }
6680 return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) + "/" +
6681 std::to_string(NumInvalidMallocs);
6682 }
6683
6684 void trackStatistics() const override {
6685 STATS_DECL(
6686 MallocCalls, Function,
6687 "Number of malloc/calloc/aligned_alloc calls converted to allocas");
6688 for (const auto &It : AllocationInfos)
6689 if (It.second->Status != AllocationInfo::INVALID)
6690 ++BUILD_STAT_NAME(MallocCalls, Function);
6691 }
6692
6693 bool isAssumedHeapToStack(const CallBase &CB) const override {
6694 if (isValidState())
6695 if (AllocationInfo *AI =
6696 AllocationInfos.lookup(const_cast<CallBase *>(&CB)))
6697 return AI->Status != AllocationInfo::INVALID;
6698 return false;
6699 }
6700
6701 bool isAssumedHeapToStackRemovedFree(CallBase &CB) const override {
6702 if (!isValidState())
6703 return false;
6704
6705 for (const auto &It : AllocationInfos) {
6706 AllocationInfo &AI = *It.second;
6707 if (AI.Status == AllocationInfo::INVALID)
6708 continue;
6709
6710 if (AI.PotentialFreeCalls.count(&CB))
6711 return true;
6712 }
6713
6714 return false;
6715 }
6716
6717 ChangeStatus manifest(Attributor &A) override {
6718 assert(getState().isValidState() &&
6719 "Attempted to manifest an invalid state!");
6720
6721 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
6722 Function *F = getAnchorScope();
6723 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6724
6725 // The new allocas may escape into tail calls.
6727 if (any_of(AllocationInfos,
6728 [](const std::pair<CallBase *, AllocationInfo *> &It) {
6729 return It.second->Status != AllocationInfo::INVALID;
6730 }) &&
6731 !collectTailCalls(A, *this, TailCalls))
6732 return ChangeStatus::UNCHANGED;
6733
6734 for (auto &It : AllocationInfos) {
6735 AllocationInfo &AI = *It.second;
6736 if (AI.Status == AllocationInfo::INVALID)
6737 continue;
6738
6739 for (CallBase *FreeCall : AI.PotentialFreeCalls) {
6740 LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
6741 if (!FreeCall->use_empty())
6742 A.changeAfterManifest(IRPosition::callsite_returned(*FreeCall),
6743 *getElidedFreeResult(FreeCall));
6744 A.deleteAfterManifest(*FreeCall);
6745 HasChanged = ChangeStatus::CHANGED;
6746 }
6747
6748 LLVM_DEBUG(dbgs() << "H2S: Removing malloc-like call: " << *AI.CB
6749 << "\n");
6750
6751 auto Remark = [&](OptimizationRemark OR) {
6752 if (AI.IsGlobalizedLocal)
6753 return OR << "Moving globalized variable to the stack.";
6754 return OR << "Moving memory allocation from the heap to the stack.";
6755 };
6756 if (AI.IsGlobalizedLocal)
6757 A.emitRemark<OptimizationRemark>(AI.CB, "OMP110", Remark);
6758 else
6759 A.emitRemark<OptimizationRemark>(AI.CB, "HeapToStack", Remark);
6760
6761 const DataLayout &DL = A.getInfoCache().getDL();
6762 Value *Size;
6763 std::optional<APInt> SizeAPI = getSize(A, *this, AI);
6764 if (SizeAPI) {
6765 Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
6766 } else {
6767 ObjectSizeOpts Opts;
6768 ObjectSizeOffsetEvaluator Eval(*AI.CB->getModule(), TLI, Opts);
6769 SizeOffsetValue SizeOffsetPair = Eval.compute(AI.CB);
6770 assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() &&
6771 cast<ConstantInt>(SizeOffsetPair.Offset)->isZero());
6772 Size = SizeOffsetPair.Size;
6773 }
6774
6775 BasicBlock::iterator IP = AI.MoveAllocaIntoEntry
6776 ? F->getEntryBlock().begin()
6777 : AI.CB->getIterator();
6778
6779 Align Alignment(1);
6780 if (MaybeAlign RetAlign = AI.CB->getRetAlign())
6781 Alignment = std::max(Alignment, *RetAlign);
6782 if (Value *Align = getAllocAlignment(AI.CB)) {
6783 std::optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align);
6784 assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 &&
6785 "Expected an alignment during manifest!");
6786 Alignment =
6787 std::max(Alignment, assumeAligned(AlignmentAPI->getZExtValue()));
6788 }
6789
6790 // TODO: Hoist the alloca towards the function entry.
6791 unsigned AS = DL.getAllocaAddrSpace();
6792 Instruction *Alloca =
6793 new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
6794 AI.CB->getName() + ".h2s", IP);
6795
6796 if (Alloca->getType() != AI.CB->getType())
6797 Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6798 Alloca, AI.CB->getType(), "malloc_cast", AI.CB->getIterator());
6799
6800 auto *I8Ty = Type::getInt8Ty(F->getContext());
6801 auto *InitVal = getInitialValueOfAllocation(AI.CB, I8Ty);
6802 assert(InitVal &&
6803 "Must be able to materialize initial memory state of allocation");
6804
6805 A.changeAfterManifest(IRPosition::inst(*AI.CB), *Alloca);
6806
6807 if (auto *II = dyn_cast<InvokeInst>(AI.CB)) {
6808 auto *NBB = II->getNormalDest();
6809 UncondBrInst::Create(NBB, AI.CB->getParent());
6810 A.deleteAfterManifest(*AI.CB);
6811 } else {
6812 A.deleteAfterManifest(*AI.CB);
6813 }
6814
6815 // Initialize the alloca with the same value as used by the allocation
6816 // function. We can skip undef as the initial value of an alloc is
6817 // undef, and the memset would simply end up being DSEd.
6818 if (!isa<UndefValue>(InitVal)) {
6819 IRBuilder<> Builder(Alloca->getNextNode());
6820 // TODO: Use alignment above if align!=1
6821 Builder.CreateMemSet(Alloca, InitVal, Size, std::nullopt);
6822 }
6823 HasChanged = ChangeStatus::CHANGED;
6824 }
6825
6826 for (CallInst *CI : TailCalls)
6827 CI->setTailCall(false);
6828
6829 return HasChanged;
6830 }
6831
6832 std::optional<APInt> getAPInt(Attributor &A, const AbstractAttribute &AA,
6833 Value &V) {
6834 bool UsedAssumedInformation = false;
6835 std::optional<Constant *> SimpleV =
6836 A.getAssumedConstant(V, AA, UsedAssumedInformation);
6837 if (!SimpleV)
6838 return APInt(64, 0);
6839 if (auto *CI = dyn_cast_or_null<ConstantInt>(*SimpleV))
6840 return CI->getValue();
6841 return std::nullopt;
6842 }
6843
6844 std::optional<APInt> getSize(Attributor &A, const AbstractAttribute &AA,
6845 AllocationInfo &AI) {
6846 auto Mapper = [&](const Value *V) -> const Value * {
6847 bool UsedAssumedInformation = false;
6848 if (std::optional<Constant *> SimpleV =
6849 A.getAssumedConstant(*V, AA, UsedAssumedInformation))
6850 if (*SimpleV)
6851 return *SimpleV;
6852 return V;
6853 };
6854
6855 const Function *F = getAnchorScope();
6856 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6857 return getAllocSize(AI.CB, TLI, Mapper);
6858 }
6859
6860 /// Collection of all malloc-like calls in a function with associated
6861 /// information.
6862 MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6863
6864 /// Collection of all free-like calls in a function with associated
6865 /// information.
6866 MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6867
6868 ChangeStatus updateImpl(Attributor &A) override;
6869};
6870
6871ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) {
6873 const Function *F = getAnchorScope();
6874
6875 const auto *LivenessAA =
6876 A.getAAFor<AAIsDead>(*this, IRPosition::function(*F), DepClassTy::NONE);
6877
6878 MustBeExecutedContextExplorer *Explorer =
6879 A.getInfoCache().getMustBeExecutedContextExplorer();
6880
6881 bool StackIsAccessibleByOtherThreads =
6882 A.getInfoCache().stackIsAccessibleByOtherThreads();
6883
6884 LoopInfo *LI =
6885 A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F);
6886 std::optional<bool> MayContainIrreducibleControl;
6887 auto IsInLoop = [&](BasicBlock &BB) {
6888 if (&F->getEntryBlock() == &BB)
6889 return false;
6890 if (!MayContainIrreducibleControl.has_value())
6891 MayContainIrreducibleControl = mayContainIrreducibleControl(*F, LI);
6892 if (*MayContainIrreducibleControl)
6893 return true;
6894 if (!LI)
6895 return true;
6896 return LI->getLoopFor(&BB) != nullptr;
6897 };
6898
6899 // Flag to ensure we update our deallocation information at most once per
6900 // updateImpl call and only if we use the free check reasoning.
6901 bool HasUpdatedFrees = false;
6902
6903 auto UpdateFrees = [&]() {
6904 HasUpdatedFrees = true;
6905
6906 for (auto &It : DeallocationInfos) {
6907 DeallocationInfo &DI = *It.second;
6908 // For now we cannot use deallocations that have unknown inputs, skip
6909 // them.
6910 if (DI.MightFreeUnknownObjects)
6911 continue;
6912
6913 // No need to analyze dead calls, ignore them instead.
6914 bool UsedAssumedInformation = false;
6915 if (A.isAssumedDead(*DI.CB, this, LivenessAA, UsedAssumedInformation,
6916 /* CheckBBLivenessOnly */ true))
6917 continue;
6918
6919 // Use the non-optimistic version to get the freed object.
6920 Value *Obj = getUnderlyingObject(DI.FreedOp);
6921 if (!Obj) {
6922 LLVM_DEBUG(dbgs() << "[H2S] Unknown underlying object for free!\n");
6923 DI.MightFreeUnknownObjects = true;
6924 continue;
6925 }
6926
6927 // Free of null and undef can be ignored as no-ops (or UB in the latter
6928 // case).
6930 continue;
6931
6932 CallBase *ObjCB = dyn_cast<CallBase>(Obj);
6933 if (!ObjCB) {
6934 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-call object: " << *Obj
6935 << "\n");
6936 DI.MightFreeUnknownObjects = true;
6937 continue;
6938 }
6939
6940 AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6941 if (!AI) {
6942 LLVM_DEBUG(dbgs() << "[H2S] Free of a non-allocation object: " << *Obj
6943 << "\n");
6944 DI.MightFreeUnknownObjects = true;
6945 continue;
6946 }
6947
6948 DI.PotentialAllocationCalls.insert(ObjCB);
6949 }
6950 };
6951
6952 auto FreeCheck = [&](AllocationInfo &AI) {
6953 // If the stack is not accessible by other threads, the "must-free" logic
6954 // doesn't apply as the pointer could be shared and needs to be places in
6955 // "shareable" memory.
6956 if (!StackIsAccessibleByOtherThreads) {
6957 bool IsKnownNoSycn;
6959 A, this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoSycn)) {
6960 LLVM_DEBUG(
6961 dbgs() << "[H2S] found an escaping use, stack is not accessible by "
6962 "other threads and function is not nosync:\n");
6963 return false;
6964 }
6965 }
6966 if (!HasUpdatedFrees)
6967 UpdateFrees();
6968
6969 // TODO: Allow multi exit functions that have different free calls.
6970 if (AI.PotentialFreeCalls.size() != 1) {
6971 LLVM_DEBUG(dbgs() << "[H2S] did not find one free call but "
6972 << AI.PotentialFreeCalls.size() << "\n");
6973 return false;
6974 }
6975 CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6976 DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6977 if (!DI) {
6978 LLVM_DEBUG(
6979 dbgs() << "[H2S] unique free call was not known as deallocation call "
6980 << *UniqueFree << "\n");
6981 return false;
6982 }
6983 if (DI->MightFreeUnknownObjects) {
6984 LLVM_DEBUG(
6985 dbgs() << "[H2S] unique free call might free unknown allocations\n");
6986 return false;
6987 }
6988 if (DI->PotentialAllocationCalls.empty())
6989 return true;
6990 if (DI->PotentialAllocationCalls.size() > 1) {
6991 LLVM_DEBUG(dbgs() << "[H2S] unique free call might free "
6992 << DI->PotentialAllocationCalls.size()
6993 << " different allocations\n");
6994 return false;
6995 }
6996 if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
6997 LLVM_DEBUG(
6998 dbgs()
6999 << "[H2S] unique free call not known to free this allocation but "
7000 << **DI->PotentialAllocationCalls.begin() << "\n");
7001 return false;
7002 }
7003
7004 // __kmpc_alloc_shared and __kmpc_free_shared are by construction matched.
7005 if (!AI.IsGlobalizedLocal) {
7006 Instruction *CtxI = isa<InvokeInst>(AI.CB) ? AI.CB : AI.CB->getNextNode();
7007 if (!Explorer || !Explorer->isInContextOf(UniqueFree, CtxI)) {
7008 LLVM_DEBUG(dbgs() << "[H2S] unique free call might not be executed "
7009 "with the allocation "
7010 << *UniqueFree << "\n");
7011 return false;
7012 }
7013 }
7014 return true;
7015 };
7016
7017 auto UsesCheck = [&](AllocationInfo &AI) {
7018 bool ValidUsesOnly = true;
7019
7020 auto Pred = [&](const Use &U, bool &Follow) -> bool {
7021 Instruction *UserI = cast<Instruction>(U.getUser());
7022 if (isa<LoadInst>(UserI))
7023 return true;
7024 if (auto *SI = dyn_cast<StoreInst>(UserI)) {
7025 if (SI->getValueOperand() == U.get()) {
7027 << "[H2S] escaping store to memory: " << *UserI << "\n");
7028 ValidUsesOnly = false;
7029 } else {
7030 // A store into the malloc'ed memory is fine.
7031 }
7032 return true;
7033 }
7034 if (auto *CB = dyn_cast<CallBase>(UserI)) {
7035 // A musttail call cannot access allocas of the caller, and its marker
7036 // cannot be removed.
7037 if (CB->isMustTailCall()) {
7038 LLVM_DEBUG(dbgs() << "[H2S] musttail user: " << *UserI << "\n");
7039 ValidUsesOnly = false;
7040 return true;
7041 }
7042
7043 if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
7044 return true;
7045 if (DeallocationInfos.count(CB)) {
7046 AI.PotentialFreeCalls.insert(CB);
7047 return true;
7048 }
7049
7050 unsigned ArgNo = CB->getArgOperandNo(&U);
7051 auto CBIRP = IRPosition::callsite_argument(*CB, ArgNo);
7052
7053 bool IsKnownNoCapture;
7054 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
7055 A, this, CBIRP, DepClassTy::OPTIONAL, IsKnownNoCapture);
7056
7057 // If a call site argument use is nofree, we are fine.
7058 bool IsKnownNoFree;
7059 bool IsAssumedNoFree = AA::hasAssumedIRAttr<Attribute::NoFree>(
7060 A, this, CBIRP, DepClassTy::OPTIONAL, IsKnownNoFree);
7061
7062 if (!IsAssumedNoCapture ||
7063 (!AI.IsGlobalizedLocal && !IsAssumedNoFree)) {
7064 AI.HasPotentiallyFreeingUnknownUses |= !IsAssumedNoFree;
7065
7066 // Emit a missed remark if this is missed OpenMP globalization.
7067 auto Remark = [&](OptimizationRemarkMissed ORM) {
7068 return ORM
7069 << "Could not move globalized variable to the stack. "
7070 "Variable is potentially captured in call. Mark "
7071 "parameter as `__attribute__((noescape))` to override.";
7072 };
7073
7074 if (ValidUsesOnly && AI.IsGlobalizedLocal)
7075 A.emitRemark<OptimizationRemarkMissed>(CB, "OMP113", Remark);
7076
7077 LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
7078 ValidUsesOnly = false;
7079 }
7080 return true;
7081 }
7082
7083 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
7084 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
7085 Follow = true;
7086 return true;
7087 }
7088 // Unknown user for which we can not track uses further (in a way that
7089 // makes sense).
7090 LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
7091 ValidUsesOnly = false;
7092 return true;
7093 };
7094 if (!A.checkForAllUses(Pred, *this, *AI.CB, /* CheckBBLivenessOnly */ false,
7095 DepClassTy::OPTIONAL, /* IgnoreDroppableUses */ true,
7096 [&](const Use &OldU, const Use &NewU) {
7097 auto *SI = dyn_cast<StoreInst>(OldU.getUser());
7098 return !SI || StackIsAccessibleByOtherThreads ||
7099 AA::isAssumedThreadLocalObject(
7100 A, *SI->getPointerOperand(), *this);
7101 }))
7102 return false;
7103 return ValidUsesOnly;
7104 };
7105
7106 // The actual update starts here. We look at all allocations and depending on
7107 // their status perform the appropriate check(s).
7108 for (auto &It : AllocationInfos) {
7109 AllocationInfo &AI = *It.second;
7110 if (AI.Status == AllocationInfo::INVALID)
7111 continue;
7112
7113 if (Value *Align = getAllocAlignment(AI.CB)) {
7114 std::optional<APInt> APAlign = getAPInt(A, *this, *Align);
7115 if (!APAlign) {
7116 // Can't generate an alloca which respects the required alignment
7117 // on the allocation.
7118 LLVM_DEBUG(dbgs() << "[H2S] Unknown allocation alignment: " << *AI.CB
7119 << "\n");
7120 AI.Status = AllocationInfo::INVALID;
7122 continue;
7123 }
7124 if (APAlign->ugt(llvm::Value::MaximumAlignment) ||
7125 !APAlign->isPowerOf2()) {
7126 LLVM_DEBUG(dbgs() << "[H2S] Invalid allocation alignment: " << APAlign
7127 << "\n");
7128 AI.Status = AllocationInfo::INVALID;
7130 continue;
7131 }
7132 }
7133
7134 std::optional<APInt> Size = getSize(A, *this, AI);
7135 if (!AI.IsGlobalizedLocal && A.Opts.max_heap_to_stack_size != -1) {
7136 if (!Size || Size->ugt(A.Opts.max_heap_to_stack_size)) {
7137 LLVM_DEBUG({
7138 if (!Size)
7139 dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n";
7140 else
7141 dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. "
7142 << A.Opts.max_heap_to_stack_size << "\n";
7143 });
7144
7145 AI.Status = AllocationInfo::INVALID;
7147 continue;
7148 }
7149 }
7150
7151 switch (AI.Status) {
7152 case AllocationInfo::STACK_DUE_TO_USE:
7153 if (UsesCheck(AI))
7154 break;
7155 AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
7156 [[fallthrough]];
7157 case AllocationInfo::STACK_DUE_TO_FREE:
7158 if (FreeCheck(AI))
7159 break;
7160 AI.Status = AllocationInfo::INVALID;
7162 break;
7163 case AllocationInfo::INVALID:
7164 llvm_unreachable("Invalid allocations should never reach this point!");
7165 };
7166
7167 // Check if we still think we can move it into the entry block. If the
7168 // alloca comes from a converted __kmpc_alloc_shared then we can usually
7169 // ignore the potential complications associated with loops.
7170 bool IsGlobalizedLocal = AI.IsGlobalizedLocal;
7171 if (AI.MoveAllocaIntoEntry &&
7172 (!Size.has_value() ||
7173 (!IsGlobalizedLocal && IsInLoop(*AI.CB->getParent()))))
7174 AI.MoveAllocaIntoEntry = false;
7175 }
7176
7177 return Changed;
7178}
7179} // namespace
7180
7181/// ----------------------- Privatizable Pointers ------------------------------
7182namespace {
7183struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
7184 AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
7185 : AAPrivatizablePtr(IRP, A), PrivatizableType(std::nullopt) {}
7186
7187 ChangeStatus indicatePessimisticFixpoint() override {
7188 AAPrivatizablePtr::indicatePessimisticFixpoint();
7189 PrivatizableType = nullptr;
7190 return ChangeStatus::CHANGED;
7191 }
7192
7193 /// Identify the type we can chose for a private copy of the underlying
7194 /// argument. std::nullopt means it is not clear yet, nullptr means there is
7195 /// none.
7196 virtual std::optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
7197
7198 /// Return a privatizable type that encloses both T0 and T1.
7199 /// TODO: This is merely a stub for now as we should manage a mapping as well.
7200 std::optional<Type *> combineTypes(std::optional<Type *> T0,
7201 std::optional<Type *> T1) {
7202 if (!T0)
7203 return T1;
7204 if (!T1)
7205 return T0;
7206 if (T0 == T1)
7207 return T0;
7208 return nullptr;
7209 }
7210
7211 std::optional<Type *> getPrivatizableType() const override {
7212 return PrivatizableType;
7213 }
7214
7215 const std::string getAsStr(Attributor *A) const override {
7216 return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
7217 }
7218
7219protected:
7220 std::optional<Type *> PrivatizableType;
7221};
7222
7223// TODO: Do this for call site arguments (probably also other values) as well.
7224
7225struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
7226 AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
7227 : AAPrivatizablePtrImpl(IRP, A) {}
7228
7229 std::optional<Type *> identifyPrivatizableType(Attributor &A) override {
7230 // If this is a byval argument and we know all the call sites (so we can
7231 // rewrite them), there is no need to check them explicitly.
7232 bool UsedAssumedInformation = false;
7234 A.getAttrs(getIRPosition(), {Attribute::ByVal}, Attrs,
7235 /* IgnoreSubsumingPositions */ true);
7236 if (!Attrs.empty() &&
7237 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
7238 true, UsedAssumedInformation))
7239 return Attrs[0].getValueAsType();
7240
7241 std::optional<Type *> Ty;
7242 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
7243
7244 // Make sure the associated call site argument has the same type at all call
7245 // sites and it is an allocation we know is safe to privatize, for now that
7246 // means we only allow alloca instructions.
7247 // TODO: We can additionally analyze the accesses in the callee to create
7248 // the type from that information instead. That is a little more
7249 // involved and will be done in a follow up patch.
7250 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7251 IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
7252 // Check if a coresponding argument was found or if it is one not
7253 // associated (which can happen for callback calls).
7254 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
7255 return false;
7256
7257 // Check that all call sites agree on a type.
7258 auto *PrivCSArgAA =
7259 A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED);
7260 if (!PrivCSArgAA)
7261 return false;
7262 std::optional<Type *> CSTy = PrivCSArgAA->getPrivatizableType();
7263
7264 LLVM_DEBUG({
7265 dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
7266 if (CSTy && *CSTy)
7267 (*CSTy)->print(dbgs());
7268 else if (CSTy)
7269 dbgs() << "<nullptr>";
7270 else
7271 dbgs() << "<none>";
7272 });
7273
7274 Ty = combineTypes(Ty, CSTy);
7275
7276 LLVM_DEBUG({
7277 dbgs() << " : New Type: ";
7278 if (Ty && *Ty)
7279 (*Ty)->print(dbgs());
7280 else if (Ty)
7281 dbgs() << "<nullptr>";
7282 else
7283 dbgs() << "<none>";
7284 dbgs() << "\n";
7285 });
7286
7287 return !Ty || *Ty;
7288 };
7289
7290 if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
7291 UsedAssumedInformation))
7292 return nullptr;
7293 return Ty;
7294 }
7295
7296 ChangeStatus updateImpl(Attributor &A) override {
7297 PrivatizableType = identifyPrivatizableType(A);
7298 if (!PrivatizableType)
7299 return ChangeStatus::UNCHANGED;
7300 if (!*PrivatizableType)
7301 return indicatePessimisticFixpoint();
7302
7303 // The dependence is optional so we don't give up once we give up on the
7304 // alignment.
7305 A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
7306 DepClassTy::OPTIONAL);
7307
7308 // Avoid arguments with padding for now.
7309 if (!A.hasAttr(getIRPosition(), Attribute::ByVal) &&
7310 !isDenselyPacked(*PrivatizableType, A.getInfoCache().getDL())) {
7311 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
7312 return indicatePessimisticFixpoint();
7313 }
7314
7315 // Collect the types that will replace the privatizable type in the function
7316 // signature.
7317 SmallVector<Type *, 16> ReplacementTypes;
7318 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7319
7320 // Verify callee and caller agree on how the promoted argument would be
7321 // passed.
7322 Function &Fn = *getIRPosition().getAnchorScope();
7323 const auto *TTI =
7324 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
7325 if (!TTI) {
7326 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Missing TTI for function "
7327 << Fn.getName() << "\n");
7328 return indicatePessimisticFixpoint();
7329 }
7330
7331 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7332 CallBase *CB = ACS.getInstruction();
7333 return TTI->areTypesABICompatible(
7334 CB->getCaller(),
7336 ReplacementTypes);
7337 };
7338 bool UsedAssumedInformation = false;
7339 if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
7340 UsedAssumedInformation)) {
7341 LLVM_DEBUG(
7342 dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
7343 << Fn.getName() << "\n");
7344 return indicatePessimisticFixpoint();
7345 }
7346
7347 // Register a rewrite of the argument.
7348 Argument *Arg = getAssociatedArgument();
7349 if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
7350 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
7351 return indicatePessimisticFixpoint();
7352 }
7353
7354 unsigned ArgNo = Arg->getArgNo();
7355
7356 // Helper to check if for the given call site the associated argument is
7357 // passed to a callback where the privatization would be different.
7358 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
7359 SmallVector<const Use *, 4> CallbackUses;
7360 AbstractCallSite::getCallbackUses(CB, CallbackUses);
7361 for (const Use *U : CallbackUses) {
7362 AbstractCallSite CBACS(U);
7363 assert(CBACS && CBACS.isCallbackCall());
7364 for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
7365 int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
7366
7367 LLVM_DEBUG({
7368 dbgs()
7369 << "[AAPrivatizablePtr] Argument " << *Arg
7370 << "check if can be privatized in the context of its parent ("
7371 << Arg->getParent()->getName()
7372 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7373 "callback ("
7374 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
7375 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
7376 << CBACS.getCallArgOperand(CBArg) << " vs "
7377 << CB.getArgOperand(ArgNo) << "\n"
7378 << "[AAPrivatizablePtr] " << CBArg << " : "
7379 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
7380 });
7381
7382 if (CBArgNo != int(ArgNo))
7383 continue;
7384 const auto *CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
7385 *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED);
7386 if (CBArgPrivAA && CBArgPrivAA->isValidState()) {
7387 auto CBArgPrivTy = CBArgPrivAA->getPrivatizableType();
7388 if (!CBArgPrivTy)
7389 continue;
7390 if (*CBArgPrivTy == PrivatizableType)
7391 continue;
7392 }
7393
7394 LLVM_DEBUG({
7395 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7396 << " cannot be privatized in the context of its parent ("
7397 << Arg->getParent()->getName()
7398 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7399 "callback ("
7400 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
7401 << ").\n[AAPrivatizablePtr] for which the argument "
7402 "privatization is not compatible.\n";
7403 });
7404 return false;
7405 }
7406 }
7407 return true;
7408 };
7409
7410 // Helper to check if for the given call site the associated argument is
7411 // passed to a direct call where the privatization would be different.
7412 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
7413 CallBase *DC = cast<CallBase>(ACS.getInstruction());
7414 int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
7415 assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->arg_size() &&
7416 "Expected a direct call operand for callback call operand");
7417
7418 Function *DCCallee =
7420 LLVM_DEBUG({
7421 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7422 << " check if be privatized in the context of its parent ("
7423 << Arg->getParent()->getName()
7424 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7425 "direct call of ("
7426 << DCArgNo << "@" << DCCallee->getName() << ").\n";
7427 });
7428
7429 if (unsigned(DCArgNo) < DCCallee->arg_size()) {
7430 const auto *DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
7431 *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)),
7432 DepClassTy::REQUIRED);
7433 if (DCArgPrivAA && DCArgPrivAA->isValidState()) {
7434 auto DCArgPrivTy = DCArgPrivAA->getPrivatizableType();
7435 if (!DCArgPrivTy)
7436 return true;
7437 if (*DCArgPrivTy == PrivatizableType)
7438 return true;
7439 }
7440 }
7441
7442 LLVM_DEBUG({
7443 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
7444 << " cannot be privatized in the context of its parent ("
7445 << Arg->getParent()->getName()
7446 << ")\n[AAPrivatizablePtr] because it is an argument in a "
7447 "direct call of ("
7449 << ").\n[AAPrivatizablePtr] for which the argument "
7450 "privatization is not compatible.\n";
7451 });
7452 return false;
7453 };
7454
7455 // Helper to check if the associated argument is used at the given abstract
7456 // call site in a way that is incompatible with the privatization assumed
7457 // here.
7458 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
7459 if (ACS.isDirectCall())
7460 return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
7461 if (ACS.isCallbackCall())
7462 return IsCompatiblePrivArgOfDirectCS(ACS);
7463 return false;
7464 };
7465
7466 if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
7467 UsedAssumedInformation))
7468 return indicatePessimisticFixpoint();
7469
7470 return ChangeStatus::UNCHANGED;
7471 }
7472
7473 /// Given a type to private \p PrivType, collect the constituates (which are
7474 /// used) in \p ReplacementTypes.
7475 static void
7476 identifyReplacementTypes(Type *PrivType,
7477 SmallVectorImpl<Type *> &ReplacementTypes) {
7478 // TODO: For now we expand the privatization type to the fullest which can
7479 // lead to dead arguments that need to be removed later.
7480 assert(PrivType && "Expected privatizable type!");
7481
7482 // Traverse the type, extract constituate types on the outermost level.
7483 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7484 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
7485 ReplacementTypes.push_back(PrivStructType->getElementType(u));
7486 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7487 ReplacementTypes.append(PrivArrayType->getNumElements(),
7488 PrivArrayType->getElementType());
7489 } else {
7490 ReplacementTypes.push_back(PrivType);
7491 }
7492 }
7493
7494 /// Initialize \p Base according to the type \p PrivType at position \p IP.
7495 /// The values needed are taken from the arguments of \p F starting at
7496 /// position \p ArgNo.
7497 static void createInitialization(Type *PrivType, Value &Base, Function &F,
7498 unsigned ArgNo, BasicBlock::iterator IP) {
7499 assert(PrivType && "Expected privatizable type!");
7500
7501 IRBuilder<NoFolder> IRB(IP);
7502 const DataLayout &DL = F.getDataLayout();
7503
7504 // Traverse the type, build GEPs and stores.
7505 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7506 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
7507 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7508 Value *Ptr =
7509 constructPointer(&Base, PrivStructLayout->getElementOffset(u), IRB);
7510 new StoreInst(F.getArg(ArgNo + u), Ptr, IP);
7511 }
7512 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7513 Type *PointeeTy = PrivArrayType->getElementType();
7514 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
7515 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7516 Value *Ptr = constructPointer(&Base, u * PointeeTySize, IRB);
7517 new StoreInst(F.getArg(ArgNo + u), Ptr, IP);
7518 }
7519 } else {
7520 new StoreInst(F.getArg(ArgNo), &Base, IP);
7521 }
7522 }
7523
7524 /// Extract values from \p Base according to the type \p PrivType at the
7525 /// call position \p ACS. The values are appended to \p ReplacementValues.
7526 void createReplacementValues(Align Alignment, Type *PrivType,
7527 AbstractCallSite ACS, Value *Base,
7528 SmallVectorImpl<Value *> &ReplacementValues) {
7529 assert(Base && "Expected base value!");
7530 assert(PrivType && "Expected privatizable type!");
7531 Instruction *IP = ACS.getInstruction();
7532
7533 IRBuilder<NoFolder> IRB(IP);
7534 const DataLayout &DL = IP->getDataLayout();
7535
7536 // Traverse the type, build GEPs and loads.
7537 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
7538 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
7539 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7540 Type *PointeeTy = PrivStructType->getElementType(u);
7541 Value *Ptr =
7542 constructPointer(Base, PrivStructLayout->getElementOffset(u), IRB);
7543 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP->getIterator());
7544 L->setAlignment(Alignment);
7545 ReplacementValues.push_back(L);
7546 }
7547 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
7548 Type *PointeeTy = PrivArrayType->getElementType();
7549 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
7550 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7551 Value *Ptr = constructPointer(Base, u * PointeeTySize, IRB);
7552 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP->getIterator());
7553 L->setAlignment(Alignment);
7554 ReplacementValues.push_back(L);
7555 }
7556 } else {
7557 LoadInst *L = new LoadInst(PrivType, Base, "", IP->getIterator());
7558 L->setAlignment(Alignment);
7559 ReplacementValues.push_back(L);
7560 }
7561 }
7562
7563 ChangeStatus manifest(Attributor &A) override {
7564 if (!PrivatizableType)
7565 return ChangeStatus::UNCHANGED;
7566 assert(*PrivatizableType && "Expected privatizable type!");
7567
7568 Argument *Arg = getAssociatedArgument();
7569 // Query AAAlign attribute for alignment of associated argument to
7570 // determine the best alignment of loads.
7571 const auto *AlignAA =
7572 A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE);
7573
7574 // Callback to repair the associated function. A new alloca is placed at the
7575 // beginning and initialized with the values passed through arguments. The
7576 // new alloca replaces the use of the old pointer argument.
7578 [=](const Attributor::ArgumentReplacementInfo &ARI,
7579 Function &ReplacementFn, Function::arg_iterator ArgIt) {
7580 BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
7582 const DataLayout &DL = IP->getDataLayout();
7583 unsigned AS = DL.getAllocaAddrSpace();
7584 Instruction *AI = new AllocaInst(*PrivatizableType, AS,
7585 Arg->getName() + ".priv", IP);
7586 createInitialization(*PrivatizableType, *AI, ReplacementFn,
7587 ArgIt->getArgNo(), IP);
7588
7589 if (AI->getType() != Arg->getType())
7590 AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
7591 AI, Arg->getType(), "", IP);
7592 Arg->replaceAllUsesWith(AI);
7593
7594 // The new alloca may escape into tail calls. Find them here, as calls
7595 // may have been replaced or deleted since manifest.
7596 for (Instruction &I : instructions(ReplacementFn)) {
7597 auto *CI = dyn_cast<CallInst>(&I);
7598 if (CI && CI->isTailCall() && !CI->isMustTailCall())
7599 CI->setTailCall(false);
7600 }
7601 };
7602
7603 // Callback to repair a call site of the associated function. The elements
7604 // of the privatizable type are loaded prior to the call and passed to the
7605 // new function version.
7607 [=](const Attributor::ArgumentReplacementInfo &ARI,
7608 AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
7609 // When no alignment is specified for the load instruction,
7610 // natural alignment is assumed.
7611 createReplacementValues(
7612 AlignAA ? AlignAA->getAssumedAlign() : Align(0),
7613 *PrivatizableType, ACS,
7614 ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
7615 NewArgOperands);
7616 };
7617
7618 // Collect the types that will replace the privatizable type in the function
7619 // signature.
7620 SmallVector<Type *, 16> ReplacementTypes;
7621 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7622
7623 // Register a rewrite of the argument.
7624 if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
7625 std::move(FnRepairCB),
7626 std::move(ACSRepairCB)))
7627 return ChangeStatus::CHANGED;
7628 return ChangeStatus::UNCHANGED;
7629 }
7630
7631 void trackStatistics() const override {
7632 STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
7633 }
7634};
7635
7636struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
7637 AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
7638 : AAPrivatizablePtrImpl(IRP, A) {}
7639
7640 void initialize(Attributor &A) override {
7641 // TODO: We can privatize more than arguments.
7642 indicatePessimisticFixpoint();
7643 }
7644
7645 ChangeStatus updateImpl(Attributor &A) override {
7646 llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
7647 "updateImpl will not be called");
7648 }
7649
7650 std::optional<Type *> identifyPrivatizableType(Attributor &A) override {
7651 Value *Obj = getUnderlyingObject(&getAssociatedValue());
7652 if (!Obj) {
7653 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
7654 return nullptr;
7655 }
7656
7657 if (auto *AI = dyn_cast<AllocaInst>(Obj))
7658 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
7659 if (CI->isOne())
7660 return AI->getAllocatedType();
7661 if (auto *Arg = dyn_cast<Argument>(Obj)) {
7662 auto *PrivArgAA = A.getAAFor<AAPrivatizablePtr>(
7663 *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED);
7664 if (PrivArgAA && PrivArgAA->isAssumedPrivatizablePtr())
7665 return PrivArgAA->getPrivatizableType();
7666 }
7667
7668 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
7669 "alloca nor privatizable argument: "
7670 << *Obj << "!\n");
7671 return nullptr;
7672 }
7673
7674 void trackStatistics() const override {
7675 STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
7676 }
7677};
7678
7679struct AAPrivatizablePtrCallSiteArgument final
7680 : public AAPrivatizablePtrFloating {
7681 AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
7682 : AAPrivatizablePtrFloating(IRP, A) {}
7683
7684 void initialize(Attributor &A) override {
7685 if (A.hasAttr(getIRPosition(), Attribute::ByVal))
7686 indicateOptimisticFixpoint();
7687 }
7688
7689 ChangeStatus updateImpl(Attributor &A) override {
7690 PrivatizableType = identifyPrivatizableType(A);
7691 if (!PrivatizableType)
7692 return ChangeStatus::UNCHANGED;
7693 if (!*PrivatizableType)
7694 return indicatePessimisticFixpoint();
7695
7696 const IRPosition &IRP = getIRPosition();
7697 bool IsKnownNoCapture;
7698 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
7699 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoCapture);
7700 if (!IsAssumedNoCapture) {
7701 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
7702 return indicatePessimisticFixpoint();
7703 }
7704
7705 bool IsKnownNoAlias;
7707 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
7708 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
7709 return indicatePessimisticFixpoint();
7710 }
7711
7712 bool IsKnown;
7713 if (!AA::isAssumedReadOnly(A, IRP, *this, IsKnown)) {
7714 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
7715 return indicatePessimisticFixpoint();
7716 }
7717
7718 return ChangeStatus::UNCHANGED;
7719 }
7720
7721 void trackStatistics() const override {
7722 STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
7723 }
7724};
7725
7726struct AAPrivatizablePtrCallSiteReturned final
7727 : public AAPrivatizablePtrFloating {
7728 AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
7729 : AAPrivatizablePtrFloating(IRP, A) {}
7730
7731 void initialize(Attributor &A) override {
7732 // TODO: We can privatize more than arguments.
7733 indicatePessimisticFixpoint();
7734 }
7735
7736 void trackStatistics() const override {
7737 STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
7738 }
7739};
7740
7741struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
7742 AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
7743 : AAPrivatizablePtrFloating(IRP, A) {}
7744
7745 void initialize(Attributor &A) override {
7746 // TODO: We can privatize more than arguments.
7747 indicatePessimisticFixpoint();
7748 }
7749
7750 void trackStatistics() const override {
7751 STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
7752 }
7753};
7754} // namespace
7755
7756/// -------------------- Memory Behavior Attributes ----------------------------
7757/// Includes read-none, read-only, and write-only.
7758/// ----------------------------------------------------------------------------
7759namespace {
7760struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
7761 AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
7762 : AAMemoryBehavior(IRP, A) {}
7763
7764 void initialize(Attributor &A) override {
7765 intersectAssumedBits(BEST_STATE);
7766 getKnownStateFromValue(A, getIRPosition(), getState());
7767 AAMemoryBehavior::initialize(A);
7768 }
7769
7770 /// Return the memory behavior information encoded in the IR for \p IRP.
7771 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
7772 BitIntegerState &State,
7773 bool IgnoreSubsumingPositions = false) {
7775 A.getAttrs(IRP, AttrKinds, Attrs, IgnoreSubsumingPositions);
7776 for (const Attribute &Attr : Attrs) {
7777 switch (Attr.getKindAsEnum()) {
7778 case Attribute::ReadNone:
7779 State.addKnownBits(NO_ACCESSES);
7780 break;
7781 case Attribute::ReadOnly:
7782 State.addKnownBits(NO_WRITES);
7783 break;
7784 case Attribute::WriteOnly:
7785 State.addKnownBits(NO_READS);
7786 break;
7787 default:
7788 llvm_unreachable("Unexpected attribute!");
7789 }
7790 }
7791
7792 // Only a call site anchor performs the accesses of the position. A floating
7793 // value is only defined by its anchor, e.g., a loaded pointer may be
7794 // written through even though the load does not write.
7796 if (Kind == IRPosition::IRP_CALL_SITE ||
7798 if (auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue())) {
7800 if (!isRefSet(MR))
7801 State.addKnownBits(NO_READS);
7802 if (!isModSet(MR))
7803 State.addKnownBits(NO_WRITES);
7804 }
7805 }
7806 }
7807
7808 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
7809 SmallVectorImpl<Attribute> &Attrs) const override {
7810 assert(Attrs.size() == 0);
7811 if (isAssumedReadNone())
7812 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7813 else if (isAssumedReadOnly())
7814 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7815 else if (isAssumedWriteOnly())
7816 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7817 assert(Attrs.size() <= 1);
7818 }
7819
7820 ChangeStatus manifest(Attributor &A) override {
7821 const IRPosition &IRP = getIRPosition();
7822
7823 if (A.hasAttr(IRP, Attribute::ReadNone,
7824 /* IgnoreSubsumingPositions */ true))
7825 return ChangeStatus::UNCHANGED;
7826
7827 // Check if we would improve the existing attributes first.
7828 SmallVector<Attribute, 4> DeducedAttrs;
7829 getDeducedAttributes(A, IRP.getAnchorValue().getContext(), DeducedAttrs);
7830 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7831 return A.hasAttr(IRP, Attr.getKindAsEnum(),
7832 /* IgnoreSubsumingPositions */ true);
7833 }))
7834 return ChangeStatus::UNCHANGED;
7835
7836 // Clear existing attributes.
7837 A.removeAttrs(IRP, AttrKinds);
7838 // Clear conflicting writable attribute.
7839 if (isAssumedReadOnly())
7840 A.removeAttrs(IRP, Attribute::Writable);
7841
7842 // Use the generic manifest method.
7843 return IRAttribute::manifest(A);
7844 }
7845
7846 const std::string getAsStr(Attributor *A) const override {
7847 if (isAssumedReadNone())
7848 return "readnone";
7849 if (isAssumedReadOnly())
7850 return "readonly";
7851 if (isAssumedWriteOnly())
7852 return "writeonly";
7853 return "may-read/write";
7854 }
7855
7856 /// The set of IR attributes AAMemoryBehavior deals with.
7857 static const Attribute::AttrKind AttrKinds[3];
7858};
7859
7860const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
7861 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7862
7863/// Memory behavior attribute for a floating value.
7864struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7865 AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
7866 : AAMemoryBehaviorImpl(IRP, A) {}
7867
7868 ChangeStatus updateImpl(Attributor &A) override;
7869
7870 void trackStatistics() const override {
7871 if (isAssumedReadNone())
7873 else if (isAssumedReadOnly())
7875 else if (isAssumedWriteOnly())
7877 }
7878
7879private:
7880 /// Return true if users of \p UserI might access the underlying
7881 /// variable/location described by \p U and should therefore be analyzed.
7882 bool followUsersOfUseIn(Attributor &A, const Use &U,
7883 const Instruction *UserI);
7884
7885 /// Update the state according to the effect of use \p U in \p UserI.
7886 void analyzeUseIn(Attributor &A, const Use &U, const Instruction *UserI);
7887};
7888
7889/// Memory behavior attribute for function argument.
7890struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7891 AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
7892 : AAMemoryBehaviorFloating(IRP, A) {}
7893
7894 void initialize(Attributor &A) override {
7895 intersectAssumedBits(BEST_STATE);
7896 const IRPosition &IRP = getIRPosition();
7897 // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
7898 // can query it when we use has/getAttr. That would allow us to reuse the
7899 // initialize of the base class here.
7900 bool HasByVal = A.hasAttr(IRP, {Attribute::ByVal},
7901 /* IgnoreSubsumingPositions */ true);
7902 getKnownStateFromValue(A, IRP, getState(),
7903 /* IgnoreSubsumingPositions */ HasByVal);
7904 }
7905
7906 ChangeStatus manifest(Attributor &A) override {
7907 // TODO: Pointer arguments are not supported on vectors of pointers yet.
7908 if (!getAssociatedValue().getType()->isPointerTy())
7909 return ChangeStatus::UNCHANGED;
7910
7911 // TODO: From readattrs.ll: "inalloca parameters are always
7912 // considered written"
7913 if (A.hasAttr(getIRPosition(),
7914 {Attribute::InAlloca, Attribute::Preallocated})) {
7915 removeKnownBits(NO_WRITES);
7916 removeAssumedBits(NO_WRITES);
7917 }
7918 A.removeAttrs(getIRPosition(), AttrKinds);
7919 return AAMemoryBehaviorFloating::manifest(A);
7920 }
7921
7922 void trackStatistics() const override {
7923 if (isAssumedReadNone())
7924 STATS_DECLTRACK_ARG_ATTR(readnone)
7925 else if (isAssumedReadOnly())
7926 STATS_DECLTRACK_ARG_ATTR(readonly)
7927 else if (isAssumedWriteOnly())
7928 STATS_DECLTRACK_ARG_ATTR(writeonly)
7929 }
7930};
7931
7932struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7933 AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
7934 : AAMemoryBehaviorArgument(IRP, A) {}
7935
7936 void initialize(Attributor &A) override {
7937 // If we don't have an associated attribute this is either a variadic call
7938 // or an indirect call, either way, nothing to do here.
7939 Argument *Arg = getAssociatedArgument();
7940 if (!Arg) {
7941 indicatePessimisticFixpoint();
7942 return;
7943 }
7944 if (Arg->hasByValAttr()) {
7945 addKnownBits(NO_WRITES);
7946 removeKnownBits(NO_READS);
7947 removeAssumedBits(NO_READS);
7948 }
7949 AAMemoryBehaviorArgument::initialize(A);
7950 if (getAssociatedFunction()->isDeclaration())
7951 indicatePessimisticFixpoint();
7952 }
7953
7954 ChangeStatus updateImpl(Attributor &A) override {
7955 // TODO: Once we have call site specific value information we can provide
7956 // call site specific liveness liveness information and then it makes
7957 // sense to specialize attributes for call sites arguments instead of
7958 // redirecting requests to the callee argument.
7959 Argument *Arg = getAssociatedArgument();
7960 const IRPosition &ArgPos = IRPosition::argument(*Arg);
7961 auto *ArgAA =
7962 A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED);
7963 if (!ArgAA)
7964 return indicatePessimisticFixpoint();
7965 return clampStateAndIndicateChange(getState(), ArgAA->getState());
7966 }
7967
7968 void trackStatistics() const override {
7969 if (isAssumedReadNone())
7971 else if (isAssumedReadOnly())
7973 else if (isAssumedWriteOnly())
7975 }
7976};
7977
7978/// Memory behavior attribute for a call site return position.
7979struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7980 AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
7981 : AAMemoryBehaviorFloating(IRP, A) {}
7982
7983 void initialize(Attributor &A) override {
7984 AAMemoryBehaviorImpl::initialize(A);
7985 }
7986 ChangeStatus manifest(Attributor &A) override {
7987 // We do not annotate returned values.
7988 return ChangeStatus::UNCHANGED;
7989 }
7990
7991 void trackStatistics() const override {}
7992};
7993
7994/// An AA to represent the memory behavior function attributes.
7995struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
7996 AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
7997 : AAMemoryBehaviorImpl(IRP, A) {}
7998
7999 ChangeStatus updateImpl(Attributor &A) override;
8000
8001 ChangeStatus manifest(Attributor &A) override {
8002 // TODO: It would be better to merge this with AAMemoryLocation, so that
8003 // we could determine read/write per location. This would also have the
8004 // benefit of only one place trying to manifest the memory attribute.
8005 Function &F = cast<Function>(getAnchorValue());
8007 if (isAssumedReadNone())
8008 ME = MemoryEffects::none();
8009 else if (isAssumedReadOnly())
8011 else if (isAssumedWriteOnly())
8013
8014 A.removeAttrs(getIRPosition(), AttrKinds);
8015 // Clear conflicting writable attribute.
8016 if (ME.onlyReadsMemory())
8017 for (Argument &Arg : F.args())
8018 A.removeAttrs(IRPosition::argument(Arg), Attribute::Writable);
8019 return A.manifestAttrs(getIRPosition(),
8020 Attribute::getWithMemoryEffects(F.getContext(), ME));
8021 }
8022
8023 void trackStatistics() const override {
8024 if (isAssumedReadNone())
8025 STATS_DECLTRACK_FN_ATTR(readnone)
8026 else if (isAssumedReadOnly())
8027 STATS_DECLTRACK_FN_ATTR(readonly)
8028 else if (isAssumedWriteOnly())
8029 STATS_DECLTRACK_FN_ATTR(writeonly)
8030 }
8031};
8032
8033/// AAMemoryBehavior attribute for call sites.
8034struct AAMemoryBehaviorCallSite final
8035 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl> {
8036 AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
8037 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl>(IRP, A) {}
8038
8039 ChangeStatus manifest(Attributor &A) override {
8040 // TODO: Deduplicate this with AAMemoryBehaviorFunction.
8041 CallBase &CB = cast<CallBase>(getAnchorValue());
8043 if (isAssumedReadNone())
8044 ME = MemoryEffects::none();
8045 else if (isAssumedReadOnly())
8047 else if (isAssumedWriteOnly())
8049
8050 A.removeAttrs(getIRPosition(), AttrKinds);
8051 // Clear conflicting writable attribute.
8052 if (ME.onlyReadsMemory())
8053 for (Use &U : CB.args())
8054 A.removeAttrs(IRPosition::callsite_argument(CB, U.getOperandNo()),
8055 Attribute::Writable);
8056 return A.manifestAttrs(
8057 getIRPosition(), Attribute::getWithMemoryEffects(CB.getContext(), ME));
8058 }
8059
8060 void trackStatistics() const override {
8061 if (isAssumedReadNone())
8062 STATS_DECLTRACK_CS_ATTR(readnone)
8063 else if (isAssumedReadOnly())
8064 STATS_DECLTRACK_CS_ATTR(readonly)
8065 else if (isAssumedWriteOnly())
8066 STATS_DECLTRACK_CS_ATTR(writeonly)
8067 }
8068};
8069
8070ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
8071
8072 // The current assumed state used to determine a change.
8073 auto AssumedState = getAssumed();
8074
8075 auto CheckRWInst = [&](Instruction &I) {
8076 // If the instruction has an own memory behavior state, use it to restrict
8077 // the local state. No further analysis is required as the other memory
8078 // state is as optimistic as it gets.
8079 if (const auto *CB = dyn_cast<CallBase>(&I)) {
8080 const auto *MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
8082 if (MemBehaviorAA) {
8083 intersectAssumedBits(MemBehaviorAA->getAssumed());
8084 return !isAtFixpoint();
8085 }
8086 }
8087
8088 // Remove access kind modifiers if necessary.
8089 if (I.mayReadFromMemory())
8090 removeAssumedBits(NO_READS);
8091 if (I.mayWriteToMemory())
8092 removeAssumedBits(NO_WRITES);
8093 return !isAtFixpoint();
8094 };
8095
8096 bool UsedAssumedInformation = false;
8097 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
8098 UsedAssumedInformation))
8099 return indicatePessimisticFixpoint();
8100
8101 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8103}
8104
8105ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
8106
8107 const IRPosition &IRP = getIRPosition();
8108 const IRPosition &FnPos = IRPosition::function_scope(IRP);
8109 AAMemoryBehavior::StateType &S = getState();
8110
8111 // First, check the function scope. We take the known information and we avoid
8112 // work if the assumed information implies the current assumed information for
8113 // this attribute. This is a valid for all but byval arguments.
8114 Argument *Arg = IRP.getAssociatedArgument();
8115 AAMemoryBehavior::base_t FnMemAssumedState =
8117 if (!Arg || !Arg->hasByValAttr()) {
8118 const auto *FnMemAA =
8119 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL);
8120 if (FnMemAA) {
8121 FnMemAssumedState = FnMemAA->getAssumed();
8122 S.addKnownBits(FnMemAA->getKnown());
8123 if ((S.getAssumed() & FnMemAA->getAssumed()) == S.getAssumed())
8125 }
8126 }
8127
8128 // The current assumed state used to determine a change.
8129 auto AssumedState = S.getAssumed();
8130
8131 // Make sure the value is not captured (except through "return"), if
8132 // it is, any information derived would be irrelevant anyway as we cannot
8133 // check the potential aliases introduced by the capture. However, no need
8134 // to fall back to anythign less optimistic than the function state.
8135 bool IsKnownNoCapture;
8136 const AANoCapture *ArgNoCaptureAA = nullptr;
8137 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
8138 A, this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture, false,
8139 &ArgNoCaptureAA);
8140
8141 if (!IsAssumedNoCapture &&
8142 (!ArgNoCaptureAA || !ArgNoCaptureAA->isAssumedNoCaptureMaybeReturned())) {
8143 S.intersectAssumedBits(FnMemAssumedState);
8144 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8146 }
8147
8148 // Visit and expand uses until all are analyzed or a fixpoint is reached.
8149 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
8150 Instruction *UserI = cast<Instruction>(U.getUser());
8151 LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << *U << " in " << *UserI
8152 << " \n");
8153
8154 // Droppable users, e.g., llvm::assume does not actually perform any action.
8155 if (UserI->isDroppable())
8156 return true;
8157
8158 // Check if the users of UserI should also be visited.
8159 Follow = followUsersOfUseIn(A, U, UserI);
8160
8161 // If UserI might touch memory we analyze the use in detail.
8162 if (UserI->mayReadOrWriteMemory())
8163 analyzeUseIn(A, U, UserI);
8164
8165 return !isAtFixpoint();
8166 };
8167
8168 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue()))
8169 return indicatePessimisticFixpoint();
8170
8171 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
8173}
8174
8175bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use &U,
8176 const Instruction *UserI) {
8177 // The loaded value is unrelated to the pointer argument, no need to
8178 // follow the users of the load.
8179 if (isa<LoadInst>(UserI) || isa<ReturnInst>(UserI))
8180 return false;
8181
8182 // By default we follow all uses assuming UserI might leak information on U,
8183 // we have special handling for call sites operands though.
8184 const auto *CB = dyn_cast<CallBase>(UserI);
8185 if (!CB || !CB->isArgOperand(&U))
8186 return true;
8187
8188 // If the use is a call argument known not to be captured, the users of
8189 // the call do not need to be visited because they have to be unrelated to
8190 // the input. Note that this check is not trivial even though we disallow
8191 // general capturing of the underlying argument. The reason is that the
8192 // call might the argument "through return", which we allow and for which we
8193 // need to check call users.
8194 if (U.get()->getType()->isPointerTy()) {
8195 unsigned ArgNo = CB->getArgOperandNo(&U);
8196 bool IsKnownNoCapture;
8198 A, this, IRPosition::callsite_argument(*CB, ArgNo),
8199 DepClassTy::OPTIONAL, IsKnownNoCapture);
8200 }
8201
8202 return true;
8203}
8204
8205void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use &U,
8206 const Instruction *UserI) {
8207 assert(UserI->mayReadOrWriteMemory());
8208
8209 switch (UserI->getOpcode()) {
8210 default:
8211 // TODO: Handle all atomics and other side-effect operations we know of.
8212 break;
8213 case Instruction::Load:
8214 // Loads cause the NO_READS property to disappear.
8215 removeAssumedBits(NO_READS);
8216 return;
8217
8218 case Instruction::Store:
8219 // Stores cause the NO_WRITES property to disappear if the use is the
8220 // pointer operand. Note that while capturing was taken care of somewhere
8221 // else we need to deal with stores of the value that is not looked through.
8222 if (cast<StoreInst>(UserI)->getPointerOperand() == U.get())
8223 removeAssumedBits(NO_WRITES);
8224 else
8225 indicatePessimisticFixpoint();
8226 return;
8227
8228 case Instruction::Call:
8229 case Instruction::CallBr:
8230 case Instruction::Invoke: {
8231 // For call sites we look at the argument memory behavior attribute (this
8232 // could be recursive!) in order to restrict our own state.
8233 const auto *CB = cast<CallBase>(UserI);
8234
8235 // Give up on operand bundles.
8236 if (CB->isBundleOperand(&U)) {
8237 indicatePessimisticFixpoint();
8238 return;
8239 }
8240
8241 // Calling a function does read the function pointer, maybe write it if the
8242 // function is self-modifying.
8243 if (CB->isCallee(&U)) {
8244 removeAssumedBits(NO_READS);
8245 break;
8246 }
8247
8248 // Adjust the possible access behavior based on the information on the
8249 // argument.
8250 IRPosition Pos;
8251 if (U.get()->getType()->isPointerTy())
8253 else
8255 const auto *MemBehaviorAA =
8256 A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL);
8257 if (!MemBehaviorAA)
8258 break;
8259 // "assumed" has at most the same bits as the MemBehaviorAA assumed
8260 // and at least "known".
8261 intersectAssumedBits(MemBehaviorAA->getAssumed());
8262 return;
8263 }
8264 };
8265
8266 // Generally, look at the "may-properties" and adjust the assumed state if we
8267 // did not trigger special handling before.
8268 if (UserI->mayReadFromMemory())
8269 removeAssumedBits(NO_READS);
8270 if (UserI->mayWriteToMemory())
8271 removeAssumedBits(NO_WRITES);
8272}
8273} // namespace
8274
8275/// -------------------- Memory Locations Attributes ---------------------------
8276/// Includes read-none, argmemonly, inaccessiblememonly,
8277/// inaccessiblememorargmemonly
8278/// ----------------------------------------------------------------------------
8279
8282 if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
8283 return "all memory";
8285 return "no memory";
8286 std::string S = "memory:";
8287 if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
8288 S += "stack,";
8289 if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
8290 S += "constant,";
8292 S += "internal global,";
8294 S += "external global,";
8295 if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
8296 S += "argument,";
8298 S += "inaccessible,";
8299 if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
8300 S += "malloced,";
8301 if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
8302 S += "unknown,";
8303 S.pop_back();
8304 return S;
8305}
8306
8307namespace {
8308struct AAMemoryLocationImpl : public AAMemoryLocation {
8309
8310 AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
8311 : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
8312 AccessKind2Accesses.fill(nullptr);
8313 }
8314
8315 ~AAMemoryLocationImpl() override {
8316 // The AccessSets are allocated via a BumpPtrAllocator, we call
8317 // the destructor manually.
8318 for (AccessSet *AS : AccessKind2Accesses)
8319 if (AS)
8320 AS->~AccessSet();
8321 }
8322
8323 void initialize(Attributor &A) override {
8324 intersectAssumedBits(BEST_STATE);
8325 getKnownStateFromValue(A, getIRPosition(), getState());
8326 AAMemoryLocation::initialize(A);
8327 }
8328
8329 /// Return the memory behavior information encoded in the IR for \p IRP.
8330 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
8331 BitIntegerState &State,
8332 bool IgnoreSubsumingPositions = false) {
8333 // For internal functions we ignore `argmemonly` and
8334 // `inaccessiblememorargmemonly` as we might break it via interprocedural
8335 // constant propagation. It is unclear if this is the best way but it is
8336 // unlikely this will cause real performance problems. If we are deriving
8337 // attributes for the anchor function we even remove the attribute in
8338 // addition to ignoring it.
8339 // TODO: A better way to handle this would be to add ~NO_GLOBAL_MEM /
8340 // MemoryEffects::Other as a possible location.
8341 bool UseArgMemOnly = true;
8342 Function *AnchorFn = IRP.getAnchorScope();
8343 if (AnchorFn && A.isRunOn(*AnchorFn))
8344 UseArgMemOnly = !AnchorFn->hasLocalLinkage();
8345
8347 A.getAttrs(IRP, {Attribute::Memory}, Attrs, IgnoreSubsumingPositions);
8348 for (const Attribute &Attr : Attrs) {
8349 // TODO: We can map MemoryEffects to Attributor locations more precisely.
8350 MemoryEffects ME = Attr.getMemoryEffects();
8351 if (ME.doesNotAccessMemory()) {
8352 State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
8353 continue;
8354 }
8355 if (ME.onlyAccessesInaccessibleMem()) {
8356 State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
8357 continue;
8358 }
8359 if (ME.onlyAccessesArgPointees()) {
8360 if (UseArgMemOnly)
8361 State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
8362 else {
8363 // Remove location information, only keep read/write info.
8364 ME = MemoryEffects(ME.getModRef());
8365 A.manifestAttrs(IRP,
8366 Attribute::getWithMemoryEffects(
8367 IRP.getAnchorValue().getContext(), ME),
8368 /*ForceReplace*/ true);
8369 }
8370 continue;
8371 }
8373 if (UseArgMemOnly)
8374 State.addKnownBits(inverseLocation(
8375 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
8376 else {
8377 // Remove location information, only keep read/write info.
8378 ME = MemoryEffects(ME.getModRef());
8379 A.manifestAttrs(IRP,
8380 Attribute::getWithMemoryEffects(
8381 IRP.getAnchorValue().getContext(), ME),
8382 /*ForceReplace*/ true);
8383 }
8384 continue;
8385 }
8386 }
8387 }
8388
8389 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
8390 SmallVectorImpl<Attribute> &Attrs) const override {
8391 // TODO: We can map Attributor locations to MemoryEffects more precisely.
8392 assert(Attrs.size() == 0);
8393 if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
8394 if (isAssumedReadNone())
8395 Attrs.push_back(
8396 Attribute::getWithMemoryEffects(Ctx, MemoryEffects::none()));
8397 else if (isAssumedInaccessibleMemOnly())
8398 Attrs.push_back(Attribute::getWithMemoryEffects(
8400 else if (isAssumedArgMemOnly())
8401 Attrs.push_back(
8402 Attribute::getWithMemoryEffects(Ctx, MemoryEffects::argMemOnly()));
8403 else if (isAssumedInaccessibleOrArgMemOnly())
8404 Attrs.push_back(Attribute::getWithMemoryEffects(
8406 }
8407 assert(Attrs.size() <= 1);
8408 }
8409
8410 ChangeStatus manifest(Attributor &A) override {
8411 // TODO: If AAMemoryLocation and AAMemoryBehavior are merged, we could
8412 // provide per-location modref information here.
8413 const IRPosition &IRP = getIRPosition();
8414
8415 SmallVector<Attribute, 1> DeducedAttrs;
8416 getDeducedAttributes(A, IRP.getAnchorValue().getContext(), DeducedAttrs);
8417 if (DeducedAttrs.size() != 1)
8418 return ChangeStatus::UNCHANGED;
8419 MemoryEffects ME = DeducedAttrs[0].getMemoryEffects();
8420
8421 // Clear conflicting writable attributes of the function arguments.
8423 !isModSet(ME.getModRef(IRMemLocation::ArgMem))) {
8424 for (Argument &Arg : IRP.getAnchorScope()->args())
8425 A.removeAttrs(IRPosition::argument(Arg), Attribute::Writable);
8426 }
8427
8428 return A.manifestAttrs(IRP, Attribute::getWithMemoryEffects(
8429 IRP.getAnchorValue().getContext(), ME));
8430 }
8431
8432 bool checkForAllAccessesToMemoryKind(
8433 function_ref<bool(const Instruction *, const Value *, AccessKind,
8434 MemoryLocationsKind)>
8435 Pred,
8436 MemoryLocationsKind RequestedMLK) const override {
8437 if (!isValidState())
8438 return false;
8439
8440 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
8441 if (AssumedMLK == NO_LOCATIONS)
8442 return true;
8443
8444 unsigned Idx = 0;
8445 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
8446 CurMLK *= 2, ++Idx) {
8447 if (CurMLK & RequestedMLK)
8448 continue;
8449
8450 if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
8451 for (const AccessInfo &AI : *Accesses)
8452 if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
8453 return false;
8454 }
8455
8456 return true;
8457 }
8458
8459 ChangeStatus indicatePessimisticFixpoint() override {
8460 // If we give up and indicate a pessimistic fixpoint this instruction will
8461 // become an access for all potential access kinds:
8462 // TODO: Add pointers for argmemonly and globals to improve the results of
8463 // checkForAllAccessesToMemoryKind.
8464 bool Changed = false;
8465 MemoryLocationsKind KnownMLK = getKnown();
8466 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
8467 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
8468 if (!(CurMLK & KnownMLK))
8469 updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
8470 getAccessKindFromInst(I));
8471 return AAMemoryLocation::indicatePessimisticFixpoint();
8472 }
8473
8474protected:
8475 /// Helper struct to tie together an instruction that has a read or write
8476 /// effect with the pointer it accesses (if any).
8477 struct AccessInfo {
8478
8479 /// The instruction that caused the access.
8480 const Instruction *I;
8481
8482 /// The base pointer that is accessed, or null if unknown.
8483 const Value *Ptr;
8484
8485 /// The kind of access (read/write/read+write).
8487
8488 bool operator==(const AccessInfo &RHS) const {
8489 return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
8490 }
8491 bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
8492 if (LHS.I != RHS.I)
8493 return LHS.I < RHS.I;
8494 if (LHS.Ptr != RHS.Ptr)
8495 return LHS.Ptr < RHS.Ptr;
8496 if (LHS.Kind != RHS.Kind)
8497 return LHS.Kind < RHS.Kind;
8498 return false;
8499 }
8500 };
8501
8502 /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
8503 /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
8504 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
8505 std::array<AccessSet *, llvm::ConstantLog2<VALID_STATE>()>
8506 AccessKind2Accesses;
8507
8508 /// Categorize the pointer arguments of CB that might access memory in
8509 /// AccessedLoc and update the state and access map accordingly.
8510 void
8511 categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
8512 AAMemoryLocation::StateType &AccessedLocs,
8513 bool &Changed);
8514
8515 /// Return the kind(s) of location that may be accessed by \p V.
8517 categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
8518
8519 /// Return the access kind as determined by \p I.
8520 AccessKind getAccessKindFromInst(const Instruction *I) {
8521 AccessKind AK = READ_WRITE;
8522 if (I) {
8523 AK = I->mayReadFromMemory() ? READ : NONE;
8524 AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
8525 }
8526 return AK;
8527 }
8528
8529 /// Update the state \p State and the AccessKind2Accesses given that \p I is
8530 /// an access of kind \p AK to a \p MLK memory location with the access
8531 /// pointer \p Ptr.
8532 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
8533 MemoryLocationsKind MLK, const Instruction *I,
8534 const Value *Ptr, bool &Changed,
8535 AccessKind AK = READ_WRITE) {
8536
8537 assert(isPowerOf2_32(MLK) && "Expected a single location set!");
8538 auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
8539 if (!Accesses)
8540 Accesses = new (Allocator) AccessSet();
8541 Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
8542 if (MLK == NO_UNKOWN_MEM)
8543 MLK = NO_LOCATIONS;
8544 State.removeAssumedBits(MLK);
8545 }
8546
8547 /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
8548 /// arguments, and update the state and access map accordingly.
8549 void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
8550 AAMemoryLocation::StateType &State, bool &Changed,
8551 unsigned AccessAS = 0);
8552
8553 /// Used to allocate access sets.
8555};
8556
8557void AAMemoryLocationImpl::categorizePtrValue(
8558 Attributor &A, const Instruction &I, const Value &Ptr,
8559 AAMemoryLocation::StateType &State, bool &Changed, unsigned AccessAS) {
8560 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
8561 << Ptr << " ["
8562 << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
8563
8564 auto Pred = [&](Value &Obj) {
8565 unsigned ObjectAS = Obj.getType()->getPointerAddressSpace();
8566 // TODO: recognize the TBAA used for constant accesses.
8567 MemoryLocationsKind MLK = NO_LOCATIONS;
8568
8569 // Filter accesses to constant (GPU) memory if we have an AS at the access
8570 // site or the object is known to actually have the associated AS.
8571 if (AA::isGPU(A.getModule())) {
8572 if (AA::isGPUConstantAddressSpace(A.getModule(), AccessAS) ||
8573 (AA::isGPUConstantAddressSpace(A.getModule(), ObjectAS) &&
8574 isIdentifiedObject(&Obj)))
8575 return true;
8576 }
8577
8578 if (isa<UndefValue>(&Obj))
8579 return true;
8580 if (isa<Argument>(&Obj)) {
8581 // TODO: For now we do not treat byval arguments as local copies performed
8582 // on the call edge, though, we should. To make that happen we need to
8583 // teach various passes, e.g., DSE, about the copy effect of a byval. That
8584 // would also allow us to mark functions only accessing byval arguments as
8585 // readnone again, arguably their accesses have no effect outside of the
8586 // function, like accesses to allocas.
8587 MLK = NO_ARGUMENT_MEM;
8588 } else if (auto *GV = dyn_cast<GlobalValue>(&Obj)) {
8589 // Reading constant memory is not treated as a read "effect" by the
8590 // function attr pass so we won't neither. Constants defined by TBAA are
8591 // similar. (We know we do not write it because it is constant.)
8592 if (auto *GVar = dyn_cast<GlobalVariable>(GV))
8593 if (GVar->isConstant())
8594 return true;
8595
8596 if (GV->hasLocalLinkage())
8597 MLK = NO_GLOBAL_INTERNAL_MEM;
8598 else
8599 MLK = NO_GLOBAL_EXTERNAL_MEM;
8600 } else if (isa<ConstantPointerNull>(&Obj) && ObjectAS == AccessAS &&
8601 !NullPointerIsDefined(getAssociatedFunction(), AccessAS)) {
8602 // Accessing null is undefined, but not accessing a null pointer cast to
8603 // another address space, which may be a valid address there.
8604 return true;
8605 } else if (isa<AllocaInst>(&Obj)) {
8606 MLK = NO_LOCAL_MEM;
8607 } else if (const auto *CB = dyn_cast<CallBase>(&Obj)) {
8608 bool IsKnownNoAlias;
8611 IsKnownNoAlias))
8612 MLK = NO_MALLOCED_MEM;
8613 else
8614 MLK = NO_UNKOWN_MEM;
8615 } else {
8616 MLK = NO_UNKOWN_MEM;
8617 }
8618
8619 assert(MLK != NO_LOCATIONS && "No location specified!");
8620 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: "
8621 << Obj << " -> " << getMemoryLocationsAsStr(MLK) << "\n");
8622 updateStateAndAccessesMap(State, MLK, &I, &Obj, Changed,
8623 getAccessKindFromInst(&I));
8624
8625 return true;
8626 };
8627
8628 const auto *AA = A.getAAFor<AAUnderlyingObjects>(
8630 if (!AA || !AA->forallUnderlyingObjects(Pred, AA::Intraprocedural)) {
8631 LLVM_DEBUG(
8632 dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
8633 updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
8634 getAccessKindFromInst(&I));
8635 return;
8636 }
8637
8638 LLVM_DEBUG(
8639 dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: "
8640 << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
8641}
8642
8643void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
8644 Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
8645 bool &Changed) {
8646 for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) {
8647
8648 // Skip non-pointer arguments.
8649 const Value *ArgOp = CB.getArgOperand(ArgNo);
8650 if (!ArgOp->getType()->isPtrOrPtrVectorTy())
8651 continue;
8652
8653 // Skip readnone arguments.
8654 const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
8655 const auto *ArgOpMemLocationAA =
8656 A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL);
8657
8658 if (ArgOpMemLocationAA && ArgOpMemLocationAA->isAssumedReadNone())
8659 continue;
8660
8661 // Categorize potentially accessed pointer arguments as if there was an
8662 // access instruction with them as pointer.
8663 categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
8664 }
8665}
8666
8668AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
8669 bool &Changed) {
8670 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
8671 << I << "\n");
8672
8673 AAMemoryLocation::StateType AccessedLocs;
8674 AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
8675
8676 if (auto *CB = dyn_cast<CallBase>(&I)) {
8677
8678 // First check if we assume any memory is access is visible.
8679 const auto *CBMemLocationAA = A.getAAFor<AAMemoryLocation>(
8681 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
8682 << " [" << CBMemLocationAA << "]\n");
8683 if (!CBMemLocationAA) {
8684 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr,
8685 Changed, getAccessKindFromInst(&I));
8686 return NO_UNKOWN_MEM;
8687 }
8688
8689 if (CBMemLocationAA->isAssumedReadNone())
8690 return NO_LOCATIONS;
8691
8692 if (CBMemLocationAA->isAssumedInaccessibleMemOnly()) {
8693 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
8694 Changed, getAccessKindFromInst(&I));
8695 return AccessedLocs.getAssumed();
8696 }
8697
8698 uint32_t CBAssumedNotAccessedLocs =
8699 CBMemLocationAA->getAssumedNotAccessedLocation();
8700
8701 // Set the argmemonly and global bit as we handle them separately below.
8702 uint32_t CBAssumedNotAccessedLocsNoArgMem =
8703 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
8704
8705 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
8706 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
8707 continue;
8708 updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
8709 getAccessKindFromInst(&I));
8710 }
8711
8712 // Now handle global memory if it might be accessed. This is slightly tricky
8713 // as NO_GLOBAL_MEM has multiple bits set.
8714 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
8715 if (HasGlobalAccesses) {
8716 auto AccessPred = [&](const Instruction *, const Value *Ptr,
8717 AccessKind Kind, MemoryLocationsKind MLK) {
8718 updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
8719 getAccessKindFromInst(&I));
8720 return true;
8721 };
8722 if (!CBMemLocationAA->checkForAllAccessesToMemoryKind(
8723 AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
8724 return AccessedLocs.getWorstState();
8725 }
8726
8727 LLVM_DEBUG(
8728 dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
8729 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8730
8731 // Now handle argument memory if it might be accessed.
8732 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
8733 if (HasArgAccesses)
8734 categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
8735
8736 LLVM_DEBUG(
8737 dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
8738 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8739
8740 return AccessedLocs.getAssumed();
8741 }
8742
8743 if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
8744 LLVM_DEBUG(
8745 dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
8746 << I << " [" << *Ptr << "]\n");
8747 categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed,
8748 Ptr->getType()->getPointerAddressSpace());
8749 return AccessedLocs.getAssumed();
8750 }
8751
8752 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
8753 << I << "\n");
8754 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
8755 getAccessKindFromInst(&I));
8756 return AccessedLocs.getAssumed();
8757}
8758
8759/// An AA to represent the memory behavior function attributes.
8760struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
8761 AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
8762 : AAMemoryLocationImpl(IRP, A) {}
8763
8764 ChangeStatus updateImpl(Attributor &A) override {
8765
8766 const auto *MemBehaviorAA =
8767 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
8768 if (MemBehaviorAA && MemBehaviorAA->isAssumedReadNone()) {
8769 if (MemBehaviorAA->isKnownReadNone())
8770 return indicateOptimisticFixpoint();
8772 "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
8773 A.recordDependence(*MemBehaviorAA, *this, DepClassTy::OPTIONAL);
8774 return ChangeStatus::UNCHANGED;
8775 }
8776
8777 // The current assumed state used to determine a change.
8778 auto AssumedState = getAssumed();
8779 bool Changed = false;
8780
8781 auto CheckRWInst = [&](Instruction &I) {
8782 MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
8783 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
8784 << ": " << getMemoryLocationsAsStr(MLK) << "\n");
8785 removeAssumedBits(inverseLocation(MLK, false, false));
8786 // Stop once only the valid bit set in the *not assumed location*, thus
8787 // once we don't actually exclude any memory locations in the state.
8788 return getAssumedNotAccessedLocation() != VALID_STATE;
8789 };
8790
8791 bool UsedAssumedInformation = false;
8792 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
8793 UsedAssumedInformation))
8794 return indicatePessimisticFixpoint();
8795
8796 Changed |= AssumedState != getAssumed();
8797 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8798 }
8799
8800 void trackStatistics() const override {
8801 if (isAssumedReadNone())
8802 STATS_DECLTRACK_FN_ATTR(readnone)
8803 else if (isAssumedArgMemOnly())
8804 STATS_DECLTRACK_FN_ATTR(argmemonly)
8805 else if (isAssumedInaccessibleMemOnly())
8806 STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
8807 else if (isAssumedInaccessibleOrArgMemOnly())
8808 STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
8809 }
8810};
8811
8812/// AAMemoryLocation attribute for call sites.
8813struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
8814 AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
8815 : AAMemoryLocationImpl(IRP, A) {}
8816
8817 void initialize(Attributor &A) override {
8818 AAMemoryLocationImpl::initialize(A);
8819
8820 // Volatile calls may also access inaccessible memory, which the callee's
8821 // attributes do not say.
8822 auto &CB = cast<CallBase>(getAnchorValue());
8823 if (CB.isVolatile()) {
8824 bool Changed = false;
8825 removeKnownBits(NO_INACCESSIBLE_MEM);
8826 updateStateAndAccessesMap(getState(), NO_INACCESSIBLE_MEM, &CB, nullptr,
8827 Changed, getAccessKindFromInst(&CB));
8828 }
8829 }
8830
8831 ChangeStatus updateImpl(Attributor &A) override {
8832 // TODO: Once we have call site specific value information we can provide
8833 // call site specific liveness liveness information and then it makes
8834 // sense to specialize attributes for call sites arguments instead of
8835 // redirecting requests to the callee argument.
8836 Function *F = getAssociatedFunction();
8837 const IRPosition &FnPos = IRPosition::function(*F);
8838 auto *FnAA =
8839 A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED);
8840 if (!FnAA)
8841 return indicatePessimisticFixpoint();
8842 bool Changed = false;
8843 auto AccessPred = [&](const Instruction *I, const Value *Ptr,
8844 AccessKind Kind, MemoryLocationsKind MLK) {
8845 updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
8846 getAccessKindFromInst(I));
8847 return true;
8848 };
8849 if (!FnAA->checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
8850 return indicatePessimisticFixpoint();
8851 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8852 }
8853
8854 void trackStatistics() const override {
8855 if (isAssumedReadNone())
8856 STATS_DECLTRACK_CS_ATTR(readnone)
8857 }
8858};
8859} // namespace
8860
8861/// ------------------ denormal-fp-math Attribute -------------------------
8862
8863namespace {
8864struct AADenormalFPMathImpl : public AADenormalFPMath {
8865 AADenormalFPMathImpl(const IRPosition &IRP, Attributor &A)
8866 : AADenormalFPMath(IRP, A) {}
8867
8868 const std::string getAsStr(Attributor *A) const override {
8869 std::string Str("AADenormalFPMath[");
8870 raw_string_ostream OS(Str);
8871
8872 DenormalState Known = getKnown();
8873 if (Known.Mode.isValid())
8874 OS << "denormal-fp-math=" << Known.Mode;
8875 else
8876 OS << "invalid";
8877
8878 if (Known.ModeF32.isValid())
8879 OS << " denormal-fp-math-f32=" << Known.ModeF32;
8880 OS << ']';
8881 return Str;
8882 }
8883};
8884
8885struct AADenormalFPMathFunction final : AADenormalFPMathImpl {
8886 AADenormalFPMathFunction(const IRPosition &IRP, Attributor &A)
8887 : AADenormalFPMathImpl(IRP, A) {}
8888
8889 void initialize(Attributor &A) override {
8890 const Function *F = getAnchorScope();
8891 DenormalFPEnv DenormEnv = F->getDenormalFPEnv();
8892
8893 Known = DenormalState{DenormEnv.DefaultMode, DenormEnv.F32Mode};
8894 if (isModeFixed())
8895 indicateFixpoint();
8896 }
8897
8898 ChangeStatus updateImpl(Attributor &A) override {
8899 ChangeStatus Change = ChangeStatus::UNCHANGED;
8900
8901 auto CheckCallSite = [=, &Change, &A](AbstractCallSite CS) {
8902 Function *Caller = CS.getInstruction()->getFunction();
8903 LLVM_DEBUG(dbgs() << "[AADenormalFPMath] Call " << Caller->getName()
8904 << "->" << getAssociatedFunction()->getName() << '\n');
8905
8906 const auto *CallerInfo = A.getAAFor<AADenormalFPMath>(
8907 *this, IRPosition::function(*Caller), DepClassTy::REQUIRED);
8908 if (!CallerInfo)
8909 return false;
8910
8911 Change = Change | clampStateAndIndicateChange(this->getState(),
8912 CallerInfo->getState());
8913 return true;
8914 };
8915
8916 bool AllCallSitesKnown = true;
8917 if (!A.checkForAllCallSites(CheckCallSite, *this, true, AllCallSitesKnown))
8918 return indicatePessimisticFixpoint();
8919
8920 if (Change == ChangeStatus::CHANGED && isModeFixed())
8921 indicateFixpoint();
8922 return Change;
8923 }
8924
8925 ChangeStatus manifest(Attributor &A) override {
8926 LLVMContext &Ctx = getAssociatedFunction()->getContext();
8927
8928 SmallVector<Attribute, 2> AttrToAdd;
8930
8931 // TODO: Change to use DenormalFPEnv everywhere.
8932 DenormalFPEnv KnownEnv(Known.Mode, Known.ModeF32);
8933
8934 if (KnownEnv == DenormalFPEnv::getDefault()) {
8935 AttrToRemove.push_back(Attribute::DenormalFPEnv);
8936 } else {
8937 AttrToAdd.push_back(Attribute::get(
8938 Ctx, Attribute::DenormalFPEnv,
8939 DenormalFPEnv(Known.Mode, Known.ModeF32).toIntValue()));
8940 }
8941
8942 auto &IRP = getIRPosition();
8943
8944 // TODO: There should be a combined add and remove API.
8945 return A.removeAttrs(IRP, AttrToRemove) |
8946 A.manifestAttrs(IRP, AttrToAdd, /*ForceReplace=*/true);
8947 }
8948
8949 void trackStatistics() const override {
8950 STATS_DECLTRACK_FN_ATTR(denormal_fpenv)
8951 }
8952};
8953} // namespace
8954
8955/// ------------------ Value Constant Range Attribute -------------------------
8956
8957namespace {
8958struct AAValueConstantRangeImpl : AAValueConstantRange {
8959 using StateType = IntegerRangeState;
8960 AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
8961 : AAValueConstantRange(IRP, A) {}
8962
8963 void initialize(Attributor &A) override {
8964 if (A.hasSimplificationCallback(getIRPosition())) {
8965 indicatePessimisticFixpoint();
8966 return;
8967 }
8968
8969 // Intersect a range given by SCEV.
8970 intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
8971
8972 // Intersect a range given by LVI.
8973 intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
8974 }
8975
8976 const std::string getAsStr(Attributor *A) const override {
8977 std::string Str;
8978 llvm::raw_string_ostream OS(Str);
8979 OS << "range(" << getBitWidth() << ")<";
8980 getKnown().print(OS);
8981 OS << " / ";
8982 getAssumed().print(OS);
8983 OS << ">";
8984 return Str;
8985 }
8986
8987 /// Helper function to get a SCEV expr for the associated value at program
8988 /// point \p I.
8989 const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
8990 if (!getAnchorScope())
8991 return nullptr;
8992
8993 ScalarEvolution *SE =
8994 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8995 *getAnchorScope());
8996
8997 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
8998 *getAnchorScope());
8999
9000 if (!SE || !LI)
9001 return nullptr;
9002
9003 const SCEV *S = SE->getSCEV(&getAssociatedValue());
9004 if (!I)
9005 return S;
9006
9007 return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
9008 }
9009
9010 /// Helper function to get a range from SCEV for the associated value at
9011 /// program point \p I.
9012 ConstantRange getConstantRangeFromSCEV(Attributor &A,
9013 const Instruction *I = nullptr) const {
9014 if (!getAnchorScope())
9015 return getWorstState(getBitWidth());
9016
9017 ScalarEvolution *SE =
9018 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
9019 *getAnchorScope());
9020
9021 const SCEV *S = getSCEV(A, I);
9022 if (!SE || !S)
9023 return getWorstState(getBitWidth());
9024
9025 return SE->getUnsignedRange(S);
9026 }
9027
9028 /// Helper function to get a range from LVI for the associated value at
9029 /// program point \p I.
9030 ConstantRange
9031 getConstantRangeFromLVI(Attributor &A,
9032 const Instruction *CtxI = nullptr) const {
9033 if (!getAnchorScope())
9034 return getWorstState(getBitWidth());
9035
9036 LazyValueInfo *LVI =
9037 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
9038 *getAnchorScope());
9039
9040 if (!LVI || !CtxI)
9041 return getWorstState(getBitWidth());
9042 return LVI->getConstantRange(&getAssociatedValue(),
9043 const_cast<Instruction *>(CtxI),
9044 /*UndefAllowed*/ false);
9045 }
9046
9047 /// Return true if \p CtxI is valid for querying outside analyses.
9048 /// This basically makes sure we do not ask intra-procedural analysis
9049 /// about a context in the wrong function or a context that violates
9050 /// dominance assumptions they might have. The \p AllowAACtxI flag indicates
9051 /// if the original context of this AA is OK or should be considered invalid.
9052 bool isValidCtxInstructionForOutsideAnalysis(Attributor &A,
9053 const Instruction *CtxI,
9054 bool AllowAACtxI) const {
9055 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
9056 return false;
9057
9058 // Our context might be in a different function, neither intra-procedural
9059 // analysis (ScalarEvolution nor LazyValueInfo) can handle that.
9060 if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction()))
9061 return false;
9062
9063 // If the context is not dominated by the value there are paths to the
9064 // context that do not define the value. This cannot be handled by
9065 // LazyValueInfo so we need to bail.
9066 if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) {
9067 InformationCache &InfoCache = A.getInfoCache();
9068 const DominatorTree *DT =
9069 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
9070 *I->getFunction());
9071 return DT && DT->dominates(I, CtxI);
9072 }
9073
9074 return true;
9075 }
9076
9077 ConstantRange
9078 getAssumedConstantRange(Attributor &A,
9079 const Instruction *CtxI = nullptr) const override {
9080 // TODO: Make SCEV use Attributor assumption.
9081 // We may be able to bound a variable range via assumptions in
9082 // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
9083 // evolve to x^2 + x, then we can say that y is in [2, 12].
9084 if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
9085 /* AllowAACtxI */ false))
9086 return getAssumed();
9087
9088 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
9089 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
9090 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
9091 }
9092
9093 /// Helper function to create MDNode for range metadata.
9094 static MDNode *
9095 getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
9096 const ConstantRange &AssumedConstantRange) {
9097 Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
9098 Ty, AssumedConstantRange.getLower())),
9099 ConstantAsMetadata::get(ConstantInt::get(
9100 Ty, AssumedConstantRange.getUpper()))};
9101 return MDNode::get(Ctx, LowAndHigh);
9102 }
9103
9104 /// Return true if \p Assumed is included in ranges from instruction \p I.
9105 static bool isBetterRange(const ConstantRange &Assumed,
9106 const Instruction &I) {
9107 if (Assumed.isFullSet())
9108 return false;
9109
9110 std::optional<ConstantRange> Known;
9111
9112 if (const auto *CB = dyn_cast<CallBase>(&I)) {
9113 Known = CB->getRange();
9114 } else if (MDNode *KnownRanges = I.getMetadata(LLVMContext::MD_range)) {
9115 // If multiple ranges are annotated in IR, we give up to annotate assumed
9116 // range for now.
9117
9118 // TODO: If there exists a known range which containts assumed range, we
9119 // can say assumed range is better.
9120 if (KnownRanges->getNumOperands() > 2)
9121 return false;
9122
9123 ConstantInt *Lower =
9124 mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
9125 ConstantInt *Upper =
9126 mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
9127
9128 Known.emplace(Lower->getValue(), Upper->getValue());
9129 }
9130 return !Known || (*Known != Assumed && Known->contains(Assumed));
9131 }
9132
9133 /// Helper function to set range metadata.
9134 static bool
9135 setRangeMetadataIfisBetterRange(Instruction *I,
9136 const ConstantRange &AssumedConstantRange) {
9137 if (isBetterRange(AssumedConstantRange, *I)) {
9138 I->setMetadata(LLVMContext::MD_range,
9139 getMDNodeForConstantRange(I->getType(), I->getContext(),
9140 AssumedConstantRange));
9141 return true;
9142 }
9143 return false;
9144 }
9145 /// Helper function to set range return attribute.
9146 static bool
9147 setRangeRetAttrIfisBetterRange(Attributor &A, const IRPosition &IRP,
9148 Instruction *I,
9149 const ConstantRange &AssumedConstantRange) {
9150 if (isBetterRange(AssumedConstantRange, *I)) {
9151 A.manifestAttrs(IRP,
9152 Attribute::get(I->getContext(), Attribute::Range,
9153 AssumedConstantRange),
9154 /*ForceReplace*/ true);
9155 return true;
9156 }
9157 return false;
9158 }
9159
9160 ChangeStatus manifest(Attributor &A) override {
9161 ChangeStatus Changed = ChangeStatus::UNCHANGED;
9162 ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
9163 assert(!AssumedConstantRange.isFullSet() && "Invalid state");
9164
9165 auto &V = getAssociatedValue();
9166 if (!AssumedConstantRange.isEmptySet() &&
9167 !AssumedConstantRange.isSingleElement()) {
9168 if (Instruction *I = dyn_cast<Instruction>(&V)) {
9169 assert(I == getCtxI() && "Should not annotate an instruction which is "
9170 "not the context instruction");
9171 if (isa<LoadInst>(I))
9172 if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
9173 Changed = ChangeStatus::CHANGED;
9174 if (isa<CallInst>(I))
9175 if (setRangeRetAttrIfisBetterRange(A, getIRPosition(), I,
9176 AssumedConstantRange))
9177 Changed = ChangeStatus::CHANGED;
9178 }
9179 }
9180
9181 return Changed;
9182 }
9183};
9184
9185struct AAValueConstantRangeArgument final
9186 : AAArgumentFromCallSiteArguments<
9187 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9188 true /* BridgeCallBaseContext */> {
9189 using Base = AAArgumentFromCallSiteArguments<
9190 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9191 true /* BridgeCallBaseContext */>;
9192 AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
9193 : Base(IRP, A) {}
9194
9195 void trackStatistics() const override {
9196 STATS_DECLTRACK_ARG_ATTR(value_range)
9197 }
9198};
9199
9200struct AAValueConstantRangeReturned
9201 : AAReturnedFromReturnedValues<AAValueConstantRange,
9202 AAValueConstantRangeImpl,
9203 AAValueConstantRangeImpl::StateType,
9204 /* PropagateCallBaseContext */ true> {
9205 using Base =
9206 AAReturnedFromReturnedValues<AAValueConstantRange,
9207 AAValueConstantRangeImpl,
9208 AAValueConstantRangeImpl::StateType,
9209 /* PropagateCallBaseContext */ true>;
9210 AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
9211 : Base(IRP, A) {}
9212
9213 void initialize(Attributor &A) override {
9214 if (!A.isFunctionIPOAmendable(*getAssociatedFunction()))
9215 indicatePessimisticFixpoint();
9216 }
9217
9218 void trackStatistics() const override {
9219 STATS_DECLTRACK_FNRET_ATTR(value_range)
9220 }
9221};
9222
9223struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
9224 AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
9225 : AAValueConstantRangeImpl(IRP, A) {}
9226
9227 void initialize(Attributor &A) override {
9228 AAValueConstantRangeImpl::initialize(A);
9229 if (isAtFixpoint())
9230 return;
9231
9232 Value &V = getAssociatedValue();
9233
9234 if (auto *C = dyn_cast<ConstantInt>(&V)) {
9235 unionAssumed(ConstantRange(C->getValue()));
9236 indicateOptimisticFixpoint();
9237 return;
9238 }
9239
9240 if (isa<UndefValue>(&V)) {
9241 // Collapse the undef state to 0.
9242 unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
9243 indicateOptimisticFixpoint();
9244 return;
9245 }
9246
9247 if (isa<CallBase>(&V))
9248 return;
9249
9251 return;
9252
9253 // If it is a load instruction with range metadata, use it.
9254 if (LoadInst *LI = dyn_cast<LoadInst>(&V))
9255 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
9256 intersectKnown(getConstantRangeFromMetadata(*RangeMD));
9257 return;
9258 }
9259
9260 // We can work with PHI and select instruction as we traverse their operands
9261 // during update.
9263 return;
9264
9265 // Otherwise we give up.
9266 indicatePessimisticFixpoint();
9267
9268 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
9269 << getAssociatedValue() << "\n");
9270 }
9271
9272 bool calculateBinaryOperator(
9273 Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
9274 const Instruction *CtxI,
9275 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9276 Value *LHS = BinOp->getOperand(0);
9277 Value *RHS = BinOp->getOperand(1);
9278
9279 // Simplify the operands first.
9280 bool UsedAssumedInformation = false;
9281 const auto &SimplifiedLHS = A.getAssumedSimplified(
9282 IRPosition::value(*LHS, getCallBaseContext()), *this,
9283 UsedAssumedInformation, AA::Interprocedural);
9284 if (!SimplifiedLHS.has_value())
9285 return true;
9286 if (!*SimplifiedLHS)
9287 return false;
9288 LHS = *SimplifiedLHS;
9289
9290 const auto &SimplifiedRHS = A.getAssumedSimplified(
9291 IRPosition::value(*RHS, getCallBaseContext()), *this,
9292 UsedAssumedInformation, AA::Interprocedural);
9293 if (!SimplifiedRHS.has_value())
9294 return true;
9295 if (!*SimplifiedRHS)
9296 return false;
9297 RHS = *SimplifiedRHS;
9298
9299 // TODO: Allow non integers as well.
9300 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9301 return false;
9302
9303 auto *LHSAA = A.getAAFor<AAValueConstantRange>(
9304 *this, IRPosition::value(*LHS, getCallBaseContext()),
9305 DepClassTy::REQUIRED);
9306 if (!LHSAA)
9307 return false;
9308 QuerriedAAs.push_back(LHSAA);
9309 auto LHSAARange = LHSAA->getAssumedConstantRange(A, CtxI);
9310
9311 auto *RHSAA = A.getAAFor<AAValueConstantRange>(
9312 *this, IRPosition::value(*RHS, getCallBaseContext()),
9313 DepClassTy::REQUIRED);
9314 if (!RHSAA)
9315 return false;
9316 QuerriedAAs.push_back(RHSAA);
9317 auto RHSAARange = RHSAA->getAssumedConstantRange(A, CtxI);
9318
9319 auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
9320
9321 T.unionAssumed(AssumedRange);
9322
9323 // TODO: Track a known state too.
9324
9325 return T.isValidState();
9326 }
9327
9328 bool calculateCastInst(
9329 Attributor &A, CastInst *CastI, IntegerRangeState &T,
9330 const Instruction *CtxI,
9331 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9332 assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
9333 // TODO: Allow non integers as well.
9334 Value *OpV = CastI->getOperand(0);
9335
9336 // Simplify the operand first.
9337 bool UsedAssumedInformation = false;
9338 const auto &SimplifiedOpV = A.getAssumedSimplified(
9339 IRPosition::value(*OpV, getCallBaseContext()), *this,
9340 UsedAssumedInformation, AA::Interprocedural);
9341 if (!SimplifiedOpV.has_value())
9342 return true;
9343 if (!*SimplifiedOpV)
9344 return false;
9345 OpV = *SimplifiedOpV;
9346
9347 if (!OpV->getType()->isIntegerTy())
9348 return false;
9349
9350 auto *OpAA = A.getAAFor<AAValueConstantRange>(
9351 *this, IRPosition::value(*OpV, getCallBaseContext()),
9352 DepClassTy::REQUIRED);
9353 if (!OpAA)
9354 return false;
9355 QuerriedAAs.push_back(OpAA);
9356 T.unionAssumed(OpAA->getAssumed().castOp(CastI->getOpcode(),
9357 getState().getBitWidth()));
9358 return T.isValidState();
9359 }
9360
9361 bool
9362 calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
9363 const Instruction *CtxI,
9364 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9365 Value *LHS = CmpI->getOperand(0);
9366 Value *RHS = CmpI->getOperand(1);
9367
9368 // Simplify the operands first.
9369 bool UsedAssumedInformation = false;
9370 const auto &SimplifiedLHS = A.getAssumedSimplified(
9371 IRPosition::value(*LHS, getCallBaseContext()), *this,
9372 UsedAssumedInformation, AA::Interprocedural);
9373 if (!SimplifiedLHS.has_value())
9374 return true;
9375 if (!*SimplifiedLHS)
9376 return false;
9377 LHS = *SimplifiedLHS;
9378
9379 const auto &SimplifiedRHS = A.getAssumedSimplified(
9380 IRPosition::value(*RHS, getCallBaseContext()), *this,
9381 UsedAssumedInformation, AA::Interprocedural);
9382 if (!SimplifiedRHS.has_value())
9383 return true;
9384 if (!*SimplifiedRHS)
9385 return false;
9386 RHS = *SimplifiedRHS;
9387
9388 // TODO: Allow non integers as well.
9389 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9390 return false;
9391
9392 auto *LHSAA = A.getAAFor<AAValueConstantRange>(
9393 *this, IRPosition::value(*LHS, getCallBaseContext()),
9394 DepClassTy::REQUIRED);
9395 if (!LHSAA)
9396 return false;
9397 QuerriedAAs.push_back(LHSAA);
9398 auto *RHSAA = A.getAAFor<AAValueConstantRange>(
9399 *this, IRPosition::value(*RHS, getCallBaseContext()),
9400 DepClassTy::REQUIRED);
9401 if (!RHSAA)
9402 return false;
9403 QuerriedAAs.push_back(RHSAA);
9404 auto LHSAARange = LHSAA->getAssumedConstantRange(A, CtxI);
9405 auto RHSAARange = RHSAA->getAssumedConstantRange(A, CtxI);
9406
9407 // If one of them is empty set, we can't decide.
9408 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
9409 return true;
9410
9411 bool MustTrue = false, MustFalse = false;
9412
9413 auto AllowedRegion =
9415
9416 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
9417 MustFalse = true;
9418
9419 if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange))
9420 MustTrue = true;
9421
9422 assert((!MustTrue || !MustFalse) &&
9423 "Either MustTrue or MustFalse should be false!");
9424
9425 if (MustTrue)
9426 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
9427 else if (MustFalse)
9428 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
9429 else
9430 T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
9431
9432 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " after "
9433 << (MustTrue ? "true" : (MustFalse ? "false" : "unknown"))
9434 << ": " << T << "\n\t" << *LHSAA << "\t<op>\n\t"
9435 << *RHSAA);
9436
9437 // TODO: Track a known state too.
9438 return T.isValidState();
9439 }
9440
9441 ChangeStatus updateImpl(Attributor &A) override {
9442
9443 IntegerRangeState T(getBitWidth());
9444 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
9446 if (!I || isa<CallBase>(I)) {
9447
9448 // Simplify the operand first.
9449 bool UsedAssumedInformation = false;
9450 const auto &SimplifiedOpV = A.getAssumedSimplified(
9451 IRPosition::value(V, getCallBaseContext()), *this,
9452 UsedAssumedInformation, AA::Interprocedural);
9453 if (!SimplifiedOpV.has_value())
9454 return true;
9455 if (!*SimplifiedOpV)
9456 return false;
9457 Value *VPtr = *SimplifiedOpV;
9458
9459 // If the value is not instruction, we query AA to Attributor.
9460 const auto *AA = A.getAAFor<AAValueConstantRange>(
9461 *this, IRPosition::value(*VPtr, getCallBaseContext()),
9462 DepClassTy::REQUIRED);
9463
9464 // Clamp operator is not used to utilize a program point CtxI.
9465 if (AA)
9466 T.unionAssumed(AA->getAssumedConstantRange(A, CtxI));
9467 else
9468 return false;
9469
9470 return T.isValidState();
9471 }
9472
9474 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
9475 if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
9476 return false;
9477 } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
9478 if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
9479 return false;
9480 } else if (auto *CastI = dyn_cast<CastInst>(I)) {
9481 if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
9482 return false;
9483 } else {
9484 // Give up with other instructions.
9485 // TODO: Add other instructions
9486
9487 T.indicatePessimisticFixpoint();
9488 return false;
9489 }
9490
9491 // Catch circular reasoning in a pessimistic way for now.
9492 // TODO: Check how the range evolves and if we stripped anything, see also
9493 // AADereferenceable or AAAlign for similar situations.
9494 for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
9495 if (QueriedAA != this)
9496 continue;
9497 // If we are in a stady state we do not need to worry.
9498 if (T.getAssumed() == getState().getAssumed())
9499 continue;
9500 T.indicatePessimisticFixpoint();
9501 }
9502
9503 return T.isValidState();
9504 };
9505
9506 if (!VisitValueCB(getAssociatedValue(), getCtxI()))
9507 return indicatePessimisticFixpoint();
9508
9509 // Ensure that long def-use chains can't cause circular reasoning either by
9510 // introducing a cutoff below.
9511 if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED)
9512 return ChangeStatus::UNCHANGED;
9513 if (++NumChanges > MaxNumChanges) {
9514 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges
9515 << " but only " << MaxNumChanges
9516 << " are allowed to avoid cyclic reasoning.");
9517 return indicatePessimisticFixpoint();
9518 }
9519 return ChangeStatus::CHANGED;
9520 }
9521
9522 void trackStatistics() const override {
9524 }
9525
9526 /// Tracker to bail after too many widening steps of the constant range.
9527 int NumChanges = 0;
9528
9529 /// Upper bound for the number of allowed changes (=widening steps) for the
9530 /// constant range before we give up.
9531 static constexpr int MaxNumChanges = 5;
9532};
9533
9534struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
9535 AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
9536 : AAValueConstantRangeImpl(IRP, A) {}
9537
9538 ChangeStatus updateImpl(Attributor &A) override {
9539 llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
9540 "not be called");
9541 }
9542
9543 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
9544};
9545
9546struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
9547 AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
9548 : AAValueConstantRangeFunction(IRP, A) {}
9549
9550 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
9551};
9552
9553struct AAValueConstantRangeCallSiteReturned
9554 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9555 AAValueConstantRangeImpl::StateType,
9556 /* IntroduceCallBaseContext */ true> {
9557 AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
9558 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9559 AAValueConstantRangeImpl::StateType,
9560 /* IntroduceCallBaseContext */ true>(IRP, A) {}
9561
9562 void initialize(Attributor &A) override {
9563 // If it is a call instruction with range attribute, use the range.
9564 if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue())) {
9565 if (std::optional<ConstantRange> Range = CI->getRange())
9566 intersectKnown(*Range);
9567 }
9568
9569 AAValueConstantRangeImpl::initialize(A);
9570 }
9571
9572 void trackStatistics() const override {
9573 STATS_DECLTRACK_CSRET_ATTR(value_range)
9574 }
9575};
9576struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
9577 AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
9578 : AAValueConstantRangeFloating(IRP, A) {}
9579
9580 ChangeStatus manifest(Attributor &A) override {
9581 return ChangeStatus::UNCHANGED;
9582 }
9583
9584 void trackStatistics() const override {
9585 STATS_DECLTRACK_CSARG_ATTR(value_range)
9586 }
9587};
9588} // namespace
9589
9590/// ------------------ Potential Values Attribute -------------------------
9591
9593 Attributor &A)
9594 : Base(IRP, true, A.Opts.attributor_max_potential_values) {}
9595
9596namespace {
9597struct AAPotentialConstantValuesImpl : AAPotentialConstantValues {
9598 using StateType = PotentialConstantIntValuesState;
9599
9600 AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A)
9601 : AAPotentialConstantValues(IRP, A) {}
9602
9603 void initialize(Attributor &A) override {
9604 if (A.hasSimplificationCallback(getIRPosition()))
9605 indicatePessimisticFixpoint();
9606 else
9608 }
9609
9610 bool fillSetWithConstantValues(Attributor &A, const IRPosition &IRP, SetTy &S,
9611 bool &ContainsUndef, bool ForSelf) {
9613 bool UsedAssumedInformation = false;
9614 if (!A.getAssumedSimplifiedValues(IRP, *this, Values, AA::Interprocedural,
9615 UsedAssumedInformation)) {
9616 // Avoid recursion when the caller is computing constant values for this
9617 // IRP itself.
9618 if (ForSelf)
9619 return false;
9620 if (!IRP.getAssociatedType()->isIntegerTy())
9621 return false;
9622 auto *PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>(
9623 *this, IRP, DepClassTy::REQUIRED);
9624 if (!PotentialValuesAA || !PotentialValuesAA->getState().isValidState())
9625 return false;
9626 ContainsUndef = PotentialValuesAA->getState().undefIsContained();
9627 S = PotentialValuesAA->getState().getAssumedSet();
9628 return true;
9629 }
9630
9631 // Copy all the constant values, except UndefValue. ContainsUndef is true
9632 // iff Values contains only UndefValue instances. If there are other known
9633 // constants, then UndefValue is dropped.
9634 ContainsUndef = false;
9635 for (auto &It : Values) {
9636 if (isa<UndefValue>(It.getValue())) {
9637 ContainsUndef = true;
9638 continue;
9639 }
9640 auto *CI = dyn_cast<ConstantInt>(It.getValue());
9641 if (!CI)
9642 return false;
9643 S.insert(CI->getValue());
9644 }
9645 ContainsUndef &= S.empty();
9646
9647 return true;
9648 }
9649
9650 const std::string getAsStr(Attributor *A) const override {
9651 std::string Str;
9652 llvm::raw_string_ostream OS(Str);
9653 OS << getState();
9654 return Str;
9655 }
9656
9657 ChangeStatus updateImpl(Attributor &A) override {
9658 return indicatePessimisticFixpoint();
9659 }
9660};
9661
9662struct AAPotentialConstantValuesArgument final
9663 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9664 AAPotentialConstantValuesImpl,
9665 PotentialConstantIntValuesState> {
9666 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9667 AAPotentialConstantValuesImpl,
9669 AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A)
9670 : Base(IRP, A) {}
9671
9672 void trackStatistics() const override {
9673 STATS_DECLTRACK_ARG_ATTR(potential_values)
9674 }
9675};
9676
9677struct AAPotentialConstantValuesReturned
9678 : AAReturnedFromReturnedValues<AAPotentialConstantValues,
9679 AAPotentialConstantValuesImpl> {
9680 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
9681 AAPotentialConstantValuesImpl>;
9682 AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A)
9683 : Base(IRP, A) {}
9684
9685 void initialize(Attributor &A) override {
9686 if (!A.isFunctionIPOAmendable(*getAssociatedFunction()))
9687 indicatePessimisticFixpoint();
9688 Base::initialize(A);
9689 }
9690
9691 void trackStatistics() const override {
9692 STATS_DECLTRACK_FNRET_ATTR(potential_values)
9693 }
9694};
9695
9696struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
9697 AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A)
9698 : AAPotentialConstantValuesImpl(IRP, A) {}
9699
9700 void initialize(Attributor &A) override {
9701 AAPotentialConstantValuesImpl::initialize(A);
9702 if (isAtFixpoint())
9703 return;
9704
9705 Value &V = getAssociatedValue();
9706
9707 if (auto *C = dyn_cast<ConstantInt>(&V)) {
9708 unionAssumed(C->getValue());
9709 indicateOptimisticFixpoint();
9710 return;
9711 }
9712
9713 if (isa<UndefValue>(&V)) {
9714 unionAssumedWithUndef();
9715 indicateOptimisticFixpoint();
9716 return;
9717 }
9718
9720 return;
9721
9723 return;
9724
9725 indicatePessimisticFixpoint();
9726
9727 LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: "
9728 << getAssociatedValue() << "\n");
9729 }
9730
9731 static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
9732 const APInt &RHS) {
9733 return ICmpInst::compare(LHS, RHS, ICI->getPredicate());
9734 }
9735
9736 static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
9737 uint32_t ResultBitWidth) {
9738 Instruction::CastOps CastOp = CI->getOpcode();
9739 switch (CastOp) {
9740 default:
9741 llvm_unreachable("unsupported or not integer cast");
9742 case Instruction::Trunc:
9743 return Src.trunc(ResultBitWidth);
9744 case Instruction::SExt:
9745 return Src.sext(ResultBitWidth);
9746 case Instruction::ZExt:
9747 return Src.zext(ResultBitWidth);
9748 case Instruction::BitCast:
9749 return Src;
9750 }
9751 }
9752
9753 static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
9754 const APInt &LHS, const APInt &RHS,
9755 bool &SkipOperation, bool &Unsupported) {
9756 Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
9757 // Unsupported is set to true when the binary operator is not supported.
9758 // SkipOperation is set to true when UB occur with the given operand pair
9759 // (LHS, RHS).
9760 // TODO: we should look at nsw and nuw keywords to handle operations
9761 // that create poison or undef value.
9762 switch (BinOpcode) {
9763 default:
9764 Unsupported = true;
9765 return LHS;
9766 case Instruction::Add:
9767 return LHS + RHS;
9768 case Instruction::Sub:
9769 return LHS - RHS;
9770 case Instruction::Mul:
9771 return LHS * RHS;
9772 case Instruction::UDiv:
9773 if (RHS.isZero()) {
9774 SkipOperation = true;
9775 return LHS;
9776 }
9777 return LHS.udiv(RHS);
9778 case Instruction::SDiv:
9779 if (RHS.isZero()) {
9780 SkipOperation = true;
9781 return LHS;
9782 }
9783 return LHS.sdiv(RHS);
9784 case Instruction::URem:
9785 if (RHS.isZero()) {
9786 SkipOperation = true;
9787 return LHS;
9788 }
9789 return LHS.urem(RHS);
9790 case Instruction::SRem:
9791 if (RHS.isZero()) {
9792 SkipOperation = true;
9793 return LHS;
9794 }
9795 return LHS.srem(RHS);
9796 case Instruction::Shl:
9797 return LHS.shl(RHS);
9798 case Instruction::LShr:
9799 return LHS.lshr(RHS);
9800 case Instruction::AShr:
9801 return LHS.ashr(RHS);
9802 case Instruction::And:
9803 return LHS & RHS;
9804 case Instruction::Or:
9805 return LHS | RHS;
9806 case Instruction::Xor:
9807 return LHS ^ RHS;
9808 }
9809 }
9810
9811 bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp,
9812 const APInt &LHS, const APInt &RHS) {
9813 bool SkipOperation = false;
9814 bool Unsupported = false;
9815 APInt Result =
9816 calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported);
9817 if (Unsupported)
9818 return false;
9819 // If SkipOperation is true, we can ignore this operand pair (L, R).
9820 if (!SkipOperation)
9821 unionAssumed(Result);
9822 return isValidState();
9823 }
9824
9825 ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
9826 auto AssumedBefore = getAssumed();
9827 Value *LHS = ICI->getOperand(0);
9828 Value *RHS = ICI->getOperand(1);
9829
9830 bool LHSContainsUndef = false, RHSContainsUndef = false;
9831 SetTy LHSAAPVS, RHSAAPVS;
9832 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9833 LHSContainsUndef, /* ForSelf */ false) ||
9834 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9835 RHSContainsUndef, /* ForSelf */ false))
9836 return indicatePessimisticFixpoint();
9837
9838 // TODO: make use of undef flag to limit potential values aggressively.
9839 bool MaybeTrue = false, MaybeFalse = false;
9840 const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0);
9841 if (LHSContainsUndef && RHSContainsUndef) {
9842 // The result of any comparison between undefs can be soundly replaced
9843 // with undef.
9844 unionAssumedWithUndef();
9845 } else if (LHSContainsUndef) {
9846 for (const APInt &R : RHSAAPVS) {
9847 bool CmpResult = calculateICmpInst(ICI, Zero, R);
9848 MaybeTrue |= CmpResult;
9849 MaybeFalse |= !CmpResult;
9850 if (MaybeTrue & MaybeFalse)
9851 return indicatePessimisticFixpoint();
9852 }
9853 } else if (RHSContainsUndef) {
9854 for (const APInt &L : LHSAAPVS) {
9855 bool CmpResult = calculateICmpInst(ICI, L, Zero);
9856 MaybeTrue |= CmpResult;
9857 MaybeFalse |= !CmpResult;
9858 if (MaybeTrue & MaybeFalse)
9859 return indicatePessimisticFixpoint();
9860 }
9861 } else {
9862 for (const APInt &L : LHSAAPVS) {
9863 for (const APInt &R : RHSAAPVS) {
9864 bool CmpResult = calculateICmpInst(ICI, L, R);
9865 MaybeTrue |= CmpResult;
9866 MaybeFalse |= !CmpResult;
9867 if (MaybeTrue & MaybeFalse)
9868 return indicatePessimisticFixpoint();
9869 }
9870 }
9871 }
9872 if (MaybeTrue)
9873 unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
9874 if (MaybeFalse)
9875 unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
9876 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9877 : ChangeStatus::CHANGED;
9878 }
9879
9880 ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
9881 auto AssumedBefore = getAssumed();
9882 Value *LHS = SI->getTrueValue();
9883 Value *RHS = SI->getFalseValue();
9884
9885 bool UsedAssumedInformation = false;
9886 std::optional<Constant *> C = A.getAssumedConstant(
9887 *SI->getCondition(), *this, UsedAssumedInformation);
9888
9889 // Check if we only need one operand.
9890 bool OnlyLeft = false, OnlyRight = false;
9891 if (C && *C && (*C)->isOneValue())
9892 OnlyLeft = true;
9893 else if (C && *C && (*C)->isNullValue())
9894 OnlyRight = true;
9895
9896 bool LHSContainsUndef = false, RHSContainsUndef = false;
9897 SetTy LHSAAPVS, RHSAAPVS;
9898 if (!OnlyRight &&
9899 !fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9900 LHSContainsUndef, /* ForSelf */ false))
9901 return indicatePessimisticFixpoint();
9902
9903 if (!OnlyLeft &&
9904 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9905 RHSContainsUndef, /* ForSelf */ false))
9906 return indicatePessimisticFixpoint();
9907
9908 if (OnlyLeft || OnlyRight) {
9909 // select (true/false), lhs, rhs
9910 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS;
9911 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef;
9912
9913 if (Undef)
9914 unionAssumedWithUndef();
9915 else {
9916 for (const auto &It : *OpAA)
9917 unionAssumed(It);
9918 }
9919
9920 } else if (LHSContainsUndef && RHSContainsUndef) {
9921 // select i1 *, undef , undef => undef
9922 unionAssumedWithUndef();
9923 } else {
9924 for (const auto &It : LHSAAPVS)
9925 unionAssumed(It);
9926 for (const auto &It : RHSAAPVS)
9927 unionAssumed(It);
9928 }
9929 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9930 : ChangeStatus::CHANGED;
9931 }
9932
9933 ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
9934 auto AssumedBefore = getAssumed();
9935 if (!CI->isIntegerCast())
9936 return indicatePessimisticFixpoint();
9937 assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
9938 uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
9939 Value *Src = CI->getOperand(0);
9940
9941 bool SrcContainsUndef = false;
9942 SetTy SrcPVS;
9943 if (!fillSetWithConstantValues(A, IRPosition::value(*Src), SrcPVS,
9944 SrcContainsUndef, /* ForSelf */ false))
9945 return indicatePessimisticFixpoint();
9946
9947 if (SrcContainsUndef)
9948 unionAssumedWithUndef();
9949 else {
9950 for (const APInt &S : SrcPVS) {
9951 APInt T = calculateCastInst(CI, S, ResultBitWidth);
9952 unionAssumed(T);
9953 }
9954 }
9955 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9956 : ChangeStatus::CHANGED;
9957 }
9958
9959 ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
9960 auto AssumedBefore = getAssumed();
9961 Value *LHS = BinOp->getOperand(0);
9962 Value *RHS = BinOp->getOperand(1);
9963
9964 bool LHSContainsUndef = false, RHSContainsUndef = false;
9965 SetTy LHSAAPVS, RHSAAPVS;
9966 if (!fillSetWithConstantValues(A, IRPosition::value(*LHS), LHSAAPVS,
9967 LHSContainsUndef, /* ForSelf */ false) ||
9968 !fillSetWithConstantValues(A, IRPosition::value(*RHS), RHSAAPVS,
9969 RHSContainsUndef, /* ForSelf */ false))
9970 return indicatePessimisticFixpoint();
9971
9972 const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0);
9973
9974 // TODO: make use of undef flag to limit potential values aggressively.
9975 if (LHSContainsUndef && RHSContainsUndef) {
9976 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero))
9977 return indicatePessimisticFixpoint();
9978 } else if (LHSContainsUndef) {
9979 for (const APInt &R : RHSAAPVS) {
9980 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R))
9981 return indicatePessimisticFixpoint();
9982 }
9983 } else if (RHSContainsUndef) {
9984 for (const APInt &L : LHSAAPVS) {
9985 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero))
9986 return indicatePessimisticFixpoint();
9987 }
9988 } else {
9989 for (const APInt &L : LHSAAPVS) {
9990 for (const APInt &R : RHSAAPVS) {
9991 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9992 return indicatePessimisticFixpoint();
9993 }
9994 }
9995 }
9996 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9997 : ChangeStatus::CHANGED;
9998 }
9999
10000 ChangeStatus updateWithInstruction(Attributor &A, Instruction *Inst) {
10001 auto AssumedBefore = getAssumed();
10002 SetTy Incoming;
10003 bool ContainsUndef;
10004 if (!fillSetWithConstantValues(A, IRPosition::value(*Inst), Incoming,
10005 ContainsUndef, /* ForSelf */ true))
10006 return indicatePessimisticFixpoint();
10007 if (ContainsUndef) {
10008 unionAssumedWithUndef();
10009 } else {
10010 for (const auto &It : Incoming)
10011 unionAssumed(It);
10012 }
10013 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10014 : ChangeStatus::CHANGED;
10015 }
10016
10017 ChangeStatus updateImpl(Attributor &A) override {
10018 Value &V = getAssociatedValue();
10020
10021 if (auto *ICI = dyn_cast<ICmpInst>(I))
10022 return updateWithICmpInst(A, ICI);
10023
10024 if (auto *SI = dyn_cast<SelectInst>(I))
10025 return updateWithSelectInst(A, SI);
10026
10027 if (auto *CI = dyn_cast<CastInst>(I))
10028 return updateWithCastInst(A, CI);
10029
10030 if (auto *BinOp = dyn_cast<BinaryOperator>(I))
10031 return updateWithBinaryOperator(A, BinOp);
10032
10033 if (isa<PHINode>(I) || isa<LoadInst>(I))
10034 return updateWithInstruction(A, I);
10035
10036 return indicatePessimisticFixpoint();
10037 }
10038
10039 void trackStatistics() const override {
10040 STATS_DECLTRACK_FLOATING_ATTR(potential_values)
10041 }
10042};
10043
10044struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
10045 AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A)
10046 : AAPotentialConstantValuesImpl(IRP, A) {}
10047
10048 ChangeStatus updateImpl(Attributor &A) override {
10050 "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
10051 "not be called");
10052 }
10053
10054 void trackStatistics() const override {
10055 STATS_DECLTRACK_FN_ATTR(potential_values)
10056 }
10057};
10058
10059struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
10060 AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A)
10061 : AAPotentialConstantValuesFunction(IRP, A) {}
10062
10063 void trackStatistics() const override {
10064 STATS_DECLTRACK_CS_ATTR(potential_values)
10065 }
10066};
10067
10068struct AAPotentialConstantValuesCallSiteReturned
10069 : AACalleeToCallSite<AAPotentialConstantValues,
10070 AAPotentialConstantValuesImpl> {
10071 AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP,
10072 Attributor &A)
10073 : AACalleeToCallSite<AAPotentialConstantValues,
10074 AAPotentialConstantValuesImpl>(IRP, A) {}
10075
10076 void trackStatistics() const override {
10077 STATS_DECLTRACK_CSRET_ATTR(potential_values)
10078 }
10079};
10080
10081struct AAPotentialConstantValuesCallSiteArgument
10082 : AAPotentialConstantValuesFloating {
10083 AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP,
10084 Attributor &A)
10085 : AAPotentialConstantValuesFloating(IRP, A) {}
10086
10087 void initialize(Attributor &A) override {
10088 AAPotentialConstantValuesImpl::initialize(A);
10089 if (isAtFixpoint())
10090 return;
10091
10092 Value &V = getAssociatedValue();
10093
10094 if (auto *C = dyn_cast<ConstantInt>(&V)) {
10095 unionAssumed(C->getValue());
10096 indicateOptimisticFixpoint();
10097 return;
10098 }
10099
10100 if (isa<UndefValue>(&V)) {
10101 unionAssumedWithUndef();
10102 indicateOptimisticFixpoint();
10103 return;
10104 }
10105 }
10106
10107 ChangeStatus updateImpl(Attributor &A) override {
10108 Value &V = getAssociatedValue();
10109 auto AssumedBefore = getAssumed();
10110 auto *AA = A.getAAFor<AAPotentialConstantValues>(
10111 *this, IRPosition::value(V), DepClassTy::REQUIRED);
10112 if (!AA)
10113 return indicatePessimisticFixpoint();
10114 const auto &S = AA->getAssumed();
10115 unionAssumed(S);
10116 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10117 : ChangeStatus::CHANGED;
10118 }
10119
10120 void trackStatistics() const override {
10121 STATS_DECLTRACK_CSARG_ATTR(potential_values)
10122 }
10123};
10124} // namespace
10125
10126/// ------------------------ NoUndef Attribute ---------------------------------
10128 Attribute::AttrKind ImpliedAttributeKind,
10129 bool IgnoreSubsumingPositions) {
10130 assert(ImpliedAttributeKind == Attribute::NoUndef &&
10131 "Unexpected attribute kind");
10132 if (A.hasAttr(IRP, {Attribute::NoUndef}, IgnoreSubsumingPositions,
10133 Attribute::NoUndef))
10134 return true;
10135
10136 Value &Val = IRP.getAssociatedValue();
10139 LLVMContext &Ctx = Val.getContext();
10140 A.manifestAttrs(IRP, Attribute::get(Ctx, Attribute::NoUndef));
10141 return true;
10142 }
10143
10144 return false;
10145}
10146
10147namespace {
10148struct AANoUndefImpl : AANoUndef {
10149 AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
10150
10151 void initialize(Attributor &A) override {
10152 Value &V = getAssociatedValue();
10153 if (isa<UndefValue>(V))
10154 indicatePessimisticFixpoint();
10155 assert(!isImpliedByIR(A, getIRPosition(), Attribute::NoUndef));
10156 }
10157
10158 /// See followUsesInMBEC
10159 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
10160 AANoUndef::StateType &State) {
10161 const Value *UseV = U->get();
10162 const DominatorTree *DT = nullptr;
10163 AssumptionCache *AC = nullptr;
10164 InformationCache &InfoCache = A.getInfoCache();
10165 if (Function *F = getAnchorScope()) {
10166 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
10167 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
10168 }
10169 State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT));
10170 bool TrackUse = false;
10171 // Track use for instructions which must produce undef or poison bits when
10172 // at least one operand contains such bits.
10174 TrackUse = true;
10175 return TrackUse;
10176 }
10177
10178 const std::string getAsStr(Attributor *A) const override {
10179 return getAssumed() ? "noundef" : "may-undef-or-poison";
10180 }
10181
10182 ChangeStatus manifest(Attributor &A) override {
10183 // We don't manifest noundef attribute for dead positions because the
10184 // associated values with dead positions would be replaced with undef
10185 // values.
10186 bool UsedAssumedInformation = false;
10187 if (A.isAssumedDead(getIRPosition(), nullptr, nullptr,
10188 UsedAssumedInformation))
10189 return ChangeStatus::UNCHANGED;
10190 // A position whose simplified value does not have any value is
10191 // considered to be dead. We don't manifest noundef in such positions for
10192 // the same reason above.
10193 if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation,
10195 .has_value())
10196 return ChangeStatus::UNCHANGED;
10197 return AANoUndef::manifest(A);
10198 }
10199};
10200
10201struct AANoUndefFloating : public AANoUndefImpl {
10202 AANoUndefFloating(const IRPosition &IRP, Attributor &A)
10203 : AANoUndefImpl(IRP, A) {}
10204
10205 void initialize(Attributor &A) override {
10206 AANoUndefImpl::initialize(A);
10207 if (!getState().isAtFixpoint() && getAnchorScope() &&
10208 !getAnchorScope()->isDeclaration())
10209 if (Instruction *CtxI = getCtxI())
10210 followUsesInMBEC(*this, A, getState(), *CtxI);
10211 }
10212
10213 ChangeStatus updateImpl(Attributor &A) override {
10214 auto VisitValueCB = [&](const IRPosition &IRP) -> bool {
10215 bool IsKnownNoUndef;
10217 A, this, IRP, DepClassTy::REQUIRED, IsKnownNoUndef);
10218 };
10219
10220 bool Stripped;
10221 bool UsedAssumedInformation = false;
10222 Value *AssociatedValue = &getAssociatedValue();
10224 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
10225 AA::AnyScope, UsedAssumedInformation))
10226 Stripped = false;
10227 else
10228 Stripped =
10229 Values.size() != 1 || Values.front().getValue() != AssociatedValue;
10230
10231 if (!Stripped) {
10232 // If we haven't stripped anything we might still be able to use a
10233 // different AA, but only if the IRP changes. Effectively when we
10234 // interpret this not as a call site value but as a floating/argument
10235 // value.
10236 const IRPosition AVIRP = IRPosition::value(*AssociatedValue);
10237 if (AVIRP == getIRPosition() || !VisitValueCB(AVIRP))
10238 return indicatePessimisticFixpoint();
10239 return ChangeStatus::UNCHANGED;
10240 }
10241
10242 for (const auto &VAC : Values)
10243 if (!VisitValueCB(IRPosition::value(*VAC.getValue())))
10244 return indicatePessimisticFixpoint();
10245
10246 return ChangeStatus::UNCHANGED;
10247 }
10248
10249 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
10250};
10251
10252/// Return true if the poison-generating attributes in \p Attrs are assumed to
10253/// hold for the value at \p Pos.
10254static bool checkPoisonGeneratingAttrsHold(Attributor &A,
10255 const AbstractAttribute &QueryingAA,
10256 AttributeSet Attrs,
10257 const IRPosition &Pos,
10258 const Instruction *CtxI) {
10259 AttributeMask AM = AttributeFuncs::getPoisonGeneratingAttributes();
10260 for (Attribute Attr : Attrs) {
10261 if (!AM.contains(Attr))
10262 continue;
10263
10264 switch (Attr.getKindAsEnum()) {
10265 case Attribute::NonNull: {
10266 bool IsKnown;
10268 A, &QueryingAA, Pos, DepClassTy::REQUIRED, IsKnown))
10269 return false;
10270 break;
10271 }
10272 case Attribute::Alignment: {
10273 const auto *AlignAA =
10274 A.getAAFor<AAAlign>(QueryingAA, Pos, DepClassTy::REQUIRED);
10275 if (!AlignAA || AlignAA->getAssumedAlign() < *Attr.getAlignment())
10276 return false;
10277 break;
10278 }
10279 case Attribute::Range: {
10280 const auto *RangeAA = A.getAAFor<AAValueConstantRange>(
10281 QueryingAA, Pos, DepClassTy::REQUIRED);
10282 if (!RangeAA ||
10283 !Attr.getRange().contains(RangeAA->getAssumedConstantRange(A, CtxI)))
10284 return false;
10285 break;
10286 }
10287 case Attribute::NoFPClass: {
10288 FPClassTest NoFPClass = Attr.getNoFPClass();
10289 const auto *NoFPClassAA =
10290 A.getAAFor<AANoFPClass>(QueryingAA, Pos, DepClassTy::REQUIRED);
10291 if (!NoFPClassAA ||
10292 (NoFPClassAA->getAssumedNoFPClass() & NoFPClass) != NoFPClass)
10293 return false;
10294 break;
10295 }
10296 default:
10297 // Conservatively assume unhandled attributes do not hold.
10298 return false;
10299 }
10300 }
10301
10302 return true;
10303}
10304
10305struct AANoUndefReturned final
10306 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
10307 using Base = AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>;
10308 AANoUndefReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
10309
10310 void initialize(Attributor &A) override {
10311 Base::initialize(A);
10312 RetAttrs = getAssociatedFunction()->getAttributes().getRetAttrs();
10313 }
10314
10315 ChangeStatus updateImpl(Attributor &A) override {
10316 // A returned value that violates a poison-generating return attribute
10317 // becomes poison, so the attributes must hold for every returned value.
10318 if (RetAttrs.hasAttributes()) {
10319 auto AttrsHold = [&](Instruction &I) {
10320 Value &V = *cast<ReturnInst>(I).getReturnValue();
10321 return checkPoisonGeneratingAttrsHold(A, *this, RetAttrs,
10322 IRPosition::value(V), &I);
10323 };
10324 bool UsedAssumedInformation = false;
10325 if (!A.checkForAllInstructions(AttrsHold, *this, {Instruction::Ret},
10326 UsedAssumedInformation))
10327 return indicatePessimisticFixpoint();
10328 }
10329
10330 return Base::updateImpl(A);
10331 }
10332
10333 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
10334
10335private:
10336 /// The function return attributes.
10337 AttributeSet RetAttrs;
10338};
10339
10340struct AANoUndefArgument final
10341 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
10342 AANoUndefArgument(const IRPosition &IRP, Attributor &A)
10343 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
10344
10345 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
10346};
10347
10348struct AANoUndefCallSiteArgument final : AANoUndefFloating {
10349 AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
10350 : AANoUndefFloating(IRP, A) {}
10351
10352 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
10353};
10354
10355struct AANoUndefCallSiteReturned final
10356 : AACalleeToCallSite<AANoUndef, AANoUndefImpl> {
10357 using Base = AACalleeToCallSite<AANoUndef, AANoUndefImpl>;
10358 AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
10359 : Base(IRP, A) {}
10360
10361 void initialize(Attributor &A) override {
10362 Base::initialize(A);
10363 RetAttrs = cast<CallBase>(getAnchorValue()).getRetAttributes();
10364 }
10365
10366 ChangeStatus updateImpl(Attributor &A) override {
10367 // The call returns poison if the callee return value violates a
10368 // poison-generating call site return attribute, so the attributes must
10369 // hold for every callee.
10370 if (RetAttrs.hasAttributes()) {
10371 auto AttrsHold = [&](ArrayRef<const Function *> Callees) {
10372 return all_of(Callees, [&](const Function *Callee) {
10373 return checkPoisonGeneratingAttrsHold(
10374 A, *this, RetAttrs, IRPosition::returned(*Callee), nullptr);
10375 });
10376 };
10377 if (!A.checkForAllCallees(AttrsHold, *this,
10378 cast<CallBase>(getAnchorValue())))
10379 return indicatePessimisticFixpoint();
10380 }
10381
10382 return Base::updateImpl(A);
10383 }
10384
10385 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
10386
10387private:
10388 /// The call site return attributes.
10389 AttributeSet RetAttrs;
10390};
10391
10392/// ------------------------ NoFPClass Attribute -------------------------------
10393
10394struct AANoFPClassImpl : AANoFPClass {
10395 AANoFPClassImpl(const IRPosition &IRP, Attributor &A) : AANoFPClass(IRP, A) {}
10396
10397 void initialize(Attributor &A) override {
10398 const IRPosition &IRP = getIRPosition();
10399
10400 Value &V = IRP.getAssociatedValue();
10401 if (isa<UndefValue>(V)) {
10402 indicateOptimisticFixpoint();
10403 return;
10404 }
10405
10407 A.getAttrs(getIRPosition(), {Attribute::NoFPClass}, Attrs, false);
10408 for (const auto &Attr : Attrs) {
10409 addKnownBits(Attr.getNoFPClass());
10410 }
10411
10412 Instruction *CtxI = getCtxI();
10413
10414 if (getPositionKind() != IRPosition::IRP_RETURNED) {
10415 const DataLayout &DL = A.getDataLayout();
10416 InformationCache &InfoCache = A.getInfoCache();
10417
10418 const DominatorTree *DT = nullptr;
10419 AssumptionCache *AC = nullptr;
10420 const TargetLibraryInfo *TLI = nullptr;
10421 Function *F = getAnchorScope();
10422 if (F) {
10424 if (!F->isDeclaration()) {
10425 DT =
10426 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
10427 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
10428 }
10429 }
10430
10431 SimplifyQuery Q(DL, TLI, DT, AC, CtxI);
10432
10433 KnownFPClass KnownFPClass = computeKnownFPClass(&V, fcAllFlags, Q);
10434 addKnownBits(~KnownFPClass.getKnownFPClasses());
10435 }
10436
10437 if (CtxI)
10438 followUsesInMBEC(*this, A, getState(), *CtxI);
10439 }
10440
10441 /// See followUsesInMBEC
10442 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
10443 AANoFPClass::StateType &State) {
10444 // TODO: Determine what instructions can be looked through.
10445 auto *CB = dyn_cast<CallBase>(I);
10446 if (!CB)
10447 return false;
10448
10449 if (!CB->isArgOperand(U))
10450 return false;
10451
10452 unsigned ArgNo = CB->getArgOperandNo(U);
10453 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
10454 if (auto *NoFPAA = A.getAAFor<AANoFPClass>(*this, IRP, DepClassTy::NONE))
10455 State.addKnownBits(NoFPAA->getState().getKnown());
10456 return false;
10457 }
10458
10459 const std::string getAsStr(Attributor *A) const override {
10460 std::string Result = "nofpclass";
10461 raw_string_ostream OS(Result);
10462 OS << getKnownNoFPClass() << '/' << getAssumedNoFPClass();
10463 return Result;
10464 }
10465
10466 void getDeducedAttributes(Attributor &A, LLVMContext &Ctx,
10467 SmallVectorImpl<Attribute> &Attrs) const override {
10468 Attrs.emplace_back(Attribute::getWithNoFPClass(Ctx, getAssumedNoFPClass()));
10469 }
10470};
10471
10472struct AANoFPClassFloating : public AANoFPClassImpl {
10473 AANoFPClassFloating(const IRPosition &IRP, Attributor &A)
10474 : AANoFPClassImpl(IRP, A) {}
10475
10476 ChangeStatus updateImpl(Attributor &A) override {
10478 bool UsedAssumedInformation = false;
10479 if (!A.getAssumedSimplifiedValues(getIRPosition(), *this, Values,
10480 AA::AnyScope, UsedAssumedInformation)) {
10481 Values.push_back({getAssociatedValue(), getCtxI()});
10482 }
10483
10484 StateType T;
10485 auto VisitValueCB = [&](Value &V, const Instruction *CtxI) -> bool {
10486 const auto *AA = A.getAAFor<AANoFPClass>(*this, IRPosition::value(V),
10487 DepClassTy::REQUIRED);
10488 if (!AA || this == AA) {
10489 T.indicatePessimisticFixpoint();
10490 } else {
10491 const AANoFPClass::StateType &S =
10492 static_cast<const AANoFPClass::StateType &>(AA->getState());
10493 T ^= S;
10494 }
10495 return T.isValidState();
10496 };
10497
10498 for (const auto &VAC : Values)
10499 if (!VisitValueCB(*VAC.getValue(), VAC.getCtxI()))
10500 return indicatePessimisticFixpoint();
10501
10502 return clampStateAndIndicateChange(getState(), T);
10503 }
10504
10505 void trackStatistics() const override {
10507 }
10508};
10509
10510struct AANoFPClassReturned final
10511 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10512 AANoFPClassImpl::StateType, false,
10513 Attribute::None, false> {
10514 AANoFPClassReturned(const IRPosition &IRP, Attributor &A)
10515 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10516 AANoFPClassImpl::StateType, false,
10517 Attribute::None, false>(IRP, A) {}
10518
10519 void trackStatistics() const override {
10521 }
10522};
10523
10524struct AANoFPClassArgument final
10525 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl> {
10526 AANoFPClassArgument(const IRPosition &IRP, Attributor &A)
10527 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl>(IRP, A) {}
10528
10529 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofpclass) }
10530};
10531
10532struct AANoFPClassCallSiteArgument final : AANoFPClassFloating {
10533 AANoFPClassCallSiteArgument(const IRPosition &IRP, Attributor &A)
10534 : AANoFPClassFloating(IRP, A) {}
10535
10536 void trackStatistics() const override {
10538 }
10539};
10540
10541struct AANoFPClassCallSiteReturned final
10542 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl> {
10543 AANoFPClassCallSiteReturned(const IRPosition &IRP, Attributor &A)
10544 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl>(IRP, A) {}
10545
10546 void trackStatistics() const override {
10548 }
10549};
10550
10551struct AACallEdgesImpl : public AACallEdges {
10552 AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {}
10553
10554 const SetVector<Function *> &getOptimisticEdges() const override {
10555 return CalledFunctions;
10556 }
10557
10558 bool hasUnknownCallee() const override { return HasUnknownCallee; }
10559
10560 bool hasNonAsmUnknownCallee() const override {
10561 return HasUnknownCalleeNonAsm;
10562 }
10563
10564 const std::string getAsStr(Attributor *A) const override {
10565 return "CallEdges[" + std::to_string(HasUnknownCallee) + "," +
10566 std::to_string(CalledFunctions.size()) + "]";
10567 }
10568
10569 void trackStatistics() const override {}
10570
10571protected:
10572 /// Return the callee of \p CB if it is a direct call whose callee has no
10573 /// callback metadata. Such a call only calls its callee.
10574 static Function *getOnlyCallee(const CallBase &CB) {
10576 if (Callee && !Callee->hasMetadata(LLVMContext::MD_callback))
10577 return Callee;
10578 return nullptr;
10579 }
10580
10581 void addCalledFunction(Function *Fn, ChangeStatus &Change) {
10582 if (CalledFunctions.insert(Fn)) {
10583 Change = ChangeStatus::CHANGED;
10584 LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName()
10585 << "\n");
10586 }
10587 }
10588
10589 void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) {
10590 if (!HasUnknownCallee)
10591 Change = ChangeStatus::CHANGED;
10592 if (NonAsm && !HasUnknownCalleeNonAsm)
10593 Change = ChangeStatus::CHANGED;
10594 HasUnknownCalleeNonAsm |= NonAsm;
10595 HasUnknownCallee = true;
10596 }
10597
10598private:
10599 /// Optimistic set of functions that might be called by this position.
10600 SetVector<Function *> CalledFunctions;
10601
10602 /// Is there any call with a unknown callee.
10603 bool HasUnknownCallee = false;
10604
10605 /// Is there any call with a unknown callee, excluding any inline asm.
10606 bool HasUnknownCalleeNonAsm = false;
10607};
10608
10609struct AACallEdgesCallSite : public AACallEdgesImpl {
10610 AACallEdgesCallSite(const IRPosition &IRP, Attributor &A)
10611 : AACallEdgesImpl(IRP, A) {}
10612
10613 void initialize(Attributor &A) override {
10614 // The only callee of a direct call without callbacks never changes.
10615 if (Function *Callee = getOnlyCallee(cast<CallBase>(getAnchorValue()))) {
10616 ChangeStatus Change = ChangeStatus::UNCHANGED;
10617 addCalledFunction(Callee, Change);
10618 indicateOptimisticFixpoint();
10619 }
10620 }
10621
10622 ChangeStatus updateImpl(Attributor &A) override {
10623 ChangeStatus Change = ChangeStatus::UNCHANGED;
10624
10625 auto VisitValue = [&](Value &V, const Instruction *CtxI) -> bool {
10626 if (Function *Fn = dyn_cast<Function>(&V)) {
10627 addCalledFunction(Fn, Change);
10628 } else {
10629 LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n");
10630 setHasUnknownCallee(true, Change);
10631 }
10632
10633 // Explore all values.
10634 return true;
10635 };
10636
10638 // Process any value that we might call.
10639 auto ProcessCalledOperand = [&](Value *V, Instruction *CtxI) {
10640 if (isa<Constant>(V)) {
10641 VisitValue(*V, CtxI);
10642 return;
10643 }
10644
10645 bool UsedAssumedInformation = false;
10646 Values.clear();
10647 if (!A.getAssumedSimplifiedValues(IRPosition::value(*V), *this, Values,
10648 AA::AnyScope, UsedAssumedInformation)) {
10649 Values.push_back({*V, CtxI});
10650 }
10651 for (auto &VAC : Values)
10652 VisitValue(*VAC.getValue(), VAC.getCtxI());
10653 };
10654
10655 CallBase *CB = cast<CallBase>(getCtxI());
10656
10657 if (auto *IA = dyn_cast<InlineAsm>(CB->getCalledOperand())) {
10658 if (IA->hasSideEffects() &&
10659 !hasAssumption(*CB->getCaller(), "ompx_no_call_asm") &&
10660 !hasAssumption(*CB, "ompx_no_call_asm")) {
10661 setHasUnknownCallee(false, Change);
10662 }
10663 return Change;
10664 }
10665
10666 if (CB->isIndirectCall())
10667 if (auto *IndirectCallAA = A.getAAFor<AAIndirectCallInfo>(
10668 *this, getIRPosition(), DepClassTy::OPTIONAL))
10669 if (IndirectCallAA->foreachCallee(
10670 [&](Function *Fn) { return VisitValue(*Fn, CB); }))
10671 return Change;
10672
10673 // The most simple case.
10674 ProcessCalledOperand(CB->getCalledOperand(), CB);
10675
10676 // Process callback functions.
10677 SmallVector<const Use *, 4u> CallbackUses;
10678 AbstractCallSite::getCallbackUses(*CB, CallbackUses);
10679 for (const Use *U : CallbackUses)
10680 ProcessCalledOperand(U->get(), CB);
10681
10682 return Change;
10683 }
10684};
10685
10686struct AACallEdgesFunction : public AACallEdgesImpl {
10687 AACallEdgesFunction(const IRPosition &IRP, Attributor &A)
10688 : AACallEdgesImpl(IRP, A) {}
10689
10690 ChangeStatus updateImpl(Attributor &A) override {
10691 ChangeStatus Change = ChangeStatus::UNCHANGED;
10692 bool AllCallsDirect = true;
10693
10694 auto ProcessCallInst = [&](Instruction &Inst) {
10695 CallBase &CB = cast<CallBase>(Inst);
10696
10697 // A direct call without callbacks only calls its callee; there is no
10698 // need for a call site attribute.
10699 if (Function *Callee = getOnlyCallee(CB)) {
10700 addCalledFunction(Callee, Change);
10701 return true;
10702 }
10703
10704 AllCallsDirect = false;
10705 auto *CBEdges = A.getAAFor<AACallEdges>(
10706 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
10707 if (!CBEdges)
10708 return false;
10709 if (CBEdges->hasNonAsmUnknownCallee())
10710 setHasUnknownCallee(true, Change);
10711 if (CBEdges->hasUnknownCallee())
10712 setHasUnknownCallee(false, Change);
10713
10714 for (Function *F : CBEdges->getOptimisticEdges())
10715 addCalledFunction(F, Change);
10716
10717 return true;
10718 };
10719
10720 // Visit all callable instructions.
10721 bool UsedAssumedInformation = false;
10722 if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this,
10723 UsedAssumedInformation,
10724 /* CheckBBLivenessOnly */ true)) {
10725 // If we haven't looked at all call like instructions, assume that there
10726 // are unknown callees.
10727 setHasUnknownCallee(true, Change);
10728 }
10729
10730 // The callees of direct calls in code known to be live do not change.
10731 if (AllCallsDirect && !UsedAssumedInformation)
10732 indicateOptimisticFixpoint();
10733
10734 return Change;
10735 }
10736};
10737
10738/// -------------------AAInterFnReachability Attribute--------------------------
10739
10740struct AAInterFnReachabilityFunction
10741 : public CachedReachabilityAA<AAInterFnReachability, Function> {
10742 using Base = CachedReachabilityAA<AAInterFnReachability, Function>;
10743 AAInterFnReachabilityFunction(const IRPosition &IRP, Attributor &A)
10744 : Base(IRP, A) {}
10745
10746 bool instructionCanReach(
10747 Attributor &A, const Instruction &From, const Function &To,
10748 const AA::InstExclusionSetTy *ExclusionSet) const override {
10749 assert(From.getFunction() == getAnchorScope() && "Queried the wrong AA!");
10750 auto *NonConstThis = const_cast<AAInterFnReachabilityFunction *>(this);
10751
10752 RQITy StackRQI(A, From, To, ExclusionSet, false);
10753 RQITy::Reachable Result;
10754 if (!NonConstThis->checkQueryCache(A, StackRQI, Result))
10755 return NonConstThis->isReachableImpl(A, StackRQI,
10756 /*IsTemporaryRQI=*/true);
10757 return Result == RQITy::Reachable::Yes;
10758 }
10759
10760 bool isReachableImpl(Attributor &A, RQITy &RQI,
10761 bool IsTemporaryRQI) override {
10762 const Instruction *EntryI =
10763 &RQI.From->getFunction()->getEntryBlock().front();
10764 if (EntryI != RQI.From &&
10765 !instructionCanReach(A, *EntryI, *RQI.To, nullptr))
10766 return rememberResult(A, RQITy::Reachable::No, RQI, false,
10767 IsTemporaryRQI);
10768
10769 auto CheckReachableCallBase = [&](CallBase *CB) {
10770 auto *CBEdges = A.getAAFor<AACallEdges>(
10771 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
10772 if (!CBEdges || !CBEdges->getState().isValidState())
10773 return false;
10774 // TODO Check To backwards in this case.
10775 if (CBEdges->hasUnknownCallee())
10776 return false;
10777
10778 for (Function *Fn : CBEdges->getOptimisticEdges()) {
10779 if (Fn == RQI.To)
10780 return false;
10781
10782 if (Fn->isDeclaration()) {
10783 if (Fn->hasFnAttribute(Attribute::NoCallback))
10784 continue;
10785 // TODO Check To backwards in this case.
10786 return false;
10787 }
10788
10789 if (Fn == getAnchorScope()) {
10790 if (EntryI == RQI.From)
10791 continue;
10792 return false;
10793 }
10794
10795 const AAInterFnReachability *InterFnReachability =
10796 A.getAAFor<AAInterFnReachability>(*this, IRPosition::function(*Fn),
10797 DepClassTy::OPTIONAL);
10798
10799 const Instruction &FnFirstInst = Fn->getEntryBlock().front();
10800 if (!InterFnReachability ||
10801 InterFnReachability->instructionCanReach(A, FnFirstInst, *RQI.To,
10802 RQI.ExclusionSet))
10803 return false;
10804 }
10805 return true;
10806 };
10807
10808 const auto *IntraFnReachability = A.getAAFor<AAIntraFnReachability>(
10809 *this, IRPosition::function(*RQI.From->getFunction()),
10810 DepClassTy::OPTIONAL);
10811
10812 // Determine call like instructions that we can reach from the inst.
10813 auto CheckCallBase = [&](Instruction &CBInst) {
10814 // There are usually less nodes in the call graph, check inter function
10815 // reachability first.
10816 if (CheckReachableCallBase(cast<CallBase>(&CBInst)))
10817 return true;
10818 return IntraFnReachability && !IntraFnReachability->isAssumedReachable(
10819 A, *RQI.From, CBInst, RQI.ExclusionSet);
10820 };
10821
10822 bool UsedExclusionSet = /* conservative */ true;
10823 bool UsedAssumedInformation = false;
10824 if (!A.checkForAllCallLikeInstructions(CheckCallBase, *this,
10825 UsedAssumedInformation,
10826 /* CheckBBLivenessOnly */ true))
10827 return rememberResult(A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
10828 IsTemporaryRQI);
10829
10830 return rememberResult(A, RQITy::Reachable::No, RQI, UsedExclusionSet,
10831 IsTemporaryRQI);
10832 }
10833
10834 void trackStatistics() const override {}
10835};
10836} // namespace
10837
10838template <typename AAType>
10839static std::optional<Constant *>
10841 const IRPosition &IRP, Type &Ty) {
10842 if (!Ty.isIntegerTy())
10843 return nullptr;
10844
10845 // This will also pass the call base context.
10846 const auto *AA = A.getAAFor<AAType>(QueryingAA, IRP, DepClassTy::NONE);
10847 if (!AA)
10848 return nullptr;
10849
10850 std::optional<Constant *> COpt = AA->getAssumedConstant(A);
10851
10852 if (!COpt.has_value()) {
10853 A.recordDependence(*AA, QueryingAA, DepClassTy::OPTIONAL);
10854 return std::nullopt;
10855 }
10856 if (auto *C = *COpt) {
10857 A.recordDependence(*AA, QueryingAA, DepClassTy::OPTIONAL);
10858 return C;
10859 }
10860 return nullptr;
10861}
10862
10864 Attributor &A, const AbstractAttribute &AA, const IRPosition &IRP,
10866 Type &Ty = *IRP.getAssociatedType();
10867 std::optional<Value *> V;
10868 for (auto &It : Values) {
10869 V = AA::combineOptionalValuesInAAValueLatice(V, It.getValue(), &Ty);
10870 if (V.has_value() && !*V)
10871 break;
10872 }
10873 if (!V.has_value())
10874 return UndefValue::get(&Ty);
10875 return *V;
10876}
10877
10878namespace {
10879struct AAPotentialValuesImpl : AAPotentialValues {
10880 using StateType = PotentialLLVMValuesState;
10881
10882 AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A)
10883 : AAPotentialValues(IRP, A) {}
10884
10885 void initialize(Attributor &A) override {
10886 if (A.hasSimplificationCallback(getIRPosition())) {
10887 indicatePessimisticFixpoint();
10888 return;
10889 }
10890 Value *Stripped = getAssociatedValue().stripPointerCasts();
10891 if (isa<Constant>(Stripped) && !isa<ConstantExpr>(Stripped)) {
10892 addValue(A, getState(), *Stripped, getCtxI(), AA::AnyScope,
10893 getAnchorScope());
10894 indicateOptimisticFixpoint();
10895 return;
10896 }
10897 AAPotentialValues::initialize(A);
10898 }
10899
10900 const std::string getAsStr(Attributor *A) const override {
10901 std::string Str;
10902 llvm::raw_string_ostream OS(Str);
10903 OS << getState();
10904 return Str;
10905 }
10906
10907 template <typename AAType>
10908 static std::optional<Value *> askOtherAA(Attributor &A,
10909 const AbstractAttribute &AA,
10910 const IRPosition &IRP, Type &Ty) {
10912 return &IRP.getAssociatedValue();
10913 std::optional<Constant *> C = askForAssumedConstant<AAType>(A, AA, IRP, Ty);
10914 if (!C)
10915 return std::nullopt;
10916 if (*C)
10917 if (auto *CC = AA::getWithType(**C, Ty))
10918 return CC;
10919 return nullptr;
10920 }
10921
10922 virtual void addValue(Attributor &A, StateType &State, Value &V,
10923 const Instruction *CtxI, AA::ValueScope S,
10924 Function *AnchorScope) const {
10925 assert(S != 0 && (S & ~AA::AnyScope) == 0 && "invalid value scope!");
10926
10927 IRPosition ValIRP = IRPosition::value(V);
10928 if (auto *CB = dyn_cast_or_null<CallBase>(CtxI)) {
10929 for (const auto &U : CB->args()) {
10930 if (U.get() != &V)
10931 continue;
10932 ValIRP = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
10933 break;
10934 }
10935 }
10936
10937 Value *VPtr = &V;
10938 if (ValIRP.getAssociatedType()->isIntegerTy()) {
10939 Type &Ty = *getAssociatedType();
10940 std::optional<Value *> SimpleV =
10941 askOtherAA<AAValueConstantRange>(A, *this, ValIRP, Ty);
10942 if (SimpleV.has_value() && !*SimpleV) {
10943 auto *PotentialConstantsAA = A.getAAFor<AAPotentialConstantValues>(
10944 *this, ValIRP, DepClassTy::OPTIONAL);
10945 if (PotentialConstantsAA && PotentialConstantsAA->isValidState()) {
10946 for (const auto &It : PotentialConstantsAA->getAssumedSet())
10947 State.unionAssumed({{*ConstantInt::get(&Ty, It), nullptr}, S});
10948 if (PotentialConstantsAA->undefIsContained())
10949 State.unionAssumed({{*UndefValue::get(&Ty), nullptr}, S});
10950 return;
10951 }
10952 }
10953 if (!SimpleV.has_value())
10954 return;
10955
10956 if (*SimpleV)
10957 VPtr = *SimpleV;
10958 }
10959
10960 if (isa<ConstantInt>(VPtr))
10961 CtxI = nullptr;
10962 if (!AA::isValidInScope(*VPtr, AnchorScope))
10964
10965 State.unionAssumed({{*VPtr, CtxI}, S});
10966 }
10967
10968 /// Helper struct to tie a value+context pair together with the scope for
10969 /// which this is the simplified version.
10970 struct ItemInfo {
10971 AA::ValueAndContext I;
10973
10974 bool operator==(const ItemInfo &II) const {
10975 return II.I == I && II.S == S;
10976 };
10977 bool operator<(const ItemInfo &II) const {
10978 return std::tie(I, S) < std::tie(II.I, II.S);
10979 };
10980 };
10981
10982 /// Add the simplified values of \p IRP in scope \p S to our state. Return
10983 /// false, and add nothing, if \p IRP could not be simplified or if it has
10984 /// more than a few values.
10985 bool recurseForValue(Attributor &A, const IRPosition &IRP, AA::ValueScope S) {
10986 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap;
10987 for (auto CS : {AA::Intraprocedural, AA::Interprocedural}) {
10988 if (!(CS & S))
10989 continue;
10990
10991 bool UsedAssumedInformation = false;
10993 if (!A.getAssumedSimplifiedValues(IRP, this, Values, CS,
10994 UsedAssumedInformation))
10995 return false;
10996
10997 for (auto &It : Values)
10998 ValueScopeMap[It] |= CS;
10999
11000 // Take at most seven value and context pairs. If there are more, the
11001 // caller uses the value of IRP itself. Without a limit, the sets can grow
11002 // with each step of a chain, and each step then needs one more fixpoint
11003 // iteration. 7 is a magic number here, but it is sufficient for most
11004 // cases.
11005 if (ValueScopeMap.size() > 7)
11006 return false;
11007 }
11008 for (auto &It : ValueScopeMap)
11009 addValue(A, getState(), *It.first.getValue(), It.first.getCtxI(),
11010 AA::ValueScope(It.second), getAnchorScope());
11011
11012 return true;
11013 }
11014
11015 void giveUpOnIntraprocedural(Attributor &A) {
11016 auto NewS = StateType::getBestState(getState());
11017 for (const auto &It : getAssumedSet()) {
11018 if (It.second == AA::Intraprocedural)
11019 continue;
11020 addValue(A, NewS, *It.first.getValue(), It.first.getCtxI(),
11021 AA::Interprocedural, getAnchorScope());
11022 }
11023 assert(!undefIsContained() && "Undef should be an explicit value!");
11024 addValue(A, NewS, getAssociatedValue(), getCtxI(), AA::Intraprocedural,
11025 getAnchorScope());
11026 getState() = NewS;
11027 }
11028
11029 ChangeStatus indicatePessimisticFixpoint() override {
11030 getState() = StateType::getBestState(getState());
11031 getState().unionAssumed({{getAssociatedValue(), getCtxI()}, AA::AnyScope});
11032 AAPotentialValues::indicateOptimisticFixpoint();
11033 return ChangeStatus::CHANGED;
11034 }
11035
11036 ChangeStatus updateImpl(Attributor &A) override {
11037 return indicatePessimisticFixpoint();
11038 }
11039
11040 ChangeStatus manifest(Attributor &A) override {
11043 Values.clear();
11044 if (!getAssumedSimplifiedValues(A, Values, S))
11045 continue;
11046 Value &OldV = getAssociatedValue();
11047 if (isa<UndefValue>(OldV))
11048 continue;
11049 Value *NewV = getSingleValue(A, *this, getIRPosition(), Values);
11050 if (!NewV || NewV == &OldV)
11051 continue;
11052 if (getCtxI() &&
11053 !AA::isValidAtPosition({*NewV, *getCtxI()}, A.getInfoCache()))
11054 continue;
11055 if (A.changeAfterManifest(getIRPosition(), *NewV))
11056 return ChangeStatus::CHANGED;
11057 }
11058 return ChangeStatus::UNCHANGED;
11059 }
11060
11061 bool getAssumedSimplifiedValues(
11062 Attributor &A, SmallVectorImpl<AA::ValueAndContext> &Values,
11063 AA::ValueScope S, bool RecurseForSelectAndPHI = false) const override {
11064 if (!isValidState())
11065 return false;
11066 bool UsedAssumedInformation = false;
11067 for (const auto &It : getAssumedSet())
11068 if (It.second & S) {
11069 if (RecurseForSelectAndPHI && (isa<PHINode>(It.first.getValue()) ||
11070 isa<SelectInst>(It.first.getValue()))) {
11071 if (A.getAssumedSimplifiedValues(
11072 IRPosition::inst(*cast<Instruction>(It.first.getValue())),
11073 this, Values, S, UsedAssumedInformation))
11074 continue;
11075 }
11076 Values.push_back(It.first);
11077 }
11078 assert(!undefIsContained() && "Undef should be an explicit value!");
11079 return true;
11080 }
11081};
11082
11083struct AAPotentialValuesFloating : AAPotentialValuesImpl {
11084 AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A)
11085 : AAPotentialValuesImpl(IRP, A) {}
11086
11087 ChangeStatus updateImpl(Attributor &A) override {
11088 auto AssumedBefore = getAssumed();
11089
11090 genericValueTraversal(A, &getAssociatedValue());
11091
11092 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11093 : ChangeStatus::CHANGED;
11094 }
11095
11096 /// Helper struct to remember which AAIsDead instances we actually used.
11097 struct LivenessInfo {
11098 const AAIsDead *LivenessAA = nullptr;
11099 bool AnyDead = false;
11100 };
11101
11102 /// Check if \p Cmp is a comparison we can simplify.
11103 ///
11104 /// We handle multiple cases, one in which at least one operand is an
11105 /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other
11106 /// operand. Return true if successful, in that case Worklist will be updated.
11107 bool handleCmp(Attributor &A, Value &Cmp, Value *LHS, Value *RHS,
11108 CmpInst::Predicate Pred, ItemInfo II,
11109 SmallVectorImpl<ItemInfo> &Worklist) {
11110
11111 // Simplify the operands first.
11112 bool UsedAssumedInformation = false;
11113 SmallVector<AA::ValueAndContext> LHSValues, RHSValues;
11114 auto GetSimplifiedValues = [&](Value &V,
11116 if (!A.getAssumedSimplifiedValues(
11117 IRPosition::value(V, getCallBaseContext()), this, Values,
11118 AA::Intraprocedural, UsedAssumedInformation)) {
11119 Values.clear();
11120 Values.push_back(AA::ValueAndContext{V, II.I.getCtxI()});
11121 }
11122 return Values.empty();
11123 };
11124 if (GetSimplifiedValues(*LHS, LHSValues))
11125 return true;
11126 if (GetSimplifiedValues(*RHS, RHSValues))
11127 return true;
11128
11129 LLVMContext &Ctx = LHS->getContext();
11130
11131 InformationCache &InfoCache = A.getInfoCache();
11132 Instruction *CmpI = dyn_cast<Instruction>(&Cmp);
11133 Function *F = CmpI ? CmpI->getFunction() : nullptr;
11134 const auto *DT =
11135 F ? InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F)
11136 : nullptr;
11137 const auto *TLI =
11138 F ? A.getInfoCache().getTargetLibraryInfoForFunction(*F) : nullptr;
11139 auto *AC =
11140 F ? InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F)
11141 : nullptr;
11142
11143 const DataLayout &DL = A.getDataLayout();
11144 SimplifyQuery Q(DL, TLI, DT, AC, CmpI);
11145
11146 auto CheckPair = [&](Value &LHSV, Value &RHSV) {
11147 if (isa<UndefValue>(LHSV) || isa<UndefValue>(RHSV)) {
11148 addValue(A, getState(), *UndefValue::get(Cmp.getType()),
11149 /* CtxI */ nullptr, II.S, getAnchorScope());
11150 return true;
11151 }
11152
11153 // Handle the trivial case first in which we don't even need to think
11154 // about null or non-null.
11155 if (&LHSV == &RHSV &&
11157 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx),
11159 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11160 getAnchorScope());
11161 return true;
11162 }
11163
11164 auto *TypedLHS = AA::getWithType(LHSV, *LHS->getType());
11165 auto *TypedRHS = AA::getWithType(RHSV, *RHS->getType());
11166 if (TypedLHS && TypedRHS) {
11167 Value *NewV = simplifyCmpInst(Pred, TypedLHS, TypedRHS, Q);
11168 if (NewV && NewV != &Cmp) {
11169 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11170 getAnchorScope());
11171 return true;
11172 }
11173 }
11174
11175 // From now on we only handle equalities (==, !=).
11177 return false;
11178
11179 bool LHSIsNull = isa<ConstantPointerNull>(LHSV);
11180 bool RHSIsNull = isa<ConstantPointerNull>(RHSV);
11181 if (!LHSIsNull && !RHSIsNull)
11182 return false;
11183
11184 // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
11185 // non-nullptr operand and if we assume it's non-null we can conclude the
11186 // result of the comparison.
11187 assert((LHSIsNull || RHSIsNull) &&
11188 "Expected nullptr versus non-nullptr comparison at this point");
11189
11190 // The index is the operand that we assume is not null.
11191 unsigned PtrIdx = LHSIsNull;
11192 bool IsKnownNonNull;
11193 bool IsAssumedNonNull = AA::hasAssumedIRAttr<Attribute::NonNull>(
11194 A, this, IRPosition::value(*(PtrIdx ? &RHSV : &LHSV)),
11195 DepClassTy::REQUIRED, IsKnownNonNull);
11196 if (!IsAssumedNonNull)
11197 return false;
11198
11199 // The new value depends on the predicate, true for != and false for ==.
11200 Constant *NewV =
11201 ConstantInt::get(Type::getInt1Ty(Ctx), Pred == CmpInst::ICMP_NE);
11202 addValue(A, getState(), *NewV, /* CtxI */ nullptr, II.S,
11203 getAnchorScope());
11204 return true;
11205 };
11206
11207 for (auto &LHSValue : LHSValues)
11208 for (auto &RHSValue : RHSValues)
11209 if (!CheckPair(*LHSValue.getValue(), *RHSValue.getValue()))
11210 return false;
11211 return true;
11212 }
11213
11214 bool handleSelectInst(Attributor &A, SelectInst &SI, ItemInfo II,
11215 SmallVectorImpl<ItemInfo> &Worklist) {
11216 const Instruction *CtxI = II.I.getCtxI();
11217 bool UsedAssumedInformation = false;
11218
11219 std::optional<Constant *> C =
11220 A.getAssumedConstant(*SI.getCondition(), *this, UsedAssumedInformation);
11221 bool NoValueYet = !C.has_value();
11222 if (NoValueYet || isa_and_nonnull<UndefValue>(*C))
11223 return true;
11224 if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) {
11225 if (CI->isZero())
11226 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
11227 else
11228 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
11229 } else if (&SI == &getAssociatedValue()) {
11230 // We could not simplify the condition, assume both values.
11231 Worklist.push_back({{*SI.getTrueValue(), CtxI}, II.S});
11232 Worklist.push_back({{*SI.getFalseValue(), CtxI}, II.S});
11233 } else {
11234 std::optional<Value *> SimpleV = A.getAssumedSimplified(
11235 IRPosition::inst(SI), *this, UsedAssumedInformation, II.S);
11236 if (!SimpleV.has_value())
11237 return true;
11238 if (*SimpleV) {
11239 addValue(A, getState(), **SimpleV, CtxI, II.S, getAnchorScope());
11240 return true;
11241 }
11242 return false;
11243 }
11244 return true;
11245 }
11246
11247 bool handleLoadInst(Attributor &A, LoadInst &LI, ItemInfo II,
11248 SmallVectorImpl<ItemInfo> &Worklist) {
11249 SmallSetVector<Value *, 4> PotentialCopies;
11250 SmallSetVector<Instruction *, 4> PotentialValueOrigins;
11251 bool UsedAssumedInformation = false;
11252 if (!AA::getPotentiallyLoadedValues(A, LI, PotentialCopies,
11253 PotentialValueOrigins, *this,
11254 UsedAssumedInformation,
11255 /* OnlyExact */ true)) {
11256 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Failed to get potentially "
11257 "loaded values for load instruction "
11258 << LI << "\n");
11259 return false;
11260 }
11261
11262 // Do not simplify loads that are only used in llvm.assume if we cannot also
11263 // remove all stores that may feed into the load. The reason is that the
11264 // assume is probably worth something as long as the stores are around.
11265 InformationCache &InfoCache = A.getInfoCache();
11266 if (InfoCache.isOnlyUsedByAssume(LI)) {
11267 if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) {
11268 if (!I || isa<AssumeInst>(I))
11269 return true;
11270 if (auto *SI = dyn_cast<StoreInst>(I))
11271 return A.isAssumedDead(SI->getOperandUse(0), this,
11272 /* LivenessAA */ nullptr,
11273 UsedAssumedInformation,
11274 /* CheckBBLivenessOnly */ false);
11275 return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr,
11276 UsedAssumedInformation,
11277 /* CheckBBLivenessOnly */ false);
11278 })) {
11279 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Load is onl used by assumes "
11280 "and we cannot delete all the stores: "
11281 << LI << "\n");
11282 return false;
11283 }
11284 }
11285
11286 // Values have to be dynamically unique or we loose the fact that a
11287 // single llvm::Value might represent two runtime values (e.g.,
11288 // stack locations in different recursive calls).
11289 const Instruction *CtxI = II.I.getCtxI();
11290 bool ScopeIsLocal = (II.S & AA::Intraprocedural);
11291 bool AllLocal = ScopeIsLocal;
11292 bool DynamicallyUnique = llvm::all_of(PotentialCopies, [&](Value *PC) {
11293 AllLocal &= AA::isValidInScope(*PC, getAnchorScope());
11294 return AA::isDynamicallyUnique(A, *this, *PC);
11295 });
11296 if (!DynamicallyUnique) {
11297 LLVM_DEBUG(dbgs() << "[AAPotentialValues] Not all potentially loaded "
11298 "values are dynamically unique: "
11299 << LI << "\n");
11300 return false;
11301 }
11302
11303 for (auto *PotentialCopy : PotentialCopies) {
11304 if (AllLocal) {
11305 Worklist.push_back({{*PotentialCopy, CtxI}, II.S});
11306 } else {
11307 Worklist.push_back({{*PotentialCopy, CtxI}, AA::Interprocedural});
11308 }
11309 }
11310 if (!AllLocal && ScopeIsLocal)
11311 addValue(A, getState(), LI, CtxI, AA::Intraprocedural, getAnchorScope());
11312 return true;
11313 }
11314
11315 bool handlePHINode(
11316 Attributor &A, PHINode &PHI, ItemInfo II,
11317 SmallVectorImpl<ItemInfo> &Worklist,
11318 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11319 auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & {
11320 LivenessInfo &LI = LivenessAAs[&F];
11321 if (!LI.LivenessAA)
11322 LI.LivenessAA = A.getAAFor<AAIsDead>(*this, IRPosition::function(F),
11323 DepClassTy::NONE);
11324 return LI;
11325 };
11326
11327 if (&PHI == &getAssociatedValue()) {
11328 LivenessInfo &LI = GetLivenessInfo(*PHI.getFunction());
11329 const auto *CI =
11330 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
11331 *PHI.getFunction());
11332
11333 CycleRef C;
11334 bool CyclePHI = mayBeInCycle(CI, &PHI, /* HeaderOnly */ true, &C);
11335 for (unsigned u = 0, e = PHI.getNumIncomingValues(); u < e; u++) {
11336 BasicBlock *IncomingBB = PHI.getIncomingBlock(u);
11337 if (LI.LivenessAA &&
11338 LI.LivenessAA->isEdgeDead(IncomingBB, PHI.getParent())) {
11339 LI.AnyDead = true;
11340 continue;
11341 }
11342 Value *V = PHI.getIncomingValue(u);
11343 if (V == &PHI)
11344 continue;
11345
11346 // If the incoming value is not the PHI but an instruction in the same
11347 // cycle we might have multiple versions of it flying around.
11348 if (CyclePHI && isa<Instruction>(V) &&
11349 (!C || CI->contains(C, cast<Instruction>(V)->getParent())))
11350 return false;
11351
11352 Worklist.push_back({{*V, IncomingBB->getTerminator()}, II.S});
11353 }
11354 return true;
11355 }
11356
11357 bool UsedAssumedInformation = false;
11358 std::optional<Value *> SimpleV = A.getAssumedSimplified(
11359 IRPosition::inst(PHI), *this, UsedAssumedInformation, II.S);
11360 if (!SimpleV.has_value())
11361 return true;
11362 if (!(*SimpleV))
11363 return false;
11364 addValue(A, getState(), **SimpleV, &PHI, II.S, getAnchorScope());
11365 return true;
11366 }
11367
11368 /// Use the generic, non-optimistic InstSimplfy functionality if we managed to
11369 /// simplify any operand of the instruction \p I. Return true if successful,
11370 /// in that case Worklist will be updated.
11371 bool handleGenericInst(Attributor &A, Instruction &I, ItemInfo II,
11372 SmallVectorImpl<ItemInfo> &Worklist) {
11373 bool SomeSimplified = false;
11374 bool UsedAssumedInformation = false;
11375
11376 SmallVector<Value *, 8> NewOps(I.getNumOperands());
11377 int Idx = 0;
11378 for (Value *Op : I.operands()) {
11379 const auto &SimplifiedOp = A.getAssumedSimplified(
11380 IRPosition::value(*Op, getCallBaseContext()), *this,
11381 UsedAssumedInformation, AA::Intraprocedural);
11382 // If we are not sure about any operand we are not sure about the entire
11383 // instruction, we'll wait.
11384 if (!SimplifiedOp.has_value())
11385 return true;
11386
11387 if (*SimplifiedOp)
11388 NewOps[Idx] = *SimplifiedOp;
11389 else
11390 NewOps[Idx] = Op;
11391
11392 SomeSimplified |= (NewOps[Idx] != Op);
11393 ++Idx;
11394 }
11395
11396 // We won't bother with the InstSimplify interface if we didn't simplify any
11397 // operand ourselves.
11398 if (!SomeSimplified)
11399 return false;
11400
11401 InformationCache &InfoCache = A.getInfoCache();
11402 Function *F = I.getFunction();
11403 const auto *DT =
11404 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
11405 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
11406 auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
11407
11408 const DataLayout &DL = I.getDataLayout();
11409 SimplifyQuery Q(DL, TLI, DT, AC, &I);
11410 Value *NewV = simplifyInstructionWithOperands(&I, NewOps, Q);
11411 if (!NewV || NewV == &I)
11412 return false;
11413
11414 LLVM_DEBUG(dbgs() << "Generic inst " << I << " assumed simplified to "
11415 << *NewV << "\n");
11416 Worklist.push_back({{*NewV, II.I.getCtxI()}, II.S});
11417 return true;
11418 }
11419
11421 Attributor &A, Instruction &I, ItemInfo II,
11422 SmallVectorImpl<ItemInfo> &Worklist,
11423 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11424 if (auto *CI = dyn_cast<CmpInst>(&I))
11425 return handleCmp(A, *CI, CI->getOperand(0), CI->getOperand(1),
11426 CI->getPredicate(), II, Worklist);
11427
11428 switch (I.getOpcode()) {
11429 case Instruction::Select:
11430 return handleSelectInst(A, cast<SelectInst>(I), II, Worklist);
11431 case Instruction::PHI:
11432 return handlePHINode(A, cast<PHINode>(I), II, Worklist, LivenessAAs);
11433 case Instruction::Load:
11434 return handleLoadInst(A, cast<LoadInst>(I), II, Worklist);
11435 default:
11436 return handleGenericInst(A, I, II, Worklist);
11437 };
11438 return false;
11439 }
11440
11441 void genericValueTraversal(Attributor &A, Value *InitialV) {
11442 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
11443
11444 SmallSet<ItemInfo, 16> Visited;
11446 Worklist.push_back({{*InitialV, getCtxI()}, AA::AnyScope});
11447
11448 int Iteration = 0;
11449 do {
11450 ItemInfo II = Worklist.pop_back_val();
11451 Value *V = II.I.getValue();
11452 assert(V);
11453 const Instruction *CtxI = II.I.getCtxI();
11454 AA::ValueScope S = II.S;
11455
11456 // Check if we should process the current value. To prevent endless
11457 // recursion keep a record of the values we followed!
11458 if (!Visited.insert(II).second)
11459 continue;
11460
11461 // Make sure we limit the compile time for complex expressions.
11462 if (Iteration++ >= A.Opts.attributor_max_potential_values_iterations) {
11463 LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: "
11464 << Iteration << "!\n");
11465 addValue(A, getState(), *V, CtxI, S, getAnchorScope());
11466 continue;
11467 }
11468
11469 // Explicitly look through calls with a "returned" attribute if we do
11470 // not have a pointer as stripPointerCasts only works on them.
11471 Value *NewV = nullptr;
11472 if (V->getType()->isPointerTy()) {
11473 NewV = AA::getWithType(*V->stripPointerCasts(), *V->getType());
11474 } else {
11475 if (auto *CB = dyn_cast<CallBase>(V))
11476 if (auto *Callee =
11478 for (Argument &Arg : Callee->args())
11479 if (Arg.hasReturnedAttr()) {
11480 NewV = CB->getArgOperand(Arg.getArgNo());
11481 break;
11482 }
11483 }
11484 }
11485 if (NewV && NewV != V) {
11486 Worklist.push_back({{*NewV, CtxI}, S});
11487 continue;
11488 }
11489
11490 if (auto *I = dyn_cast<Instruction>(V)) {
11491 if (simplifyInstruction(A, *I, II, Worklist, LivenessAAs))
11492 continue;
11493 }
11494
11495 if (V != InitialV || isa<Argument>(V))
11496 if (recurseForValue(A, IRPosition::value(*V), II.S))
11497 continue;
11498
11499 // If we haven't stripped anything we give up.
11500 if (V == InitialV && CtxI == getCtxI()) {
11501 indicatePessimisticFixpoint();
11502 return;
11503 }
11504
11505 addValue(A, getState(), *V, CtxI, S, getAnchorScope());
11506 } while (!Worklist.empty());
11507
11508 // If we actually used liveness information so we have to record a
11509 // dependence.
11510 for (auto &It : LivenessAAs)
11511 if (It.second.AnyDead)
11512 A.recordDependence(*It.second.LivenessAA, *this, DepClassTy::OPTIONAL);
11513 }
11514
11515 void trackStatistics() const override {
11516 STATS_DECLTRACK_FLOATING_ATTR(potential_values)
11517 }
11518};
11519
11520struct AAPotentialValuesArgument final : AAPotentialValuesImpl {
11521 using Base = AAPotentialValuesImpl;
11522 AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A)
11523 : Base(IRP, A) {}
11524
11525 void initialize(Attributor &A) override {
11526 auto &Arg = cast<Argument>(getAssociatedValue());
11528 indicatePessimisticFixpoint();
11529 }
11530
11531 ChangeStatus updateImpl(Attributor &A) override {
11532 auto AssumedBefore = getAssumed();
11533
11534 unsigned ArgNo = getCalleeArgNo();
11535
11536 bool UsedAssumedInformation = false;
11538 auto CallSitePred = [&](AbstractCallSite ACS) {
11539 const auto CSArgIRP = IRPosition::callsite_argument(ACS, ArgNo);
11540 if (CSArgIRP.getPositionKind() == IRP_INVALID)
11541 return false;
11542
11543 if (!A.getAssumedSimplifiedValues(CSArgIRP, this, Values,
11545 UsedAssumedInformation))
11546 return false;
11547
11548 return isValidState();
11549 };
11550
11551 if (!A.checkForAllCallSites(CallSitePred, *this,
11552 /* RequireAllCallSites */ true,
11553 UsedAssumedInformation))
11554 return indicatePessimisticFixpoint();
11555
11556 Function *Fn = getAssociatedFunction();
11557 bool AnyNonLocal = false;
11558 for (auto &It : Values) {
11559 if (isa<Constant>(It.getValue())) {
11560 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
11561 getAnchorScope());
11562 continue;
11563 }
11564 if (!AA::isDynamicallyUnique(A, *this, *It.getValue()))
11565 return indicatePessimisticFixpoint();
11566
11567 if (auto *Arg = dyn_cast<Argument>(It.getValue()))
11568 if (Arg->getParent() == Fn) {
11569 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::AnyScope,
11570 getAnchorScope());
11571 continue;
11572 }
11573 addValue(A, getState(), *It.getValue(), It.getCtxI(), AA::Interprocedural,
11574 getAnchorScope());
11575 AnyNonLocal = true;
11576 }
11577 assert(!undefIsContained() && "Undef should be an explicit value!");
11578 if (AnyNonLocal)
11579 giveUpOnIntraprocedural(A);
11580
11581 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11582 : ChangeStatus::CHANGED;
11583 }
11584
11585 void trackStatistics() const override {
11586 STATS_DECLTRACK_ARG_ATTR(potential_values)
11587 }
11588};
11589
11590struct AAPotentialValuesReturned : public AAPotentialValuesFloating {
11591 using Base = AAPotentialValuesFloating;
11592 AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A)
11593 : Base(IRP, A) {}
11594
11595 void initialize(Attributor &A) override {
11596 Function *F = getAssociatedFunction();
11597 if (!F || F->isDeclaration() || F->getReturnType()->isVoidTy()) {
11598 indicatePessimisticFixpoint();
11599 return;
11600 }
11601
11602 for (Argument &Arg : F->args())
11603 if (Arg.hasReturnedAttr()) {
11604 addValue(A, getState(), Arg, nullptr, AA::AnyScope, F);
11605 ReturnedArg = &Arg;
11606 break;
11607 }
11608 if (!A.isFunctionIPOAmendable(*F) ||
11609 A.hasSimplificationCallback(getIRPosition())) {
11610 if (!ReturnedArg)
11611 indicatePessimisticFixpoint();
11612 else
11613 indicateOptimisticFixpoint();
11614 }
11615 }
11616
11617 ChangeStatus updateImpl(Attributor &A) override {
11618 auto AssumedBefore = getAssumed();
11619 bool UsedAssumedInformation = false;
11620
11622 Function *AnchorScope = getAnchorScope();
11623 auto HandleReturnedValue = [&](Value &V, Instruction *CtxI,
11624 bool AddValues) {
11626 Values.clear();
11627 if (!A.getAssumedSimplifiedValues(IRPosition::value(V), this, Values, S,
11628 UsedAssumedInformation,
11629 /* RecurseForSelectAndPHI */ true))
11630 return false;
11631 if (!AddValues)
11632 continue;
11633
11634 bool AllInterAreIntra = false;
11635 if (S == AA::Interprocedural)
11636 AllInterAreIntra =
11637 llvm::all_of(Values, [&](const AA::ValueAndContext &VAC) {
11638 return AA::isValidInScope(*VAC.getValue(), AnchorScope);
11639 });
11640
11641 for (const AA::ValueAndContext &VAC : Values) {
11642 addValue(A, getState(), *VAC.getValue(),
11643 VAC.getCtxI() ? VAC.getCtxI() : CtxI,
11644 AllInterAreIntra ? AA::AnyScope : S, AnchorScope);
11645 }
11646 if (AllInterAreIntra)
11647 break;
11648 }
11649 return true;
11650 };
11651
11652 if (ReturnedArg) {
11653 HandleReturnedValue(*ReturnedArg, nullptr, true);
11654 } else {
11655 auto RetInstPred = [&](Instruction &RetI) {
11656 bool AddValues = true;
11657 if (isa<PHINode>(RetI.getOperand(0)) ||
11658 isa<SelectInst>(RetI.getOperand(0))) {
11659 addValue(A, getState(), *RetI.getOperand(0), &RetI, AA::AnyScope,
11660 AnchorScope);
11661 AddValues = false;
11662 }
11663 return HandleReturnedValue(*RetI.getOperand(0), &RetI, AddValues);
11664 };
11665
11666 if (!A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
11667 UsedAssumedInformation,
11668 /* CheckBBLivenessOnly */ true))
11669 return indicatePessimisticFixpoint();
11670 }
11671
11672 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11673 : ChangeStatus::CHANGED;
11674 }
11675
11676 ChangeStatus manifest(Attributor &A) override {
11677 if (ReturnedArg)
11678 return ChangeStatus::UNCHANGED;
11680 if (!getAssumedSimplifiedValues(A, Values, AA::ValueScope::Intraprocedural,
11681 /* RecurseForSelectAndPHI */ true))
11682 return ChangeStatus::UNCHANGED;
11683 Value *NewVal = getSingleValue(A, *this, getIRPosition(), Values);
11684 if (!NewVal)
11685 return ChangeStatus::UNCHANGED;
11686
11687 ChangeStatus Changed = ChangeStatus::UNCHANGED;
11688 if (auto *Arg = dyn_cast<Argument>(NewVal)) {
11689 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
11690 "Number of function with unique return");
11691 Changed |= A.manifestAttrs(
11693 {Attribute::get(Arg->getContext(), Attribute::Returned)});
11694 STATS_DECLTRACK_ARG_ATTR(returned);
11695 }
11696
11697 auto RetInstPred = [&](Instruction &RetI) {
11698 Value *RetOp = RetI.getOperand(0);
11699 if (isa<UndefValue>(RetOp) || RetOp == NewVal)
11700 return true;
11701 if (AA::isValidAtPosition({*NewVal, RetI}, A.getInfoCache()))
11702 if (A.changeUseAfterManifest(RetI.getOperandUse(0), *NewVal))
11703 Changed = ChangeStatus::CHANGED;
11704 return true;
11705 };
11706 bool UsedAssumedInformation = false;
11707 (void)A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
11708 UsedAssumedInformation,
11709 /* CheckBBLivenessOnly */ true);
11710 return Changed;
11711 }
11712
11713 ChangeStatus indicatePessimisticFixpoint() override {
11714 return AAPotentialValues::indicatePessimisticFixpoint();
11715 }
11716
11717 void trackStatistics() const override{
11718 STATS_DECLTRACK_FNRET_ATTR(potential_values)}
11719
11720 /// The argumented with an existing `returned` attribute.
11721 Argument *ReturnedArg = nullptr;
11722};
11723
11724struct AAPotentialValuesFunction : AAPotentialValuesImpl {
11725 AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A)
11726 : AAPotentialValuesImpl(IRP, A) {}
11727
11728 ChangeStatus updateImpl(Attributor &A) override {
11729 llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will "
11730 "not be called");
11731 }
11732
11733 void trackStatistics() const override {
11734 STATS_DECLTRACK_FN_ATTR(potential_values)
11735 }
11736};
11737
11738struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
11739 AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A)
11740 : AAPotentialValuesFunction(IRP, A) {}
11741
11742 void trackStatistics() const override {
11743 STATS_DECLTRACK_CS_ATTR(potential_values)
11744 }
11745};
11746
11747struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl {
11748 AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A)
11749 : AAPotentialValuesImpl(IRP, A) {}
11750
11751 ChangeStatus updateImpl(Attributor &A) override {
11752 auto AssumedBefore = getAssumed();
11753
11754 Function *Callee = getAssociatedFunction();
11755 if (!Callee)
11756 return indicatePessimisticFixpoint();
11757
11758 bool UsedAssumedInformation = false;
11759 auto *CB = cast<CallBase>(getCtxI());
11760 if (CB->isMustTailCall() &&
11761 !A.isAssumedDead(IRPosition::inst(*CB), this, nullptr,
11762 UsedAssumedInformation))
11763 return indicatePessimisticFixpoint();
11764
11765 Function *Caller = CB->getCaller();
11766
11767 auto AddValues = [&](ArrayRef<AA::ValueAndContext> Values,
11768 AA::ValueScope S) {
11769 for (const AA::ValueAndContext &It : Values) {
11770 Value *V = It.getValue();
11771 std::optional<Value *> CallerV = A.translateArgumentToCallSiteContent(
11772 V, *CB, *this, UsedAssumedInformation);
11773 if (!CallerV.has_value()) {
11774 // Nothing to do as long as no value was determined.
11775 continue;
11776 }
11777 V = *CallerV ? *CallerV : V;
11778 if (*CallerV && AA::isDynamicallyUnique(A, *this, *V)) {
11779 if (recurseForValue(A, IRPosition::value(*V), S))
11780 continue;
11781 }
11782 if (S == AA::Intraprocedural && !AA::isValidInScope(*V, Caller)) {
11783 giveUpOnIntraprocedural(A);
11784 return;
11785 }
11786 addValue(A, getState(), *V, CB, S, getAnchorScope());
11787 }
11788 };
11789
11791 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this,
11793 UsedAssumedInformation))
11794 return indicatePessimisticFixpoint();
11795 AddValues(Values, AA::Intraprocedural);
11796
11797 // If the callee returns only its arguments and constants, these values,
11798 // translated to this call site, are also the interprocedural values of the
11799 // call. The interprocedural values of the callee would add the values
11800 // passed at all other call sites, which is imprecise and very expensive if
11801 // the callee has many call sites. An empty set does not count, as the
11802 // interprocedural values of the callee can be known before the
11803 // intraprocedural ones.
11804 bool OnlyArgsAndConstants =
11805 !Values.empty() && all_of(Values, [&](const AA::ValueAndContext &VAC) {
11806 const Value *V = VAC.getValue();
11807 if (isa<Constant>(V))
11808 return true;
11809 const auto *Arg = dyn_cast<Argument>(V);
11810 return Arg && Arg->getParent() == Callee;
11811 });
11812 if (!OnlyArgsAndConstants) {
11813 Values.clear();
11814 if (!A.getAssumedSimplifiedValues(IRPosition::returned(*Callee), this,
11816 UsedAssumedInformation))
11817 return indicatePessimisticFixpoint();
11818 }
11819 AddValues(Values, AA::Interprocedural);
11820
11821 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11822 : ChangeStatus::CHANGED;
11823 }
11824
11825 ChangeStatus indicatePessimisticFixpoint() override {
11826 return AAPotentialValues::indicatePessimisticFixpoint();
11827 }
11828
11829 void trackStatistics() const override {
11830 STATS_DECLTRACK_CSRET_ATTR(potential_values)
11831 }
11832};
11833
11834struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
11835 AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A)
11836 : AAPotentialValuesFloating(IRP, A) {}
11837
11838 void trackStatistics() const override {
11839 STATS_DECLTRACK_CSARG_ATTR(potential_values)
11840 }
11841};
11842} // namespace
11843
11844/// ---------------------- Assumption Propagation ------------------------------
11845namespace {
11846struct AAAssumptionInfoImpl : public AAAssumptionInfo {
11847 AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A,
11848 const DenseSet<StringRef> &Known)
11849 : AAAssumptionInfo(IRP, A, Known) {}
11850
11851 ChangeStatus manifest(Attributor &A) override {
11852 // Don't manifest a universal set if it somehow made it here.
11853 if (getKnown().isUniversal())
11854 return ChangeStatus::UNCHANGED;
11855
11856 const IRPosition &IRP = getIRPosition();
11857 SmallVector<StringRef, 0> Set(getAssumed().getSet().begin(),
11858 getAssumed().getSet().end());
11859 llvm::sort(Set);
11860 return A.manifestAttrs(IRP,
11861 Attribute::get(IRP.getAnchorValue().getContext(),
11863 llvm::join(Set, ",")),
11864 /*ForceReplace=*/true);
11865 }
11866
11867 bool hasAssumption(const StringRef Assumption) const override {
11868 return isValidState() && setContains(Assumption);
11869 }
11870
11871 const std::string getAsStr(Attributor *A) const override {
11872 const SetContents &Known = getKnown();
11873 const SetContents &Assumed = getAssumed();
11874
11875 SmallVector<StringRef, 0> Set(Known.getSet().begin(), Known.getSet().end());
11876 llvm::sort(Set);
11877 const std::string KnownStr = llvm::join(Set, ",");
11878
11879 std::string AssumedStr = "Universal";
11880 if (!Assumed.isUniversal()) {
11881 Set.assign(Assumed.getSet().begin(), Assumed.getSet().end());
11882 AssumedStr = llvm::join(Set, ",");
11883 }
11884 return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]";
11885 }
11886};
11887
11888/// Propagates assumption information from parent functions to all of their
11889/// successors. An assumption can be propagated if the containing function
11890/// dominates the called function.
11891///
11892/// We start with a "known" set of assumptions already valid for the associated
11893/// function and an "assumed" set that initially contains all possible
11894/// assumptions. The assumed set is inter-procedurally updated by narrowing its
11895/// contents as concrete values are known. The concrete values are seeded by the
11896/// first nodes that are either entries into the call graph, or contains no
11897/// assumptions. Each node is updated as the intersection of the assumed state
11898/// with all of its predecessors.
11899struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
11900 AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A)
11901 : AAAssumptionInfoImpl(IRP, A,
11902 getAssumptions(*IRP.getAssociatedFunction())) {}
11903
11904 ChangeStatus updateImpl(Attributor &A) override {
11905 bool Changed = false;
11906
11907 auto CallSitePred = [&](AbstractCallSite ACS) {
11908 const auto *AssumptionAA = A.getAAFor<AAAssumptionInfo>(
11909 *this, IRPosition::callsite_function(*ACS.getInstruction()),
11910 DepClassTy::REQUIRED);
11911 if (!AssumptionAA)
11912 return false;
11913 // Get the set of assumptions shared by all of this function's callers.
11914 Changed |= getIntersection(AssumptionAA->getAssumed());
11915 return !getAssumed().empty() || !getKnown().empty();
11916 };
11917
11918 bool UsedAssumedInformation = false;
11919 // Get the intersection of all assumptions held by this node's predecessors.
11920 // If we don't know all the call sites then this is either an entry into the
11921 // call graph or an empty node. This node is known to only contain its own
11922 // assumptions and can be propagated to its successors.
11923 if (!A.checkForAllCallSites(CallSitePred, *this, true,
11924 UsedAssumedInformation))
11925 return indicatePessimisticFixpoint();
11926
11927 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11928 }
11929
11930 void trackStatistics() const override {}
11931};
11932
11933/// Assumption Info defined for call sites.
11934struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
11935
11936 AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A)
11937 : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {}
11938
11939 void initialize(Attributor &A) override {
11940 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
11941 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
11942 }
11943
11944 ChangeStatus updateImpl(Attributor &A) override {
11945 const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
11946 auto *AssumptionAA =
11947 A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
11948 if (!AssumptionAA)
11949 return indicatePessimisticFixpoint();
11950 bool Changed = getIntersection(AssumptionAA->getAssumed());
11951 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11952 }
11953
11954 void trackStatistics() const override {}
11955
11956private:
11957 /// Helper to initialized the known set as all the assumptions this call and
11958 /// the callee contain.
11959 DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) {
11960 const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue());
11961 auto Assumptions = getAssumptions(CB);
11962 if (const Function *F = CB.getCaller())
11963 set_union(Assumptions, getAssumptions(*F));
11964 if (Function *F = IRP.getAssociatedFunction())
11965 set_union(Assumptions, getAssumptions(*F));
11966 return Assumptions;
11967 }
11968};
11969} // namespace
11970
11972 return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>(
11973 A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I))));
11974}
11975
11977
11978/// ------------------------ UnderlyingObjects ---------------------------------
11979
11980namespace {
11981struct AAUnderlyingObjectsImpl
11982 : StateWrapper<BooleanState, AAUnderlyingObjects> {
11984 AAUnderlyingObjectsImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {}
11985
11986 const std::string getAsStr(Attributor *A) const override {
11987 if (!isValidState())
11988 return "<invalid>";
11989 std::string Str;
11991 OS << "underlying objects: inter " << InterAssumedUnderlyingObjects.size()
11992 << " objects, intra " << IntraAssumedUnderlyingObjects.size()
11993 << " objects.\n";
11994 if (!InterAssumedUnderlyingObjects.empty()) {
11995 OS << "inter objects:\n";
11996 for (auto *Obj : InterAssumedUnderlyingObjects)
11997 OS << *Obj << '\n';
11998 }
11999 if (!IntraAssumedUnderlyingObjects.empty()) {
12000 OS << "intra objects:\n";
12001 for (auto *Obj : IntraAssumedUnderlyingObjects)
12002 OS << *Obj << '\n';
12003 }
12004 return Str;
12005 }
12006
12007 void trackStatistics() const override {}
12008
12009 ChangeStatus updateImpl(Attributor &A) override {
12010 auto &Ptr = getAssociatedValue();
12011
12012 bool UsedAssumedInformation = false;
12013 auto DoUpdate = [&](SmallSetVector<Value *, 8> &UnderlyingObjects,
12015 SmallPtrSet<Value *, 8> SeenObjects;
12017
12018 if (!A.getAssumedSimplifiedValues(IRPosition::value(Ptr), *this, Values,
12019 Scope, UsedAssumedInformation))
12020 return UnderlyingObjects.insert(&Ptr);
12021
12022 bool Changed = false;
12023
12024 for (unsigned I = 0; I < Values.size(); ++I) {
12025 auto &VAC = Values[I];
12026 auto *Obj = VAC.getValue();
12027 Value *UO = getUnderlyingObject(Obj);
12028 if (!SeenObjects.insert(UO ? UO : Obj).second)
12029 continue;
12030 if (UO && UO != Obj) {
12031 if (isa<AllocaInst>(UO) || isa<GlobalValue>(UO)) {
12032 Changed |= UnderlyingObjects.insert(UO);
12033 continue;
12034 }
12035
12036 const auto *OtherAA = A.getAAFor<AAUnderlyingObjects>(
12037 *this, IRPosition::value(*UO), DepClassTy::OPTIONAL);
12038 auto Pred = [&](Value &V) {
12039 if (&V == UO)
12040 Changed |= UnderlyingObjects.insert(UO);
12041 else
12042 Values.emplace_back(V, nullptr);
12043 return true;
12044 };
12045
12046 if (!OtherAA || !OtherAA->forallUnderlyingObjects(Pred, Scope))
12048 "The forall call should not return false at this position");
12049 UsedAssumedInformation |= !OtherAA->getState().isAtFixpoint();
12050 continue;
12051 }
12052
12053 if (isa<SelectInst>(Obj)) {
12054 Changed |= handleIndirect(A, *Obj, UnderlyingObjects, Scope,
12055 UsedAssumedInformation);
12056 continue;
12057 }
12058 if (auto *PHI = dyn_cast<PHINode>(Obj)) {
12059 // Explicitly look through PHIs as we do not care about dynamically
12060 // uniqueness.
12061 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
12062 Changed |=
12063 handleIndirect(A, *PHI->getIncomingValue(u), UnderlyingObjects,
12064 Scope, UsedAssumedInformation);
12065 }
12066 continue;
12067 }
12068
12069 Changed |= UnderlyingObjects.insert(Obj);
12070 }
12071
12072 return Changed;
12073 };
12074
12075 bool Changed = false;
12076 Changed |= DoUpdate(IntraAssumedUnderlyingObjects, AA::Intraprocedural);
12077 Changed |= DoUpdate(InterAssumedUnderlyingObjects, AA::Interprocedural);
12078 if (!UsedAssumedInformation)
12079 indicateOptimisticFixpoint();
12080 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
12081 }
12082
12083 bool forallUnderlyingObjects(
12084 function_ref<bool(Value &)> Pred,
12085 AA::ValueScope Scope = AA::Interprocedural) const override {
12086 if (!isValidState())
12087 return Pred(getAssociatedValue());
12088
12089 auto &AssumedUnderlyingObjects = Scope == AA::Intraprocedural
12090 ? IntraAssumedUnderlyingObjects
12091 : InterAssumedUnderlyingObjects;
12092 for (Value *Obj : AssumedUnderlyingObjects)
12093 if (!Pred(*Obj))
12094 return false;
12095
12096 return true;
12097 }
12098
12099private:
12100 /// Handle the case where the value is not the actual underlying value, such
12101 /// as a phi node or a select instruction.
12102 bool handleIndirect(Attributor &A, Value &V,
12103 SmallSetVector<Value *, 8> &UnderlyingObjects,
12104 AA::ValueScope Scope, bool &UsedAssumedInformation) {
12105 bool Changed = false;
12106 const auto *AA = A.getAAFor<AAUnderlyingObjects>(
12107 *this, IRPosition::value(V), DepClassTy::OPTIONAL);
12108 auto Pred = [&](Value &V) {
12109 Changed |= UnderlyingObjects.insert(&V);
12110 return true;
12111 };
12112 if (!AA || !AA->forallUnderlyingObjects(Pred, Scope))
12114 "The forall call should not return false at this position");
12115 UsedAssumedInformation |= !AA->getState().isAtFixpoint();
12116 return Changed;
12117 }
12118
12119 /// All the underlying objects collected so far via intra procedural scope.
12120 SmallSetVector<Value *, 8> IntraAssumedUnderlyingObjects;
12121 /// All the underlying objects collected so far via inter procedural scope.
12122 SmallSetVector<Value *, 8> InterAssumedUnderlyingObjects;
12123};
12124
12125struct AAUnderlyingObjectsFloating final : AAUnderlyingObjectsImpl {
12126 AAUnderlyingObjectsFloating(const IRPosition &IRP, Attributor &A)
12127 : AAUnderlyingObjectsImpl(IRP, A) {}
12128};
12129
12130struct AAUnderlyingObjectsArgument final : AAUnderlyingObjectsImpl {
12131 AAUnderlyingObjectsArgument(const IRPosition &IRP, Attributor &A)
12132 : AAUnderlyingObjectsImpl(IRP, A) {}
12133};
12134
12135struct AAUnderlyingObjectsCallSite final : AAUnderlyingObjectsImpl {
12136 AAUnderlyingObjectsCallSite(const IRPosition &IRP, Attributor &A)
12137 : AAUnderlyingObjectsImpl(IRP, A) {}
12138};
12139
12140struct AAUnderlyingObjectsCallSiteArgument final : AAUnderlyingObjectsImpl {
12141 AAUnderlyingObjectsCallSiteArgument(const IRPosition &IRP, Attributor &A)
12142 : AAUnderlyingObjectsImpl(IRP, A) {}
12143};
12144
12145struct AAUnderlyingObjectsReturned final : AAUnderlyingObjectsImpl {
12146 AAUnderlyingObjectsReturned(const IRPosition &IRP, Attributor &A)
12147 : AAUnderlyingObjectsImpl(IRP, A) {}
12148};
12149
12150struct AAUnderlyingObjectsCallSiteReturned final : AAUnderlyingObjectsImpl {
12151 AAUnderlyingObjectsCallSiteReturned(const IRPosition &IRP, Attributor &A)
12152 : AAUnderlyingObjectsImpl(IRP, A) {}
12153};
12154
12155struct AAUnderlyingObjectsFunction final : AAUnderlyingObjectsImpl {
12156 AAUnderlyingObjectsFunction(const IRPosition &IRP, Attributor &A)
12157 : AAUnderlyingObjectsImpl(IRP, A) {}
12158};
12159} // namespace
12160
12161/// ------------------------ Global Value Info -------------------------------
12162namespace {
12163struct AAGlobalValueInfoFloating : public AAGlobalValueInfo {
12164 AAGlobalValueInfoFloating(const IRPosition &IRP, Attributor &A)
12165 : AAGlobalValueInfo(IRP, A) {}
12166
12167 void initialize(Attributor &A) override {}
12168
12169 bool checkUse(Attributor &A, const Use &U, bool &Follow,
12170 SmallVectorImpl<const Value *> &Worklist) {
12171 Instruction *UInst = dyn_cast<Instruction>(U.getUser());
12172 if (!UInst) {
12173 // Outside a closed world, code outside the module can read an
12174 // externally visible global, so the value escapes through it.
12175 if (auto *GV = dyn_cast<GlobalValue>(U.getUser()))
12176 if (!GV->hasLocalLinkage() && !A.isClosedWorldModule())
12177 return false;
12178 Follow = true;
12179 return true;
12180 }
12181
12182 LLVM_DEBUG(dbgs() << "[AAGlobalValueInfo] Check use: " << *U.get() << " in "
12183 << *UInst << "\n");
12184
12185 if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
12186 int Idx = &Cmp->getOperandUse(0) == &U;
12187 if (isa<Constant>(Cmp->getOperand(Idx)))
12188 return true;
12189 return U == &getAnchorValue();
12190 }
12191
12192 // Explicitly catch return instructions.
12193 if (isa<ReturnInst>(UInst)) {
12194 auto CallSitePred = [&](AbstractCallSite ACS) {
12195 Worklist.push_back(ACS.getInstruction());
12196 return true;
12197 };
12198 bool UsedAssumedInformation = false;
12199 // TODO: We should traverse the uses or add a "non-call-site" CB.
12200 if (!A.checkForAllCallSites(CallSitePred, *UInst->getFunction(),
12201 /*RequireAllCallSites=*/true, this,
12202 UsedAssumedInformation))
12203 return false;
12204 return true;
12205 }
12206
12207 // For now we only use special logic for call sites. However, the tracker
12208 // itself knows about a lot of other non-capturing cases already.
12209 auto *CB = dyn_cast<CallBase>(UInst);
12210 if (!CB)
12211 return false;
12212 // Direct calls are OK uses.
12213 if (CB->isCallee(&U))
12214 return true;
12215 // Non-argument uses are scary.
12216 if (!CB->isArgOperand(&U))
12217 return false;
12218 // TODO: Iterate callees.
12219 auto *Fn = dyn_cast<Function>(CB->getCalledOperand());
12220 if (!Fn || !A.isFunctionIPOAmendable(*Fn))
12221 return false;
12222
12223 unsigned ArgNo = CB->getArgOperandNo(&U);
12224 Worklist.push_back(Fn->getArg(ArgNo));
12225 return true;
12226 }
12227
12228 ChangeStatus updateImpl(Attributor &A) override {
12229 unsigned NumUsesBefore = Uses.size();
12230
12231 SmallPtrSet<const Value *, 8> Visited;
12233 Worklist.push_back(&getAnchorValue());
12234
12235 auto UsePred = [&](const Use &U, bool &Follow) -> bool {
12236 Uses.insert(&U);
12237 // TODO(captures): Make this more precise.
12238 UseCaptureInfo CI = DetermineUseCaptureKind(U, /*Base=*/nullptr);
12239 if (CI.isPassthrough()) {
12240 Follow = true;
12241 return true;
12242 }
12243 return checkUse(A, U, Follow, Worklist);
12244 };
12245 auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
12246 Uses.insert(&OldU);
12247 return true;
12248 };
12249
12250 while (!Worklist.empty()) {
12251 const Value *V = Worklist.pop_back_val();
12252 if (!Visited.insert(V).second)
12253 continue;
12254 if (!A.checkForAllUses(UsePred, *this, *V,
12255 /* CheckBBLivenessOnly */ true,
12256 DepClassTy::OPTIONAL,
12257 /* IgnoreDroppableUses */ true, EquivalentUseCB)) {
12258 return indicatePessimisticFixpoint();
12259 }
12260 }
12261
12262 return Uses.size() == NumUsesBefore ? ChangeStatus::UNCHANGED
12263 : ChangeStatus::CHANGED;
12264 }
12265
12266 bool isPotentialUse(const Use &U) const override {
12267 return !isValidState() || Uses.contains(&U);
12268 }
12269
12270 ChangeStatus manifest(Attributor &A) override {
12271 return ChangeStatus::UNCHANGED;
12272 }
12273
12274 const std::string getAsStr(Attributor *A) const override {
12275 return "[" + std::to_string(Uses.size()) + " uses]";
12276 }
12277
12278 void trackStatistics() const override {
12279 STATS_DECLTRACK_FLOATING_ATTR(GlobalValuesTracked);
12280 }
12281
12282private:
12283 /// Set of (transitive) uses of this GlobalValue.
12284 SmallPtrSet<const Use *, 8> Uses;
12285};
12286} // namespace
12287
12288/// ------------------------ Indirect Call Info -------------------------------
12289namespace {
12290struct AAIndirectCallInfoCallSite : public AAIndirectCallInfo {
12291 AAIndirectCallInfoCallSite(const IRPosition &IRP, Attributor &A)
12292 : AAIndirectCallInfo(IRP, A) {}
12293
12294 void initialize(Attributor &A) override {
12295 auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees);
12296 if (!MD && !A.isClosedWorldModule())
12297 return;
12298
12299 if (MD) {
12300 for (const auto &Op : MD->operands())
12302 PotentialCallees.insert(Callee);
12303 } else if (A.isClosedWorldModule()) {
12304 ArrayRef<Function *> IndirectlyCallableFunctions =
12305 A.getInfoCache().getIndirectlyCallableFunctions(A);
12306 PotentialCallees.insert_range(IndirectlyCallableFunctions);
12307 }
12308
12309 if (PotentialCallees.empty())
12310 indicateOptimisticFixpoint();
12311 }
12312
12313 ChangeStatus updateImpl(Attributor &A) override {
12314 CallBase *CB = cast<CallBase>(getCtxI());
12315 const Use &CalleeUse = CB->getCalledOperandUse();
12316 Value *FP = CB->getCalledOperand();
12317
12318 SmallSetVector<Function *, 4> AssumedCalleesNow;
12319 bool AllCalleesKnownNow = AllCalleesKnown;
12320
12321 auto CheckPotentialCalleeUse = [&](Function &PotentialCallee,
12322 bool &UsedAssumedInformation) {
12323 const auto *GIAA = A.getAAFor<AAGlobalValueInfo>(
12324 *this, IRPosition::value(PotentialCallee), DepClassTy::OPTIONAL);
12325 if (!GIAA || GIAA->isPotentialUse(CalleeUse))
12326 return true;
12327 UsedAssumedInformation = !GIAA->isAtFixpoint();
12328 return false;
12329 };
12330
12331 auto AddPotentialCallees = [&]() {
12332 for (auto *PotentialCallee : PotentialCallees) {
12333 bool UsedAssumedInformation = false;
12334 if (CheckPotentialCalleeUse(*PotentialCallee, UsedAssumedInformation))
12335 AssumedCalleesNow.insert(PotentialCallee);
12336 }
12337 };
12338
12339 // Use simplification to find potential callees, if !callees was present,
12340 // fallback to that set if necessary.
12341 bool UsedAssumedInformation = false;
12343 if (!A.getAssumedSimplifiedValues(IRPosition::value(*FP), this, Values,
12344 AA::ValueScope::AnyScope,
12345 UsedAssumedInformation)) {
12346 if (PotentialCallees.empty())
12347 return indicatePessimisticFixpoint();
12348 AddPotentialCallees();
12349 }
12350
12351 // Try to find a reason for \p Fn not to be a potential callee. If none was
12352 // found, add it to the assumed callees set.
12353 auto CheckPotentialCallee = [&](Function &Fn) {
12354 if (!PotentialCallees.empty() && !PotentialCallees.count(&Fn))
12355 return false;
12356
12357 auto &CachedResult = FilterResults[&Fn];
12358 if (CachedResult.has_value())
12359 return CachedResult.value();
12360
12361 bool UsedAssumedInformation = false;
12362 if (!CheckPotentialCalleeUse(Fn, UsedAssumedInformation)) {
12363 if (!UsedAssumedInformation)
12364 CachedResult = false;
12365 return false;
12366 }
12367
12368 int NumFnArgs = Fn.arg_size();
12369 int NumCBArgs = CB->arg_size();
12370
12371 // Check if any excess argument (which we fill up with poison) is known to
12372 // be UB on undef.
12373 for (int I = NumCBArgs; I < NumFnArgs; ++I) {
12374 bool IsKnown = false;
12376 A, this, IRPosition::argument(*Fn.getArg(I)),
12377 DepClassTy::OPTIONAL, IsKnown)) {
12378 if (IsKnown)
12379 CachedResult = false;
12380 return false;
12381 }
12382 }
12383
12384 CachedResult = true;
12385 return true;
12386 };
12387
12388 // Check simplification result, prune known UB callees, also restrict it to
12389 // the !callees set, if present.
12390 for (auto &VAC : Values) {
12391 if (isa<UndefValue>(VAC.getValue()))
12392 continue;
12394 VAC.getValue()->getType()->getPointerAddressSpace() == 0)
12395 continue;
12396 // TODO: Check for known UB, e.g., poison + noundef.
12397 if (auto *VACFn = dyn_cast<Function>(VAC.getValue())) {
12398 if (CheckPotentialCallee(*VACFn))
12399 AssumedCalleesNow.insert(VACFn);
12400 continue;
12401 }
12402 if (!PotentialCallees.empty()) {
12403 AddPotentialCallees();
12404 break;
12405 }
12406 AllCalleesKnownNow = false;
12407 }
12408
12409 if (AssumedCalleesNow == AssumedCallees &&
12410 AllCalleesKnown == AllCalleesKnownNow)
12411 return ChangeStatus::UNCHANGED;
12412
12413 std::swap(AssumedCallees, AssumedCalleesNow);
12414 AllCalleesKnown = AllCalleesKnownNow;
12415 return ChangeStatus::CHANGED;
12416 }
12417
12418 ChangeStatus manifest(Attributor &A) override {
12419 // If we can't specialize at all, give up now.
12420 if (!AllCalleesKnown && AssumedCallees.empty())
12421 return ChangeStatus::UNCHANGED;
12422
12423 CallBase *CB = cast<CallBase>(getCtxI());
12424 bool UsedAssumedInformation = false;
12425 if (A.isAssumedDead(*CB, this, /*LivenessAA=*/nullptr,
12426 UsedAssumedInformation))
12427 return ChangeStatus::UNCHANGED;
12428
12429 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12430 unsigned ProgramAS = CB->getDataLayout().getProgramAddressSpace();
12431 Value *FP = CB->getCalledOperand();
12432 if (FP->getType()->getPointerAddressSpace() != ProgramAS)
12433 FP = new AddrSpaceCastInst(
12434 FP, PointerType::get(FP->getContext(), ProgramAS),
12435 FP->getName() + ".as" + Twine(ProgramAS), CB->getIterator());
12436
12437 bool CBIsVoid = CB->getType()->isVoidTy();
12439 FunctionType *CSFT = CB->getFunctionType();
12440 SmallVector<Value *> CSArgs(CB->args());
12441
12442 // If we know all callees and there are none, the call site is (effectively)
12443 // dead (or UB).
12444 if (AssumedCallees.empty()) {
12445 assert(AllCalleesKnown &&
12446 "Expected all callees to be known if there are none.");
12447 A.changeToUnreachableAfterManifest(CB);
12448 return ChangeStatus::CHANGED;
12449 }
12450
12451 // Special handling for the single callee case.
12452 if (AllCalleesKnown && AssumedCallees.size() == 1) {
12453 auto *NewCallee = AssumedCallees.front();
12454 if (!A.shouldSpecializeCallSiteForCallee(*this, *CB, *NewCallee,
12455 /*NumAssumedCallees=*/1))
12456 return ChangeStatus::UNCHANGED;
12457
12458 if (isLegalToPromote(*CB, NewCallee)) {
12459 promoteCall(*CB, NewCallee, nullptr);
12460 NumIndirectCallsPromoted++;
12461 return ChangeStatus::CHANGED;
12462 }
12463 Instruction *NewCall =
12464 CallInst::Create(FunctionCallee(CSFT, NewCallee), CSArgs,
12465 CB->getName(), CB->getIterator());
12466 NewCall->setDebugLoc(CB->getDebugLoc());
12467 if (!CBIsVoid)
12468 A.changeAfterManifest(IRPosition::callsite_returned(*CB), *NewCall);
12469 A.deleteAfterManifest(*CB);
12470 return ChangeStatus::CHANGED;
12471 }
12472
12473 // For each potential value we create a conditional
12474 //
12475 // ```
12476 // if (ptr == value) value(args);
12477 // else ...
12478 // ```
12479 //
12480 bool SpecializedForAnyCallees = false;
12481 bool SpecializedForAllCallees = AllCalleesKnown;
12482 ICmpInst *LastCmp = nullptr;
12483 SmallVector<Function *, 8> SkippedAssumedCallees;
12485 for (Function *NewCallee : AssumedCallees) {
12486 if (!A.shouldSpecializeCallSiteForCallee(*this, *CB, *NewCallee,
12487 AssumedCallees.size())) {
12488 SkippedAssumedCallees.push_back(NewCallee);
12489 SpecializedForAllCallees = false;
12490 continue;
12491 }
12492 SpecializedForAnyCallees = true;
12493
12494 LastCmp = new ICmpInst(IP, llvm::CmpInst::ICMP_EQ, FP, NewCallee);
12495 Instruction *ThenTI =
12496 SplitBlockAndInsertIfThen(LastCmp, IP, /* Unreachable */ false);
12497 BasicBlock *CBBB = CB->getParent();
12498 A.registerManifestAddedBasicBlock(*ThenTI->getParent());
12499 A.registerManifestAddedBasicBlock(*IP->getParent());
12500 auto *SplitTI = cast<CondBrInst>(LastCmp->getNextNode());
12501 BasicBlock *ElseBB;
12502 if (&*IP == CB) {
12503 ElseBB = BasicBlock::Create(ThenTI->getContext(), "",
12504 ThenTI->getFunction(), CBBB);
12505 A.registerManifestAddedBasicBlock(*ElseBB);
12506 IP = UncondBrInst::Create(CBBB, ElseBB)->getIterator();
12507 SplitTI->replaceUsesOfWith(CBBB, ElseBB);
12508 } else {
12509 ElseBB = IP->getParent();
12510 ThenTI->replaceUsesOfWith(ElseBB, CBBB);
12511 }
12512 CastInst *RetBC = nullptr;
12513 CallInst *NewCall = nullptr;
12514 if (isLegalToPromote(*CB, NewCallee)) {
12515 auto *CBClone = cast<CallBase>(CB->clone());
12516 CBClone->insertBefore(ThenTI->getIterator());
12517 NewCall = &cast<CallInst>(promoteCall(*CBClone, NewCallee, &RetBC));
12518 NumIndirectCallsPromoted++;
12519 } else {
12520 NewCall = CallInst::Create(FunctionCallee(CSFT, NewCallee), CSArgs,
12521 CB->getName(), ThenTI->getIterator());
12522 NewCall->setDebugLoc(CB->getDebugLoc());
12523 }
12524 NewCalls.push_back({NewCall, RetBC});
12525 }
12526
12527 auto AttachCalleeMetadata = [&](CallBase &IndirectCB) {
12528 if (!AllCalleesKnown)
12529 return ChangeStatus::UNCHANGED;
12530 MDBuilder MDB(IndirectCB.getContext());
12531 MDNode *Callees = MDB.createCallees(SkippedAssumedCallees);
12532 IndirectCB.setMetadata(LLVMContext::MD_callees, Callees);
12533 return ChangeStatus::CHANGED;
12534 };
12535
12536 if (!SpecializedForAnyCallees)
12537 return AttachCalleeMetadata(*CB);
12538
12539 // Check if we need the fallback indirect call still.
12540 if (SpecializedForAllCallees) {
12542 LastCmp->eraseFromParent();
12543 new UnreachableInst(IP->getContext(), IP);
12544 IP->eraseFromParent();
12545 } else {
12546 auto *CBClone = cast<CallInst>(CB->clone());
12547 CBClone->setName(CB->getName());
12548 CBClone->insertBefore(*IP->getParent(), IP);
12549 NewCalls.push_back({CBClone, nullptr});
12550 AttachCalleeMetadata(*CBClone);
12551 }
12552
12553 // Check if we need a PHI to merge the results.
12554 if (!CBIsVoid) {
12555 auto *PHI = PHINode::Create(CB->getType(), NewCalls.size(),
12556 CB->getName() + ".phi",
12557 CB->getParent()->getFirstInsertionPt());
12558 for (auto &It : NewCalls) {
12559 CallBase *NewCall = It.first;
12560 Instruction *CallRet = It.second ? It.second : It.first;
12561 if (CallRet->getType() == CB->getType())
12562 PHI->addIncoming(CallRet, CallRet->getParent());
12563 else if (NewCall->getType()->isVoidTy())
12564 PHI->addIncoming(PoisonValue::get(CB->getType()),
12565 NewCall->getParent());
12566 else
12567 llvm_unreachable("Call return should match or be void!");
12568 }
12569 A.changeAfterManifest(IRPosition::callsite_returned(*CB), *PHI);
12570 }
12571
12572 A.deleteAfterManifest(*CB);
12573 Changed = ChangeStatus::CHANGED;
12574
12575 return Changed;
12576 }
12577
12578 const std::string getAsStr(Attributor *A) const override {
12579 return std::string(AllCalleesKnown ? "eliminate" : "specialize") +
12580 " indirect call site with " + std::to_string(AssumedCallees.size()) +
12581 " functions";
12582 }
12583
12584 void trackStatistics() const override {
12585 if (AllCalleesKnown) {
12587 Eliminated, CallSites,
12588 "Number of indirect call sites eliminated via specialization")
12589 } else {
12590 STATS_DECLTRACK(Specialized, CallSites,
12591 "Number of indirect call sites specialized")
12592 }
12593 }
12594
12595 bool foreachCallee(function_ref<bool(Function *)> CB) const override {
12596 return isValidState() && AllCalleesKnown && all_of(AssumedCallees, CB);
12597 }
12598
12599private:
12600 /// Map to remember filter results.
12601 DenseMap<Function *, std::optional<bool>> FilterResults;
12602
12603 /// If the !callee metadata was present, this set will contain all potential
12604 /// callees (superset).
12605 SmallSetVector<Function *, 4> PotentialCallees;
12606
12607 /// This set contains all currently assumed calllees, which might grow over
12608 /// time.
12609 SmallSetVector<Function *, 4> AssumedCallees;
12610
12611 /// Flag to indicate if all possible callees are in the AssumedCallees set or
12612 /// if there could be others.
12613 bool AllCalleesKnown = true;
12614};
12615} // namespace
12616
12617/// --------------------- Invariant Load Pointer -------------------------------
12618namespace {
12619
12620struct AAInvariantLoadPointerImpl
12621 : public StateWrapper<BitIntegerState<uint8_t, 15>,
12622 AAInvariantLoadPointer> {
12623
12624 enum {
12625 // pointer does not alias within the bounds of the function
12626 IS_NOALIAS = 1 << 0,
12627 // pointer is not involved in any effectful instructions within the bounds
12628 // of the function
12629 IS_NOEFFECT = 1 << 1,
12630 // loads are invariant within the bounds of the function
12631 IS_LOCALLY_INVARIANT = 1 << 2,
12632 // memory lifetime is constrained within the bounds of the function
12633 IS_LOCALLY_CONSTRAINED = 1 << 3,
12634
12635 IS_BEST_STATE = IS_NOALIAS | IS_NOEFFECT | IS_LOCALLY_INVARIANT |
12636 IS_LOCALLY_CONSTRAINED,
12637 };
12638 static_assert(getBestState() == IS_BEST_STATE, "Unexpected best state");
12639
12640 using Base =
12641 StateWrapper<BitIntegerState<uint8_t, 15>, AAInvariantLoadPointer>;
12642
12643 // the BitIntegerState is optimistic about IS_NOALIAS and IS_NOEFFECT, but
12644 // pessimistic about IS_KNOWN_INVARIANT
12645 AAInvariantLoadPointerImpl(const IRPosition &IRP, Attributor &A)
12646 : Base(IRP) {}
12647
12648 bool isKnownInvariant() const final {
12649 return isKnownLocallyInvariant() && isKnown(IS_LOCALLY_CONSTRAINED);
12650 }
12651
12652 bool isKnownLocallyInvariant() const final {
12653 if (isKnown(IS_LOCALLY_INVARIANT))
12654 return true;
12655 return isKnown(IS_NOALIAS | IS_NOEFFECT);
12656 }
12657
12658 bool isAssumedInvariant() const final {
12659 return isAssumedLocallyInvariant() && isAssumed(IS_LOCALLY_CONSTRAINED);
12660 }
12661
12662 bool isAssumedLocallyInvariant() const final {
12663 if (isAssumed(IS_LOCALLY_INVARIANT))
12664 return true;
12665 return isAssumed(IS_NOALIAS | IS_NOEFFECT);
12666 }
12667
12668 ChangeStatus updateImpl(Attributor &A) override {
12669 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12670
12671 Changed |= updateNoAlias(A);
12672 if (requiresNoAlias() && !isAssumed(IS_NOALIAS))
12673 return indicatePessimisticFixpoint();
12674
12675 Changed |= updateNoEffect(A);
12676
12677 Changed |= updateLocalInvariance(A);
12678
12679 return Changed;
12680 }
12681
12682 ChangeStatus manifest(Attributor &A) override {
12683 if (!isKnownInvariant())
12684 return ChangeStatus::UNCHANGED;
12685
12686 ChangeStatus Changed = ChangeStatus::UNCHANGED;
12687 const Value *Ptr = &getAssociatedValue();
12688 const auto TagInvariantLoads = [&](const Use &U, bool &) {
12689 if (U.get() != Ptr)
12690 return true;
12691 auto *I = dyn_cast<Instruction>(U.getUser());
12692 if (!I)
12693 return true;
12694
12695 // Ensure that we are only changing uses from the corresponding callgraph
12696 // SSC in the case that the AA isn't run on the entire module
12697 if (!A.isRunOn(I->getFunction()))
12698 return true;
12699
12700 if (I->hasMetadata(LLVMContext::MD_invariant_load))
12701 return true;
12702
12703 if (auto *LI = dyn_cast<LoadInst>(I)) {
12704 LI->setMetadata(LLVMContext::MD_invariant_load,
12705 MDNode::get(LI->getContext(), {}));
12706 Changed = ChangeStatus::CHANGED;
12707 }
12708 return true;
12709 };
12710
12711 (void)A.checkForAllUses(TagInvariantLoads, *this, *Ptr);
12712 return Changed;
12713 }
12714
12715 const std::string getAsStr(Attributor *) const override {
12716 if (isKnownInvariant())
12717 return "load-invariant pointer";
12718 return "non-invariant pointer";
12719 }
12720
12721 void trackStatistics() const override {}
12722
12723private:
12724 /// Indicate that noalias is required for the pointer to be invariant.
12725 bool requiresNoAlias() const {
12726 switch (getPositionKind()) {
12727 default:
12728 // Conservatively default to require noalias.
12729 return true;
12730 case IRP_FLOAT:
12731 case IRP_RETURNED:
12732 case IRP_CALL_SITE:
12733 return false;
12734 case IRP_CALL_SITE_RETURNED: {
12735 const auto &CB = cast<CallBase>(getAnchorValue());
12737 &CB, /*MustPreserveOffset=*/false);
12738 }
12739 case IRP_ARGUMENT: {
12740 const Function *F = getAssociatedFunction();
12741 assert(F && "no associated function for argument");
12742 return !isCallableCC(F->getCallingConv());
12743 }
12744 }
12745 }
12746
12747 bool isExternal() const {
12748 const Function *F = getAssociatedFunction();
12749 if (!F)
12750 return true;
12751 return isCallableCC(F->getCallingConv()) &&
12752 getPositionKind() != IRP_CALL_SITE_RETURNED;
12753 }
12754
12755 ChangeStatus updateNoAlias(Attributor &A) {
12756 if (isKnown(IS_NOALIAS) || !isAssumed(IS_NOALIAS))
12757 return ChangeStatus::UNCHANGED;
12758
12759 // Try to use AANoAlias.
12760 if (const auto *ANoAlias = A.getOrCreateAAFor<AANoAlias>(
12761 getIRPosition(), this, DepClassTy::REQUIRED)) {
12762 if (ANoAlias->isKnownNoAlias()) {
12763 addKnownBits(IS_NOALIAS);
12764 return ChangeStatus::CHANGED;
12765 }
12766
12767 if (!ANoAlias->isAssumedNoAlias()) {
12768 removeAssumedBits(IS_NOALIAS);
12769 return ChangeStatus::CHANGED;
12770 }
12771
12772 return ChangeStatus::UNCHANGED;
12773 }
12774
12775 // Try to infer noalias from argument attribute, since it is applicable for
12776 // the duration of the function.
12777 if (const Argument *Arg = getAssociatedArgument()) {
12778 if (Arg->hasNoAliasAttr()) {
12779 addKnownBits(IS_NOALIAS);
12780 return ChangeStatus::UNCHANGED;
12781 }
12782
12783 // Noalias information is not provided, and cannot be inferred,
12784 // so we conservatively assume the pointer aliases.
12785 removeAssumedBits(IS_NOALIAS);
12786 return ChangeStatus::CHANGED;
12787 }
12788
12789 return ChangeStatus::UNCHANGED;
12790 }
12791
12792 ChangeStatus updateNoEffect(Attributor &A) {
12793 if (isKnown(IS_NOEFFECT) || !isAssumed(IS_NOEFFECT))
12794 return ChangeStatus::UNCHANGED;
12795
12796 if (!getAssociatedFunction())
12797 return indicatePessimisticFixpoint();
12798
12799 if (isa<AllocaInst>(&getAssociatedValue()))
12800 return indicatePessimisticFixpoint();
12801
12802 const auto HasNoEffectLoads = [&](const Use &U, bool &) {
12803 const auto *LI = dyn_cast<LoadInst>(U.getUser());
12804 return !LI || !LI->mayHaveSideEffects();
12805 };
12806 if (!A.checkForAllUses(HasNoEffectLoads, *this, getAssociatedValue()))
12807 return indicatePessimisticFixpoint();
12808
12809 if (const auto *AMemoryBehavior = A.getOrCreateAAFor<AAMemoryBehavior>(
12810 getIRPosition(), this, DepClassTy::REQUIRED)) {
12811 // For non-instructions, try to use AAMemoryBehavior to infer the readonly
12812 // attribute
12813 if (!AMemoryBehavior->isAssumedReadOnly())
12814 return indicatePessimisticFixpoint();
12815
12816 if (AMemoryBehavior->isKnownReadOnly()) {
12817 addKnownBits(IS_NOEFFECT);
12818 return ChangeStatus::UNCHANGED;
12819 }
12820
12821 return ChangeStatus::UNCHANGED;
12822 }
12823
12824 if (const Argument *Arg = getAssociatedArgument()) {
12825 if (Arg->onlyReadsMemory()) {
12826 addKnownBits(IS_NOEFFECT);
12827 return ChangeStatus::UNCHANGED;
12828 }
12829
12830 // Readonly information is not provided, and cannot be inferred from
12831 // AAMemoryBehavior.
12832 return indicatePessimisticFixpoint();
12833 }
12834
12835 return ChangeStatus::UNCHANGED;
12836 }
12837
12838 ChangeStatus updateLocalInvariance(Attributor &A) {
12839 if (isKnown(IS_LOCALLY_INVARIANT) || !isAssumed(IS_LOCALLY_INVARIANT))
12840 return ChangeStatus::UNCHANGED;
12841
12842 // try to infer invariance from underlying objects
12843 const auto *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(
12844 getIRPosition(), this, DepClassTy::REQUIRED);
12845 if (!AUO)
12846 return ChangeStatus::UNCHANGED;
12847
12848 bool UsedAssumedInformation = false;
12849 const auto IsLocallyInvariantLoadIfPointer = [&](const Value &V) {
12850 if (!V.getType()->isPointerTy())
12851 return true;
12852 const auto *IsInvariantLoadPointer =
12853 A.getOrCreateAAFor<AAInvariantLoadPointer>(IRPosition::value(V), this,
12854 DepClassTy::REQUIRED);
12855 // Conservatively fail if invariance cannot be inferred.
12856 if (!IsInvariantLoadPointer)
12857 return false;
12858
12859 if (IsInvariantLoadPointer->isKnownLocallyInvariant())
12860 return true;
12861 if (!IsInvariantLoadPointer->isAssumedLocallyInvariant())
12862 return false;
12863
12864 UsedAssumedInformation = true;
12865 return true;
12866 };
12867 if (!AUO->forallUnderlyingObjects(IsLocallyInvariantLoadIfPointer))
12868 return indicatePessimisticFixpoint();
12869
12870 if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue())) {
12872 CB, /*MustPreserveOffset=*/false)) {
12873 for (const Value *Arg : CB->args()) {
12874 if (!IsLocallyInvariantLoadIfPointer(*Arg))
12875 return indicatePessimisticFixpoint();
12876 }
12877 }
12878 }
12879
12880 if (!UsedAssumedInformation) {
12881 // Pointer is known and not just assumed to be locally invariant.
12882 addKnownBits(IS_LOCALLY_INVARIANT);
12883 return ChangeStatus::CHANGED;
12884 }
12885
12886 return ChangeStatus::UNCHANGED;
12887 }
12888};
12889
12890struct AAInvariantLoadPointerFloating final : AAInvariantLoadPointerImpl {
12891 AAInvariantLoadPointerFloating(const IRPosition &IRP, Attributor &A)
12892 : AAInvariantLoadPointerImpl(IRP, A) {}
12893};
12894
12895struct AAInvariantLoadPointerReturned final : AAInvariantLoadPointerImpl {
12896 AAInvariantLoadPointerReturned(const IRPosition &IRP, Attributor &A)
12897 : AAInvariantLoadPointerImpl(IRP, A) {}
12898
12899 void initialize(Attributor &) override {
12900 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12901 }
12902};
12903
12904struct AAInvariantLoadPointerCallSiteReturned final
12905 : AAInvariantLoadPointerImpl {
12906 AAInvariantLoadPointerCallSiteReturned(const IRPosition &IRP, Attributor &A)
12907 : AAInvariantLoadPointerImpl(IRP, A) {}
12908
12909 void initialize(Attributor &A) override {
12910 // Nothing is known about the result of an indirect call.
12911 const Function *F = getAssociatedFunction();
12912 if (!F) {
12913 indicatePessimisticFixpoint();
12914 return;
12915 }
12916
12917 if (!F->isDeclaration() && !F->isIntrinsic())
12918 return AAInvariantLoadPointerImpl::initialize(A);
12919
12920 const auto &CB = cast<CallBase>(getAnchorValue());
12922 &CB, /*MustPreserveOffset=*/false))
12923 return AAInvariantLoadPointerImpl::initialize(A);
12924
12925 if (F->onlyReadsMemory() && F->hasNoSync())
12926 return AAInvariantLoadPointerImpl::initialize(A);
12927
12928 // At this point, the function is opaque, so we conservatively assume
12929 // non-invariance.
12930 indicatePessimisticFixpoint();
12931 }
12932};
12933
12934struct AAInvariantLoadPointerArgument final : AAInvariantLoadPointerImpl {
12935 AAInvariantLoadPointerArgument(const IRPosition &IRP, Attributor &A)
12936 : AAInvariantLoadPointerImpl(IRP, A) {}
12937
12938 void initialize(Attributor &) override {
12939 const Function *F = getAssociatedFunction();
12940 assert(F && "no associated function for argument");
12941
12942 if (!isCallableCC(F->getCallingConv())) {
12943 addKnownBits(IS_LOCALLY_CONSTRAINED);
12944 return;
12945 }
12946
12947 if (!F->hasLocalLinkage())
12948 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12949 }
12950};
12951
12952struct AAInvariantLoadPointerCallSiteArgument final
12953 : AAInvariantLoadPointerImpl {
12954 AAInvariantLoadPointerCallSiteArgument(const IRPosition &IRP, Attributor &A)
12955 : AAInvariantLoadPointerImpl(IRP, A) {}
12956};
12957} // namespace
12958
12959/// ------------------------ Address Space ------------------------------------
12960namespace {
12961
12962template <typename InstType>
12963static bool makeChange(Attributor &A, InstType *MemInst, const Use &U,
12964 Value *OriginalValue, PointerType *NewPtrTy,
12965 bool UseOriginalValue) {
12966 if (U.getOperandNo() != InstType::getPointerOperandIndex())
12967 return false;
12968
12969 if (MemInst->isVolatile()) {
12970 auto *TTI = A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(
12971 *MemInst->getFunction());
12972 unsigned NewAS = NewPtrTy->getPointerAddressSpace();
12973 if (!TTI || !TTI->hasVolatileVariant(MemInst, NewAS))
12974 return false;
12975 }
12976
12977 if (UseOriginalValue) {
12978 A.changeUseAfterManifest(const_cast<Use &>(U), *OriginalValue);
12979 return true;
12980 }
12981
12982 Instruction *CastInst = new AddrSpaceCastInst(OriginalValue, NewPtrTy);
12983 CastInst->insertBefore(MemInst->getIterator());
12984 A.changeUseAfterManifest(const_cast<Use &>(U), *CastInst);
12985 return true;
12986}
12987
12988struct AAAddressSpaceImpl : public AAAddressSpace {
12989 AAAddressSpaceImpl(const IRPosition &IRP, Attributor &A)
12990 : AAAddressSpace(IRP, A) {}
12991
12992 uint32_t getAddressSpace() const override {
12993 assert(isValidState() && "the AA is invalid");
12994 return AssumedAddressSpace;
12995 }
12996
12997 void initialize(Attributor &A) override {
12998 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
12999 "Associated value is not a pointer");
13000
13001 if (!A.getInfoCache().getFlatAddressSpace().has_value()) {
13002 indicatePessimisticFixpoint();
13003 return;
13004 }
13005
13006 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13007 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13008 if (AS != FlatAS) {
13009 [[maybe_unused]] bool R = takeAddressSpace(AS);
13010 assert(R && "The take should happen");
13011 indicateOptimisticFixpoint();
13012 }
13013 }
13014
13015 ChangeStatus updateImpl(Attributor &A) override {
13016 uint32_t OldAddressSpace = AssumedAddressSpace;
13017 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13018
13019 auto CheckAddressSpace = [&](Value &Obj) {
13020 // Ignore undef.
13021 if (isa<UndefValue>(&Obj))
13022 return true;
13023
13024 // If the object already has a non-flat address space, we simply take it.
13025 unsigned ObjAS = Obj.getType()->getPointerAddressSpace();
13026 if (ObjAS != FlatAS)
13027 return takeAddressSpace(ObjAS);
13028
13029 // At this point, we know Obj is in the flat address space. For a final
13030 // attempt, we want to use getAssumedAddrSpace, but first we must get the
13031 // associated function, if possible.
13032 Function *F = nullptr;
13033 if (auto *Arg = dyn_cast<Argument>(&Obj))
13034 F = Arg->getParent();
13035 else if (auto *I = dyn_cast<Instruction>(&Obj))
13036 F = I->getFunction();
13037
13038 // Use getAssumedAddrSpace if the associated function exists.
13039 if (F) {
13040 auto *TTI =
13041 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(*F);
13042 unsigned AssumedAS = TTI->getAssumedAddrSpace(&Obj);
13043 if (AssumedAS != ~0U)
13044 return takeAddressSpace(AssumedAS);
13045 }
13046
13047 // Now we can't do anything else but to take the flat AS.
13048 return takeAddressSpace(FlatAS);
13049 };
13050
13051 auto *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(getIRPosition(), this,
13052 DepClassTy::REQUIRED);
13053 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13054 return indicatePessimisticFixpoint();
13055
13056 return OldAddressSpace == AssumedAddressSpace ? ChangeStatus::UNCHANGED
13057 : ChangeStatus::CHANGED;
13058 }
13059
13060 ChangeStatus manifest(Attributor &A) override {
13061 unsigned NewAS = getAddressSpace();
13062
13063 if (NewAS == InvalidAddressSpace ||
13064 NewAS == getAssociatedType()->getPointerAddressSpace())
13065 return ChangeStatus::UNCHANGED;
13066
13067 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13068
13069 Value *AssociatedValue = &getAssociatedValue();
13070 Value *OriginalValue = peelAddrspacecast(AssociatedValue, FlatAS);
13071
13072 PointerType *NewPtrTy =
13073 PointerType::get(getAssociatedType()->getContext(), NewAS);
13074 bool UseOriginalValue =
13075 OriginalValue->getType()->getPointerAddressSpace() == NewAS;
13076
13077 bool Changed = false;
13078
13079 auto Pred = [&](const Use &U, bool &) {
13080 if (U.get() != AssociatedValue)
13081 return true;
13082 auto *Inst = dyn_cast<Instruction>(U.getUser());
13083 if (!Inst)
13084 return true;
13085 // This is a WA to make sure we only change uses from the corresponding
13086 // CGSCC if the AA is run on CGSCC instead of the entire module.
13087 if (!A.isRunOn(Inst->getFunction()))
13088 return true;
13089 if (auto *LI = dyn_cast<LoadInst>(Inst)) {
13090 Changed |=
13091 makeChange(A, LI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13092 } else if (auto *SI = dyn_cast<StoreInst>(Inst)) {
13093 Changed |=
13094 makeChange(A, SI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13095 } else if (auto *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
13096 Changed |=
13097 makeChange(A, RMW, U, OriginalValue, NewPtrTy, UseOriginalValue);
13098 } else if (auto *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
13099 Changed |=
13100 makeChange(A, CmpX, U, OriginalValue, NewPtrTy, UseOriginalValue);
13101 }
13102 return true;
13103 };
13104
13105 // It doesn't matter if we can't check all uses as we can simply
13106 // conservatively ignore those that can not be visited.
13107 (void)A.checkForAllUses(Pred, *this, getAssociatedValue(),
13108 /* CheckBBLivenessOnly */ true);
13109
13110 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13111 }
13112
13113 const std::string getAsStr(Attributor *A) const override {
13114 if (!isValidState())
13115 return "addrspace(<invalid>)";
13116 return "addrspace(" +
13117 (AssumedAddressSpace == InvalidAddressSpace
13118 ? "none"
13119 : std::to_string(AssumedAddressSpace)) +
13120 ")";
13121 }
13122
13123private:
13124 uint32_t AssumedAddressSpace = InvalidAddressSpace;
13125
13126 bool takeAddressSpace(uint32_t AS) {
13127 if (AssumedAddressSpace == InvalidAddressSpace) {
13128 AssumedAddressSpace = AS;
13129 return true;
13130 }
13131 return AssumedAddressSpace == AS;
13132 }
13133
13134 static Value *peelAddrspacecast(Value *V, unsigned FlatAS) {
13135 if (auto *I = dyn_cast<AddrSpaceCastInst>(V)) {
13136 assert(I->getSrcAddressSpace() != FlatAS &&
13137 "there should not be flat AS -> non-flat AS");
13138 return I->getPointerOperand();
13139 }
13140 if (auto *C = dyn_cast<ConstantExpr>(V))
13141 if (C->getOpcode() == Instruction::AddrSpaceCast) {
13142 assert(C->getOperand(0)->getType()->getPointerAddressSpace() !=
13143 FlatAS &&
13144 "there should not be flat AS -> non-flat AS X");
13145 return C->getOperand(0);
13146 }
13147 return V;
13148 }
13149};
13150
13151struct AAAddressSpaceFloating final : AAAddressSpaceImpl {
13152 AAAddressSpaceFloating(const IRPosition &IRP, Attributor &A)
13153 : AAAddressSpaceImpl(IRP, A) {}
13154
13155 void trackStatistics() const override {
13157 }
13158};
13159
13160struct AAAddressSpaceReturned final : AAAddressSpaceImpl {
13161 AAAddressSpaceReturned(const IRPosition &IRP, Attributor &A)
13162 : AAAddressSpaceImpl(IRP, A) {}
13163
13164 void initialize(Attributor &A) override {
13165 // TODO: we don't rewrite function argument for now because it will need to
13166 // rewrite the function signature and all call sites.
13167 (void)indicatePessimisticFixpoint();
13168 }
13169
13170 void trackStatistics() const override {
13171 STATS_DECLTRACK_FNRET_ATTR(addrspace);
13172 }
13173};
13174
13175struct AAAddressSpaceCallSiteReturned final : AAAddressSpaceImpl {
13176 AAAddressSpaceCallSiteReturned(const IRPosition &IRP, Attributor &A)
13177 : AAAddressSpaceImpl(IRP, A) {}
13178
13179 void trackStatistics() const override {
13180 STATS_DECLTRACK_CSRET_ATTR(addrspace);
13181 }
13182};
13183
13184struct AAAddressSpaceArgument final : AAAddressSpaceImpl {
13185 AAAddressSpaceArgument(const IRPosition &IRP, Attributor &A)
13186 : AAAddressSpaceImpl(IRP, A) {}
13187
13188 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(addrspace); }
13189};
13190
13191struct AAAddressSpaceCallSiteArgument final : AAAddressSpaceImpl {
13192 AAAddressSpaceCallSiteArgument(const IRPosition &IRP, Attributor &A)
13193 : AAAddressSpaceImpl(IRP, A) {}
13194
13195 void initialize(Attributor &A) override {
13196 // TODO: we don't rewrite call site argument for now because it will need to
13197 // rewrite the function signature of the callee.
13198 (void)indicatePessimisticFixpoint();
13199 }
13200
13201 void trackStatistics() const override {
13202 STATS_DECLTRACK_CSARG_ATTR(addrspace);
13203 }
13204};
13205} // namespace
13206
13207/// ------------------------ No Alias Address Space ---------------------------
13208// This attribute assumes flat address space can alias all other address space
13209
13210// TODO: this is similar to AAAddressSpace, most of the code should be merged.
13211// But merging it created failing cased on gateway test that cannot be
13212// reproduced locally. So should open a separated PR to handle the merge of
13213// AANoAliasAddrSpace and AAAddressSpace attribute
13214
13215namespace {
13216struct AANoAliasAddrSpaceImpl : public AANoAliasAddrSpace {
13217 AANoAliasAddrSpaceImpl(const IRPosition &IRP, Attributor &A)
13218 : AANoAliasAddrSpace(IRP, A) {}
13219
13220 void initialize(Attributor &A) override {
13221 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
13222 "Associated value is not a pointer");
13223
13224 resetASRanges(A);
13225
13226 std::optional<unsigned> FlatAS = A.getInfoCache().getFlatAddressSpace();
13227 if (!FlatAS.has_value()) {
13228 indicatePessimisticFixpoint();
13229 return;
13230 }
13231
13232 removeAS(*FlatAS);
13233
13234 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13235 if (AS != *FlatAS) {
13236 removeAS(AS);
13237 indicateOptimisticFixpoint();
13238 }
13239 }
13240
13241 ChangeStatus updateImpl(Attributor &A) override {
13242 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13243 uint32_t OldAssumed = getAssumed();
13244
13245 auto CheckAddressSpace = [&](Value &Obj) {
13246 if (isa<PoisonValue>(&Obj))
13247 return true;
13248
13249 unsigned AS = Obj.getType()->getPointerAddressSpace();
13250 if (AS == FlatAS)
13251 return false;
13252
13253 removeAS(Obj.getType()->getPointerAddressSpace());
13254 return true;
13255 };
13256
13257 const AAUnderlyingObjects *AUO = A.getOrCreateAAFor<AAUnderlyingObjects>(
13258 getIRPosition(), this, DepClassTy::REQUIRED);
13259 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13260 return indicatePessimisticFixpoint();
13261
13262 return OldAssumed == getAssumed() ? ChangeStatus::UNCHANGED
13263 : ChangeStatus::CHANGED;
13264 }
13265
13266 ChangeStatus manifest(Attributor &A) override {
13267 unsigned FlatAS = A.getInfoCache().getFlatAddressSpace().value();
13268
13269 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13270 if (AS != FlatAS || Map.empty())
13271 return ChangeStatus::UNCHANGED;
13272
13273 LLVMContext &Ctx = getAssociatedValue().getContext();
13274 MDNode *NoAliasASNode = nullptr;
13275 MDBuilder MDB(Ctx);
13276 // Has to use iterator to get the range info.
13277 for (RangeMap::const_iterator I = Map.begin(); I != Map.end(); I++) {
13278 if (!I.value())
13279 continue;
13280 unsigned Upper = I.stop();
13281 unsigned Lower = I.start();
13282 if (!NoAliasASNode) {
13283 NoAliasASNode = MDB.createRange(APInt(32, Lower), APInt(32, Upper + 1));
13284 continue;
13285 }
13286 MDNode *ASRange = MDB.createRange(APInt(32, Lower), APInt(32, Upper + 1));
13287 NoAliasASNode = MDNode::getMostGenericRange(NoAliasASNode, ASRange);
13288 }
13289
13290 Value *AssociatedValue = &getAssociatedValue();
13291 bool Changed = false;
13292
13293 auto AddNoAliasAttr = [&](const Use &U, bool &) {
13294 if (U.get() != AssociatedValue)
13295 return true;
13296 Instruction *Inst = dyn_cast<Instruction>(U.getUser());
13297 if (!Inst || Inst->hasMetadata(LLVMContext::MD_noalias_addrspace))
13298 return true;
13299 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst) &&
13301 return true;
13302 if (!A.isRunOn(Inst->getFunction()))
13303 return true;
13304 Inst->setMetadata(LLVMContext::MD_noalias_addrspace, NoAliasASNode);
13305 Changed = true;
13306 return true;
13307 };
13308 (void)A.checkForAllUses(AddNoAliasAttr, *this, *AssociatedValue,
13309 /*CheckBBLivenessOnly=*/true);
13310 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13311 }
13312
13313 const std::string getAsStr(Attributor *A) const override {
13314 if (!isValidState())
13315 return "<invalid>";
13316 std::string Str;
13317 raw_string_ostream OS(Str);
13318 OS << "CanNotBeAddrSpace(";
13319 for (RangeMap::const_iterator I = Map.begin(); I != Map.end(); I++) {
13320 unsigned Upper = I.stop();
13321 unsigned Lower = I.start();
13322 OS << ' ' << '[' << Upper << ',' << Lower + 1 << ')';
13323 }
13324 OS << " )";
13325 return OS.str();
13326 }
13327
13328private:
13329 void removeAS(unsigned AS) {
13330 RangeMap::iterator I = Map.find(AS);
13331
13332 if (I != Map.end()) {
13333 unsigned Upper = I.stop();
13334 unsigned Lower = I.start();
13335 I.erase();
13336 if (Upper == Lower)
13337 return;
13338 if (AS != ~((unsigned)0) && AS + 1 <= Upper)
13339 Map.insert(AS + 1, Upper, /*what ever this variable name is=*/true);
13340 if (AS != 0 && Lower <= AS - 1)
13341 Map.insert(Lower, AS - 1, true);
13342 }
13343 }
13344
13345 void resetASRanges(Attributor &A) {
13346 Map.clear();
13347 Map.insert(0, A.getInfoCache().getMaxAddrSpace(), true);
13348 }
13349};
13350
13351struct AANoAliasAddrSpaceFloating final : AANoAliasAddrSpaceImpl {
13352 AANoAliasAddrSpaceFloating(const IRPosition &IRP, Attributor &A)
13353 : AANoAliasAddrSpaceImpl(IRP, A) {}
13354
13355 void trackStatistics() const override {
13356 STATS_DECLTRACK_FLOATING_ATTR(noaliasaddrspace);
13357 }
13358};
13359
13360struct AANoAliasAddrSpaceReturned final : AANoAliasAddrSpaceImpl {
13361 AANoAliasAddrSpaceReturned(const IRPosition &IRP, Attributor &A)
13362 : AANoAliasAddrSpaceImpl(IRP, A) {}
13363
13364 void trackStatistics() const override {
13365 STATS_DECLTRACK_FNRET_ATTR(noaliasaddrspace);
13366 }
13367};
13368
13369struct AANoAliasAddrSpaceCallSiteReturned final : AANoAliasAddrSpaceImpl {
13370 AANoAliasAddrSpaceCallSiteReturned(const IRPosition &IRP, Attributor &A)
13371 : AANoAliasAddrSpaceImpl(IRP, A) {}
13372
13373 void trackStatistics() const override {
13374 STATS_DECLTRACK_CSRET_ATTR(noaliasaddrspace);
13375 }
13376};
13377
13378struct AANoAliasAddrSpaceArgument final : AANoAliasAddrSpaceImpl {
13379 AANoAliasAddrSpaceArgument(const IRPosition &IRP, Attributor &A)
13380 : AANoAliasAddrSpaceImpl(IRP, A) {}
13381
13382 void trackStatistics() const override {
13383 STATS_DECLTRACK_ARG_ATTR(noaliasaddrspace);
13384 }
13385};
13386
13387struct AANoAliasAddrSpaceCallSiteArgument final : AANoAliasAddrSpaceImpl {
13388 AANoAliasAddrSpaceCallSiteArgument(const IRPosition &IRP, Attributor &A)
13389 : AANoAliasAddrSpaceImpl(IRP, A) {}
13390
13391 void trackStatistics() const override {
13392 STATS_DECLTRACK_CSARG_ATTR(noaliasaddrspace);
13393 }
13394};
13395} // namespace
13396/// ----------- Allocation Info ----------
13397namespace {
13398struct AAAllocationInfoImpl : public AAAllocationInfo {
13399 AAAllocationInfoImpl(const IRPosition &IRP, Attributor &A)
13400 : AAAllocationInfo(IRP, A) {}
13401
13402 std::optional<TypeSize> getAllocatedSize() const override {
13403 assert(isValidState() && "the AA is invalid");
13404 return AssumedAllocatedSize;
13405 }
13406
13407 std::optional<TypeSize> findInitialAllocationSize(Instruction *I,
13408 const DataLayout &DL) {
13409
13410 // TODO: implement case for malloc like instructions
13411 switch (I->getOpcode()) {
13412 case Instruction::Alloca: {
13413 AllocaInst *AI = cast<AllocaInst>(I);
13414 return AI->getAllocationSize(DL);
13415 }
13416 default:
13417 return std::nullopt;
13418 }
13419 }
13420
13421 ChangeStatus updateImpl(Attributor &A) override {
13422
13423 const IRPosition &IRP = getIRPosition();
13424 Instruction *I = IRP.getCtxI();
13425
13426 // TODO: update check for malloc like calls
13427 if (!isa<AllocaInst>(I))
13428 return indicatePessimisticFixpoint();
13429
13430 bool IsKnownNoCapture;
13432 A, this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture))
13433 return indicatePessimisticFixpoint();
13434
13435 const AAPointerInfo *PI =
13436 A.getOrCreateAAFor<AAPointerInfo>(IRP, *this, DepClassTy::REQUIRED);
13437
13438 if (!PI)
13439 return indicatePessimisticFixpoint();
13440
13441 if (!PI->getState().isValidState() || PI->reachesReturn())
13442 return indicatePessimisticFixpoint();
13443
13444 const DataLayout &DL = A.getDataLayout();
13445 const auto AllocationSize = findInitialAllocationSize(I, DL);
13446
13447 // If allocation size is nullopt, we give up.
13448 if (!AllocationSize)
13449 return indicatePessimisticFixpoint();
13450
13451 // For zero sized allocations, we give up.
13452 // Since we can't reduce further
13453 if (*AllocationSize == 0)
13454 return indicatePessimisticFixpoint();
13455
13456 int64_t BinSize = PI->numOffsetBins();
13457
13458 // TODO: implement for multiple bins
13459 if (BinSize > 1)
13460 return indicatePessimisticFixpoint();
13461
13462 if (BinSize == 0) {
13463 auto NewAllocationSize = std::make_optional<TypeSize>(0, false);
13464 if (!changeAllocationSize(NewAllocationSize))
13465 return ChangeStatus::UNCHANGED;
13466 return ChangeStatus::CHANGED;
13467 }
13468
13469 // TODO: refactor this to be part of multiple bin case
13470 const auto &It = PI->begin();
13471
13472 // TODO: handle if Offset is not zero
13473 if (It->first.Offset != 0)
13474 return indicatePessimisticFixpoint();
13475
13476 uint64_t SizeOfBin = It->first.Offset + It->first.Size;
13477
13478 if (SizeOfBin >= *AllocationSize)
13479 return indicatePessimisticFixpoint();
13480
13481 auto NewAllocationSize = std::make_optional<TypeSize>(SizeOfBin * 8, false);
13482
13483 if (!changeAllocationSize(NewAllocationSize))
13484 return ChangeStatus::UNCHANGED;
13485
13486 return ChangeStatus::CHANGED;
13487 }
13488
13489 ChangeStatus manifest(Attributor &A) override {
13490
13491 assert(isValidState() &&
13492 "Manifest should only be called if the state is valid.");
13493
13494 Instruction *I = getIRPosition().getCtxI();
13495
13496 auto FixedAllocatedSizeInBits = getAllocatedSize()->getFixedValue();
13497
13498 unsigned long NumBytesToAllocate = (FixedAllocatedSizeInBits + 7) / 8;
13499
13500 switch (I->getOpcode()) {
13501 // TODO: add case for malloc like calls
13502 case Instruction::Alloca: {
13503
13504 AllocaInst *AI = cast<AllocaInst>(I);
13505
13506 Type *CharType = Type::getInt8Ty(I->getContext());
13507
13508 auto *NumBytesToValue =
13509 ConstantInt::get(I->getContext(), APInt(32, NumBytesToAllocate));
13510
13511 BasicBlock::iterator insertPt = AI->getIterator();
13512 insertPt = std::next(insertPt);
13513 AllocaInst *NewAllocaInst =
13514 new AllocaInst(CharType, AI->getAddressSpace(), NumBytesToValue,
13515 AI->getAlign(), AI->getName(), insertPt);
13516
13517 if (A.changeAfterManifest(IRPosition::inst(*AI), *NewAllocaInst))
13518 return ChangeStatus::CHANGED;
13519
13520 break;
13521 }
13522 default:
13523 break;
13524 }
13525
13526 return ChangeStatus::UNCHANGED;
13527 }
13528
13529 const std::string getAsStr(Attributor *A) const override {
13530 if (!isValidState())
13531 return "allocationinfo(<invalid>)";
13532 return "allocationinfo(" +
13533 (AssumedAllocatedSize == HasNoAllocationSize
13534 ? "none"
13535 : std::to_string(AssumedAllocatedSize->getFixedValue())) +
13536 ")";
13537 }
13538
13539private:
13540 std::optional<TypeSize> AssumedAllocatedSize = HasNoAllocationSize;
13541
13542 // Maintain the computed allocation size of the object.
13543 // Returns (bool) weather the size of the allocation was modified or not.
13544 bool changeAllocationSize(std::optional<TypeSize> Size) {
13545 if (AssumedAllocatedSize == HasNoAllocationSize ||
13546 AssumedAllocatedSize != Size) {
13547 AssumedAllocatedSize = Size;
13548 return true;
13549 }
13550 return false;
13551 }
13552};
13553
13554struct AAAllocationInfoFloating : AAAllocationInfoImpl {
13555 AAAllocationInfoFloating(const IRPosition &IRP, Attributor &A)
13556 : AAAllocationInfoImpl(IRP, A) {}
13557
13558 void trackStatistics() const override {
13559 STATS_DECLTRACK_FLOATING_ATTR(allocationinfo);
13560 }
13561};
13562
13563struct AAAllocationInfoReturned : AAAllocationInfoImpl {
13564 AAAllocationInfoReturned(const IRPosition &IRP, Attributor &A)
13565 : AAAllocationInfoImpl(IRP, A) {}
13566
13567 void initialize(Attributor &A) override {
13568 // TODO: we don't rewrite function argument for now because it will need to
13569 // rewrite the function signature and all call sites
13570 (void)indicatePessimisticFixpoint();
13571 }
13572
13573 void trackStatistics() const override {
13574 STATS_DECLTRACK_FNRET_ATTR(allocationinfo);
13575 }
13576};
13577
13578struct AAAllocationInfoCallSiteReturned : AAAllocationInfoImpl {
13579 AAAllocationInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
13580 : AAAllocationInfoImpl(IRP, A) {}
13581
13582 void trackStatistics() const override {
13583 STATS_DECLTRACK_CSRET_ATTR(allocationinfo);
13584 }
13585};
13586
13587struct AAAllocationInfoArgument : AAAllocationInfoImpl {
13588 AAAllocationInfoArgument(const IRPosition &IRP, Attributor &A)
13589 : AAAllocationInfoImpl(IRP, A) {}
13590
13591 void trackStatistics() const override {
13592 STATS_DECLTRACK_ARG_ATTR(allocationinfo);
13593 }
13594};
13595
13596struct AAAllocationInfoCallSiteArgument : AAAllocationInfoImpl {
13597 AAAllocationInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
13598 : AAAllocationInfoImpl(IRP, A) {}
13599
13600 void initialize(Attributor &A) override {
13601
13602 (void)indicatePessimisticFixpoint();
13603 }
13604
13605 void trackStatistics() const override {
13606 STATS_DECLTRACK_CSARG_ATTR(allocationinfo);
13607 }
13608};
13609} // namespace
13610
13611const char AANoUnwind::ID = 0;
13612const char AANoSync::ID = 0;
13613const char AANoFree::ID = 0;
13614const char AANonNull::ID = 0;
13615const char AAMustProgress::ID = 0;
13616const char AANoRecurse::ID = 0;
13617const char AANonConvergent::ID = 0;
13618const char AAWillReturn::ID = 0;
13619const char AAUndefinedBehavior::ID = 0;
13620const char AANoAlias::ID = 0;
13621const char AAIntraFnReachability::ID = 0;
13622const char AANoReturn::ID = 0;
13623const char AAIsDead::ID = 0;
13624const char AADereferenceable::ID = 0;
13625const char AAAlign::ID = 0;
13626const char AAInstanceInfo::ID = 0;
13627const char AANoCapture::ID = 0;
13628const char AAValueSimplify::ID = 0;
13629const char AAHeapToStack::ID = 0;
13630const char AAPrivatizablePtr::ID = 0;
13631const char AAMemoryBehavior::ID = 0;
13632const char AAMemoryLocation::ID = 0;
13633const char AAValueConstantRange::ID = 0;
13634const char AAPotentialConstantValues::ID = 0;
13635const char AAPotentialValues::ID = 0;
13636const char AANoUndef::ID = 0;
13637const char AANoFPClass::ID = 0;
13638const char AACallEdges::ID = 0;
13639const char AAInterFnReachability::ID = 0;
13640const char AAPointerInfo::ID = 0;
13641const char AAAssumptionInfo::ID = 0;
13642const char AAUnderlyingObjects::ID = 0;
13643const char AAInvariantLoadPointer::ID = 0;
13644const char AAAddressSpace::ID = 0;
13645const char AANoAliasAddrSpace::ID = 0;
13646const char AAAllocationInfo::ID = 0;
13647const char AAIndirectCallInfo::ID = 0;
13648const char AAGlobalValueInfo::ID = 0;
13649const char AADenormalFPMath::ID = 0;
13650
13651// Macro magic to create the static generator function for attributes that
13652// follow the naming scheme.
13653
13654#define SWITCH_PK_INV(CLASS, PK, POS_NAME) \
13655 case IRPosition::PK: \
13656 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
13657
13658#define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \
13659 case IRPosition::PK: \
13660 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \
13661 ++NumAAs; \
13662 break;
13663
13664#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13665 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13666 CLASS *AA = nullptr; \
13667 switch (IRP.getPositionKind()) { \
13668 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13669 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13670 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13671 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13672 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13673 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13674 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13675 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13676 } \
13677 return *AA; \
13678 }
13679
13680#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13681 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13682 CLASS *AA = nullptr; \
13683 switch (IRP.getPositionKind()) { \
13684 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13685 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \
13686 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13687 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13688 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13689 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13690 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13691 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13692 } \
13693 return *AA; \
13694 }
13695
13696#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS) \
13697 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13698 CLASS *AA = nullptr; \
13699 switch (IRP.getPositionKind()) { \
13700 SWITCH_PK_CREATE(CLASS, IRP, POS, SUFFIX) \
13701 default: \
13702 llvm_unreachable("Cannot create " #CLASS " for position otherthan " #POS \
13703 " position!"); \
13704 } \
13705 return *AA; \
13706 }
13707
13708#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13709 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13710 CLASS *AA = nullptr; \
13711 switch (IRP.getPositionKind()) { \
13712 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13713 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13714 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13715 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13716 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13717 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13718 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13719 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13720 } \
13721 return *AA; \
13722 }
13723
13724#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13725 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13726 CLASS *AA = nullptr; \
13727 switch (IRP.getPositionKind()) { \
13728 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13729 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13730 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13731 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13732 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13733 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13734 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13735 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13736 } \
13737 return *AA; \
13738 }
13739
13740#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13741 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13742 CLASS *AA = nullptr; \
13743 switch (IRP.getPositionKind()) { \
13744 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13745 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13746 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13747 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13748 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13749 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13750 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13751 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13752 } \
13753 return *AA; \
13754 }
13755
13765
13783
13788
13793
13800
13802
13803#undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
13804#undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
13805#undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
13806#undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
13807#undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
13808#undef CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION
13809#undef SWITCH_PK_CREATE
13810#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
if(!TBB||Cond.size()< 1) return false
#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:170
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:445
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
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:137
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
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:61
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:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
const Instruction & front() const
Definition BasicBlock.h:462
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
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:63
unsigned getProgramAddressSpace() const
Definition DataLayout.h:271
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
size_type size() const
Definition MapVector.h:59
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:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
TypeSize getSizeInBits() const
Definition DataLayout.h:756
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition DataLayout.h:781
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:109
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
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.
LLVM_ABI Value * getAllocAlignment(const CallBase *V)
Gets the alignment argument for an aligned_alloc-like function based on the allocalign attribute.
@ 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.
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
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
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:388
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)
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.
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
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:376
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:416
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
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 >
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:475
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:487
@ NONE
Do not track a dependence between source and target.
Definition Attributor.h:488
@ REQUIRED
The target cannot be valid if the source is not.
Definition Attributor.h:486
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
LLVM_ABI Constant * getElidedFreeResult(const Value *V)
If this is a call to a free function that returns a value, return the value that will be returned whe...
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
LLVM_ABI Value * getFreedOperand(const CallBase *CB)
If this if a call to a free function, return the freed operand.
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
LLVM_ABI bool isRemovableAlloc(const CallBase *V)
Return true if this is a call to an allocation function that does not have side effects that we are r...
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:571
Function * getAssociatedFunction() const
Return the associated function, if any.
Definition Attributor.h:702
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
Definition Attributor.h:639
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
Definition Attributor.h:621
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:595
CallBase CallBaseContext
Definition Attributor.h:574
int getCalleeArgNo() const
Return the callee argument number of the associated value if it is an argument or call site argument,...
Definition Attributor.h:788
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
Definition Attributor.h:607
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Definition Attributor.h:644
Kind
The positions we distinguish in the IR.
Definition Attributor.h:577
@ IRP_ARGUMENT
An attribute for a function argument.
Definition Attributor.h:585
@ IRP_RETURNED
An attribute for the function return value.
Definition Attributor.h:581
@ IRP_CALL_SITE
An attribute for a call site (function scope).
Definition Attributor.h:584
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
Definition Attributor.h:582
@ IRP_FUNCTION
An attribute for a function (scope).
Definition Attributor.h:583
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
Definition Attributor.h:586
@ IRP_INVALID
An invalid position.
Definition Attributor.h:578
Instruction * getCtxI() const
Return the context instruction, if any.
Definition Attributor.h:755
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
Definition Attributor.h:628
Type * getAssociatedType() const
Return the type this abstract attribute is associated with.
Definition Attributor.h:777
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
Definition Attributor.h:614
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Definition Attributor.h:894
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Definition Attributor.h:769
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
Definition Attributor.h:688
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:797
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:667
Kind getPositionKind() const
Return the associated position kind.
Definition Attributor.h:844
bool isArgumentPosition() const
Return true if the position is an argument or call site argument.
Definition Attributor.h:876
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Definition Attributor.h:634
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
Definition Attributor.h:743
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.