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;
59  replaceAndRecursivelySimplify(II, NewValue, nullptr, nullptr, nullptr,
60  &Worklist);
61  for (auto I : Worklist) {
62  BranchInst *BI = dyn_cast<BranchInst>(I);
63  if (!BI)
64  continue;
65  if (BI->isUnconditional())
66  continue;
67 
69  if (match(BI->getOperand(0), m_Zero())) {
70  Target = BI->getSuccessor(1);
71  Other = BI->getSuccessor(0);
72  } else if (match(BI->getOperand(0), m_One())) {
73  Target = BI->getSuccessor(0);
74  Other = BI->getSuccessor(1);
75  } else {
76  Target = nullptr;
77  Other = nullptr;
78  }
79  if (Target && Target != Other) {
80  BasicBlock *Source = BI->getParent();
81  Other->removePredecessor(Source);
82  BI->eraseFromParent();
84  if (DTU)
86  if (pred_empty(Other))
87  HasDeadBlocks = true;
88  }
89  }
90  return HasDeadBlocks;
91 }
92 
94  DominatorTree *DT) {
96  if (DT)
98 
99  bool HasDeadBlocks = false;
100  const auto &DL = F.getParent()->getDataLayout();
102 
104  for (BasicBlock *BB : RPOT) {
105  for (Instruction &I: *BB) {
106  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
107  if (!II)
108  continue;
109  switch (II->getIntrinsicID()) {
110  default:
111  break;
112  case Intrinsic::is_constant:
113  case Intrinsic::objectsize:
114  Worklist.push_back(WeakTrackingVH(&I));
115  break;
116  }
117  }
118  }
119  for (WeakTrackingVH &VH: Worklist) {
120  // Items on the worklist can be mutated by earlier recursive replaces.
121  // This can remove the intrinsic as dead (VH == null), but also replace
122  // the intrinsic in place.
123  if (!VH)
124  continue;
125  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&*VH);
126  if (!II)
127  continue;
128  Value *NewValue;
129  switch (II->getIntrinsicID()) {
130  default:
131  continue;
132  case Intrinsic::is_constant:
133  NewValue = lowerIsConstantIntrinsic(II);
134  IsConstantIntrinsicsHandled++;
135  break;
136  case Intrinsic::objectsize:
137  NewValue = lowerObjectSizeCall(II, DL, TLI, true);
138  ObjectSizeIntrinsicsHandled++;
139  break;
140  }
141  HasDeadBlocks |= replaceConditionalBranchesOnConstant(
142  II, NewValue, DTU.hasValue() ? DTU.getPointer() : nullptr);
143  }
144  if (HasDeadBlocks)
145  removeUnreachableBlocks(F, DTU.hasValue() ? DTU.getPointer() : nullptr);
146  return !Worklist.empty();
147 }
148 
155  return PA;
156  }
157 
158  return PreservedAnalyses::all();
159 }
160 
161 namespace {
162 /// Legacy pass for lowering is.constant intrinsics out of the IR.
163 ///
164 /// When this pass is run over a function it converts is.constant intrinsics
165 /// into 'true' or 'false'. This complements the normal constant folding
166 /// to 'true' as part of Instruction Simplify passes.
167 class LowerConstantIntrinsics : public FunctionPass {
168 public:
169  static char ID;
170  LowerConstantIntrinsics() : FunctionPass(ID) {
172  }
173 
174  bool runOnFunction(Function &F) override {
175  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
176  const TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
177  DominatorTree *DT = nullptr;
178  if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
179  DT = &DTWP->getDomTree();
180  return lowerConstantIntrinsics(F, TLI, DT);
181  }
182 
183  void getAnalysisUsage(AnalysisUsage &AU) const override {
186  }
187 };
188 } // namespace
189 
191 INITIALIZE_PASS_BEGIN(LowerConstantIntrinsics, "lower-constant-intrinsics",
192  "Lower constant intrinsics", false, false)
194 INITIALIZE_PASS_END(LowerConstantIntrinsics, "lower-constant-intrinsics",
196 
198  return new LowerConstantIntrinsics();
199 }
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::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:150
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:93
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:194
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:3116
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:526
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:3138
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
Instructions.h
PostOrderIterator.h
llvm::createLowerConstantIntrinsicsPass
FunctionPass * createLowerConstantIntrinsicsPass()
Definition: LowerConstantIntrinsics.cpp:197
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:3060
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:3153
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