50 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
55 if (DIFinder && TheModule)
60 NewInst->
setName(
I.getName() + NameSuffix);
64 hasCalls |= (isa<CallInst>(
I) && !isa<DbgInfoIntrinsic>(
I));
65 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
66 if (isa<ConstantInt>(AI->getArraySize()))
67 hasStaticAllocas =
true;
69 hasDynamicAllocas =
true;
77 BB != &BB->getParent()->getEntryBlock();
87 bool ModuleLevelChanges,
92 assert(NameSuffix &&
"NameSuffix cannot be null!");
96 assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
110 TypeMapper, Materializer));
117 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
118 NewArgAttrs[NewArg->getArgNo()] =
119 OldAttrs.getParamAttributes(OldArg.getArgNo());
125 OldAttrs.getRetAttributes(), NewArgAttrs));
131 assert(!MustCloneSP || ModuleLevelChanges);
134 auto &MD = VMap.
MD();
135 MD[SP->getUnit()].reset(SP->getUnit());
136 MD[SP->getType()].reset(SP->getType());
146 for (
auto MD : MDs) {
151 TypeMapper, Materializer));
171 ModuleLevelChanges ? &DIFinder :
nullptr);
184 const_cast<BasicBlock*>(&BB));
195 VMap.
MD()[ISP].reset(ISP);
206 cast<BasicBlock>(VMap[&OldFunc->
front()])->getIterator(),
213 TypeMapper, Materializer);
225 std::vector<Type*> ArgTypes;
232 ArgTypes.push_back(
I.getType());
245 if (VMap.
count(&
I) == 0) {
247 VMap[&
I] = &*DestI++;
261 struct PruningFunctionCloner {
265 bool ModuleLevelChanges;
266 const char *NameSuffix;
273 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
274 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
275 CodeInfo(codeInfo) {}
281 std::vector<const BasicBlock*> &ToClone);
287 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
289 std::vector<const BasicBlock*> &ToClone){
311 const_cast<BasicBlock*>(BB));
315 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
326 if (!isa<PHINode>(NewInst)) {
337 if (NewFunc != OldFunc)
338 if (
Value *MappedV = VMap.lookup(V))
350 NewInst->
setName(II->getName()+NameSuffix);
351 VMap[&*II] = NewInst;
353 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
357 if (CS.hasOperandBundles())
358 CodeInfo->OperandBundleCallSites.push_back(NewInst);
360 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
361 if (isa<ConstantInt>(AI->getArraySize()))
362 hasStaticAllocas =
true;
364 hasDynamicAllocas =
true;
370 bool TerminatorDone =
false;
371 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
372 if (BI->isConditional()) {
377 Value *V = VMap.lookup(BI->getCondition());
378 Cond = dyn_cast_or_null<ConstantInt>(V);
385 ToClone.push_back(Dest);
386 TerminatorDone =
true;
389 }
else if (
const SwitchInst *
SI = dyn_cast<SwitchInst>(OldTI)) {
393 Value *V = VMap.lookup(
SI->getCondition());
394 Cond = dyn_cast_or_null<ConstantInt>(V);
400 ToClone.push_back(Dest);
401 TerminatorDone =
true;
405 if (!TerminatorDone) {
410 VMap[OldTI] = NewInst;
414 if (CS.hasOperandBundles())
415 CodeInfo->OperandBundleCallSites.push_back(NewInst);
420 ToClone.push_back(Succ);
424 CodeInfo->ContainsCalls |= hasCalls;
425 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
426 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
437 bool ModuleLevelChanges,
439 const char *NameSuffix,
441 assert(NameSuffix &&
"NameSuffix cannot be null!");
451 assert(VMap.
count(&II) &&
"No mapping from source argument specified!");
454 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
455 NameSuffix, CodeInfo);
461 StartingInst = &StartingBB->
front();
465 std::vector<const BasicBlock*> CloneWorklist;
466 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
467 while (!CloneWorklist.empty()) {
469 CloneWorklist.pop_back();
470 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
481 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
482 if (!NewBB)
continue;
489 for (
const PHINode &PN : BI.phis()) {
492 if (isa<PHINode>(VMap[&PN]))
502 TypeMapper, Materializer);
507 for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e; ) {
508 const PHINode *OPN = PHIToResolve[phino];
511 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
515 for (; phino != PHIToResolve.
size() &&
516 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
517 OPN = PHIToResolve[phino];
518 PHINode *PN = cast<PHINode>(VMap[OPN]);
519 for (
unsigned pred = 0, e = NumPreds;
pred != e; ++
pred) {
521 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
525 assert(InVal &&
"Unknown input value?");
544 assert(NumPreds < PN->getNumIncomingValues());
546 std::map<BasicBlock*, unsigned> PredCount;
560 for (
const auto &PCI : PredCount) {
562 for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
571 PN = cast<PHINode>(NewBB->
begin());
575 while ((PN = dyn_cast<PHINode>(I++))) {
578 assert(VMap[&*OldI] == PN &&
"VMap mismatch");
595 for (
unsigned Idx = 0,
Size = PHIToResolve.
size(); Idx !=
Size; ++Idx)
596 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
597 Worklist.
insert(PHIToResolve[Idx]);
600 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
601 const Value *OrigV = Worklist[Idx];
602 auto *
I = dyn_cast_or_null<Instruction>(VMap.
lookup(OrigV));
621 Worklist.
insert(cast<Instruction>(U));
624 I->replaceAllUsesWith(SimpleV);
628 I->eraseFromParent();
639 while (I != NewFunc->
end()) {
660 I->getSinglePredecessor() == &*
I)) {
686 I->getInstList().splice(I->end(), Dest->
getInstList());
700 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
714 bool ModuleLevelChanges,
716 const char *NameSuffix,
720 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
727 for (
auto *BB : Blocks)
728 for (
auto &Inst : *BB)
744 "Loop to be cloned cannot have inner loop");
755 assert(OrigPH &&
"No preheader");
758 VMap[OrigPH] = NewPH;
785 cast<BasicBlock>(VMap[IDomBB]));
789 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
791 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
804 "There must be a single edge between PredBB and BB!");
826 for (; StopAt != &*BI && BB->
getTerminator() != &*BI; ++BI) {
830 ValueMapping[&*BI] = New;
835 auto I = ValueMapping.
find(Inst);
836 if (
I != ValueMapping.
end())
Return a value (possibly void), from a function.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
This class represents an incoming formal argument to a Function.
DiagnosticInfoOptimizationBase::Argument NV
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
This class represents lattice values for constants.
size_type size() const
Determine the number of elements in the SetVector.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(const T &Elt)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Delete the specified block, which must have no predecessors.
void deleteValue()
Delete a pointer to a generic Value.
BasicBlock * getSuccessor(unsigned i) const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
LLVMContext & getContext() const
Get the context in which this basic block lives.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Lookup or compute a mapping for a piece of metadata.
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values...
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static constexpr UpdateKind Delete
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Utility to find all debug info in a module.
void setName(const Twine &Name)
Change the name of the value.
BlockT * getHeader() const
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, Instruction *TheCall=nullptr)
This works exactly like CloneFunctionInto, except that it does some simple constant prop and DCE on t...
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
iterator find(const KeyT &Val)
iterator_range< type_iterator > types() const
AttributeList getAttributes() const
Return the attribute list for this Function.
bool hasPersonalityFn() const
Check whether this function has a personality function.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
const BasicBlock & getEntryBlock() const
This is a class that can be implemented by clients to materialize Values on demand.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
DISubprogram * getSubprogram() const
Get the attached subprogram.
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
const Instruction & back() const
unsigned getAddressSpace() const
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc, const Instruction *StartingInst, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr)
This works like CloneAndPruneFunctionInto, except that it does not clone the entire function...
iterator_range< compile_unit_iterator > compile_units() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
void processInstruction(const Module &M, const Instruction &I)
Process a single instruction and collect debug info anchors.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LoopT * AllocateLoop(ArgsTy &&... Args)
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates, bool ForceRemoveDuplicates=false)
Apply updates on all available trees.
Type * getReturnType() const
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setOperand(unsigned i, Value *Val)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void push_back(pointer val)
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
bool ContainsCalls
This is set to true if the cloned code contains a normal call instruction.
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
This struct can be used to capture information about code being cloned, while it is being cloned...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Helper struct that represents how a value is mapped through different register banks.
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool ContainsDynamicAllocas
This is set to true if the cloned code contains a 'dynamic' alloca.
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
succ_range successors(Instruction *I)
iterator_range< subprogram_iterator > subprograms() const
Loop * cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB, Loop *OrigLoop, ValueToValueMapTy &VMap, const Twine &NameSuffix, LoopInfo *LI, DominatorTree *DT, SmallVectorImpl< BasicBlock *> &Blocks)
Clones a loop OrigLoop.
A handle to a particular switch case.
void setPersonalityFn(Constant *Fn)
void setIncomingValue(unsigned i, Value *V)
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock *> &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.