LLVM 20.0.0git
XCoreLowerThreadLocal.cpp
Go to the documentation of this file.
1//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains a pass that lowers thread local variables on the
11/// XCore.
12///
13//===----------------------------------------------------------------------===//
14
15#include "XCore.h"
16#include "llvm/IR/Constants.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/IntrinsicsXCore.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Pass.h"
27
28#define DEBUG_TYPE "xcore-lower-thread-local"
29
30using namespace llvm;
31
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));
36
37namespace {
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 {
42 static char ID;
43
44 XCoreLowerThreadLocal() : ModulePass(ID) {
46 }
47
48 bool lowerGlobal(GlobalVariable *GV);
49
50 bool runOnModule(Module &M) override;
51 };
52}
53
54char XCoreLowerThreadLocal::ID = 0;
55
56INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
57 "Lower thread local variables", false, false)
58
60 return new XCoreLowerThreadLocal();
61}
62
63static ArrayType *createLoweredType(Type *OriginalType) {
64 return ArrayType::get(OriginalType, MaxThreads);
65}
66
67static Constant *
68createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
70 for (unsigned i = 0; i != MaxThreads; ++i) {
71 Elements[i] = OriginalInitializer;
72 }
73 return ConstantArray::get(NewType, Elements);
74}
75
76
78 do {
79 SmallVector<WeakTrackingVH, 8> WUsers(CE->users());
80 llvm::sort(WUsers);
81 WUsers.erase(llvm::unique(WUsers), WUsers.end());
82 while (!WUsers.empty())
83 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
84 if (PHINode *PN = dyn_cast<PHINode>(WU)) {
85 for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
86 if (PN->getIncomingValue(I) == CE) {
87 BasicBlock *PredBB = PN->getIncomingBlock(I);
88 if (PredBB->getTerminator()->getNumSuccessors() > 1)
89 PredBB = SplitEdge(PredBB, PN->getParent());
90 BasicBlock::iterator InsertPos =
91 PredBB->getTerminator()->getIterator();
92 Instruction *NewInst = CE->getAsInstruction();
93 NewInst->insertBefore(*PredBB, InsertPos);
94 PN->setOperand(I, NewInst);
95 }
96 } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
97 Instruction *NewInst = CE->getAsInstruction();
98 NewInst->insertBefore(*Instr->getParent(), Instr->getIterator());
99 Instr->replaceUsesOfWith(CE, NewInst);
100 } else {
101 ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU);
102 if (!CExpr || !replaceConstantExprOp(CExpr, P))
103 return false;
104 }
105 }
106 } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
107 // sibling may have used 'CE' when getAsInstruction was called.
108 CE->destroyConstant();
109 return true;
110}
111
114 for (User *U : GV->users())
115 if (!isa<Instruction>(U))
116 WUsers.push_back(WeakTrackingVH(U));
117 while (!WUsers.empty())
118 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
119 ConstantExpr *CE = dyn_cast<ConstantExpr>(WU);
120 if (!CE || !replaceConstantExprOp(CE, P))
121 return false;
122 }
123 return true;
124}
125
126static bool isZeroLengthArray(Type *Ty) {
127 ArrayType *AT = dyn_cast<ArrayType>(Ty);
128 return AT && (AT->getNumElements() == 0);
129}
130
131bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) {
132 Module *M = GV->getParent();
133 if (!GV->isThreadLocal())
134 return false;
135
136 // Skip globals that we can't lower and leave it for the backend to error.
137 if (!rewriteNonInstructionUses(GV, this) ||
138 !GV->getType()->isSized() || isZeroLengthArray(GV->getType()))
139 return false;
140
141 // Create replacement global.
142 ArrayType *NewType = createLoweredType(GV->getValueType());
143 Constant *NewInitializer = nullptr;
144 if (GV->hasInitializer())
145 NewInitializer = createLoweredInitializer(NewType,
146 GV->getInitializer());
147 GlobalVariable *NewGV =
148 new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
149 NewInitializer, "", nullptr,
150 GlobalVariable::NotThreadLocal,
151 GV->getType()->getAddressSpace(),
153
154 // Update uses.
156 for (User *U : Users) {
157 Instruction *Inst = cast<Instruction>(U);
158 IRBuilder<> Builder(Inst);
159 Value *ThreadID = Builder.CreateIntrinsic(Intrinsic::xcore_getid, {}, {});
160 Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
161 {Builder.getInt64(0), ThreadID});
162 U->replaceUsesOfWith(GV, Addr);
163 }
164
165 // Remove old global.
166 NewGV->takeName(GV);
167 GV->eraseFromParent();
168 return true;
169}
170
171bool XCoreLowerThreadLocal::runOnModule(Module &M) {
172 // Find thread local globals.
173 bool MadeChange = false;
174 SmallVector<GlobalVariable *, 16> ThreadLocalGlobals;
175 for (GlobalVariable &GV : M.globals())
176 if (GV.isThreadLocal())
177 ThreadLocalGlobals.push_back(&GV);
178 for (GlobalVariable *GV : ThreadLocalGlobals)
179 MadeChange |= lowerGlobal(GV);
180 return MadeChange;
181}
This file contains the declarations for the subclasses of Constant, which represent the different fla...
uint64_t Addr
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P)
static bool isZeroLengthArray(Type *Ty)
static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer)
static cl::opt< unsigned > MaxThreads("xcore-max-threads", cl::Optional, cl::desc("Maximum number of threads (for emulation thread-local storage)"), cl::Hidden, cl::value_desc("number"), cl::init(8))
static bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P)
static ArrayType * createLoweredType(Type *OriginalType)
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1108
This is an important base class in LLVM.
Definition: Constant.h:42
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:263
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:488
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:97
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:703
bool empty() const
Definition: SmallVector.h:81
iterator erase(const_iterator CI)
Definition: SmallVector.h:737
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:310
LLVM Value Representation.
Definition: Value.h:74
iterator_range< user_iterator > users()
Definition: Value.h:421
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Value handle that is nullable, but tries to track the Value.
Definition: ValueHandle.h:204
self_iterator getIterator()
Definition: ilist_node.h:132
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto unique(Range &&R, Predicate P)
Definition: STLExtras.h:2055
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
void initializeXCoreLowerThreadLocalPass(PassRegistry &p)
ModulePass * createXCoreLowerThreadLocalPass()
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...