Cloning.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Cloning.h - Clone various parts of LLVM programs ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines various functions that are used to clone chunks of LLVM
  15. // code for various purposes. This varies from copying whole modules into new
  16. // modules, to cloning functions with different arguments, to inlining
  17. // functions, to copying basic blocks to support loop unrolling or superblock
  18. // formation, etc.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_TRANSFORMS_UTILS_CLONING_H
  22. #define LLVM_TRANSFORMS_UTILS_CLONING_H
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/Analysis/AssumptionCache.h"
  26. #include "llvm/Analysis/InlineCost.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. #include "llvm/Transforms/Utils/ValueMapper.h"
  29. #include <functional>
  30. #include <memory>
  31. #include <vector>
  32. namespace llvm {
  33. class AAResults;
  34. class AllocaInst;
  35. class BasicBlock;
  36. class BlockFrequencyInfo;
  37. class CallGraph;
  38. class DebugInfoFinder;
  39. class DominatorTree;
  40. class Function;
  41. class Instruction;
  42. class Loop;
  43. class LoopInfo;
  44. class Module;
  45. class ProfileSummaryInfo;
  46. class ReturnInst;
  47. class DomTreeUpdater;
  48. /// Return an exact copy of the specified module
  49. std::unique_ptr<Module> CloneModule(const Module &M);
  50. std::unique_ptr<Module> CloneModule(const Module &M, ValueToValueMapTy &VMap);
  51. /// Return a copy of the specified module. The ShouldCloneDefinition function
  52. /// controls whether a specific GlobalValue's definition is cloned. If the
  53. /// function returns false, the module copy will contain an external reference
  54. /// in place of the global definition.
  55. std::unique_ptr<Module>
  56. CloneModule(const Module &M, ValueToValueMapTy &VMap,
  57. function_ref<bool(const GlobalValue *)> ShouldCloneDefinition);
  58. /// This struct can be used to capture information about code
  59. /// being cloned, while it is being cloned.
  60. struct ClonedCodeInfo {
  61. /// This is set to true if the cloned code contains a normal call instruction.
  62. bool ContainsCalls = false;
  63. /// This is set to true if the cloned code contains a 'dynamic' alloca.
  64. /// Dynamic allocas are allocas that are either not in the entry block or they
  65. /// are in the entry block but are not a constant size.
  66. bool ContainsDynamicAllocas = false;
  67. /// All cloned call sites that have operand bundles attached are appended to
  68. /// this vector. This vector may contain nulls or undefs if some of the
  69. /// originally inserted callsites were DCE'ed after they were cloned.
  70. std::vector<WeakTrackingVH> OperandBundleCallSites;
  71. /// Like VMap, but maps only unsimplified instructions. Values in the map
  72. /// may be dangling, it is only intended to be used via isSimplified(), to
  73. /// check whether the main VMap mapping involves simplification or not.
  74. DenseMap<const Value *, const Value *> OrigVMap;
  75. ClonedCodeInfo() = default;
  76. bool isSimplified(const Value *From, const Value *To) const {
  77. return OrigVMap.lookup(From) != To;
  78. }
  79. };
  80. /// Return a copy of the specified basic block, but without
  81. /// embedding the block into a particular function. The block returned is an
  82. /// exact copy of the specified basic block, without any remapping having been
  83. /// performed. Because of this, this is only suitable for applications where
  84. /// the basic block will be inserted into the same function that it was cloned
  85. /// from (loop unrolling would use this, for example).
  86. ///
  87. /// Also, note that this function makes a direct copy of the basic block, and
  88. /// can thus produce illegal LLVM code. In particular, it will copy any PHI
  89. /// nodes from the original block, even though there are no predecessors for the
  90. /// newly cloned block (thus, phi nodes will have to be updated). Also, this
  91. /// block will branch to the old successors of the original block: these
  92. /// successors will have to have any PHI nodes updated to account for the new
  93. /// incoming edges.
  94. ///
  95. /// The correlation between instructions in the source and result basic blocks
  96. /// is recorded in the VMap map.
  97. ///
  98. /// If you have a particular suffix you'd like to use to add to any cloned
  99. /// names, specify it as the optional third parameter.
  100. ///
  101. /// If you would like the basic block to be auto-inserted into the end of a
  102. /// function, you can specify it as the optional fourth parameter.
  103. ///
  104. /// If you would like to collect additional information about the cloned
  105. /// function, you can specify a ClonedCodeInfo object with the optional fifth
  106. /// parameter.
  107. BasicBlock *CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap,
  108. const Twine &NameSuffix = "", Function *F = nullptr,
  109. ClonedCodeInfo *CodeInfo = nullptr,
  110. DebugInfoFinder *DIFinder = nullptr);
  111. /// Return a copy of the specified function and add it to that
  112. /// function's module. Also, any references specified in the VMap are changed
  113. /// to refer to their mapped value instead of the original one. If any of the
  114. /// arguments to the function are in the VMap, the arguments are deleted from
  115. /// the resultant function. The VMap is updated to include mappings from all of
  116. /// the instructions and basicblocks in the function from their old to new
  117. /// values. The final argument captures information about the cloned code if
  118. /// non-null.
  119. ///
  120. /// \pre VMap contains no non-identity GlobalValue mappings.
  121. ///
  122. Function *CloneFunction(Function *F, ValueToValueMapTy &VMap,
  123. ClonedCodeInfo *CodeInfo = nullptr);
  124. enum class CloneFunctionChangeType {
  125. LocalChangesOnly,
  126. GlobalChanges,
  127. DifferentModule,
  128. ClonedModule,
  129. };
  130. /// Clone OldFunc into NewFunc, transforming the old arguments into references
  131. /// to VMap values. Note that if NewFunc already has basic blocks, the ones
  132. /// cloned into it will be added to the end of the function. This function
  133. /// fills in a list of return instructions, and can optionally remap types
  134. /// and/or append the specified suffix to all values cloned.
  135. ///
  136. /// If \p Changes is \a CloneFunctionChangeType::LocalChangesOnly, VMap is
  137. /// required to contain no non-identity GlobalValue mappings. Otherwise,
  138. /// referenced metadata will be cloned.
  139. ///
  140. /// If \p Changes is less than \a CloneFunctionChangeType::DifferentModule
  141. /// indicating cloning into the same module (even if it's LocalChangesOnly), if
  142. /// debug info metadata transitively references a \a DISubprogram, it will be
  143. /// cloned, effectively upgrading \p Changes to GlobalChanges while suppressing
  144. /// cloning of types and compile units.
  145. ///
  146. /// If \p Changes is \a CloneFunctionChangeType::DifferentModule, the new
  147. /// module's \c !llvm.dbg.cu will get updated with any newly created compile
  148. /// units. (\a CloneFunctionChangeType::ClonedModule leaves that work for the
  149. /// caller.)
  150. ///
  151. /// FIXME: Consider simplifying this function by splitting out \a
  152. /// CloneFunctionMetadataInto() and expecting / updating callers to call it
  153. /// first when / how it's needed.
  154. void CloneFunctionInto(Function *NewFunc, const Function *OldFunc,
  155. ValueToValueMapTy &VMap, CloneFunctionChangeType Changes,
  156. SmallVectorImpl<ReturnInst *> &Returns,
  157. const char *NameSuffix = "",
  158. ClonedCodeInfo *CodeInfo = nullptr,
  159. ValueMapTypeRemapper *TypeMapper = nullptr,
  160. ValueMaterializer *Materializer = nullptr);
  161. void CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
  162. const Instruction *StartingInst,
  163. ValueToValueMapTy &VMap, bool ModuleLevelChanges,
  164. SmallVectorImpl<ReturnInst *> &Returns,
  165. const char *NameSuffix = "",
  166. ClonedCodeInfo *CodeInfo = nullptr);
  167. /// This works exactly like CloneFunctionInto,
  168. /// except that it does some simple constant prop and DCE on the fly. The
  169. /// effect of this is to copy significantly less code in cases where (for
  170. /// example) a function call with constant arguments is inlined, and those
  171. /// constant arguments cause a significant amount of code in the callee to be
  172. /// dead. Since this doesn't produce an exactly copy of the input, it can't be
  173. /// used for things like CloneFunction or CloneModule.
  174. ///
  175. /// If ModuleLevelChanges is false, VMap contains no non-identity GlobalValue
  176. /// mappings.
  177. ///
  178. void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
  179. ValueToValueMapTy &VMap, bool ModuleLevelChanges,
  180. SmallVectorImpl<ReturnInst*> &Returns,
  181. const char *NameSuffix = "",
  182. ClonedCodeInfo *CodeInfo = nullptr);
  183. /// This class captures the data input to the InlineFunction call, and records
  184. /// the auxiliary results produced by it.
  185. class InlineFunctionInfo {
  186. public:
  187. explicit InlineFunctionInfo(
  188. CallGraph *cg = nullptr,
  189. function_ref<AssumptionCache &(Function &)> GetAssumptionCache = nullptr,
  190. ProfileSummaryInfo *PSI = nullptr,
  191. BlockFrequencyInfo *CallerBFI = nullptr,
  192. BlockFrequencyInfo *CalleeBFI = nullptr, bool UpdateProfile = true)
  193. : CG(cg), GetAssumptionCache(GetAssumptionCache), PSI(PSI),
  194. CallerBFI(CallerBFI), CalleeBFI(CalleeBFI),
  195. UpdateProfile(UpdateProfile) {}
  196. /// If non-null, InlineFunction will update the callgraph to reflect the
  197. /// changes it makes.
  198. CallGraph *CG;
  199. function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
  200. ProfileSummaryInfo *PSI;
  201. BlockFrequencyInfo *CallerBFI, *CalleeBFI;
  202. /// InlineFunction fills this in with all static allocas that get copied into
  203. /// the caller.
  204. SmallVector<AllocaInst *, 4> StaticAllocas;
  205. /// InlineFunction fills this in with callsites that were inlined from the
  206. /// callee. This is only filled in if CG is non-null.
  207. SmallVector<WeakTrackingVH, 8> InlinedCalls;
  208. /// All of the new call sites inlined into the caller.
  209. ///
  210. /// 'InlineFunction' fills this in by scanning the inlined instructions, and
  211. /// only if CG is null. If CG is non-null, instead the value handle
  212. /// `InlinedCalls` above is used.
  213. SmallVector<CallBase *, 8> InlinedCallSites;
  214. /// Update profile for callee as well as cloned version. We need to do this
  215. /// for regular inlining, but not for inlining from sample profile loader.
  216. bool UpdateProfile;
  217. void reset() {
  218. StaticAllocas.clear();
  219. InlinedCalls.clear();
  220. InlinedCallSites.clear();
  221. }
  222. };
  223. /// This function inlines the called function into the basic
  224. /// block of the caller. This returns false if it is not possible to inline
  225. /// this call. The program is still in a well defined state if this occurs
  226. /// though.
  227. ///
  228. /// Note that this only does one level of inlining. For example, if the
  229. /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
  230. /// exists in the instruction stream. Similarly this will inline a recursive
  231. /// function by one level.
  232. ///
  233. /// Note that while this routine is allowed to cleanup and optimize the
  234. /// *inlined* code to minimize the actual inserted code, it must not delete
  235. /// code in the caller as users of this routine may have pointers to
  236. /// instructions in the caller that need to remain stable.
  237. ///
  238. /// If ForwardVarArgsTo is passed, inlining a function with varargs is allowed
  239. /// and all varargs at the callsite will be passed to any calls to
  240. /// ForwardVarArgsTo. The caller of InlineFunction has to make sure any varargs
  241. /// are only used by ForwardVarArgsTo.
  242. InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
  243. AAResults *CalleeAAR = nullptr,
  244. bool InsertLifetime = true,
  245. Function *ForwardVarArgsTo = nullptr);
  246. /// Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
  247. /// Blocks.
  248. ///
  249. /// Updates LoopInfo and DominatorTree assuming the loop is dominated by block
  250. /// \p LoopDomBB. Insert the new blocks before block specified in \p Before.
  251. /// Note: Only innermost loops are supported.
  252. Loop *cloneLoopWithPreheader(BasicBlock *Before, BasicBlock *LoopDomBB,
  253. Loop *OrigLoop, ValueToValueMapTy &VMap,
  254. const Twine &NameSuffix, LoopInfo *LI,
  255. DominatorTree *DT,
  256. SmallVectorImpl<BasicBlock *> &Blocks);
  257. /// Remaps instructions in \p Blocks using the mapping in \p VMap.
  258. void remapInstructionsInBlocks(const SmallVectorImpl<BasicBlock *> &Blocks,
  259. ValueToValueMapTy &VMap);
  260. /// Split edge between BB and PredBB and duplicate all non-Phi instructions
  261. /// from BB between its beginning and the StopAt instruction into the split
  262. /// block. Phi nodes are not duplicated, but their uses are handled correctly:
  263. /// we replace them with the uses of corresponding Phi inputs. ValueMapping
  264. /// is used to map the original instructions from BB to their newly-created
  265. /// copies. Returns the split block.
  266. BasicBlock *DuplicateInstructionsInSplitBetween(BasicBlock *BB,
  267. BasicBlock *PredBB,
  268. Instruction *StopAt,
  269. ValueToValueMapTy &ValueMapping,
  270. DomTreeUpdater &DTU);
  271. /// Updates profile information by adjusting the entry count by adding
  272. /// EntryDelta then scaling callsite information by the new count divided by the
  273. /// old count. VMap is used during inlinng to also update the new clone
  274. void updateProfileCallee(
  275. Function *Callee, int64_t EntryDelta,
  276. const ValueMap<const Value *, WeakTrackingVH> *VMap = nullptr);
  277. /// Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified
  278. /// basic blocks and extract their scope. These are candidates for duplication
  279. /// when cloning.
  280. void identifyNoAliasScopesToClone(
  281. ArrayRef<BasicBlock *> BBs, SmallVectorImpl<MDNode *> &NoAliasDeclScopes);
  282. /// Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified
  283. /// instruction range and extract their scope. These are candidates for
  284. /// duplication when cloning.
  285. void identifyNoAliasScopesToClone(
  286. BasicBlock::iterator Start, BasicBlock::iterator End,
  287. SmallVectorImpl<MDNode *> &NoAliasDeclScopes);
  288. /// Duplicate the specified list of noalias decl scopes.
  289. /// The 'Ext' string is added as an extension to the name.
  290. /// Afterwards, the ClonedScopes contains the mapping of the original scope
  291. /// MDNode onto the cloned scope.
  292. /// Be aware that the cloned scopes are still part of the original scope domain.
  293. void cloneNoAliasScopes(
  294. ArrayRef<MDNode *> NoAliasDeclScopes,
  295. DenseMap<MDNode *, MDNode *> &ClonedScopes,
  296. StringRef Ext, LLVMContext &Context);
  297. /// Adapt the metadata for the specified instruction according to the
  298. /// provided mapping. This is normally used after cloning an instruction, when
  299. /// some noalias scopes needed to be cloned.
  300. void adaptNoAliasScopes(
  301. llvm::Instruction *I, const DenseMap<MDNode *, MDNode *> &ClonedScopes,
  302. LLVMContext &Context);
  303. /// Clone the specified noalias decl scopes. Then adapt all instructions in the
  304. /// NewBlocks basicblocks to the cloned versions.
  305. /// 'Ext' will be added to the duplicate scope names.
  306. void cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
  307. ArrayRef<BasicBlock *> NewBlocks,
  308. LLVMContext &Context, StringRef Ext);
  309. /// Clone the specified noalias decl scopes. Then adapt all instructions in the
  310. /// [IStart, IEnd] (IEnd included !) range to the cloned versions. 'Ext' will be
  311. /// added to the duplicate scope names.
  312. void cloneAndAdaptNoAliasScopes(ArrayRef<MDNode *> NoAliasDeclScopes,
  313. Instruction *IStart, Instruction *IEnd,
  314. LLVMContext &Context, StringRef Ext);
  315. } // end namespace llvm
  316. #endif // LLVM_TRANSFORMS_UTILS_CLONING_H
  317. #ifdef __GNUC__
  318. #pragma GCC diagnostic pop
  319. #endif