GCRootLowering.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //===-- GCRootLowering.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 the lowering for the gc.root mechanism.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/GCMetadata.h"
  14. #include "llvm/CodeGen/GCStrategy.h"
  15. #include "llvm/CodeGen/MachineFrameInfo.h"
  16. #include "llvm/CodeGen/MachineFunctionPass.h"
  17. #include "llvm/CodeGen/MachineInstrBuilder.h"
  18. #include "llvm/CodeGen/MachineModuleInfo.h"
  19. #include "llvm/CodeGen/Passes.h"
  20. #include "llvm/IR/Dominators.h"
  21. #include "llvm/IR/IntrinsicInst.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/Target/TargetFrameLowering.h"
  27. #include "llvm/Target/TargetInstrInfo.h"
  28. #include "llvm/Target/TargetMachine.h"
  29. #include "llvm/Target/TargetRegisterInfo.h"
  30. #include "llvm/Target/TargetSubtargetInfo.h"
  31. using namespace llvm;
  32. namespace {
  33. /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
  34. /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
  35. /// directed by the GCStrategy. It also performs automatic root initialization
  36. /// and custom intrinsic lowering.
  37. class LowerIntrinsics : public FunctionPass {
  38. bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
  39. public:
  40. static char ID;
  41. LowerIntrinsics();
  42. const char *getPassName() const override;
  43. void getAnalysisUsage(AnalysisUsage &AU) const override;
  44. bool doInitialization(Module &M) override;
  45. bool runOnFunction(Function &F) override;
  46. };
  47. /// GCMachineCodeAnalysis - This is a target-independent pass over the machine
  48. /// function representation to identify safe points for the garbage collector
  49. /// in the machine code. It inserts labels at safe points and populates a
  50. /// GCMetadata record for each function.
  51. class GCMachineCodeAnalysis : public MachineFunctionPass {
  52. GCFunctionInfo *FI;
  53. MachineModuleInfo *MMI;
  54. const TargetInstrInfo *TII;
  55. void FindSafePoints(MachineFunction &MF);
  56. void VisitCallPoint(MachineBasicBlock::iterator MI);
  57. MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  58. DebugLoc DL) const;
  59. void FindStackOffsets(MachineFunction &MF);
  60. public:
  61. static char ID;
  62. GCMachineCodeAnalysis();
  63. void getAnalysisUsage(AnalysisUsage &AU) const override;
  64. bool runOnMachineFunction(MachineFunction &MF) override;
  65. };
  66. }
  67. // -----------------------------------------------------------------------------
  68. INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
  69. false)
  70. INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
  71. INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
  72. FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
  73. char LowerIntrinsics::ID = 0;
  74. LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
  75. initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
  76. }
  77. const char *LowerIntrinsics::getPassName() const {
  78. return "Lower Garbage Collection Instructions";
  79. }
  80. void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
  81. FunctionPass::getAnalysisUsage(AU);
  82. AU.addRequired<GCModuleInfo>();
  83. AU.addPreserved<DominatorTreeWrapperPass>();
  84. }
  85. static bool NeedsDefaultLoweringPass(const GCStrategy &C) {
  86. // Default lowering is necessary only if read or write barriers have a default
  87. // action. The default for roots is no action.
  88. return !C.customWriteBarrier() || !C.customReadBarrier() ||
  89. C.initializeRoots();
  90. }
  91. /// doInitialization - If this module uses the GC intrinsics, find them now.
  92. bool LowerIntrinsics::doInitialization(Module &M) {
  93. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  94. assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
  95. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  96. if (!I->isDeclaration() && I->hasGC())
  97. MI->getFunctionInfo(*I); // Instantiate the GC strategy.
  98. return false;
  99. }
  100. /// CouldBecomeSafePoint - Predicate to conservatively determine whether the
  101. /// instruction could introduce a safe point.
  102. static bool CouldBecomeSafePoint(Instruction *I) {
  103. // The natural definition of instructions which could introduce safe points
  104. // are:
  105. //
  106. // - call, invoke (AfterCall, BeforeCall)
  107. // - phis (Loops)
  108. // - invoke, ret, unwind (Exit)
  109. //
  110. // However, instructions as seemingly inoccuous as arithmetic can become
  111. // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
  112. // it is necessary to take a conservative approach.
  113. if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
  114. isa<LoadInst>(I))
  115. return false;
  116. // llvm.gcroot is safe because it doesn't do anything at runtime.
  117. if (CallInst *CI = dyn_cast<CallInst>(I))
  118. if (Function *F = CI->getCalledFunction())
  119. if (Intrinsic::ID IID = F->getIntrinsicID())
  120. if (IID == Intrinsic::gcroot)
  121. return false;
  122. return true;
  123. }
  124. static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
  125. unsigned Count) {
  126. // Scroll past alloca instructions.
  127. BasicBlock::iterator IP = F.getEntryBlock().begin();
  128. while (isa<AllocaInst>(IP))
  129. ++IP;
  130. // Search for initializers in the initial BB.
  131. SmallPtrSet<AllocaInst *, 16> InitedRoots;
  132. for (; !CouldBecomeSafePoint(IP); ++IP)
  133. if (StoreInst *SI = dyn_cast<StoreInst>(IP))
  134. if (AllocaInst *AI =
  135. dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
  136. InitedRoots.insert(AI);
  137. // Add root initializers.
  138. bool MadeChange = false;
  139. for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
  140. if (!InitedRoots.count(*I)) {
  141. StoreInst *SI = new StoreInst(
  142. ConstantPointerNull::get(cast<PointerType>(
  143. cast<PointerType>((*I)->getType())->getElementType())),
  144. *I);
  145. SI->insertAfter(*I);
  146. MadeChange = true;
  147. }
  148. return MadeChange;
  149. }
  150. /// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
  151. /// Leave gcroot intrinsics; the code generator needs to see those.
  152. bool LowerIntrinsics::runOnFunction(Function &F) {
  153. // Quick exit for functions that do not use GC.
  154. if (!F.hasGC())
  155. return false;
  156. GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
  157. GCStrategy &S = FI.getStrategy();
  158. bool MadeChange = false;
  159. if (NeedsDefaultLoweringPass(S))
  160. MadeChange |= PerformDefaultLowering(F, S);
  161. return MadeChange;
  162. }
  163. bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
  164. bool LowerWr = !S.customWriteBarrier();
  165. bool LowerRd = !S.customReadBarrier();
  166. bool InitRoots = S.initializeRoots();
  167. SmallVector<AllocaInst *, 32> Roots;
  168. bool MadeChange = false;
  169. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  170. for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
  171. if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
  172. Function *F = CI->getCalledFunction();
  173. switch (F->getIntrinsicID()) {
  174. case Intrinsic::gcwrite:
  175. if (LowerWr) {
  176. // Replace a write barrier with a simple store.
  177. Value *St =
  178. new StoreInst(CI->getArgOperand(0), CI->getArgOperand(2), CI);
  179. CI->replaceAllUsesWith(St);
  180. CI->eraseFromParent();
  181. }
  182. break;
  183. case Intrinsic::gcread:
  184. if (LowerRd) {
  185. // Replace a read barrier with a simple load.
  186. Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
  187. Ld->takeName(CI);
  188. CI->replaceAllUsesWith(Ld);
  189. CI->eraseFromParent();
  190. }
  191. break;
  192. case Intrinsic::gcroot:
  193. if (InitRoots) {
  194. // Initialize the GC root, but do not delete the intrinsic. The
  195. // backend needs the intrinsic to flag the stack slot.
  196. Roots.push_back(
  197. cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
  198. }
  199. break;
  200. default:
  201. continue;
  202. }
  203. MadeChange = true;
  204. }
  205. }
  206. }
  207. if (Roots.size())
  208. MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
  209. return MadeChange;
  210. }
  211. // -----------------------------------------------------------------------------
  212. char GCMachineCodeAnalysis::ID = 0;
  213. char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
  214. INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
  215. "Analyze Machine Code For Garbage Collection", false, false)
  216. GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
  217. void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  218. MachineFunctionPass::getAnalysisUsage(AU);
  219. AU.setPreservesAll();
  220. AU.addRequired<MachineModuleInfo>();
  221. AU.addRequired<GCModuleInfo>();
  222. }
  223. MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
  224. MachineBasicBlock::iterator MI,
  225. DebugLoc DL) const {
  226. MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
  227. BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
  228. return Label;
  229. }
  230. void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
  231. // Find the return address (next instruction), too, so as to bracket the call
  232. // instruction.
  233. MachineBasicBlock::iterator RAI = CI;
  234. ++RAI;
  235. if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
  236. MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
  237. FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
  238. }
  239. if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
  240. MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
  241. FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
  242. }
  243. }
  244. void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
  245. for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
  246. ++BBI)
  247. for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
  248. MI != ME; ++MI)
  249. if (MI->isCall()) {
  250. // Do not treat tail or sibling call sites as safe points. This is
  251. // legal since any arguments passed to the callee which live in the
  252. // remnants of the callers frame will be owned and updated by the
  253. // callee if required.
  254. if (MI->isTerminator())
  255. continue;
  256. VisitCallPoint(MI);
  257. }
  258. }
  259. void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
  260. const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
  261. assert(TFI && "TargetRegisterInfo not available!");
  262. for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
  263. RI != FI->roots_end();) {
  264. // If the root references a dead object, no need to keep it.
  265. if (MF.getFrameInfo()->isDeadObjectIndex(RI->Num)) {
  266. RI = FI->removeStackRoot(RI);
  267. } else {
  268. RI->StackOffset = TFI->getFrameIndexOffset(MF, RI->Num);
  269. ++RI;
  270. }
  271. }
  272. }
  273. bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
  274. // Quick exit for functions that do not use GC.
  275. if (!MF.getFunction()->hasGC())
  276. return false;
  277. FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
  278. MMI = &getAnalysis<MachineModuleInfo>();
  279. TII = MF.getSubtarget().getInstrInfo();
  280. // Find the size of the stack frame. There may be no correct static frame
  281. // size, we use UINT64_MAX to represent this.
  282. const MachineFrameInfo *MFI = MF.getFrameInfo();
  283. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  284. const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
  285. RegInfo->needsStackRealignment(MF);
  286. FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI->getStackSize());
  287. // Find all safe points.
  288. if (FI->getStrategy().needsSafePoints())
  289. FindSafePoints(MF);
  290. // Find the concrete stack offsets for all roots (stack slots)
  291. FindStackOffsets(MF);
  292. return false;
  293. }