LLVM 24.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 "XCoreSubtarget.h"
17#include "llvm/IR/Constants.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/IntrinsicsXCore.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/ValueHandle.h"
25#include "llvm/Pass.h"
28
29#define DEBUG_TYPE "xcore-lower-thread-local"
30
31using namespace llvm;
32
33namespace {
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
40 XCoreLowerThreadLocal() : ModulePass(ID) {}
41
42 bool lowerGlobal(GlobalVariable *GV, unsigned MaxThreads);
43
44 bool runOnModule(Module &M) override;
45 };
46}
47
48char XCoreLowerThreadLocal::ID = 0;
49
50INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local",
51 "Lower thread local variables", false, false)
52
54 return new XCoreLowerThreadLocal();
55}
56
57static ArrayType *createLoweredType(Type *OriginalType, unsigned MaxThreads) {
58 return ArrayType::get(OriginalType, MaxThreads);
59}
60
61static Constant *
62createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) {
63 SmallVector<Constant *, 8> Elements(NewType->getNumElements());
64 for (unsigned i = 0; i != NewType->getNumElements(); ++i) {
65 Elements[i] = OriginalInitializer;
66 }
67 return ConstantArray::get(NewType, Elements);
68}
69
70
72 do {
73 SmallVector<WeakTrackingVH, 8> WUsers(CE->users());
74 llvm::sort(WUsers);
75 WUsers.erase(llvm::unique(WUsers), WUsers.end());
76 while (!WUsers.empty())
77 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
78 if (PHINode *PN = dyn_cast<PHINode>(WU)) {
79 for (int I = 0, E = PN->getNumIncomingValues(); I < E; ++I)
80 if (PN->getIncomingValue(I) == CE) {
81 BasicBlock *PredBB = PN->getIncomingBlock(I);
82 if (PredBB->getTerminator()->getNumSuccessors() > 1)
83 PredBB = SplitEdge(PredBB, PN->getParent());
84 BasicBlock::iterator InsertPos =
85 PredBB->getTerminator()->getIterator();
86 Instruction *NewInst = CE->getAsInstruction();
87 NewInst->insertBefore(*PredBB, InsertPos);
88 PN->setOperand(I, NewInst);
89 }
90 } else if (Instruction *Instr = dyn_cast<Instruction>(WU)) {
91 Instruction *NewInst = CE->getAsInstruction();
92 NewInst->insertBefore(*Instr->getParent(), Instr->getIterator());
93 Instr->replaceUsesOfWith(CE, NewInst);
94 } else {
96 if (!CExpr || !replaceConstantExprOp(CExpr, P))
97 return false;
98 }
99 }
100 } while (CE->hasNUsesOrMore(1)); // We need to check because a recursive
101 // sibling may have used 'CE' when getAsInstruction was called.
102 CE->destroyConstant();
103 return true;
104}
105
108 for (User *U : GV->users())
109 if (!isa<Instruction>(U))
110 WUsers.push_back(WeakTrackingVH(U));
111 while (!WUsers.empty())
112 if (WeakTrackingVH WU = WUsers.pop_back_val()) {
114 if (!CE || !replaceConstantExprOp(CE, P))
115 return false;
116 }
117 return true;
118}
119
120bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV,
121 unsigned MaxThreads) {
122 Module *M = GV->getParent();
123 if (!GV->isThreadLocal())
124 return false;
125
126 if (!rewriteNonInstructionUses(GV, this))
127 return false;
128
129 // The lowered representation needs an ArrayType of the value type, which
130 // requires a known per-element stride: reject anything that can't provide
131 // one now, with a clear diagnostic, rather than emitting a malformed GEP
132 // that only fails much later (and much less clearly) in instruction
133 // selection.
134 if (!GV->getValueType()->isSized() ||
135 GV->getGlobalSize(M->getDataLayout()) == 0)
136 reportFatalUsageError("Size of thread local object '" + GV->getName() +
137 "' is unknown");
138
139 // Create replacement global.
140 ArrayType *NewType = createLoweredType(GV->getValueType(), MaxThreads);
141 Constant *NewInitializer = nullptr;
142 if (GV->hasInitializer())
143 NewInitializer = createLoweredInitializer(NewType,
144 GV->getInitializer());
145 GlobalVariable *NewGV =
146 new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(),
147 NewInitializer, "", nullptr,
148 GlobalVariable::NotThreadLocal,
149 GV->getType()->getAddressSpace(),
151
152 // Update uses.
154 for (User *U : Users) {
156 IRBuilder<> Builder(Inst);
157 Value *ThreadID = Builder.CreateIntrinsic(Intrinsic::xcore_getid, {});
158 Value *Addr = Builder.CreateInBoundsGEP(NewGV->getValueType(), NewGV,
159 {Builder.getInt64(0), ThreadID});
160 U->replaceUsesOfWith(GV, Addr);
161 }
162
163 // Remove old global.
164 NewGV->takeName(GV);
165 GV->eraseFromParent();
166 return true;
167}
168
169bool XCoreLowerThreadLocal::runOnModule(Module &M) {
170 unsigned MaxThreads =
171 M.getContext().getLibraryOptions().get<XCoreOptions>().max_threads;
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, MaxThreads);
180 return MadeChange;
181}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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:57
Machine Check Debug Module
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P)
static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer)
static ArrayType * createLoweredType(Type *OriginalType, unsigned MaxThreads)
static bool rewriteNonInstructionUses(GlobalVariable *GV, Pass *P)
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
This is an important base class in LLVM.
Definition Constant.h:43
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LinkageTypes getLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
unsigned getAddressSpace() const
Return the address space of the Pointer type.
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Value handle that is nullable, but tries to track the Value.
self_iterator getIterator()
Definition ilist_node.h:123
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModulePass * createXCoreLowerThreadLocalPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI 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...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177