1251607Sdim//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
2251607Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6251607Sdim//
7251607Sdim//===----------------------------------------------------------------------===//
8251607Sdim///
9251607Sdim/// \file
10341825Sdim/// This file contains a pass that lowers thread local variables on the
11251607Sdim///        XCore.
12251607Sdim///
13251607Sdim//===----------------------------------------------------------------------===//
14251607Sdim
15251607Sdim#include "XCore.h"
16251607Sdim#include "llvm/IR/Constants.h"
17251607Sdim#include "llvm/IR/DerivedTypes.h"
18251607Sdim#include "llvm/IR/GlobalVariable.h"
19276479Sdim#include "llvm/IR/IRBuilder.h"
20251607Sdim#include "llvm/IR/Intrinsics.h"
21360784Sdim#include "llvm/IR/IntrinsicsXCore.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) {
79309124Sdim  IRBuilder<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 {
131321369Sdim    SmallVector<WeakTrackingVH, 8> WUsers(CE->user_begin(), CE->user_end());
132344779Sdim    llvm::sort(WUsers);
133261991Sdim    WUsers.erase(std::unique(WUsers.begin(), WUsers.end()), WUsers.end());
134261991Sdim    while (!WUsers.empty())
135321369Sdim      if (WeakTrackingVH 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) {
162321369Sdim  SmallVector<WeakTrackingVH, 8> WUsers;
163276479Sdim  for (User *U : GV->users())
164276479Sdim    if (!isa<Instruction>(U))
165321369Sdim      WUsers.push_back(WeakTrackingVH(U));
166261991Sdim  while (!WUsers.empty())
167321369Sdim    if (WeakTrackingVH 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  if (!GV->isThreadLocal())
183251607Sdim    return false;
184251607Sdim
185251607Sdim  // Skip globals that we can't lower and leave it for the backend to error.
186261991Sdim  if (!rewriteNonInstructionUses(GV, this) ||
187251607Sdim      !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
188251607Sdim    return false;
189251607Sdim
190251607Sdim  // Create replacement global.
191309124Sdim  ArrayType *NewType = createLoweredType(GV->getValueType());
192276479Sdim  Constant *NewInitializer = nullptr;
193261991Sdim  if (GV->hasInitializer())
194261991Sdim    NewInitializer = createLoweredInitializer(NewType,
195261991Sdim                                              GV->getInitializer());
196251607Sdim  GlobalVariable *NewGV =
197251607Sdim    new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
198276479Sdim                       NewInitializer, "", nullptr,
199276479Sdim                       GlobalVariable::NotThreadLocal,
200251607Sdim                       GV->getType()->getAddressSpace(),
201251607Sdim                       GV->isExternallyInitialized());
202251607Sdim
203251607Sdim  // Update uses.
204276479Sdim  SmallVector<User *, 16> Users(GV->user_begin(), GV->user_end());
205251607Sdim  for (unsigned I = 0, E = Users.size(); I != E; ++I) {
206251607Sdim    User *U = Users[I];
207251607Sdim    Instruction *Inst = cast<Instruction>(U);
208251607Sdim    IRBuilder<> Builder(Inst);
209251607Sdim    Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
210251607Sdim                                                Intrinsic::xcore_getid);
211288943Sdim    Value *ThreadID = Builder.CreateCall(GetID, {});
212309124Sdim    Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
213309124Sdim                                            {Builder.getInt64(0), ThreadID});
214251607Sdim    U->replaceUsesOfWith(GV, Addr);
215251607Sdim  }
216251607Sdim
217251607Sdim  // Remove old global.
218251607Sdim  NewGV->takeName(GV);
219251607Sdim  GV->eraseFromParent();
220251607Sdim  return true;
221251607Sdim}
222251607Sdim
223251607Sdimbool XCoreLowerThreadLocal::runOnModule(Module &M) {
224251607Sdim  // Find thread local globals.
225251607Sdim  bool MadeChange = false;
226251607Sdim  SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
227296417Sdim  for (GlobalVariable &GV : M.globals())
228296417Sdim    if (GV.isThreadLocal())
229296417Sdim      ThreadLocalGlobals.push_back(&GV);
230251607Sdim  for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
231251607Sdim    MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);
232251607Sdim  }
233251607Sdim  return MadeChange;
234251607Sdim}
235