LLVM  14.0.0git
LowerConstantIntrinsics.cpp
Go to the documentation of this file.
1 //===- LowerConstantIntrinsics.cpp - Lower constant intrinsic calls -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass lowers all remaining 'objectsize' 'is.constant' intrinsic calls
10 // and provides constant propagation and basic CFG cleanup on the result.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Transforms/Scalar.h"
36 
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 #define DEBUG_TYPE "lower-is-constant-intrinsic"
41 
42 STATISTIC(IsConstantIntrinsicsHandled,
43  "Number of 'is.constant' intrinsic calls handled");
44 STATISTIC(ObjectSizeIntrinsicsHandled,
45  "Number of 'objectsize' intrinsic calls handled");
46 
48  if (auto *C = dyn_cast<Constant>(II->getOperand(0)))
49  if (C->isManifestConstant())
50  return ConstantInt::getTrue(II->getType());
51  return ConstantInt::getFalse(II->getType());
52 }
53 
55  Value *NewValue,
56  DomTreeUpdater *DTU) {
57  bool HasDeadBlocks = false;
58  SmallSetVector<Instruction *, 8> UnsimplifiedUsers;
59  replaceAndRecursivelySimplify(II, NewValue, nullptr, nullptr, nullptr,
60  &UnsimplifiedUsers);
61  // UnsimplifiedUsers can contain PHI nodes that may be removed when
62  // replacing the branch instructions, so use a value handle worklist
63  // to handle those possibly removed instructions.
64  SmallVector<WeakVH, 8> Worklist(UnsimplifiedUsers.begin(),
65  UnsimplifiedUsers.end());
66 
67  for (auto &VH : Worklist) {
68  BranchInst *BI = dyn_cast_or_null<BranchInst>(VH);
69  if (!BI)
70  continue;
71  if (BI->isUnconditional())
72  continue;
73 
75  if (match(BI->getOperand(0), m_Zero())) {
76  Target = BI->getSuccessor(1);
77  Other = BI->getSuccessor(0);
78  } else if (match(BI->getOperand(0), m_One())) {
79  Target = BI->getSuccessor(0);
80  Other = BI->getSuccessor(1);
81  } else {
82  Target = nullptr;
83  Other = nullptr;
84  }
85  if (Target && Target != Other) {
86  BasicBlock *Source = BI->getParent();
87  Other->removePredecessor(Source);
88  BI->eraseFromParent();
90  if (DTU)
92  if (pred_empty(Other))
93  HasDeadBlocks = true;
94  }
95  }
96  return HasDeadBlocks;
97 }
98 
100  DominatorTree *DT) {
102  if (DT)
104 
105  bool HasDeadBlocks = false;
106  const auto &DL = F.getParent()->getDataLayout();
108 
110  for (BasicBlock *BB : RPOT) {
111  for (Instruction &I: *BB) {
112  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
113  if (!II)
114  continue;
115  switch (II->getIntrinsicID()) {
116  default:
117  break;
118  case Intrinsic::is_constant:
119  case Intrinsic::objectsize:
120  Worklist.push_back(WeakTrackingVH(&I));
121  break;
122  }
123  }
124  }
125  for (WeakTrackingVH &VH: Worklist) {
126  // Items on the worklist can be mutated by earlier recursive replaces.
127  // This can remove the intrinsic as dead (VH == null), but also replace
128  // the intrinsic in place.
129  if (!VH)
130  continue;
131  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&*VH);
132  if (!II)
133  continue;
134  Value *NewValue;
135  switch (II->getIntrinsicID()) {
136  default:
137  continue;
138  case Intrinsic::is_constant:
139  NewValue = lowerIsConstantIntrinsic(II);
140  IsConstantIntrinsicsHandled++;
141  break;
142  case Intrinsic::objectsize:
143  NewValue = lowerObjectSizeCall(II, DL, TLI, true);
144  ObjectSizeIntrinsicsHandled++;
145  break;
146  }
147  HasDeadBlocks |= replaceConditionalBranchesOnConstant(
148  II, NewValue, DTU.hasValue() ? DTU.getPointer() : nullptr);
149  }
150  if (HasDeadBlocks)
151  removeUnreachableBlocks(F, DTU.hasValue() ? DTU.getPointer() : nullptr);
152  return !Worklist.empty();
153 }
154 
161  return PA;
162  }
163 
164  return PreservedAnalyses::all();
165 }
166 
167 namespace {
168 /// Legacy pass for lowering is.constant intrinsics out of the IR.
169 ///
170 /// When this pass is run over a function it converts is.constant intrinsics
171 /// into 'true' or 'false'. This complements the normal constant folding
172 /// to 'true' as part of Instruction Simplify passes.
173 class LowerConstantIntrinsics : public FunctionPass {
174 public:
175  static char ID;
176  LowerConstantIntrinsics() : FunctionPass(ID) {
178  }
179 
180  bool runOnFunction(Function &F) override {
181  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
182  const TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
183  DominatorTree *DT = nullptr;
184  if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
185  DT = &DTWP->getDomTree();
186  return lowerConstantIntrinsics(F, TLI, DT);
187  }
188 
189  void getAnalysisUsage(AnalysisUsage &AU) const override {
192  }
193 };
194 } // namespace
195 
197 INITIALIZE_PASS_BEGIN(LowerConstantIntrinsics, "lower-constant-intrinsics",
198  "Lower constant intrinsics", false, false)
200 INITIALIZE_PASS_END(LowerConstantIntrinsics, "lower-constant-intrinsics",
202 
204  return new LowerConstantIntrinsics();
205 }
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
constant
we should consider alternate ways to model stack dependencies Lots of things could be done in WebAssemblyTargetTransformInfo cpp there are numerous optimization related hooks that can be overridden in WebAssemblyTargetLowering Instead of the OptimizeReturned which should consider preserving the returned attribute through to MachineInstrs and extending the MemIntrinsicResults pass to do this optimization on calls too That would also let the WebAssemblyPeephole pass clean up dead defs for such as it does for stores Consider implementing and or getMachineCombinerPatterns Find a clean way to fix the problem which leads to the Shrink Wrapping pass being run after the WebAssembly PEI pass When setting multiple variables to the same constant
Definition: README.txt:91
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::WeakTrackingVH
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
IntrinsicInst.h
Scalar.h
llvm::DomTreeUpdater::applyUpdates
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
Definition: DomTreeUpdater.cpp:230
llvm::Function
Definition: Function.h:61
Pass.h
llvm::IntrinsicInst::getIntrinsicID
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:52
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:137
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
Statistic.h
DomTreeUpdater.h
Local.h
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:151
GlobalsModRef.h
llvm::removeUnreachableBlocks
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:2459
MemoryBuiltins.h
llvm::AMDGPU::Exp::Target
Target
Definition: SIDefines.h:739
llvm::Optional
Definition: APInt.h:33
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::DomTreeUpdater::UpdateStrategy::Lazy
@ Lazy
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::Optional::getPointer
constexpr const T * getPointer() const
Definition: Optional.h:280
llvm::Optional::hasValue
constexpr bool hasValue() const
Definition: Optional.h:288
llvm::SetVector< T, SmallVector< T, N >, SmallDenseSet< T, N > >::begin
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:82
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
Constants.h
llvm::PatternMatch::match
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
Intrinsics.h
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
lowerIsConstantIntrinsic
static Value * lowerIsConstantIntrinsic(IntrinsicInst *II)
Definition: LowerConstantIntrinsics.cpp:47
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
TargetLibraryInfo.h
false
Definition: StackSlotColoring.cpp:142
llvm::Instruction
Definition: Instruction.h:45
llvm::DominatorTreeWrapperPass
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:287
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::LowerConstantIntrinsicsPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
Run the pass over the function.
Definition: LowerConstantIntrinsics.cpp:156
llvm::DomTreeUpdater
Definition: DomTreeUpdater.h:28
PatternMatch.h
llvm::PatternMatch::m_One
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:513
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
BasicBlock.h
llvm::PatternMatch::m_Zero
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:535
llvm::Instruction::eraseFromParent
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:78
INITIALIZE_PASS_BEGIN
INITIALIZE_PASS_BEGIN(LowerConstantIntrinsics, "lower-constant-intrinsics", "Lower constant intrinsics", false, false) INITIALIZE_PASS_END(LowerConstantIntrinsics
lowerConstantIntrinsics
static bool lowerConstantIntrinsics(Function &F, const TargetLibraryInfo *TLI, DominatorTree *DT)
Definition: LowerConstantIntrinsics.cpp:99
INITIALIZE_PASS_DEPENDENCY
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
llvm::PreservedAnalyses::preserve
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:176
intrinsics
lower constant intrinsics
Definition: LowerConstantIntrinsics.cpp:200
llvm::Optional::emplace
void emplace(ArgTypes &&... Args)
Create a new object by constructing it in place with the given arguments.
Definition: Optional.h:264
llvm::BranchInst::Create
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
Definition: Instructions.h:3124
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::lowerObjectSizeCall
Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
Definition: MemoryBuiltins.cpp:525
llvm::replaceAndRecursivelySimplify
bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
Definition: InstructionSimplify.cpp:6369
replaceConditionalBranchesOnConstant
static bool replaceConditionalBranchesOnConstant(Instruction *II, Value *NewValue, DomTreeUpdater *DTU)
Definition: LowerConstantIntrinsics.cpp:54
llvm::BranchInst::isUnconditional
bool isUnconditional() const
Definition: Instructions.h:3146
llvm::Sched::Source
@ Source
Definition: TargetLowering.h:100
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
llvm::AnalysisUsage::addPreserved
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Definition: PassAnalysisSupport.h:98
DL
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Definition: AArch64SLSHardening.cpp:76
llvm::pred_empty
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:119
llvm::ConstantInt::getFalse
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:855
runOnFunction
static bool runOnFunction(Function &F, bool PostInlining)
Definition: EntryExitInstrumenter.cpp:69
llvm::ConstantInt::getTrue
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:848
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
llvm::initializeLowerConstantIntrinsicsPass
void initializeLowerConstantIntrinsicsPass(PassRegistry &)
llvm::AnalysisManager::getCachedResult
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:798
Function.h
llvm::TargetLibraryInfo
Provides information about what library functions are available for the current target.
Definition: TargetLibraryInfo.h:219
LowerConstantIntrinsics.h
llvm::ReversePostOrderTraversal
Definition: PostOrderIterator.h:290
llvm::IntrinsicInst
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:45
llvm::DominatorTreeAnalysis
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:252
llvm::SetVector< T, SmallVector< T, N >, SmallDenseSet< T, N > >::end
iterator end()
Get an iterator to the end of the SetVector.
Definition: SetVector.h:92
Instructions.h
PostOrderIterator.h
llvm::createLowerConstantIntrinsicsPass
FunctionPass * createLowerConstantIntrinsicsPass()
Definition: LowerConstantIntrinsics.cpp:203
Dominators.h
llvm::Instruction::getParent
const BasicBlock * getParent() const
Definition: Instruction.h:94
InstructionSimplify.h
llvm::GlobalsAAWrapperPass
Legacy wrapper pass to provide the GlobalsAAResult object.
Definition: GlobalsModRef.h:143
llvm::PatternMatch
Definition: PatternMatch.h:47
llvm::SmallSetVector
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:307
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:44
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
llvm::User::getOperand
Value * getOperand(unsigned i) const
Definition: User.h:169
llvm::BranchInst
Conditional or Unconditional Branch instruction.
Definition: Instructions.h:3068
InitializePasses.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
Debug.h
llvm::TargetLibraryAnalysis
Analysis pass providing the TargetLibraryInfo.
Definition: TargetLibraryInfo.h:438
llvm::BranchInst::getSuccessor
BasicBlock * getSuccessor(unsigned i) const
Definition: Instructions.h:3161
SetVector.h
llvm::DominatorTreeBase< BasicBlock, false >::Delete
static constexpr UpdateKind Delete
Definition: GenericDomTree.h:243
Other
Optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1172
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:37