49 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
54 if (DIFinder && TheModule)
59 NewInst->
setName(
I.getName() + NameSuffix);
63 hasCalls |= (isa<CallInst>(
I) && !isa<DbgInfoIntrinsic>(
I));
64 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
65 if (isa<ConstantInt>(AI->getArraySize()))
66 hasStaticAllocas =
true;
68 hasDynamicAllocas =
true;
76 BB != &BB->getParent()->getEntryBlock();
86 bool ModuleLevelChanges,
91 assert(NameSuffix &&
"NameSuffix cannot be null!");
95 assert(VMap.
count(&
I) &&
"No mapping from source argument specified!");
109 TypeMapper, Materializer));
116 if (
Argument *NewArg = dyn_cast<Argument>(VMap[&OldArg])) {
117 NewArgAttrs[NewArg->getArgNo()] =
118 OldAttrs.getParamAttributes(OldArg.getArgNo());
124 OldAttrs.getRetAttributes(), NewArgAttrs));
130 assert(!MustCloneSP || ModuleLevelChanges);
133 auto &MD = VMap.
MD();
134 MD[SP->getUnit()].reset(SP->getUnit());
135 MD[SP->getType()].reset(SP->getType());
145 for (
auto MD : MDs) {
150 TypeMapper, Materializer));
170 ModuleLevelChanges ? &DIFinder :
nullptr);
183 const_cast<BasicBlock*>(&BB));
194 VMap.
MD()[ISP].reset(ISP);
205 cast<BasicBlock>(VMap[&OldFunc->
front()])->getIterator(),
212 TypeMapper, Materializer);
224 std::vector<Type*> ArgTypes;
231 ArgTypes.push_back(
I.getType());
244 if (VMap.
count(&
I) == 0) {
246 VMap[&
I] = &*DestI++;
260 struct PruningFunctionCloner {
264 bool ModuleLevelChanges;
265 const char *NameSuffix;
272 : NewFunc(newFunc), OldFunc(oldFunc), VMap(valueMap),
273 ModuleLevelChanges(moduleLevelChanges), NameSuffix(nameSuffix),
274 CodeInfo(codeInfo) {}
280 std::vector<const BasicBlock*> &ToClone);
286 void PruningFunctionCloner::CloneBlock(
const BasicBlock *BB,
288 std::vector<const BasicBlock*> &ToClone){
310 const_cast<BasicBlock*>(BB));
314 bool hasCalls =
false, hasDynamicAllocas =
false, hasStaticAllocas =
false;
325 if (!isa<PHINode>(NewInst)) {
336 if (NewFunc != OldFunc)
337 if (
Value *MappedV = VMap.lookup(V))
349 NewInst->
setName(II->getName()+NameSuffix);
350 VMap[&*II] = NewInst;
352 hasCalls |= (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
356 if (CS.hasOperandBundles())
357 CodeInfo->OperandBundleCallSites.push_back(NewInst);
359 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
360 if (isa<ConstantInt>(AI->getArraySize()))
361 hasStaticAllocas =
true;
363 hasDynamicAllocas =
true;
369 bool TerminatorDone =
false;
370 if (
const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
371 if (BI->isConditional()) {
376 Value *V = VMap.lookup(BI->getCondition());
377 Cond = dyn_cast_or_null<ConstantInt>(V);
384 ToClone.push_back(Dest);
385 TerminatorDone =
true;
388 }
else if (
const SwitchInst *
SI = dyn_cast<SwitchInst>(OldTI)) {
392 Value *V = VMap.lookup(
SI->getCondition());
393 Cond = dyn_cast_or_null<ConstantInt>(V);
399 ToClone.push_back(Dest);
400 TerminatorDone =
true;
404 if (!TerminatorDone) {
409 VMap[OldTI] = NewInst;
413 if (CS.hasOperandBundles())
414 CodeInfo->OperandBundleCallSites.push_back(NewInst);
419 ToClone.push_back(Succ);
423 CodeInfo->ContainsCalls |= hasCalls;
424 CodeInfo->ContainsDynamicAllocas |= hasDynamicAllocas;
425 CodeInfo->ContainsDynamicAllocas |= hasStaticAllocas &&
436 bool ModuleLevelChanges,
438 const char *NameSuffix,
440 assert(NameSuffix &&
"NameSuffix cannot be null!");
450 assert(VMap.
count(&II) &&
"No mapping from source argument specified!");
453 PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
454 NameSuffix, CodeInfo);
460 StartingInst = &StartingBB->
front();
464 std::vector<const BasicBlock*> CloneWorklist;
465 PFC.CloneBlock(StartingBB, StartingInst->
getIterator(), CloneWorklist);
466 while (!CloneWorklist.empty()) {
468 CloneWorklist.pop_back();
469 PFC.CloneBlock(BB, BB->
begin(), CloneWorklist);
480 BasicBlock *NewBB = cast_or_null<BasicBlock>(V);
481 if (!NewBB)
continue;
488 for (
const PHINode &PN : BI.phis()) {
491 if (isa<PHINode>(VMap[&PN]))
501 TypeMapper, Materializer);
506 for (
unsigned phino = 0, e = PHIToResolve.
size(); phino != e; ) {
507 const PHINode *OPN = PHIToResolve[phino];
510 BasicBlock *NewBB = cast<BasicBlock>(VMap[OldBB]);
514 for (; phino != PHIToResolve.
size() &&
515 PHIToResolve[phino]->getParent() == OldBB; ++phino) {
516 OPN = PHIToResolve[phino];
517 PHINode *PN = cast<PHINode>(VMap[OPN]);
518 for (
unsigned pred = 0, e = NumPreds;
pred != e; ++
pred) {
520 if (
BasicBlock *MappedBlock = cast_or_null<BasicBlock>(V)) {
524 assert(InVal &&
"Unknown input value?");
543 assert(NumPreds < PN->getNumIncomingValues());
545 std::map<BasicBlock*, unsigned> PredCount;
559 for (
const auto &PCI : PredCount) {
561 for (
unsigned NumToRemove = PCI.second; NumToRemove; --NumToRemove)
570 PN = cast<PHINode>(NewBB->
begin());
574 while ((PN = dyn_cast<PHINode>(I++))) {
577 assert(VMap[&*OldI] == PN &&
"VMap mismatch");
594 for (
unsigned Idx = 0,
Size = PHIToResolve.
size(); Idx !=
Size; ++Idx)
595 if (isa<PHINode>(VMap[PHIToResolve[Idx]]))
596 Worklist.
insert(PHIToResolve[Idx]);
599 for (
unsigned Idx = 0; Idx != Worklist.
size(); ++Idx) {
600 const Value *OrigV = Worklist[Idx];
601 auto *
I = dyn_cast_or_null<Instruction>(VMap.
lookup(OrigV));
620 Worklist.
insert(cast<Instruction>(U));
623 I->replaceAllUsesWith(SimpleV);
627 I->eraseFromParent();
638 while (I != NewFunc->
end()) {
643 I->getSinglePredecessor() == &*
I)) {
676 I->getInstList().splice(I->end(), Dest->
getInstList());
690 if (
ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
704 bool ModuleLevelChanges,
706 const char *NameSuffix,
710 ModuleLevelChanges, Returns, NameSuffix, CodeInfo);
717 for (
auto *BB : Blocks)
718 for (
auto &Inst : *BB)
734 "Loop to be cloned cannot have inner loop");
745 assert(OrigPH &&
"No preheader");
748 VMap[OrigPH] = NewPH;
775 cast<BasicBlock>(VMap[IDomBB]));
779 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
781 F->getBasicBlockList().splice(Before->
getIterator(), F->getBasicBlockList(),
809 for (; StopAt != &*BI && BB->
getTerminator() != &*BI; ++BI) {
813 ValueMapping[&*BI] = New;
818 auto I = ValueMapping.
find(Inst);
819 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.
void push_back(const T &Elt)
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
Compute iterated dominance frontiers using a linear time algorithm.
size_type size() const
Determine the number of elements in the SetVector.
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DominatorTree *DT=nullptr)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
CloneFunction - Return a copy of the specified function and add it to that function's module...
void deleteValue()
Delete a pointer to a generic Value.
BasicBlock * getSuccessor(unsigned i) const
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.
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.
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)
CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, except that it does some simpl...
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...
const BasicBlock & getEntryBlock() const
This is a class that can be implemented by clients to materialize Values on demand.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Subclasses of this class are all able to terminate a basic block.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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
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
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
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)
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)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
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
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.
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)
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.
ClonedCodeInfo - 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
ContainsDynamicAllocas - This is set to true if the cloned code contains a 'dynamic' alloca...
const BasicBlock & front() const
void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT=nullptr)
Delete the specified block, which must have no predecessors.
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.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
A handle to a particular switch case.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void setPersonalityFn(Constant *Fn)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.