GCStrategy.cpp 13 KB

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