1251607Sdim//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
2251607Sdim//
3251607Sdim//                     The LLVM Compiler Infrastructure
4251607Sdim//
5251607Sdim// This file is distributed under the University of Illinois Open Source
6251607Sdim// License. See LICENSE.TXT for details.
7251607Sdim//
8251607Sdim//===----------------------------------------------------------------------===//
9251607Sdim///
10251607Sdim/// \file
11251607Sdim/// \brief This file contains a pass that lowers thread local variables on the
12251607Sdim///        XCore.
13251607Sdim///
14251607Sdim//===----------------------------------------------------------------------===//
15251607Sdim
16251607Sdim#include "XCore.h"
17251607Sdim#include "llvm/IR/Constants.h"
18251607Sdim#include "llvm/IR/DerivedTypes.h"
19251607Sdim#include "llvm/IR/GlobalVariable.h"
20276479Sdim#include "llvm/IR/IRBuilder.h"
21251607Sdim#include "llvm/IR/Intrinsics.h"
22251607Sdim#include "llvm/IR/Module.h"
23276479Sdim#include "llvm/IR/NoFolder.h"
24276479Sdim#include "llvm/IR/ValueHandle.h"
25251607Sdim#include "llvm/Pass.h"
26251607Sdim#include "llvm/Support/CommandLine.h"
27261991Sdim#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28251607Sdim
29251607Sdim#define DEBUG_TYPE "xcore-lower-thread-local"
30251607Sdim
31251607Sdimusing namespace llvm;
32251607Sdim
33251607Sdimstatic cl::opt<unsigned> MaxThreads(
34251607Sdim  "xcore-max-threads", cl::Optional,
35251607Sdim  cl::desc("Maximum number of threads (for emulation thread-local storage)"),
36251607Sdim  cl::Hidden, cl::value_desc("number"), cl::init(8));
37251607Sdim
38251607Sdimnamespace {
39251607Sdim  /// Lowers thread local variables on the XCore. Each thread local variable is
40251607Sdim  /// expanded to an array of n elements indexed by the thread ID where n is the
41251607Sdim  /// fixed number hardware threads supported by the device.
42251607Sdim  struct XCoreLowerThreadLocal : public ModulePass {
43251607Sdim    static char ID;
44251607Sdim
45251607Sdim    XCoreLowerThreadLocal() : ModulePass(ID) {
46251607Sdim      initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry());
47251607Sdim    }
48251607Sdim
49251607Sdim    bool lowerGlobal(GlobalVariable *GV);
50251607Sdim
51276479Sdim    bool runOnModule(Module &M) override;
52251607Sdim  };
53251607Sdim}
54251607Sdim
55251607Sdimchar XCoreLowerThreadLocal::ID = 0;
56251607Sdim
57251607SdimINITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
58251607Sdim                "Lower thread local variables", false, false)
59251607Sdim
60251607SdimModulePass *llvm::createXCoreLowerThreadLocalPass() {
61251607Sdim  return new XCoreLowerThreadLocal();
62251607Sdim}
63251607Sdim
64251607Sdimstatic ArrayType *createLoweredType(Type *OriginalType) {
65251607Sdim  return ArrayType::get(OriginalType, MaxThreads);
66251607Sdim}
67251607Sdim
68251607Sdimstatic Constant *
69251607SdimcreateLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
70251607Sdim  SmallVector<Constant *, 8> Elements(MaxThreads);
71251607Sdim  for (unsigned i = 0; i != MaxThreads; ++i) {
72251607Sdim    Elements[i] = OriginalInitializer;
73251607Sdim  }
74251607Sdim  return ConstantArray::get(NewType, Elements);
75251607Sdim}
76251607Sdim
77261991Sdimstatic Instruction *
78261991SdimcreateReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
79261991Sdim  IRBuilder<true,NoFolder> Builder(Instr);
80261991Sdim  unsigned OpCode = CE->getOpcode();
81261991Sdim  switch (OpCode) {
82261991Sdim    case Instruction::GetElementPtr: {
83261991Sdim      SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
84261991Sdim      ArrayRef<Value *> CEOps(CEOpVec);
85288943Sdim      return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(
86288943Sdim          cast<GEPOperator>(CE)->getSourceElementType(), CEOps[0],
87288943Sdim          CEOps.slice(1)));
88261991Sdim    }
89261991Sdim    case Instruction::Add:
90261991Sdim    case Instruction::Sub:
91261991Sdim    case Instruction::Mul:
92261991Sdim    case Instruction::UDiv:
93261991Sdim    case Instruction::SDiv:
94261991Sdim    case Instruction::FDiv:
95261991Sdim    case Instruction::URem:
96261991Sdim    case Instruction::SRem:
97261991Sdim    case Instruction::FRem:
98261991Sdim    case Instruction::Shl:
99261991Sdim    case Instruction::LShr:
100261991Sdim    case Instruction::AShr:
101261991Sdim    case Instruction::And:
102261991Sdim    case Instruction::Or:
103261991Sdim    case Instruction::Xor:
104261991Sdim      return dyn_cast<Instruction>(
105261991Sdim                  Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
106261991Sdim                                      CE->getOperand(0), CE->getOperand(1),
107261991Sdim                                      CE->getName()));
108261991Sdim    case Instruction::Trunc:
109261991Sdim    case Instruction::ZExt:
110261991Sdim    case Instruction::SExt:
111261991Sdim    case Instruction::FPToUI:
112261991Sdim    case Instruction::FPToSI:
113261991Sdim    case Instruction::UIToFP:
114261991Sdim    case Instruction::SIToFP:
115261991Sdim    case Instruction::FPTrunc:
116261991Sdim    case Instruction::FPExt:
117261991Sdim    case Instruction::PtrToInt:
118261991Sdim    case Instruction::IntToPtr:
119261991Sdim    case Instruction::BitCast:
120261991Sdim      return dyn_cast<Instruction>(
121261991Sdim                  Builder.CreateCast((Instruction::CastOps)OpCode,
122261991Sdim                                     CE->getOperand(0), CE->getType(),
123261991Sdim                                     CE->getName()));
124261991Sdim    default:
125261991Sdim      llvm_unreachable("Unhandled constant expression!\n");
126261991Sdim  }
127261991Sdim}
128251607Sdim
129261991Sdimstatic bool replaceConstantExprOp(ConstantExpr *CE, Pass *P) {
130261991Sdim  do {
131276479Sdim    SmallVector<WeakVH,8> WUsers(CE->user_begin(), CE->user_end());
132261991Sdim    std::sort(WUsers.begin(), WUsers.end());
133261991Sdim    WUsers.erase(std::unique(WUsers.begin(), WUsers.end()), WUsers.end());
134261991Sdim    while (!WUsers.empty())
135261991Sdim      if (WeakVH WU = WUsers.pop_back_val()) {
136261991Sdim        if (PHINode *PN = dyn_cast<PHINode>(WU)) {
137261991Sdim          for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
138261991Sdim            if (PN->getIncomingValue(I) == CE) {
139261991Sdim              BasicBlock *PredBB = PN->getIncomingBlock(I);
140261991Sdim              if (PredBB->getTerminator()->getNumSuccessors() > 1)
141288943Sdim                PredBB = SplitEdge(PredBB, PN->getParent());
142261991Sdim              Instruction *InsertPos = PredBB->getTerminator();
143261991Sdim              Instruction *NewInst = createReplacementInstr(CE, InsertPos);
144261991Sdim              PN->setOperand(I, NewInst);
145261991Sdim            }
146261991Sdim        } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
147261991Sdim          Instruction *NewInst = createReplacementInstr(CE, Instr);
148261991Sdim          Instr->replaceUsesOfWith(CE, NewInst);
149261991Sdim        } else {
150261991Sdim          ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
151261991Sdim          if (!CExpr || !replaceConstantExprOp(CExpr, P))
152261991Sdim            return false;
153261991Sdim        }
154261991Sdim      }
155276479Sdim  } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
156276479Sdim  // sibling may have used 'CE' when createReplacementInstr was called.
157261991Sdim  CE->destroyConstant();
158261991Sdim  return true;
159251607Sdim}
160251607Sdim
161261991Sdimstatic bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P) {
162261991Sdim  SmallVector<WeakVH,8> WUsers;
163276479Sdim  for (User *U : GV->users())
164276479Sdim    if (!isa<Instruction>(U))
165276479Sdim      WUsers.push_back(WeakVH(U));
166261991Sdim  while (!WUsers.empty())
167261991Sdim    if (WeakVH WU = WUsers.pop_back_val()) {
168261991Sdim      ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
169261991Sdim      if (!CE || !replaceConstantExprOp(CE, P))
170261991Sdim        return false;
171261991Sdim    }
172261991Sdim  return true;
173261991Sdim}
174261991Sdim
175251607Sdimstatic bool isZeroLengthArray(Type *Ty) {
176251607Sdim  ArrayType *AT = dyn_cast<ArrayType>(Ty);
177251607Sdim  return AT && (AT->getNumElements() == 0);
178251607Sdim}
179251607Sdim
180251607Sdimbool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
181251607Sdim  Module *M = GV->getParent();
182251607Sdim  LLVMContext &Ctx = M->getContext();
183251607Sdim  if (!GV->isThreadLocal())
184251607Sdim    return false;
185251607Sdim
186251607Sdim  // Skip globals that we can't lower and leave it for the backend to error.
187261991Sdim  if (!rewriteNonInstructionUses(GV, this) ||
188251607Sdim      !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
189251607Sdim    return false;
190251607Sdim
191251607Sdim  // Create replacement global.
192251607Sdim  ArrayType *NewType = createLoweredType(GV->getType()->getElementType());
193276479Sdim  Constant *NewInitializer = nullptr;
194261991Sdim  if (GV->hasInitializer())
195261991Sdim    NewInitializer = createLoweredInitializer(NewType,
196261991Sdim                                              GV->getInitializer());
197251607Sdim  GlobalVariable *NewGV =
198251607Sdim    new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
199276479Sdim                       NewInitializer, "", nullptr,
200276479Sdim                       GlobalVariable::NotThreadLocal,
201251607Sdim                       GV->getType()->getAddressSpace(),
202251607Sdim                       GV->isExternallyInitialized());
203251607Sdim
204251607Sdim  // Update uses.
205276479Sdim  SmallVector<User *, 16> Users(GV->user_begin(), GV->user_end());
206251607Sdim  for (unsigned I = 0, E = Users.size(); I != E; ++I) {
207251607Sdim    User *U = Users[I];
208251607Sdim    Instruction *Inst = cast<Instruction>(U);
209251607Sdim    IRBuilder<> Builder(Inst);
210251607Sdim    Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
211251607Sdim                                                Intrinsic::xcore_getid);
212288943Sdim    Value *ThreadID = Builder.CreateCall(GetID, {});
213251607Sdim    SmallVector<Value *, 2> Indices;
214251607Sdim    Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx)));
215251607Sdim    Indices.push_back(ThreadID);
216288943Sdim    Value *Addr =
217288943Sdim        Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV, Indices);
218251607Sdim    U->replaceUsesOfWith(GV, Addr);
219251607Sdim  }
220251607Sdim
221251607Sdim  // Remove old global.
222251607Sdim  NewGV->takeName(GV);
223251607Sdim  GV->eraseFromParent();
224251607Sdim  return true;
225251607Sdim}
226251607Sdim
227251607Sdimbool XCoreLowerThreadLocal::runOnModule(Module &M) {
228251607Sdim  // Find thread local globals.
229251607Sdim  bool MadeChange = false;
230251607Sdim  SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
231296417Sdim  for (GlobalVariable &GV : M.globals())
232296417Sdim    if (GV.isThreadLocal())
233296417Sdim      ThreadLocalGlobals.push_back(&GV);
234251607Sdim  for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
235251607Sdim    MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
236251607Sdim  }
237251607Sdim  return MadeChange;
238251607Sdim}
239