GCStrategy.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. //===-- GCStrategy.cpp - Garbage collection infrastructure -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements target- and collector-independent garbage collection
  11. // infrastructure.
  12. //
  13. // GCMachineCodeAnalysis identifies the GC safe points in the machine code.
  14. // Roots are identified in SelectionDAGISel.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/CodeGen/GCStrategy.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineFunctionPass.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineModuleInfo.h"
  22. #include "llvm/CodeGen/Passes.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Target/TargetFrameLowering.h"
  30. #include "llvm/Target/TargetInstrInfo.h"
  31. #include "llvm/Target/TargetMachine.h"
  32. #include "llvm/Target/TargetRegisterInfo.h"
  33. #include "llvm/Target/TargetSubtargetInfo.h"
  34. using namespace llvm;
  35. namespace {
  36. /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
  37. /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
  38. /// directed by the GCStrategy. It also performs automatic root initialization
  39. /// and custom intrinsic lowering.
  40. class LowerIntrinsics : public FunctionPass {
  41. static bool NeedsDefaultLoweringPass(const GCStrategy &C);
  42. static bool NeedsCustomLoweringPass(const GCStrategy &C);
  43. static bool CouldBecomeSafePoint(Instruction *I);
  44. bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
  45. static bool InsertRootInitializers(Function &F,
  46. AllocaInst **Roots, unsigned Count);
  47. public:
  48. static char ID;
  49. LowerIntrinsics();
  50. const char *getPassName() const override;
  51. void getAnalysisUsage(AnalysisUsage &AU) const override;
  52. bool doInitialization(Module &M) override;
  53. bool runOnFunction(Function &F) override;
  54. };
  55. /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
  56. /// function representation to identify safe points for the garbage collector
  57. /// in the machine code. It inserts labels at safe points and populates a
  58. /// GCMetadata record for each function.
  59. class GCMachineCodeAnalysis : public MachineFunctionPass {
  60. const TargetMachine *TM;
  61. GCFunctionInfo *FI;
  62. MachineModuleInfo *MMI;
  63. const TargetInstrInfo *TII;
  64. void FindSafePoints(MachineFunction &MF);
  65. void VisitCallPoint(MachineBasicBlock::iterator MI);
  66. MCSymbol *InsertLabel(MachineBasicBlock &MBB,
  67. MachineBasicBlock::iterator MI,
  68. DebugLoc DL) const;
  69. void FindStackOffsets(MachineFunction &MF);
  70. public:
  71. static char ID;
  72. GCMachineCodeAnalysis();
  73. void getAnalysisUsage(AnalysisUsage &AU) const override;
  74. bool runOnMachineFunction(MachineFunction &MF) override;
  75. };
  76. }
  77. // -----------------------------------------------------------------------------
  78. GCStrategy::GCStrategy() :
  79. NeededSafePoints(0),
  80. CustomReadBarriers(false),
  81. CustomWriteBarriers(false),
  82. CustomRoots(false),
  83. CustomSafePoints(false),
  84. InitRoots(true),
  85. UsesMetadata(false)
  86. {}
  87. bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
  88. bool GCStrategy::performCustomLowering(Function &F) {
  89. dbgs() << "gc " << getName() << " must override performCustomLowering.\n";
  90. llvm_unreachable("must override performCustomLowering");
  91. }
  92. bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction &F) {
  93. dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
  94. llvm_unreachable(nullptr);
  95. }
  96. GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
  97. Functions.push_back(make_unique<GCFunctionInfo>(F, *this));
  98. return Functions.back().get();
  99. }
  100. // -----------------------------------------------------------------------------
  101. INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering",
  102. false, false)
  103. INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
  104. INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
  105. FunctionPass *llvm::createGCLoweringPass() {
  106. return new LowerIntrinsics();
  107. }
  108. char LowerIntrinsics::ID = 0;
  109. LowerIntrinsics::LowerIntrinsics()
  110. : FunctionPass(ID) {
  111. initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
  112. }
  113. const char *LowerIntrinsics::getPassName() const {
  114. return "Lower Garbage Collection Instructions";
  115. }
  116. void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
  117. FunctionPass::getAnalysisUsage(AU);
  118. AU.addRequired<GCModuleInfo>();
  119. AU.addPreserved<DominatorTreeWrapperPass>();
  120. }
  121. /// doInitialization - If this module uses the GC intrinsics, find them now.
  122. bool LowerIntrinsics::doInitialization(Module &M) {
  123. // FIXME: This is rather antisocial in the context of a JIT since it performs
  124. // work against the entire module. But this cannot be done at
  125. // runFunction time (initializeCustomLowering likely needs to change
  126. // the module).
  127. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  128. assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
  129. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  130. if (!I->isDeclaration() && I->hasGC())
  131. MI->getFunctionInfo(*I); // Instantiate the GC strategy.
  132. bool MadeChange = false;
  133. for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
  134. if (NeedsCustomLoweringPass(**I))
  135. if ((*I)->initializeCustomLowering(M))
  136. MadeChange = true;
  137. return MadeChange;
  138. }
  139. bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roots,
  140. unsigned Count) {
  141. // Scroll past alloca instructions.
  142. BasicBlock::iterator IP = F.getEntryBlock().begin();
  143. while (isa<AllocaInst>(IP)) ++IP;
  144. // Search for initializers in the initial BB.
  145. SmallPtrSet<AllocaInst*,16> InitedRoots;
  146. for (; !CouldBecomeSafePoint(IP); ++IP)
  147. if (StoreInst *SI = dyn_cast<StoreInst>(IP))
  148. if (AllocaInst *AI =
  149. dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
  150. InitedRoots.insert(AI);
  151. // Add root initializers.
  152. bool MadeChange = false;
  153. for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
  154. if (!InitedRoots.count(*I)) {
  155. StoreInst* SI = new StoreInst(ConstantPointerNull::get(cast<PointerType>(
  156. cast<PointerType>((*I)->getType())->getElementType())),
  157. *I);
  158. SI->insertAfter(*I);
  159. MadeChange = true;
  160. }
  161. return MadeChange;
  162. }
  163. bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
  164. // Default lowering is necessary only if read or write barriers have a default
  165. // action. The default for roots is no action.
  166. return !C.customWriteBarrier()
  167. || !C.customReadBarrier()
  168. || C.initializeRoots();
  169. }
  170. bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
  171. // Custom lowering is only necessary if enabled for some action.
  172. return C.customWriteBarrier()
  173. || C.customReadBarrier()
  174. || C.customRoots();
  175. }
  176. /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
  177. /// instruction could introduce a safe point.
  178. bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
  179. // The natural definition of instructions which could introduce safe points
  180. // are:
  181. //
  182. // - call, invoke (AfterCall, BeforeCall)
  183. // - phis (Loops)
  184. // - invoke, ret, unwind (Exit)
  185. //
  186. // However, instructions as seemingly inoccuous as arithmetic can become
  187. // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
  188. // it is necessary to take a conservative approach.
  189. if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
  190. isa<StoreInst>(I) || isa<LoadInst>(I))
  191. return false;
  192. // llvm.gcroot is safe because it doesn't do anything at runtime.
  193. if (CallInst *CI = dyn_cast<CallInst>(I))
  194. if (Function *F = CI->getCalledFunction())
  195. if (unsigned IID = F->getIntrinsicID())
  196. if (IID == Intrinsic::gcroot)
  197. return false;
  198. return true;
  199. }
  200. /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
  201. /// Leave gcroot intrinsics; the code generator needs to see those.
  202. bool LowerIntrinsics::runOnFunction(Function &F) {
  203. // Quick exit for functions that do not use GC.
  204. if (!F.hasGC())
  205. return false;
  206. GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
  207. GCStrategy &S = FI.getStrategy();
  208. bool MadeChange = false;
  209. if (NeedsDefaultLoweringPass(S))
  210. MadeChange |= PerformDefaultLowering(F, S);
  211. bool UseCustomLoweringPass = NeedsCustomLoweringPass(S);
  212. if (UseCustomLoweringPass)
  213. MadeChange |= S.performCustomLowering(F);
  214. // Custom lowering may modify the CFG, so dominators must be recomputed.
  215. if (UseCustomLoweringPass) {
  216. if (DominatorTreeWrapperPass *DTWP =
  217. getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  218. DTWP->getDomTree().recalculate(F);
  219. }
  220. return MadeChange;
  221. }
  222. bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
  223. bool LowerWr = !S.customWriteBarrier();
  224. bool LowerRd = !S.customReadBarrier();
  225. bool InitRoots = S.initializeRoots();
  226. SmallVector<AllocaInst*, 32> Roots;
  227. bool MadeChange = false;
  228. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  229. for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
  230. if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
  231. Function *F = CI->getCalledFunction();
  232. switch (F->getIntrinsicID()) {
  233. case Intrinsic::gcwrite:
  234. if (LowerWr) {
  235. // Replace a write barrier with a simple store.
  236. Value *St = new StoreInst(CI->getArgOperand(0),
  237. CI->getArgOperand(2), CI);
  238. CI->replaceAllUsesWith(St);
  239. CI->eraseFromParent();
  240. }
  241. break;
  242. case Intrinsic::gcread:
  243. if (LowerRd) {
  244. // Replace a read barrier with a simple load.
  245. Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
  246. Ld->takeName(CI);
  247. CI->replaceAllUsesWith(Ld);
  248. CI->eraseFromParent();
  249. }
  250. break;
  251. case Intrinsic::gcroot:
  252. if (InitRoots) {
  253. // Initialize the GC root, but do not delete the intrinsic. The
  254. // backend needs the intrinsic to flag the stack slot.
  255. Roots.push_back(cast<AllocaInst>(
  256. CI->getArgOperand(0)->stripPointerCasts()));
  257. }
  258. break;
  259. default:
  260. continue;
  261. }
  262. MadeChange = true;
  263. }
  264. }
  265. }
  266. if (Roots.size())
  267. MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
  268. return MadeChange;
  269. }
  270. // -----------------------------------------------------------------------------
  271. char GCMachineCodeAnalysis::ID = 0;
  272. char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
  273. INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
  274. "Analyze Machine Code For Garbage Collection", false, false)
  275. GCMachineCodeAnalysis::GCMachineCodeAnalysis()
  276. : MachineFunctionPass(ID) {}
  277. void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  278. MachineFunctionPass::getAnalysisUsage(AU);
  279. AU.setPreservesAll();
  280. AU.addRequired<MachineModuleInfo>();
  281. AU.addRequired<GCModuleInfo>();
  282. }
  283. MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
  284. MachineBasicBlock::iterator MI,
  285. DebugLoc DL) const {
  286. MCSymbol *Label = MBB.getParent()->getContext().CreateTempSymbol();
  287. BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
  288. return Label;
  289. }
  290. void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
  291. // Find the return address (next instruction), too, so as to bracket the call
  292. // instruction.
  293. MachineBasicBlock::iterator RAI = CI;
  294. ++RAI;
  295. if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
  296. MCSymbol* Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
  297. FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
  298. }
  299. if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
  300. MCSymbol* Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
  301. FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
  302. }
  303. }
  304. void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
  305. for (MachineFunction::iterator BBI = MF.begin(),
  306. BBE = MF.end(); BBI != BBE; ++BBI)
  307. for (MachineBasicBlock::iterator MI = BBI->begin(),
  308. ME = BBI->end(); MI != ME; ++MI)
  309. if (MI->isCall())
  310. VisitCallPoint(MI);
  311. }
  312. void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
  313. const TargetFrameLowering *TFI = TM->getSubtargetImpl()->getFrameLowering();
  314. assert(TFI && "TargetRegisterInfo not available!");
  315. for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
  316. RI != FI->roots_end();) {
  317. // If the root references a dead object, no need to keep it.
  318. if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
  319. RI = FI->removeStackRoot(RI);
  320. } else {
  321. RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
  322. ++RI;
  323. }
  324. }
  325. }
  326. bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
  327. // Quick exit for functions that do not use GC.
  328. if (!MF.getFunction()->hasGC())
  329. return false;
  330. FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
  331. if (!FI->getStrategy().needsSafePoints())
  332. return false;
  333. TM = &MF.getTarget();
  334. MMI = &getAnalysis<MachineModuleInfo>();
  335. TII = TM->getSubtargetImpl()->getInstrInfo();
  336. // Find the size of the stack frame.
  337. FI->setFrameSize(MF.getFrameInfo()->getStackSize());
  338. // Find all safe points.
  339. if (FI->getStrategy().customSafePoints()) {
  340. FI->getStrategy().findCustomSafePoints(*FI, MF);
  341. } else {
  342. FindSafePoints(MF);
  343. }
  344. // Find the stack offsets for all roots.
  345. FindStackOffsets(MF);
  346. return false;
  347. }