XCoreLowerThreadLocal.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. //===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
  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. /// \file
  11. /// \brief This file contains a pass that lowers thread local variables on the
  12. /// XCore.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "XCore.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/GlobalVariable.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Intrinsics.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/IR/NoFolder.h"
  23. #include "llvm/IR/ValueHandle.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  27. #define DEBUG_TYPE "xcore-lower-thread-local"
  28. using namespace llvm;
  29. static cl::opt<unsigned> MaxThreads(
  30. "xcore-max-threads", cl::Optional,
  31. cl::desc("Maximum number of threads (for emulation thread-local storage)"),
  32. cl::Hidden, cl::value_desc("number"), cl::init(8));
  33. namespace {
  34. /// Lowers thread local variables on the XCore. Each thread local variable is
  35. /// expanded to an array of n elements indexed by the thread ID where n is the
  36. /// fixed number hardware threads supported by the device.
  37. struct XCoreLowerThreadLocal : public ModulePass {
  38. static char ID;
  39. XCoreLowerThreadLocal() : ModulePass(ID) {
  40. initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry());
  41. }
  42. bool lowerGlobal(GlobalVariable *GV);
  43. bool runOnModule(Module &M) override;
  44. };
  45. }
  46. char XCoreLowerThreadLocal::ID = 0;
  47. INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
  48. "Lower thread local variables", false, false)
  49. ModulePass *llvm::createXCoreLowerThreadLocalPass() {
  50. return new XCoreLowerThreadLocal();
  51. }
  52. static ArrayType *createLoweredType(Type *OriginalType) {
  53. return ArrayType::get(OriginalType, MaxThreads);
  54. }
  55. static Constant *
  56. createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
  57. SmallVector<Constant *, 8> Elements(MaxThreads);
  58. for (unsigned i = 0; i != MaxThreads; ++i) {
  59. Elements[i] = OriginalInitializer;
  60. }
  61. return ConstantArray::get(NewType, Elements);
  62. }
  63. static Instruction *
  64. createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
  65. IRBuilder<true,NoFolder> Builder(Instr);
  66. unsigned OpCode = CE->getOpcode();
  67. switch (OpCode) {
  68. case Instruction::GetElementPtr: {
  69. SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
  70. ArrayRef<Value *> CEOps(CEOpVec);
  71. return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(
  72. cast<GEPOperator>(CE)->getSourceElementType(), CEOps[0],
  73. CEOps.slice(1)));
  74. }
  75. case Instruction::Add:
  76. case Instruction::Sub:
  77. case Instruction::Mul:
  78. case Instruction::UDiv:
  79. case Instruction::SDiv:
  80. case Instruction::FDiv:
  81. case Instruction::URem:
  82. case Instruction::SRem:
  83. case Instruction::FRem:
  84. case Instruction::Shl:
  85. case Instruction::LShr:
  86. case Instruction::AShr:
  87. case Instruction::And:
  88. case Instruction::Or:
  89. case Instruction::Xor:
  90. return dyn_cast<Instruction>(
  91. Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
  92. CE->getOperand(0), CE->getOperand(1),
  93. CE->getName()));
  94. case Instruction::Trunc:
  95. case Instruction::ZExt:
  96. case Instruction::SExt:
  97. case Instruction::FPToUI:
  98. case Instruction::FPToSI:
  99. case Instruction::UIToFP:
  100. case Instruction::SIToFP:
  101. case Instruction::FPTrunc:
  102. case Instruction::FPExt:
  103. case Instruction::PtrToInt:
  104. case Instruction::IntToPtr:
  105. case Instruction::BitCast:
  106. return dyn_cast<Instruction>(
  107. Builder.CreateCast((Instruction::CastOps)OpCode,
  108. CE->getOperand(0), CE->getType(),
  109. CE->getName()));
  110. default:
  111. llvm_unreachable("Unhandled constant expression!\n");
  112. }
  113. }
  114. static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P) {
  115. do {
  116. SmallVector<WeakVH,8> WUsers(CE->user_begin(), CE->user_end());
  117. std::sort(WUsers.begin(), WUsers.end());
  118. WUsers.erase(std::unique(WUsers.begin(), WUsers.end()), WUsers.end());
  119. while (!WUsers.empty())
  120. if (WeakVH WU = WUsers.pop_back_val()) {
  121. if (PHINode *PN = dyn_cast<PHINode>(WU)) {
  122. for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
  123. if (PN->getIncomingValue(I) == CE) {
  124. BasicBlock *PredBB = PN->getIncomingBlock(I);
  125. if (PredBB->getTerminator()->getNumSuccessors() > 1)
  126. PredBB = SplitEdge(PredBB, PN->getParent());
  127. Instruction *InsertPos = PredBB->getTerminator();
  128. Instruction *NewInst = createReplacementInstr(CE, InsertPos);
  129. PN->setOperand(I, NewInst);
  130. }
  131. } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
  132. Instruction *NewInst = createReplacementInstr(CE, Instr);
  133. Instr->replaceUsesOfWith(CE, NewInst);
  134. } else {
  135. ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
  136. if (!CExpr || !replaceConstantExprOp(CExpr, P))
  137. return false;
  138. }
  139. }
  140. } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
  141. // sibling may have used 'CE' when createReplacementInstr was called.
  142. CE->destroyConstant();
  143. return true;
  144. }
  145. static bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P) {
  146. SmallVector<WeakVH,8> WUsers;
  147. for (User *U : GV->users())
  148. if (!isa<Instruction>(U))
  149. WUsers.push_back(WeakVH(U));
  150. while (!WUsers.empty())
  151. if (WeakVH WU = WUsers.pop_back_val()) {
  152. ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
  153. if (!CE || !replaceConstantExprOp(CE, P))
  154. return false;
  155. }
  156. return true;
  157. }
  158. static bool isZeroLengthArray(Type *Ty) {
  159. ArrayType *AT = dyn_cast<ArrayType>(Ty);
  160. return AT && (AT->getNumElements() == 0);
  161. }
  162. bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
  163. Module *M = GV->getParent();
  164. LLVMContext &Ctx = M->getContext();
  165. if (!GV->isThreadLocal())
  166. return false;
  167. // Skip globals that we can't lower and leave it for the backend to error.
  168. if (!rewriteNonInstructionUses(GV, this) ||
  169. !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
  170. return false;
  171. // Create replacement global.
  172. ArrayType *NewType = createLoweredType(GV->getType()->getElementType());
  173. Constant *NewInitializer = nullptr;
  174. if (GV->hasInitializer())
  175. NewInitializer = createLoweredInitializer(NewType,
  176. GV->getInitializer());
  177. GlobalVariable *NewGV =
  178. new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
  179. NewInitializer, "", nullptr,
  180. GlobalVariable::NotThreadLocal,
  181. GV->getType()->getAddressSpace(),
  182. GV->isExternallyInitialized());
  183. // Update uses.
  184. SmallVector<User *, 16> Users(GV->user_begin(), GV->user_end());
  185. for (unsigned I = 0, E = Users.size(); I != E; ++I) {
  186. User *U = Users[I];
  187. Instruction *Inst = cast<Instruction>(U);
  188. IRBuilder<> Builder(Inst);
  189. Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
  190. Intrinsic::xcore_getid);
  191. Value *ThreadID = Builder.CreateCall(GetID, {});
  192. SmallVector<Value *, 2> Indices;
  193. Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx)));
  194. Indices.push_back(ThreadID);
  195. Value *Addr =
  196. Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV, Indices);
  197. U->replaceUsesOfWith(GV, Addr);
  198. }
  199. // Remove old global.
  200. NewGV->takeName(GV);
  201. GV->eraseFromParent();
  202. return true;
  203. }
  204. bool XCoreLowerThreadLocal::runOnModule(Module &M) {
  205. // Find thread local globals.
  206. bool MadeChange = false;
  207. SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
  208. for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
  209. GVI != E; ++GVI) {
  210. GlobalVariable *GV = GVI;
  211. if (GV->isThreadLocal())
  212. ThreadLocalGlobals.push_back(GV);
  213. }
  214. for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
  215. MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
  216. }
  217. return MadeChange;
  218. }