1 //===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains a pass that lowers thread local variables on the
14 //===----------------------------------------------------------------------===//
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/NoFolder.h"
26 #include "llvm/Support/ValueHandle.h"
28 #define DEBUG_TYPE "xcore-lower-thread-local"
32 static cl::opt<unsigned> MaxThreads(
33 "xcore-max-threads", cl::Optional,
34 cl::desc("Maximum number of threads (for emulation thread-local storage)"),
35 cl::Hidden, cl::value_desc("number"), cl::init(8));
38 /// Lowers thread local variables on the XCore. Each thread local variable is
39 /// expanded to an array of n elements indexed by the thread ID where n is the
40 /// fixed number hardware threads supported by the device.
41 struct XCoreLowerThreadLocal : public ModulePass {
44 XCoreLowerThreadLocal() : ModulePass(ID) {
45 initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry());
48 bool lowerGlobal(GlobalVariable *GV);
50 bool runOnModule(Module &M);
54 char XCoreLowerThreadLocal::ID = 0;
56 INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
57 "Lower thread local variables", false, false)
59 ModulePass *llvm::createXCoreLowerThreadLocalPass() {
60 return new XCoreLowerThreadLocal();
63 static ArrayType *createLoweredType(Type *OriginalType) {
64 return ArrayType::get(OriginalType, MaxThreads);
68 createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
69 SmallVector<Constant *, 8> Elements(MaxThreads);
70 for (unsigned i = 0; i != MaxThreads; ++i) {
71 Elements[i] = OriginalInitializer;
73 return ConstantArray::get(NewType, Elements);
77 createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
78 IRBuilder<true,NoFolder> Builder(Instr);
79 unsigned OpCode = CE->getOpcode();
81 case Instruction::GetElementPtr: {
82 SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end());
83 ArrayRef<Value *> CEOps(CEOpVec);
84 return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(CEOps[0],
87 case Instruction::Add:
88 case Instruction::Sub:
89 case Instruction::Mul:
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 case Instruction::Shl:
97 case Instruction::LShr:
98 case Instruction::AShr:
99 case Instruction::And:
100 case Instruction::Or:
101 case Instruction::Xor:
102 return dyn_cast<Instruction>(
103 Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
104 CE->getOperand(0), CE->getOperand(1),
106 case Instruction::Trunc:
107 case Instruction::ZExt:
108 case Instruction::SExt:
109 case Instruction::FPToUI:
110 case Instruction::FPToSI:
111 case Instruction::UIToFP:
112 case Instruction::SIToFP:
113 case Instruction::FPTrunc:
114 case Instruction::FPExt:
115 case Instruction::PtrToInt:
116 case Instruction::IntToPtr:
117 case Instruction::BitCast:
118 return dyn_cast<Instruction>(
119 Builder.CreateCast((Instruction::CastOps)OpCode,
120 CE->getOperand(0), CE->getType(),
123 llvm_unreachable("Unhandled constant expression!\n");
127 static bool replaceConstantExprOp(ConstantExpr *CE) {
129 SmallVector<WeakVH,8> WUsers;
130 for (Value::use_iterator I = CE->use_begin(), E = CE->use_end();
132 WUsers.push_back(WeakVH(*I));
133 while (!WUsers.empty())
134 if (WeakVH WU = WUsers.pop_back_val()) {
135 if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
136 Instruction *NewInst = createReplacementInstr(CE, Instr);
137 assert(NewInst && "Must build an instruction\n");
138 // If NewInst uses a CE being handled in an earlier recursion the
139 // earlier recursion's do-while-hasNUsesOrMore(1) will run again.
140 Instr->replaceUsesOfWith(CE, NewInst);
142 ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
143 if (!CExpr || !replaceConstantExprOp(CExpr))
147 } while (CE->hasNUsesOrMore(1)); // Does a recursion's NewInst use CE?
148 CE->destroyConstant();
152 static bool rewriteNonInstructionUses(GlobalVariable *GV) {
153 SmallVector<WeakVH,8> WUsers;
154 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
155 if (!isa<Instruction>(*I))
156 WUsers.push_back(WeakVH(*I));
157 while (!WUsers.empty())
158 if (WeakVH WU = WUsers.pop_back_val()) {
159 ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
160 if (!CE || !replaceConstantExprOp(CE))
166 static bool isZeroLengthArray(Type *Ty) {
167 ArrayType *AT = dyn_cast<ArrayType>(Ty);
168 return AT && (AT->getNumElements() == 0);
171 bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
172 Module *M = GV->getParent();
173 LLVMContext &Ctx = M->getContext();
174 if (!GV->isThreadLocal())
177 // Skip globals that we can't lower and leave it for the backend to error.
178 if (!rewriteNonInstructionUses(GV) ||
179 !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
182 // Create replacement global.
183 ArrayType *NewType = createLoweredType(GV->getType()->getElementType());
184 Constant *NewInitializer = 0;
185 if (GV->hasInitializer())
186 NewInitializer = createLoweredInitializer(NewType,
187 GV->getInitializer());
188 GlobalVariable *NewGV =
189 new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
190 NewInitializer, "", 0, GlobalVariable::NotThreadLocal,
191 GV->getType()->getAddressSpace(),
192 GV->isExternallyInitialized());
195 SmallVector<User *, 16> Users(GV->use_begin(), GV->use_end());
196 for (unsigned I = 0, E = Users.size(); I != E; ++I) {
198 Instruction *Inst = cast<Instruction>(U);
199 IRBuilder<> Builder(Inst);
200 Function *GetID = Intrinsic::getDeclaration(GV->getParent(),
201 Intrinsic::xcore_getid);
202 Value *ThreadID = Builder.CreateCall(GetID);
203 SmallVector<Value *, 2> Indices;
204 Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx)));
205 Indices.push_back(ThreadID);
206 Value *Addr = Builder.CreateInBoundsGEP(NewGV, Indices);
207 U->replaceUsesOfWith(GV, Addr);
210 // Remove old global.
212 GV->eraseFromParent();
216 bool XCoreLowerThreadLocal::runOnModule(Module &M) {
217 // Find thread local globals.
218 bool MadeChange = false;
219 SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
220 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
222 GlobalVariable *GV = GVI;
223 if (GV->isThreadLocal())
224 ThreadLocalGlobals.push_back(GV);
226 for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) {
227 MadeChange |= lowerGlobal(ThreadLocalGlobals[I]);