LLVM 22.0.0git
Reg2Mem.cpp
Go to the documentation of this file.
1//===- Reg2Mem.cpp - Convert registers to allocas -------------------------===//
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 file demotes all registers to memory references. It is intended to be
10// the inverse of PromoteMemoryToRegister. By converting to loads, the only
11// values live across basic blocks are allocas and loads before phi nodes.
12// It is intended that this should make CFG hacking much easier.
13// To make later hacking easier, the entry block is split into two, such that
14// all introduced allocas and nothing else are in the entry block.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/Statistic.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/CFG.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Function.h"
27#include "llvm/IR/PassManager.h"
33#include <list>
34using namespace llvm;
35
36#define DEBUG_TYPE "reg2mem"
37
38STATISTIC(NumRegsDemoted, "Number of registers demoted");
39STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
40
41static bool valueEscapes(const Instruction &Inst) {
42 if (!Inst.getType()->isSized())
43 return false;
44
45 const BasicBlock *BB = Inst.getParent();
46 for (const User *U : Inst.users()) {
47 const Instruction *UI = cast<Instruction>(U);
48 if (UI->getParent() != BB || isa<PHINode>(UI))
49 return true;
50 }
51 return false;
52}
53
54static bool runPass(Function &F) {
55 // Insert all new allocas into entry block.
56 BasicBlock *BBEntry = &F.getEntryBlock();
57 assert(pred_empty(BBEntry) &&
58 "Entry block to function must not have predecessors!");
59
60 // Find first non-alloca instruction and create insertion point. This is
61 // safe if block is well-formed: it always have terminator, otherwise
62 // we'll get and assertion.
63 BasicBlock::iterator I = BBEntry->begin();
64 while (isa<AllocaInst>(I)) ++I;
65
66 CastInst *AllocaInsertionPoint = new BitCastInst(
68 Type::getInt32Ty(F.getContext()), "reg2mem alloca point", I);
69
70 // Find the escaped instructions. But don't create stack slots for
71 // allocas in entry block.
72 std::list<Instruction*> WorkList;
73 for (Instruction &I : instructions(F))
74 if (!(isa<AllocaInst>(I) && I.getParent() == BBEntry) && valueEscapes(I))
75 WorkList.push_front(&I);
76
77 // Demote escaped instructions
78 NumRegsDemoted += WorkList.size();
79 for (Instruction *I : WorkList)
80 DemoteRegToStack(*I, false, AllocaInsertionPoint->getIterator());
81
82 WorkList.clear();
83
84 // Find all phi's
85 for (BasicBlock &BB : F)
86 for (auto &Phi : BB.phis())
87 WorkList.push_front(&Phi);
88
89 // Demote phi nodes
90 NumPhisDemoted += WorkList.size();
91 for (Instruction *I : WorkList)
92 DemotePHIToStack(cast<PHINode>(I), AllocaInsertionPoint->getIterator());
93
94 return true;
95}
96
98 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
99 auto *LI = &AM.getResult<LoopAnalysis>(F);
101 bool Changed = runPass(F);
102 if (N == 0 && !Changed)
103 return PreservedAnalyses::all();
107 return PA;
108}
109
110namespace llvm {
111
113
115public:
116 static char ID;
117
119
129
130 bool runOnFunction(Function &F) override {
132 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
133
135 bool Changed = runPass(F);
136 return N != 0 || Changed;
137 }
138};
139} // namespace llvm
140
141INITIALIZE_PASS_BEGIN(RegToMemWrapperPass, "reg2mem", "", true, true)
145
146char RegToMemWrapperPass::ID = 0;
147
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static bool valueEscapes(const Instruction &Inst)
Definition Reg2Mem.cpp:41
static bool runPass(Function &F)
Definition Reg2Mem.cpp:54
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:167
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class represents a no-op cast from one type to another.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:448
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:322
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
FunctionPass(char &pid)
Definition Pass.h:316
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:570
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:597
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition Reg2Mem.cpp:97
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Reg2Mem.cpp:120
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Definition Reg2Mem.cpp:130
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:297
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
iterator_range< user_iterator > users()
Definition Value.h:426
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:134
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createRegToMemWrapperPass()
Definition Reg2Mem.cpp:148
LLVM_ABI AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by an Instruction and replaces it with a slot in the ...
LLVM_ABI AllocaInst * DemotePHIToStack(PHINode *P, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by a phi node and replaces it with a slot in the stac...
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:548
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
LLVM_ABI void initializeRegToMemWrapperPassPass(PassRegistry &)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:119
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
#define N
Option class for critical edge splitting.