xref: /aosp_15_r20/external/llvm/lib/CodeGen/AtomicExpandPass.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file contains a pass (at IR level) to replace atomic instructions with
11*9880d681SAndroid Build Coastguard Worker // __atomic_* library calls, or target specific instruction which implement the
12*9880d681SAndroid Build Coastguard Worker // same semantics in a way which better fits the target backend.  This can
13*9880d681SAndroid Build Coastguard Worker // include the use of (intrinsic-based) load-linked/store-conditional loops,
14*9880d681SAndroid Build Coastguard Worker // AtomicCmpXchg, or type coercions.
15*9880d681SAndroid Build Coastguard Worker //
16*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
17*9880d681SAndroid Build Coastguard Worker 
18*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/AtomicExpandUtils.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/Passes.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InstIterator.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Intrinsics.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetLowering.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetMachine.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Target/TargetSubtargetInfo.h"
31*9880d681SAndroid Build Coastguard Worker 
32*9880d681SAndroid Build Coastguard Worker using namespace llvm;
33*9880d681SAndroid Build Coastguard Worker 
34*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "atomic-expand"
35*9880d681SAndroid Build Coastguard Worker 
36*9880d681SAndroid Build Coastguard Worker namespace {
37*9880d681SAndroid Build Coastguard Worker   class AtomicExpand: public FunctionPass {
38*9880d681SAndroid Build Coastguard Worker     const TargetMachine *TM;
39*9880d681SAndroid Build Coastguard Worker     const TargetLowering *TLI;
40*9880d681SAndroid Build Coastguard Worker   public:
41*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass identification, replacement for typeid
AtomicExpand(const TargetMachine * TM=nullptr)42*9880d681SAndroid Build Coastguard Worker     explicit AtomicExpand(const TargetMachine *TM = nullptr)
43*9880d681SAndroid Build Coastguard Worker       : FunctionPass(ID), TM(TM), TLI(nullptr) {
44*9880d681SAndroid Build Coastguard Worker       initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
45*9880d681SAndroid Build Coastguard Worker     }
46*9880d681SAndroid Build Coastguard Worker 
47*9880d681SAndroid Build Coastguard Worker     bool runOnFunction(Function &F) override;
48*9880d681SAndroid Build Coastguard Worker 
49*9880d681SAndroid Build Coastguard Worker   private:
50*9880d681SAndroid Build Coastguard Worker     bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
51*9880d681SAndroid Build Coastguard Worker                                bool IsStore, bool IsLoad);
52*9880d681SAndroid Build Coastguard Worker     IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
53*9880d681SAndroid Build Coastguard Worker     LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
54*9880d681SAndroid Build Coastguard Worker     bool tryExpandAtomicLoad(LoadInst *LI);
55*9880d681SAndroid Build Coastguard Worker     bool expandAtomicLoadToLL(LoadInst *LI);
56*9880d681SAndroid Build Coastguard Worker     bool expandAtomicLoadToCmpXchg(LoadInst *LI);
57*9880d681SAndroid Build Coastguard Worker     StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
58*9880d681SAndroid Build Coastguard Worker     bool expandAtomicStore(StoreInst *SI);
59*9880d681SAndroid Build Coastguard Worker     bool tryExpandAtomicRMW(AtomicRMWInst *AI);
60*9880d681SAndroid Build Coastguard Worker     Value *
61*9880d681SAndroid Build Coastguard Worker     insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
62*9880d681SAndroid Build Coastguard Worker                       AtomicOrdering MemOpOrder,
63*9880d681SAndroid Build Coastguard Worker                       function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
64*9880d681SAndroid Build Coastguard Worker     void expandAtomicOpToLLSC(
65*9880d681SAndroid Build Coastguard Worker         Instruction *I, Type *ResultTy, Value *Addr, AtomicOrdering MemOpOrder,
66*9880d681SAndroid Build Coastguard Worker         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
67*9880d681SAndroid Build Coastguard Worker     void expandPartwordAtomicRMW(
68*9880d681SAndroid Build Coastguard Worker         AtomicRMWInst *I,
69*9880d681SAndroid Build Coastguard Worker         TargetLoweringBase::AtomicExpansionKind ExpansionKind);
70*9880d681SAndroid Build Coastguard Worker     void expandPartwordCmpXchg(AtomicCmpXchgInst *I);
71*9880d681SAndroid Build Coastguard Worker 
72*9880d681SAndroid Build Coastguard Worker     AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
73*9880d681SAndroid Build Coastguard Worker     static Value *insertRMWCmpXchgLoop(
74*9880d681SAndroid Build Coastguard Worker         IRBuilder<> &Builder, Type *ResultType, Value *Addr,
75*9880d681SAndroid Build Coastguard Worker         AtomicOrdering MemOpOrder,
76*9880d681SAndroid Build Coastguard Worker         function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
77*9880d681SAndroid Build Coastguard Worker         CreateCmpXchgInstFun CreateCmpXchg);
78*9880d681SAndroid Build Coastguard Worker 
79*9880d681SAndroid Build Coastguard Worker     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
80*9880d681SAndroid Build Coastguard Worker     bool isIdempotentRMW(AtomicRMWInst *AI);
81*9880d681SAndroid Build Coastguard Worker     bool simplifyIdempotentRMW(AtomicRMWInst *AI);
82*9880d681SAndroid Build Coastguard Worker 
83*9880d681SAndroid Build Coastguard Worker     bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, unsigned Align,
84*9880d681SAndroid Build Coastguard Worker                                  Value *PointerOperand, Value *ValueOperand,
85*9880d681SAndroid Build Coastguard Worker                                  Value *CASExpected, AtomicOrdering Ordering,
86*9880d681SAndroid Build Coastguard Worker                                  AtomicOrdering Ordering2,
87*9880d681SAndroid Build Coastguard Worker                                  ArrayRef<RTLIB::Libcall> Libcalls);
88*9880d681SAndroid Build Coastguard Worker     void expandAtomicLoadToLibcall(LoadInst *LI);
89*9880d681SAndroid Build Coastguard Worker     void expandAtomicStoreToLibcall(StoreInst *LI);
90*9880d681SAndroid Build Coastguard Worker     void expandAtomicRMWToLibcall(AtomicRMWInst *I);
91*9880d681SAndroid Build Coastguard Worker     void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
92*9880d681SAndroid Build Coastguard Worker 
93*9880d681SAndroid Build Coastguard Worker     friend bool
94*9880d681SAndroid Build Coastguard Worker     llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
95*9880d681SAndroid Build Coastguard Worker                                    CreateCmpXchgInstFun CreateCmpXchg);
96*9880d681SAndroid Build Coastguard Worker   };
97*9880d681SAndroid Build Coastguard Worker }
98*9880d681SAndroid Build Coastguard Worker 
99*9880d681SAndroid Build Coastguard Worker char AtomicExpand::ID = 0;
100*9880d681SAndroid Build Coastguard Worker char &llvm::AtomicExpandID = AtomicExpand::ID;
101*9880d681SAndroid Build Coastguard Worker INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand", "Expand Atomic instructions",
102*9880d681SAndroid Build Coastguard Worker                    false, false)
103*9880d681SAndroid Build Coastguard Worker 
createAtomicExpandPass(const TargetMachine * TM)104*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
105*9880d681SAndroid Build Coastguard Worker   return new AtomicExpand(TM);
106*9880d681SAndroid Build Coastguard Worker }
107*9880d681SAndroid Build Coastguard Worker 
108*9880d681SAndroid Build Coastguard Worker namespace {
109*9880d681SAndroid Build Coastguard Worker // Helper functions to retrieve the size of atomic instructions.
getAtomicOpSize(LoadInst * LI)110*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpSize(LoadInst *LI) {
111*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = LI->getModule()->getDataLayout();
112*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(LI->getType());
113*9880d681SAndroid Build Coastguard Worker }
114*9880d681SAndroid Build Coastguard Worker 
getAtomicOpSize(StoreInst * SI)115*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpSize(StoreInst *SI) {
116*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = SI->getModule()->getDataLayout();
117*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
118*9880d681SAndroid Build Coastguard Worker }
119*9880d681SAndroid Build Coastguard Worker 
getAtomicOpSize(AtomicRMWInst * RMWI)120*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
121*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = RMWI->getModule()->getDataLayout();
122*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
123*9880d681SAndroid Build Coastguard Worker }
124*9880d681SAndroid Build Coastguard Worker 
getAtomicOpSize(AtomicCmpXchgInst * CASI)125*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
126*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = CASI->getModule()->getDataLayout();
127*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
128*9880d681SAndroid Build Coastguard Worker }
129*9880d681SAndroid Build Coastguard Worker 
130*9880d681SAndroid Build Coastguard Worker // Helper functions to retrieve the alignment of atomic instructions.
getAtomicOpAlign(LoadInst * LI)131*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpAlign(LoadInst *LI) {
132*9880d681SAndroid Build Coastguard Worker   unsigned Align = LI->getAlignment();
133*9880d681SAndroid Build Coastguard Worker   // In the future, if this IR restriction is relaxed, we should
134*9880d681SAndroid Build Coastguard Worker   // return DataLayout::getABITypeAlignment when there's no align
135*9880d681SAndroid Build Coastguard Worker   // value.
136*9880d681SAndroid Build Coastguard Worker   assert(Align != 0 && "An atomic LoadInst always has an explicit alignment");
137*9880d681SAndroid Build Coastguard Worker   return Align;
138*9880d681SAndroid Build Coastguard Worker }
139*9880d681SAndroid Build Coastguard Worker 
getAtomicOpAlign(StoreInst * SI)140*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpAlign(StoreInst *SI) {
141*9880d681SAndroid Build Coastguard Worker   unsigned Align = SI->getAlignment();
142*9880d681SAndroid Build Coastguard Worker   // In the future, if this IR restriction is relaxed, we should
143*9880d681SAndroid Build Coastguard Worker   // return DataLayout::getABITypeAlignment when there's no align
144*9880d681SAndroid Build Coastguard Worker   // value.
145*9880d681SAndroid Build Coastguard Worker   assert(Align != 0 && "An atomic StoreInst always has an explicit alignment");
146*9880d681SAndroid Build Coastguard Worker   return Align;
147*9880d681SAndroid Build Coastguard Worker }
148*9880d681SAndroid Build Coastguard Worker 
getAtomicOpAlign(AtomicRMWInst * RMWI)149*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpAlign(AtomicRMWInst *RMWI) {
150*9880d681SAndroid Build Coastguard Worker   // TODO(PR27168): This instruction has no alignment attribute, but unlike the
151*9880d681SAndroid Build Coastguard Worker   // default alignment for load/store, the default here is to assume
152*9880d681SAndroid Build Coastguard Worker   // it has NATURAL alignment, not DataLayout-specified alignment.
153*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = RMWI->getModule()->getDataLayout();
154*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
155*9880d681SAndroid Build Coastguard Worker }
156*9880d681SAndroid Build Coastguard Worker 
getAtomicOpAlign(AtomicCmpXchgInst * CASI)157*9880d681SAndroid Build Coastguard Worker unsigned getAtomicOpAlign(AtomicCmpXchgInst *CASI) {
158*9880d681SAndroid Build Coastguard Worker   // TODO(PR27168): same comment as above.
159*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = CASI->getModule()->getDataLayout();
160*9880d681SAndroid Build Coastguard Worker   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
161*9880d681SAndroid Build Coastguard Worker }
162*9880d681SAndroid Build Coastguard Worker 
163*9880d681SAndroid Build Coastguard Worker // Determine if a particular atomic operation has a supported size,
164*9880d681SAndroid Build Coastguard Worker // and is of appropriate alignment, to be passed through for target
165*9880d681SAndroid Build Coastguard Worker // lowering. (Versus turning into a __atomic libcall)
166*9880d681SAndroid Build Coastguard Worker template <typename Inst>
atomicSizeSupported(const TargetLowering * TLI,Inst * I)167*9880d681SAndroid Build Coastguard Worker bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
168*9880d681SAndroid Build Coastguard Worker   unsigned Size = getAtomicOpSize(I);
169*9880d681SAndroid Build Coastguard Worker   unsigned Align = getAtomicOpAlign(I);
170*9880d681SAndroid Build Coastguard Worker   return Align >= Size && Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
171*9880d681SAndroid Build Coastguard Worker }
172*9880d681SAndroid Build Coastguard Worker 
173*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
174*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)175*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::runOnFunction(Function &F) {
176*9880d681SAndroid Build Coastguard Worker   if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
177*9880d681SAndroid Build Coastguard Worker     return false;
178*9880d681SAndroid Build Coastguard Worker   TLI = TM->getSubtargetImpl(F)->getTargetLowering();
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker   SmallVector<Instruction *, 1> AtomicInsts;
181*9880d681SAndroid Build Coastguard Worker 
182*9880d681SAndroid Build Coastguard Worker   // Changing control-flow while iterating through it is a bad idea, so gather a
183*9880d681SAndroid Build Coastguard Worker   // list of all atomic instructions before we start.
184*9880d681SAndroid Build Coastguard Worker   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
185*9880d681SAndroid Build Coastguard Worker     Instruction *I = &*II;
186*9880d681SAndroid Build Coastguard Worker     if (I->isAtomic() && !isa<FenceInst>(I))
187*9880d681SAndroid Build Coastguard Worker       AtomicInsts.push_back(I);
188*9880d681SAndroid Build Coastguard Worker   }
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker   bool MadeChange = false;
191*9880d681SAndroid Build Coastguard Worker   for (auto I : AtomicInsts) {
192*9880d681SAndroid Build Coastguard Worker     auto LI = dyn_cast<LoadInst>(I);
193*9880d681SAndroid Build Coastguard Worker     auto SI = dyn_cast<StoreInst>(I);
194*9880d681SAndroid Build Coastguard Worker     auto RMWI = dyn_cast<AtomicRMWInst>(I);
195*9880d681SAndroid Build Coastguard Worker     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
196*9880d681SAndroid Build Coastguard Worker     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
197*9880d681SAndroid Build Coastguard Worker 
198*9880d681SAndroid Build Coastguard Worker     // If the Size/Alignment is not supported, replace with a libcall.
199*9880d681SAndroid Build Coastguard Worker     if (LI) {
200*9880d681SAndroid Build Coastguard Worker       if (!atomicSizeSupported(TLI, LI)) {
201*9880d681SAndroid Build Coastguard Worker         expandAtomicLoadToLibcall(LI);
202*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
203*9880d681SAndroid Build Coastguard Worker         continue;
204*9880d681SAndroid Build Coastguard Worker       }
205*9880d681SAndroid Build Coastguard Worker     } else if (SI) {
206*9880d681SAndroid Build Coastguard Worker       if (!atomicSizeSupported(TLI, SI)) {
207*9880d681SAndroid Build Coastguard Worker         expandAtomicStoreToLibcall(SI);
208*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
209*9880d681SAndroid Build Coastguard Worker         continue;
210*9880d681SAndroid Build Coastguard Worker       }
211*9880d681SAndroid Build Coastguard Worker     } else if (RMWI) {
212*9880d681SAndroid Build Coastguard Worker       if (!atomicSizeSupported(TLI, RMWI)) {
213*9880d681SAndroid Build Coastguard Worker         expandAtomicRMWToLibcall(RMWI);
214*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
215*9880d681SAndroid Build Coastguard Worker         continue;
216*9880d681SAndroid Build Coastguard Worker       }
217*9880d681SAndroid Build Coastguard Worker     } else if (CASI) {
218*9880d681SAndroid Build Coastguard Worker       if (!atomicSizeSupported(TLI, CASI)) {
219*9880d681SAndroid Build Coastguard Worker         expandAtomicCASToLibcall(CASI);
220*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
221*9880d681SAndroid Build Coastguard Worker         continue;
222*9880d681SAndroid Build Coastguard Worker       }
223*9880d681SAndroid Build Coastguard Worker     }
224*9880d681SAndroid Build Coastguard Worker 
225*9880d681SAndroid Build Coastguard Worker     if (TLI->shouldInsertFencesForAtomic(I)) {
226*9880d681SAndroid Build Coastguard Worker       auto FenceOrdering = AtomicOrdering::Monotonic;
227*9880d681SAndroid Build Coastguard Worker       bool IsStore, IsLoad;
228*9880d681SAndroid Build Coastguard Worker       if (LI && isAcquireOrStronger(LI->getOrdering())) {
229*9880d681SAndroid Build Coastguard Worker         FenceOrdering = LI->getOrdering();
230*9880d681SAndroid Build Coastguard Worker         LI->setOrdering(AtomicOrdering::Monotonic);
231*9880d681SAndroid Build Coastguard Worker         IsStore = false;
232*9880d681SAndroid Build Coastguard Worker         IsLoad = true;
233*9880d681SAndroid Build Coastguard Worker       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
234*9880d681SAndroid Build Coastguard Worker         FenceOrdering = SI->getOrdering();
235*9880d681SAndroid Build Coastguard Worker         SI->setOrdering(AtomicOrdering::Monotonic);
236*9880d681SAndroid Build Coastguard Worker         IsStore = true;
237*9880d681SAndroid Build Coastguard Worker         IsLoad = false;
238*9880d681SAndroid Build Coastguard Worker       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
239*9880d681SAndroid Build Coastguard Worker                           isAcquireOrStronger(RMWI->getOrdering()))) {
240*9880d681SAndroid Build Coastguard Worker         FenceOrdering = RMWI->getOrdering();
241*9880d681SAndroid Build Coastguard Worker         RMWI->setOrdering(AtomicOrdering::Monotonic);
242*9880d681SAndroid Build Coastguard Worker         IsStore = IsLoad = true;
243*9880d681SAndroid Build Coastguard Worker       } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
244*9880d681SAndroid Build Coastguard Worker                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
245*9880d681SAndroid Build Coastguard Worker                   isAcquireOrStronger(CASI->getSuccessOrdering()))) {
246*9880d681SAndroid Build Coastguard Worker         // If a compare and swap is lowered to LL/SC, we can do smarter fence
247*9880d681SAndroid Build Coastguard Worker         // insertion, with a stronger one on the success path than on the
248*9880d681SAndroid Build Coastguard Worker         // failure path. As a result, fence insertion is directly done by
249*9880d681SAndroid Build Coastguard Worker         // expandAtomicCmpXchg in that case.
250*9880d681SAndroid Build Coastguard Worker         FenceOrdering = CASI->getSuccessOrdering();
251*9880d681SAndroid Build Coastguard Worker         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
252*9880d681SAndroid Build Coastguard Worker         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
253*9880d681SAndroid Build Coastguard Worker         IsStore = IsLoad = true;
254*9880d681SAndroid Build Coastguard Worker       }
255*9880d681SAndroid Build Coastguard Worker 
256*9880d681SAndroid Build Coastguard Worker       if (FenceOrdering != AtomicOrdering::Monotonic) {
257*9880d681SAndroid Build Coastguard Worker         MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
258*9880d681SAndroid Build Coastguard Worker       }
259*9880d681SAndroid Build Coastguard Worker     }
260*9880d681SAndroid Build Coastguard Worker 
261*9880d681SAndroid Build Coastguard Worker     if (LI) {
262*9880d681SAndroid Build Coastguard Worker       if (LI->getType()->isFloatingPointTy()) {
263*9880d681SAndroid Build Coastguard Worker         // TODO: add a TLI hook to control this so that each target can
264*9880d681SAndroid Build Coastguard Worker         // convert to lowering the original type one at a time.
265*9880d681SAndroid Build Coastguard Worker         LI = convertAtomicLoadToIntegerType(LI);
266*9880d681SAndroid Build Coastguard Worker         assert(LI->getType()->isIntegerTy() && "invariant broken");
267*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
268*9880d681SAndroid Build Coastguard Worker       }
269*9880d681SAndroid Build Coastguard Worker 
270*9880d681SAndroid Build Coastguard Worker       MadeChange |= tryExpandAtomicLoad(LI);
271*9880d681SAndroid Build Coastguard Worker     } else if (SI) {
272*9880d681SAndroid Build Coastguard Worker       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
273*9880d681SAndroid Build Coastguard Worker         // TODO: add a TLI hook to control this so that each target can
274*9880d681SAndroid Build Coastguard Worker         // convert to lowering the original type one at a time.
275*9880d681SAndroid Build Coastguard Worker         SI = convertAtomicStoreToIntegerType(SI);
276*9880d681SAndroid Build Coastguard Worker         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
277*9880d681SAndroid Build Coastguard Worker                "invariant broken");
278*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
279*9880d681SAndroid Build Coastguard Worker       }
280*9880d681SAndroid Build Coastguard Worker 
281*9880d681SAndroid Build Coastguard Worker       if (TLI->shouldExpandAtomicStoreInIR(SI))
282*9880d681SAndroid Build Coastguard Worker         MadeChange |= expandAtomicStore(SI);
283*9880d681SAndroid Build Coastguard Worker     } else if (RMWI) {
284*9880d681SAndroid Build Coastguard Worker       // There are two different ways of expanding RMW instructions:
285*9880d681SAndroid Build Coastguard Worker       // - into a load if it is idempotent
286*9880d681SAndroid Build Coastguard Worker       // - into a Cmpxchg/LL-SC loop otherwise
287*9880d681SAndroid Build Coastguard Worker       // we try them in that order.
288*9880d681SAndroid Build Coastguard Worker 
289*9880d681SAndroid Build Coastguard Worker       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
290*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
291*9880d681SAndroid Build Coastguard Worker       } else {
292*9880d681SAndroid Build Coastguard Worker         MadeChange |= tryExpandAtomicRMW(RMWI);
293*9880d681SAndroid Build Coastguard Worker       }
294*9880d681SAndroid Build Coastguard Worker     } else if (CASI) {
295*9880d681SAndroid Build Coastguard Worker       // TODO: when we're ready to make the change at the IR level, we can
296*9880d681SAndroid Build Coastguard Worker       // extend convertCmpXchgToInteger for floating point too.
297*9880d681SAndroid Build Coastguard Worker       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
298*9880d681SAndroid Build Coastguard Worker              "unimplemented - floating point not legal at IR level");
299*9880d681SAndroid Build Coastguard Worker       if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
300*9880d681SAndroid Build Coastguard Worker         // TODO: add a TLI hook to control this so that each target can
301*9880d681SAndroid Build Coastguard Worker         // convert to lowering the original type one at a time.
302*9880d681SAndroid Build Coastguard Worker         CASI = convertCmpXchgToIntegerType(CASI);
303*9880d681SAndroid Build Coastguard Worker         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
304*9880d681SAndroid Build Coastguard Worker                "invariant broken");
305*9880d681SAndroid Build Coastguard Worker         MadeChange = true;
306*9880d681SAndroid Build Coastguard Worker       }
307*9880d681SAndroid Build Coastguard Worker 
308*9880d681SAndroid Build Coastguard Worker       unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
309*9880d681SAndroid Build Coastguard Worker       unsigned ValueSize = getAtomicOpSize(CASI);
310*9880d681SAndroid Build Coastguard Worker       if (ValueSize < MinCASSize) {
311*9880d681SAndroid Build Coastguard Worker         assert(!TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
312*9880d681SAndroid Build Coastguard Worker                "MinCmpXchgSizeInBits not yet supported for LL/SC expansions.");
313*9880d681SAndroid Build Coastguard Worker         expandPartwordCmpXchg(CASI);
314*9880d681SAndroid Build Coastguard Worker       } else {
315*9880d681SAndroid Build Coastguard Worker         if (TLI->shouldExpandAtomicCmpXchgInIR(CASI))
316*9880d681SAndroid Build Coastguard Worker           MadeChange |= expandAtomicCmpXchg(CASI);
317*9880d681SAndroid Build Coastguard Worker       }
318*9880d681SAndroid Build Coastguard Worker     }
319*9880d681SAndroid Build Coastguard Worker   }
320*9880d681SAndroid Build Coastguard Worker   return MadeChange;
321*9880d681SAndroid Build Coastguard Worker }
322*9880d681SAndroid Build Coastguard Worker 
bracketInstWithFences(Instruction * I,AtomicOrdering Order,bool IsStore,bool IsLoad)323*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
324*9880d681SAndroid Build Coastguard Worker                                          bool IsStore, bool IsLoad) {
325*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(I);
326*9880d681SAndroid Build Coastguard Worker 
327*9880d681SAndroid Build Coastguard Worker   auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
328*9880d681SAndroid Build Coastguard Worker 
329*9880d681SAndroid Build Coastguard Worker   auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
330*9880d681SAndroid Build Coastguard Worker   // The trailing fence is emitted before the instruction instead of after
331*9880d681SAndroid Build Coastguard Worker   // because there is no easy way of setting Builder insertion point after
332*9880d681SAndroid Build Coastguard Worker   // an instruction. So we must erase it from the BB, and insert it back
333*9880d681SAndroid Build Coastguard Worker   // in the right place.
334*9880d681SAndroid Build Coastguard Worker   // We have a guard here because not every atomic operation generates a
335*9880d681SAndroid Build Coastguard Worker   // trailing fence.
336*9880d681SAndroid Build Coastguard Worker   if (TrailingFence) {
337*9880d681SAndroid Build Coastguard Worker     TrailingFence->removeFromParent();
338*9880d681SAndroid Build Coastguard Worker     TrailingFence->insertAfter(I);
339*9880d681SAndroid Build Coastguard Worker   }
340*9880d681SAndroid Build Coastguard Worker 
341*9880d681SAndroid Build Coastguard Worker   return (LeadingFence || TrailingFence);
342*9880d681SAndroid Build Coastguard Worker }
343*9880d681SAndroid Build Coastguard Worker 
344*9880d681SAndroid Build Coastguard Worker /// Get the iX type with the same bitwidth as T.
getCorrespondingIntegerType(Type * T,const DataLayout & DL)345*9880d681SAndroid Build Coastguard Worker IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
346*9880d681SAndroid Build Coastguard Worker                                                        const DataLayout &DL) {
347*9880d681SAndroid Build Coastguard Worker   EVT VT = TLI->getValueType(DL, T);
348*9880d681SAndroid Build Coastguard Worker   unsigned BitWidth = VT.getStoreSizeInBits();
349*9880d681SAndroid Build Coastguard Worker   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
350*9880d681SAndroid Build Coastguard Worker   return IntegerType::get(T->getContext(), BitWidth);
351*9880d681SAndroid Build Coastguard Worker }
352*9880d681SAndroid Build Coastguard Worker 
353*9880d681SAndroid Build Coastguard Worker /// Convert an atomic load of a non-integral type to an integer load of the
354*9880d681SAndroid Build Coastguard Worker /// equivalent bitwidth.  See the function comment on
355*9880d681SAndroid Build Coastguard Worker /// convertAtomicStoreToIntegerType for background.
convertAtomicLoadToIntegerType(LoadInst * LI)356*9880d681SAndroid Build Coastguard Worker LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
357*9880d681SAndroid Build Coastguard Worker   auto *M = LI->getModule();
358*9880d681SAndroid Build Coastguard Worker   Type *NewTy = getCorrespondingIntegerType(LI->getType(),
359*9880d681SAndroid Build Coastguard Worker                                             M->getDataLayout());
360*9880d681SAndroid Build Coastguard Worker 
361*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(LI);
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   Value *Addr = LI->getPointerOperand();
364*9880d681SAndroid Build Coastguard Worker   Type *PT = PointerType::get(NewTy,
365*9880d681SAndroid Build Coastguard Worker                               Addr->getType()->getPointerAddressSpace());
366*9880d681SAndroid Build Coastguard Worker   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
367*9880d681SAndroid Build Coastguard Worker 
368*9880d681SAndroid Build Coastguard Worker   auto *NewLI = Builder.CreateLoad(NewAddr);
369*9880d681SAndroid Build Coastguard Worker   NewLI->setAlignment(LI->getAlignment());
370*9880d681SAndroid Build Coastguard Worker   NewLI->setVolatile(LI->isVolatile());
371*9880d681SAndroid Build Coastguard Worker   NewLI->setAtomic(LI->getOrdering(), LI->getSynchScope());
372*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
375*9880d681SAndroid Build Coastguard Worker   LI->replaceAllUsesWith(NewVal);
376*9880d681SAndroid Build Coastguard Worker   LI->eraseFromParent();
377*9880d681SAndroid Build Coastguard Worker   return NewLI;
378*9880d681SAndroid Build Coastguard Worker }
379*9880d681SAndroid Build Coastguard Worker 
tryExpandAtomicLoad(LoadInst * LI)380*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
381*9880d681SAndroid Build Coastguard Worker   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
382*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::None:
383*9880d681SAndroid Build Coastguard Worker     return false;
384*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::LLSC:
385*9880d681SAndroid Build Coastguard Worker     expandAtomicOpToLLSC(
386*9880d681SAndroid Build Coastguard Worker         LI, LI->getType(), LI->getPointerOperand(), LI->getOrdering(),
387*9880d681SAndroid Build Coastguard Worker         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
388*9880d681SAndroid Build Coastguard Worker     return true;
389*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
390*9880d681SAndroid Build Coastguard Worker     return expandAtomicLoadToLL(LI);
391*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
392*9880d681SAndroid Build Coastguard Worker     return expandAtomicLoadToCmpXchg(LI);
393*9880d681SAndroid Build Coastguard Worker   }
394*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
395*9880d681SAndroid Build Coastguard Worker }
396*9880d681SAndroid Build Coastguard Worker 
expandAtomicLoadToLL(LoadInst * LI)397*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
398*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(LI);
399*9880d681SAndroid Build Coastguard Worker 
400*9880d681SAndroid Build Coastguard Worker   // On some architectures, load-linked instructions are atomic for larger
401*9880d681SAndroid Build Coastguard Worker   // sizes than normal loads. For example, the only 64-bit load guaranteed
402*9880d681SAndroid Build Coastguard Worker   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
403*9880d681SAndroid Build Coastguard Worker   Value *Val =
404*9880d681SAndroid Build Coastguard Worker       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
405*9880d681SAndroid Build Coastguard Worker   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
406*9880d681SAndroid Build Coastguard Worker 
407*9880d681SAndroid Build Coastguard Worker   LI->replaceAllUsesWith(Val);
408*9880d681SAndroid Build Coastguard Worker   LI->eraseFromParent();
409*9880d681SAndroid Build Coastguard Worker 
410*9880d681SAndroid Build Coastguard Worker   return true;
411*9880d681SAndroid Build Coastguard Worker }
412*9880d681SAndroid Build Coastguard Worker 
expandAtomicLoadToCmpXchg(LoadInst * LI)413*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
414*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(LI);
415*9880d681SAndroid Build Coastguard Worker   AtomicOrdering Order = LI->getOrdering();
416*9880d681SAndroid Build Coastguard Worker   Value *Addr = LI->getPointerOperand();
417*9880d681SAndroid Build Coastguard Worker   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
418*9880d681SAndroid Build Coastguard Worker   Constant *DummyVal = Constant::getNullValue(Ty);
419*9880d681SAndroid Build Coastguard Worker 
420*9880d681SAndroid Build Coastguard Worker   Value *Pair = Builder.CreateAtomicCmpXchg(
421*9880d681SAndroid Build Coastguard Worker       Addr, DummyVal, DummyVal, Order,
422*9880d681SAndroid Build Coastguard Worker       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
423*9880d681SAndroid Build Coastguard Worker   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
424*9880d681SAndroid Build Coastguard Worker 
425*9880d681SAndroid Build Coastguard Worker   LI->replaceAllUsesWith(Loaded);
426*9880d681SAndroid Build Coastguard Worker   LI->eraseFromParent();
427*9880d681SAndroid Build Coastguard Worker 
428*9880d681SAndroid Build Coastguard Worker   return true;
429*9880d681SAndroid Build Coastguard Worker }
430*9880d681SAndroid Build Coastguard Worker 
431*9880d681SAndroid Build Coastguard Worker /// Convert an atomic store of a non-integral type to an integer store of the
432*9880d681SAndroid Build Coastguard Worker /// equivalent bitwidth.  We used to not support floating point or vector
433*9880d681SAndroid Build Coastguard Worker /// atomics in the IR at all.  The backends learned to deal with the bitcast
434*9880d681SAndroid Build Coastguard Worker /// idiom because that was the only way of expressing the notion of a atomic
435*9880d681SAndroid Build Coastguard Worker /// float or vector store.  The long term plan is to teach each backend to
436*9880d681SAndroid Build Coastguard Worker /// instruction select from the original atomic store, but as a migration
437*9880d681SAndroid Build Coastguard Worker /// mechanism, we convert back to the old format which the backends understand.
438*9880d681SAndroid Build Coastguard Worker /// Each backend will need individual work to recognize the new format.
convertAtomicStoreToIntegerType(StoreInst * SI)439*9880d681SAndroid Build Coastguard Worker StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
440*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(SI);
441*9880d681SAndroid Build Coastguard Worker   auto *M = SI->getModule();
442*9880d681SAndroid Build Coastguard Worker   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
443*9880d681SAndroid Build Coastguard Worker                                             M->getDataLayout());
444*9880d681SAndroid Build Coastguard Worker   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
445*9880d681SAndroid Build Coastguard Worker 
446*9880d681SAndroid Build Coastguard Worker   Value *Addr = SI->getPointerOperand();
447*9880d681SAndroid Build Coastguard Worker   Type *PT = PointerType::get(NewTy,
448*9880d681SAndroid Build Coastguard Worker                               Addr->getType()->getPointerAddressSpace());
449*9880d681SAndroid Build Coastguard Worker   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
450*9880d681SAndroid Build Coastguard Worker 
451*9880d681SAndroid Build Coastguard Worker   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
452*9880d681SAndroid Build Coastguard Worker   NewSI->setAlignment(SI->getAlignment());
453*9880d681SAndroid Build Coastguard Worker   NewSI->setVolatile(SI->isVolatile());
454*9880d681SAndroid Build Coastguard Worker   NewSI->setAtomic(SI->getOrdering(), SI->getSynchScope());
455*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
456*9880d681SAndroid Build Coastguard Worker   SI->eraseFromParent();
457*9880d681SAndroid Build Coastguard Worker   return NewSI;
458*9880d681SAndroid Build Coastguard Worker }
459*9880d681SAndroid Build Coastguard Worker 
expandAtomicStore(StoreInst * SI)460*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
461*9880d681SAndroid Build Coastguard Worker   // This function is only called on atomic stores that are too large to be
462*9880d681SAndroid Build Coastguard Worker   // atomic if implemented as a native store. So we replace them by an
463*9880d681SAndroid Build Coastguard Worker   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
464*9880d681SAndroid Build Coastguard Worker   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
465*9880d681SAndroid Build Coastguard Worker   // It is the responsibility of the target to only signal expansion via
466*9880d681SAndroid Build Coastguard Worker   // shouldExpandAtomicRMW in cases where this is required and possible.
467*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(SI);
468*9880d681SAndroid Build Coastguard Worker   AtomicRMWInst *AI =
469*9880d681SAndroid Build Coastguard Worker       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
470*9880d681SAndroid Build Coastguard Worker                               SI->getValueOperand(), SI->getOrdering());
471*9880d681SAndroid Build Coastguard Worker   SI->eraseFromParent();
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker   // Now we have an appropriate swap instruction, lower it as usual.
474*9880d681SAndroid Build Coastguard Worker   return tryExpandAtomicRMW(AI);
475*9880d681SAndroid Build Coastguard Worker }
476*9880d681SAndroid Build Coastguard Worker 
createCmpXchgInstFun(IRBuilder<> & Builder,Value * Addr,Value * Loaded,Value * NewVal,AtomicOrdering MemOpOrder,Value * & Success,Value * & NewLoaded)477*9880d681SAndroid Build Coastguard Worker static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
478*9880d681SAndroid Build Coastguard Worker                                  Value *Loaded, Value *NewVal,
479*9880d681SAndroid Build Coastguard Worker                                  AtomicOrdering MemOpOrder,
480*9880d681SAndroid Build Coastguard Worker                                  Value *&Success, Value *&NewLoaded) {
481*9880d681SAndroid Build Coastguard Worker   Value* Pair = Builder.CreateAtomicCmpXchg(
482*9880d681SAndroid Build Coastguard Worker       Addr, Loaded, NewVal, MemOpOrder,
483*9880d681SAndroid Build Coastguard Worker       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
484*9880d681SAndroid Build Coastguard Worker   Success = Builder.CreateExtractValue(Pair, 1, "success");
485*9880d681SAndroid Build Coastguard Worker   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
486*9880d681SAndroid Build Coastguard Worker }
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker /// Emit IR to implement the given atomicrmw operation on values in registers,
489*9880d681SAndroid Build Coastguard Worker /// returning the new value.
performAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Inc)490*9880d681SAndroid Build Coastguard Worker static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
491*9880d681SAndroid Build Coastguard Worker                               Value *Loaded, Value *Inc) {
492*9880d681SAndroid Build Coastguard Worker   Value *NewVal;
493*9880d681SAndroid Build Coastguard Worker   switch (Op) {
494*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xchg:
495*9880d681SAndroid Build Coastguard Worker     return Inc;
496*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Add:
497*9880d681SAndroid Build Coastguard Worker     return Builder.CreateAdd(Loaded, Inc, "new");
498*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Sub:
499*9880d681SAndroid Build Coastguard Worker     return Builder.CreateSub(Loaded, Inc, "new");
500*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::And:
501*9880d681SAndroid Build Coastguard Worker     return Builder.CreateAnd(Loaded, Inc, "new");
502*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Nand:
503*9880d681SAndroid Build Coastguard Worker     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
504*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Or:
505*9880d681SAndroid Build Coastguard Worker     return Builder.CreateOr(Loaded, Inc, "new");
506*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xor:
507*9880d681SAndroid Build Coastguard Worker     return Builder.CreateXor(Loaded, Inc, "new");
508*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Max:
509*9880d681SAndroid Build Coastguard Worker     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
510*9880d681SAndroid Build Coastguard Worker     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
511*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Min:
512*9880d681SAndroid Build Coastguard Worker     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
513*9880d681SAndroid Build Coastguard Worker     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
514*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMax:
515*9880d681SAndroid Build Coastguard Worker     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
516*9880d681SAndroid Build Coastguard Worker     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
517*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMin:
518*9880d681SAndroid Build Coastguard Worker     NewVal = Builder.CreateICmpULE(Loaded, Inc);
519*9880d681SAndroid Build Coastguard Worker     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
520*9880d681SAndroid Build Coastguard Worker   default:
521*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unknown atomic op");
522*9880d681SAndroid Build Coastguard Worker   }
523*9880d681SAndroid Build Coastguard Worker }
524*9880d681SAndroid Build Coastguard Worker 
tryExpandAtomicRMW(AtomicRMWInst * AI)525*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
526*9880d681SAndroid Build Coastguard Worker   switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
527*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::None:
528*9880d681SAndroid Build Coastguard Worker     return false;
529*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
530*9880d681SAndroid Build Coastguard Worker     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
531*9880d681SAndroid Build Coastguard Worker     unsigned ValueSize = getAtomicOpSize(AI);
532*9880d681SAndroid Build Coastguard Worker     if (ValueSize < MinCASSize) {
533*9880d681SAndroid Build Coastguard Worker       llvm_unreachable(
534*9880d681SAndroid Build Coastguard Worker           "MinCmpXchgSizeInBits not yet supported for LL/SC architectures.");
535*9880d681SAndroid Build Coastguard Worker     } else {
536*9880d681SAndroid Build Coastguard Worker       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
537*9880d681SAndroid Build Coastguard Worker         return performAtomicOp(AI->getOperation(), Builder, Loaded,
538*9880d681SAndroid Build Coastguard Worker                                AI->getValOperand());
539*9880d681SAndroid Build Coastguard Worker       };
540*9880d681SAndroid Build Coastguard Worker       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
541*9880d681SAndroid Build Coastguard Worker                            AI->getOrdering(), PerformOp);
542*9880d681SAndroid Build Coastguard Worker     }
543*9880d681SAndroid Build Coastguard Worker     return true;
544*9880d681SAndroid Build Coastguard Worker   }
545*9880d681SAndroid Build Coastguard Worker   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
546*9880d681SAndroid Build Coastguard Worker     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
547*9880d681SAndroid Build Coastguard Worker     unsigned ValueSize = getAtomicOpSize(AI);
548*9880d681SAndroid Build Coastguard Worker     if (ValueSize < MinCASSize) {
549*9880d681SAndroid Build Coastguard Worker       expandPartwordAtomicRMW(AI,
550*9880d681SAndroid Build Coastguard Worker                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
551*9880d681SAndroid Build Coastguard Worker     } else {
552*9880d681SAndroid Build Coastguard Worker       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
553*9880d681SAndroid Build Coastguard Worker     }
554*9880d681SAndroid Build Coastguard Worker     return true;
555*9880d681SAndroid Build Coastguard Worker   }
556*9880d681SAndroid Build Coastguard Worker   default:
557*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
558*9880d681SAndroid Build Coastguard Worker   }
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker 
561*9880d681SAndroid Build Coastguard Worker namespace {
562*9880d681SAndroid Build Coastguard Worker 
563*9880d681SAndroid Build Coastguard Worker /// Result values from createMaskInstrs helper.
564*9880d681SAndroid Build Coastguard Worker struct PartwordMaskValues {
565*9880d681SAndroid Build Coastguard Worker   Type *WordType;
566*9880d681SAndroid Build Coastguard Worker   Type *ValueType;
567*9880d681SAndroid Build Coastguard Worker   Value *AlignedAddr;
568*9880d681SAndroid Build Coastguard Worker   Value *ShiftAmt;
569*9880d681SAndroid Build Coastguard Worker   Value *Mask;
570*9880d681SAndroid Build Coastguard Worker   Value *Inv_Mask;
571*9880d681SAndroid Build Coastguard Worker };
572*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker /// This is a helper function which builds instructions to provide
575*9880d681SAndroid Build Coastguard Worker /// values necessary for partword atomic operations. It takes an
576*9880d681SAndroid Build Coastguard Worker /// incoming address, Addr, and ValueType, and constructs the address,
577*9880d681SAndroid Build Coastguard Worker /// shift-amounts and masks needed to work with a larger value of size
578*9880d681SAndroid Build Coastguard Worker /// WordSize.
579*9880d681SAndroid Build Coastguard Worker ///
580*9880d681SAndroid Build Coastguard Worker /// AlignedAddr: Addr rounded down to a multiple of WordSize
581*9880d681SAndroid Build Coastguard Worker ///
582*9880d681SAndroid Build Coastguard Worker /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
583*9880d681SAndroid Build Coastguard Worker ///           from AlignAddr for it to have the same value as if
584*9880d681SAndroid Build Coastguard Worker ///           ValueType was loaded from Addr.
585*9880d681SAndroid Build Coastguard Worker ///
586*9880d681SAndroid Build Coastguard Worker /// Mask: Value to mask with the value loaded from AlignAddr to
587*9880d681SAndroid Build Coastguard Worker ///       include only the part that would've been loaded from Addr.
588*9880d681SAndroid Build Coastguard Worker ///
589*9880d681SAndroid Build Coastguard Worker /// Inv_Mask: The inverse of Mask.
590*9880d681SAndroid Build Coastguard Worker 
createMaskInstrs(IRBuilder<> & Builder,Instruction * I,Type * ValueType,Value * Addr,unsigned WordSize)591*9880d681SAndroid Build Coastguard Worker static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
592*9880d681SAndroid Build Coastguard Worker                                            Type *ValueType, Value *Addr,
593*9880d681SAndroid Build Coastguard Worker                                            unsigned WordSize) {
594*9880d681SAndroid Build Coastguard Worker   PartwordMaskValues Ret;
595*9880d681SAndroid Build Coastguard Worker 
596*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = I->getParent();
597*9880d681SAndroid Build Coastguard Worker   Function *F = BB->getParent();
598*9880d681SAndroid Build Coastguard Worker   Module *M = I->getModule();
599*9880d681SAndroid Build Coastguard Worker 
600*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = F->getContext();
601*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = M->getDataLayout();
602*9880d681SAndroid Build Coastguard Worker 
603*9880d681SAndroid Build Coastguard Worker   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
604*9880d681SAndroid Build Coastguard Worker 
605*9880d681SAndroid Build Coastguard Worker   assert(ValueSize < WordSize);
606*9880d681SAndroid Build Coastguard Worker 
607*9880d681SAndroid Build Coastguard Worker   Ret.ValueType = ValueType;
608*9880d681SAndroid Build Coastguard Worker   Ret.WordType = Type::getIntNTy(Ctx, WordSize * 8);
609*9880d681SAndroid Build Coastguard Worker 
610*9880d681SAndroid Build Coastguard Worker   Type *WordPtrType =
611*9880d681SAndroid Build Coastguard Worker       Ret.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
612*9880d681SAndroid Build Coastguard Worker 
613*9880d681SAndroid Build Coastguard Worker   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
614*9880d681SAndroid Build Coastguard Worker   Ret.AlignedAddr = Builder.CreateIntToPtr(
615*9880d681SAndroid Build Coastguard Worker       Builder.CreateAnd(AddrInt, ~(uint64_t)(WordSize - 1)), WordPtrType,
616*9880d681SAndroid Build Coastguard Worker       "AlignedAddr");
617*9880d681SAndroid Build Coastguard Worker 
618*9880d681SAndroid Build Coastguard Worker   Value *PtrLSB = Builder.CreateAnd(AddrInt, WordSize - 1, "PtrLSB");
619*9880d681SAndroid Build Coastguard Worker   if (DL.isLittleEndian()) {
620*9880d681SAndroid Build Coastguard Worker     // turn bytes into bits
621*9880d681SAndroid Build Coastguard Worker     Ret.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
622*9880d681SAndroid Build Coastguard Worker   } else {
623*9880d681SAndroid Build Coastguard Worker     // turn bytes into bits, and count from the other side.
624*9880d681SAndroid Build Coastguard Worker     Ret.ShiftAmt =
625*9880d681SAndroid Build Coastguard Worker         Builder.CreateShl(Builder.CreateXor(PtrLSB, WordSize - ValueSize), 3);
626*9880d681SAndroid Build Coastguard Worker   }
627*9880d681SAndroid Build Coastguard Worker 
628*9880d681SAndroid Build Coastguard Worker   Ret.ShiftAmt = Builder.CreateTrunc(Ret.ShiftAmt, Ret.WordType, "ShiftAmt");
629*9880d681SAndroid Build Coastguard Worker   Ret.Mask = Builder.CreateShl(
630*9880d681SAndroid Build Coastguard Worker       ConstantInt::get(Ret.WordType, (1 << ValueSize * 8) - 1), Ret.ShiftAmt,
631*9880d681SAndroid Build Coastguard Worker       "Mask");
632*9880d681SAndroid Build Coastguard Worker   Ret.Inv_Mask = Builder.CreateNot(Ret.Mask, "Inv_Mask");
633*9880d681SAndroid Build Coastguard Worker 
634*9880d681SAndroid Build Coastguard Worker   return Ret;
635*9880d681SAndroid Build Coastguard Worker }
636*9880d681SAndroid Build Coastguard Worker 
637*9880d681SAndroid Build Coastguard Worker /// Emit IR to implement a masked version of a given atomicrmw
638*9880d681SAndroid Build Coastguard Worker /// operation. (That is, only the bits under the Mask should be
639*9880d681SAndroid Build Coastguard Worker /// affected by the operation)
performMaskedAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Shifted_Inc,Value * Inc,const PartwordMaskValues & PMV)640*9880d681SAndroid Build Coastguard Worker static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
641*9880d681SAndroid Build Coastguard Worker                                     IRBuilder<> &Builder, Value *Loaded,
642*9880d681SAndroid Build Coastguard Worker                                     Value *Shifted_Inc, Value *Inc,
643*9880d681SAndroid Build Coastguard Worker                                     const PartwordMaskValues &PMV) {
644*9880d681SAndroid Build Coastguard Worker   switch (Op) {
645*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xchg: {
646*9880d681SAndroid Build Coastguard Worker     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
647*9880d681SAndroid Build Coastguard Worker     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
648*9880d681SAndroid Build Coastguard Worker     return FinalVal;
649*9880d681SAndroid Build Coastguard Worker   }
650*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Or:
651*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xor:
652*9880d681SAndroid Build Coastguard Worker     // Or/Xor won't affect any other bits, so can just be done
653*9880d681SAndroid Build Coastguard Worker     // directly.
654*9880d681SAndroid Build Coastguard Worker     return performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
655*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Add:
656*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Sub:
657*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::And:
658*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Nand: {
659*9880d681SAndroid Build Coastguard Worker     // The other arithmetic ops need to be masked into place.
660*9880d681SAndroid Build Coastguard Worker     Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
661*9880d681SAndroid Build Coastguard Worker     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
662*9880d681SAndroid Build Coastguard Worker     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
663*9880d681SAndroid Build Coastguard Worker     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
664*9880d681SAndroid Build Coastguard Worker     return FinalVal;
665*9880d681SAndroid Build Coastguard Worker   }
666*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Max:
667*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Min:
668*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMax:
669*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMin: {
670*9880d681SAndroid Build Coastguard Worker     // Finally, comparison ops will operate on the full value, so
671*9880d681SAndroid Build Coastguard Worker     // truncate down to the original size, and expand out again after
672*9880d681SAndroid Build Coastguard Worker     // doing the operation.
673*9880d681SAndroid Build Coastguard Worker     Value *Loaded_Shiftdown = Builder.CreateTrunc(
674*9880d681SAndroid Build Coastguard Worker         Builder.CreateLShr(Loaded, PMV.ShiftAmt), PMV.ValueType);
675*9880d681SAndroid Build Coastguard Worker     Value *NewVal = performAtomicOp(Op, Builder, Loaded_Shiftdown, Inc);
676*9880d681SAndroid Build Coastguard Worker     Value *NewVal_Shiftup = Builder.CreateShl(
677*9880d681SAndroid Build Coastguard Worker         Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
678*9880d681SAndroid Build Coastguard Worker     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
679*9880d681SAndroid Build Coastguard Worker     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shiftup);
680*9880d681SAndroid Build Coastguard Worker     return FinalVal;
681*9880d681SAndroid Build Coastguard Worker   }
682*9880d681SAndroid Build Coastguard Worker   default:
683*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Unknown atomic op");
684*9880d681SAndroid Build Coastguard Worker   }
685*9880d681SAndroid Build Coastguard Worker }
686*9880d681SAndroid Build Coastguard Worker 
687*9880d681SAndroid Build Coastguard Worker /// Expand a sub-word atomicrmw operation into an appropriate
688*9880d681SAndroid Build Coastguard Worker /// word-sized operation.
689*9880d681SAndroid Build Coastguard Worker ///
690*9880d681SAndroid Build Coastguard Worker /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
691*9880d681SAndroid Build Coastguard Worker /// way as a typical atomicrmw expansion. The only difference here is
692*9880d681SAndroid Build Coastguard Worker /// that the operation inside of the loop must operate only upon a
693*9880d681SAndroid Build Coastguard Worker /// part of the value.
expandPartwordAtomicRMW(AtomicRMWInst * AI,TargetLoweringBase::AtomicExpansionKind ExpansionKind)694*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandPartwordAtomicRMW(
695*9880d681SAndroid Build Coastguard Worker     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
696*9880d681SAndroid Build Coastguard Worker 
697*9880d681SAndroid Build Coastguard Worker   assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg);
698*9880d681SAndroid Build Coastguard Worker 
699*9880d681SAndroid Build Coastguard Worker   AtomicOrdering MemOpOrder = AI->getOrdering();
700*9880d681SAndroid Build Coastguard Worker 
701*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(AI);
702*9880d681SAndroid Build Coastguard Worker 
703*9880d681SAndroid Build Coastguard Worker   PartwordMaskValues PMV =
704*9880d681SAndroid Build Coastguard Worker       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
705*9880d681SAndroid Build Coastguard Worker                        TLI->getMinCmpXchgSizeInBits() / 8);
706*9880d681SAndroid Build Coastguard Worker 
707*9880d681SAndroid Build Coastguard Worker   Value *ValOperand_Shifted =
708*9880d681SAndroid Build Coastguard Worker       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
709*9880d681SAndroid Build Coastguard Worker                         PMV.ShiftAmt, "ValOperand_Shifted");
710*9880d681SAndroid Build Coastguard Worker 
711*9880d681SAndroid Build Coastguard Worker   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
712*9880d681SAndroid Build Coastguard Worker     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
713*9880d681SAndroid Build Coastguard Worker                                  ValOperand_Shifted, AI->getValOperand(), PMV);
714*9880d681SAndroid Build Coastguard Worker   };
715*9880d681SAndroid Build Coastguard Worker 
716*9880d681SAndroid Build Coastguard Worker   // TODO: When we're ready to support LLSC conversions too, use
717*9880d681SAndroid Build Coastguard Worker   // insertRMWLLSCLoop here for ExpansionKind==LLSC.
718*9880d681SAndroid Build Coastguard Worker   Value *OldResult =
719*9880d681SAndroid Build Coastguard Worker       insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder,
720*9880d681SAndroid Build Coastguard Worker                            PerformPartwordOp, createCmpXchgInstFun);
721*9880d681SAndroid Build Coastguard Worker   Value *FinalOldResult = Builder.CreateTrunc(
722*9880d681SAndroid Build Coastguard Worker       Builder.CreateLShr(OldResult, PMV.ShiftAmt), PMV.ValueType);
723*9880d681SAndroid Build Coastguard Worker   AI->replaceAllUsesWith(FinalOldResult);
724*9880d681SAndroid Build Coastguard Worker   AI->eraseFromParent();
725*9880d681SAndroid Build Coastguard Worker }
726*9880d681SAndroid Build Coastguard Worker 
expandPartwordCmpXchg(AtomicCmpXchgInst * CI)727*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
728*9880d681SAndroid Build Coastguard Worker   // The basic idea here is that we're expanding a cmpxchg of a
729*9880d681SAndroid Build Coastguard Worker   // smaller memory size up to a word-sized cmpxchg. To do this, we
730*9880d681SAndroid Build Coastguard Worker   // need to add a retry-loop for strong cmpxchg, so that
731*9880d681SAndroid Build Coastguard Worker   // modifications to other parts of the word don't cause a spurious
732*9880d681SAndroid Build Coastguard Worker   // failure.
733*9880d681SAndroid Build Coastguard Worker 
734*9880d681SAndroid Build Coastguard Worker   // This generates code like the following:
735*9880d681SAndroid Build Coastguard Worker   //     [[Setup mask values PMV.*]]
736*9880d681SAndroid Build Coastguard Worker   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
737*9880d681SAndroid Build Coastguard Worker   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
738*9880d681SAndroid Build Coastguard Worker   //     %InitLoaded = load i32* %addr
739*9880d681SAndroid Build Coastguard Worker   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
740*9880d681SAndroid Build Coastguard Worker   //     br partword.cmpxchg.loop
741*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.loop:
742*9880d681SAndroid Build Coastguard Worker   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
743*9880d681SAndroid Build Coastguard Worker   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
744*9880d681SAndroid Build Coastguard Worker   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
745*9880d681SAndroid Build Coastguard Worker   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
746*9880d681SAndroid Build Coastguard Worker   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
747*9880d681SAndroid Build Coastguard Worker   //        i32 %FullWord_NewVal success_ordering failure_ordering
748*9880d681SAndroid Build Coastguard Worker   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
749*9880d681SAndroid Build Coastguard Worker   //     %Success = extractvalue { i32, i1 } %NewCI, 1
750*9880d681SAndroid Build Coastguard Worker   //     br i1 %Success, label %partword.cmpxchg.end,
751*9880d681SAndroid Build Coastguard Worker   //        label %partword.cmpxchg.failure
752*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.failure:
753*9880d681SAndroid Build Coastguard Worker   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
754*9880d681SAndroid Build Coastguard Worker   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
755*9880d681SAndroid Build Coastguard Worker   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
756*9880d681SAndroid Build Coastguard Worker   //         label %partword.cmpxchg.end
757*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.end:
758*9880d681SAndroid Build Coastguard Worker   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
759*9880d681SAndroid Build Coastguard Worker   //    %FinalOldVal = trunc i32 %tmp1 to i8
760*9880d681SAndroid Build Coastguard Worker   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
761*9880d681SAndroid Build Coastguard Worker   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
762*9880d681SAndroid Build Coastguard Worker 
763*9880d681SAndroid Build Coastguard Worker   Value *Addr = CI->getPointerOperand();
764*9880d681SAndroid Build Coastguard Worker   Value *Cmp = CI->getCompareOperand();
765*9880d681SAndroid Build Coastguard Worker   Value *NewVal = CI->getNewValOperand();
766*9880d681SAndroid Build Coastguard Worker 
767*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = CI->getParent();
768*9880d681SAndroid Build Coastguard Worker   Function *F = BB->getParent();
769*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(CI);
770*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = Builder.getContext();
771*9880d681SAndroid Build Coastguard Worker 
772*9880d681SAndroid Build Coastguard Worker   const int WordSize = TLI->getMinCmpXchgSizeInBits() / 8;
773*9880d681SAndroid Build Coastguard Worker 
774*9880d681SAndroid Build Coastguard Worker   BasicBlock *EndBB =
775*9880d681SAndroid Build Coastguard Worker       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
776*9880d681SAndroid Build Coastguard Worker   auto FailureBB =
777*9880d681SAndroid Build Coastguard Worker       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
778*9880d681SAndroid Build Coastguard Worker   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
779*9880d681SAndroid Build Coastguard Worker 
780*9880d681SAndroid Build Coastguard Worker   // The split call above "helpfully" added a branch at the end of BB
781*9880d681SAndroid Build Coastguard Worker   // (to the wrong place).
782*9880d681SAndroid Build Coastguard Worker   std::prev(BB->end())->eraseFromParent();
783*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(BB);
784*9880d681SAndroid Build Coastguard Worker 
785*9880d681SAndroid Build Coastguard Worker   PartwordMaskValues PMV = createMaskInstrs(
786*9880d681SAndroid Build Coastguard Worker       Builder, CI, CI->getCompareOperand()->getType(), Addr, WordSize);
787*9880d681SAndroid Build Coastguard Worker 
788*9880d681SAndroid Build Coastguard Worker   // Shift the incoming values over, into the right location in the word.
789*9880d681SAndroid Build Coastguard Worker   Value *NewVal_Shifted =
790*9880d681SAndroid Build Coastguard Worker       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
791*9880d681SAndroid Build Coastguard Worker   Value *Cmp_Shifted =
792*9880d681SAndroid Build Coastguard Worker       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
793*9880d681SAndroid Build Coastguard Worker 
794*9880d681SAndroid Build Coastguard Worker   // Load the entire current word, and mask into place the expected and new
795*9880d681SAndroid Build Coastguard Worker   // values
796*9880d681SAndroid Build Coastguard Worker   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
797*9880d681SAndroid Build Coastguard Worker   InitLoaded->setVolatile(CI->isVolatile());
798*9880d681SAndroid Build Coastguard Worker   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
799*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(LoopBB);
800*9880d681SAndroid Build Coastguard Worker 
801*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.loop:
802*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(LoopBB);
803*9880d681SAndroid Build Coastguard Worker   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
804*9880d681SAndroid Build Coastguard Worker   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
805*9880d681SAndroid Build Coastguard Worker 
806*9880d681SAndroid Build Coastguard Worker   // Mask/Or the expected and new values into place in the loaded word.
807*9880d681SAndroid Build Coastguard Worker   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
808*9880d681SAndroid Build Coastguard Worker   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
809*9880d681SAndroid Build Coastguard Worker   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
810*9880d681SAndroid Build Coastguard Worker       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, CI->getSuccessOrdering(),
811*9880d681SAndroid Build Coastguard Worker       CI->getFailureOrdering(), CI->getSynchScope());
812*9880d681SAndroid Build Coastguard Worker   NewCI->setVolatile(CI->isVolatile());
813*9880d681SAndroid Build Coastguard Worker   // When we're building a strong cmpxchg, we need a loop, so you
814*9880d681SAndroid Build Coastguard Worker   // might think we could use a weak cmpxchg inside. But, using strong
815*9880d681SAndroid Build Coastguard Worker   // allows the below comparison for ShouldContinue, and we're
816*9880d681SAndroid Build Coastguard Worker   // expecting the underlying cmpxchg to be a machine instruction,
817*9880d681SAndroid Build Coastguard Worker   // which is strong anyways.
818*9880d681SAndroid Build Coastguard Worker   NewCI->setWeak(CI->isWeak());
819*9880d681SAndroid Build Coastguard Worker 
820*9880d681SAndroid Build Coastguard Worker   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
821*9880d681SAndroid Build Coastguard Worker   Value *Success = Builder.CreateExtractValue(NewCI, 1);
822*9880d681SAndroid Build Coastguard Worker 
823*9880d681SAndroid Build Coastguard Worker   if (CI->isWeak())
824*9880d681SAndroid Build Coastguard Worker     Builder.CreateBr(EndBB);
825*9880d681SAndroid Build Coastguard Worker   else
826*9880d681SAndroid Build Coastguard Worker     Builder.CreateCondBr(Success, EndBB, FailureBB);
827*9880d681SAndroid Build Coastguard Worker 
828*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.failure:
829*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(FailureBB);
830*9880d681SAndroid Build Coastguard Worker   // Upon failure, verify that the masked-out part of the loaded value
831*9880d681SAndroid Build Coastguard Worker   // has been modified.  If it didn't, abort the cmpxchg, since the
832*9880d681SAndroid Build Coastguard Worker   // masked-in part must've.
833*9880d681SAndroid Build Coastguard Worker   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
834*9880d681SAndroid Build Coastguard Worker   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
835*9880d681SAndroid Build Coastguard Worker   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
836*9880d681SAndroid Build Coastguard Worker 
837*9880d681SAndroid Build Coastguard Worker   // Add the second value to the phi from above
838*9880d681SAndroid Build Coastguard Worker   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
839*9880d681SAndroid Build Coastguard Worker 
840*9880d681SAndroid Build Coastguard Worker   // partword.cmpxchg.end:
841*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(CI);
842*9880d681SAndroid Build Coastguard Worker 
843*9880d681SAndroid Build Coastguard Worker   Value *FinalOldVal = Builder.CreateTrunc(
844*9880d681SAndroid Build Coastguard Worker       Builder.CreateLShr(OldVal, PMV.ShiftAmt), PMV.ValueType);
845*9880d681SAndroid Build Coastguard Worker   Value *Res = UndefValue::get(CI->getType());
846*9880d681SAndroid Build Coastguard Worker   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
847*9880d681SAndroid Build Coastguard Worker   Res = Builder.CreateInsertValue(Res, Success, 1);
848*9880d681SAndroid Build Coastguard Worker 
849*9880d681SAndroid Build Coastguard Worker   CI->replaceAllUsesWith(Res);
850*9880d681SAndroid Build Coastguard Worker   CI->eraseFromParent();
851*9880d681SAndroid Build Coastguard Worker }
852*9880d681SAndroid Build Coastguard Worker 
expandAtomicOpToLLSC(Instruction * I,Type * ResultType,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)853*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandAtomicOpToLLSC(
854*9880d681SAndroid Build Coastguard Worker     Instruction *I, Type *ResultType, Value *Addr, AtomicOrdering MemOpOrder,
855*9880d681SAndroid Build Coastguard Worker     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
856*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(I);
857*9880d681SAndroid Build Coastguard Worker   Value *Loaded =
858*9880d681SAndroid Build Coastguard Worker       insertRMWLLSCLoop(Builder, ResultType, Addr, MemOpOrder, PerformOp);
859*9880d681SAndroid Build Coastguard Worker 
860*9880d681SAndroid Build Coastguard Worker   I->replaceAllUsesWith(Loaded);
861*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
862*9880d681SAndroid Build Coastguard Worker }
863*9880d681SAndroid Build Coastguard Worker 
insertRMWLLSCLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)864*9880d681SAndroid Build Coastguard Worker Value *AtomicExpand::insertRMWLLSCLoop(
865*9880d681SAndroid Build Coastguard Worker     IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
866*9880d681SAndroid Build Coastguard Worker     AtomicOrdering MemOpOrder,
867*9880d681SAndroid Build Coastguard Worker     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
868*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = Builder.getContext();
869*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = Builder.GetInsertBlock();
870*9880d681SAndroid Build Coastguard Worker   Function *F = BB->getParent();
871*9880d681SAndroid Build Coastguard Worker 
872*9880d681SAndroid Build Coastguard Worker   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
873*9880d681SAndroid Build Coastguard Worker   //
874*9880d681SAndroid Build Coastguard Worker   // The standard expansion we produce is:
875*9880d681SAndroid Build Coastguard Worker   //     [...]
876*9880d681SAndroid Build Coastguard Worker   // atomicrmw.start:
877*9880d681SAndroid Build Coastguard Worker   //     %loaded = @load.linked(%addr)
878*9880d681SAndroid Build Coastguard Worker   //     %new = some_op iN %loaded, %incr
879*9880d681SAndroid Build Coastguard Worker   //     %stored = @store_conditional(%new, %addr)
880*9880d681SAndroid Build Coastguard Worker   //     %try_again = icmp i32 ne %stored, 0
881*9880d681SAndroid Build Coastguard Worker   //     br i1 %try_again, label %loop, label %atomicrmw.end
882*9880d681SAndroid Build Coastguard Worker   // atomicrmw.end:
883*9880d681SAndroid Build Coastguard Worker   //     [...]
884*9880d681SAndroid Build Coastguard Worker   BasicBlock *ExitBB =
885*9880d681SAndroid Build Coastguard Worker       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
886*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
887*9880d681SAndroid Build Coastguard Worker 
888*9880d681SAndroid Build Coastguard Worker   // The split call above "helpfully" added a branch at the end of BB (to the
889*9880d681SAndroid Build Coastguard Worker   // wrong place).
890*9880d681SAndroid Build Coastguard Worker   std::prev(BB->end())->eraseFromParent();
891*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(BB);
892*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(LoopBB);
893*9880d681SAndroid Build Coastguard Worker 
894*9880d681SAndroid Build Coastguard Worker   // Start the main loop block now that we've taken care of the preliminaries.
895*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(LoopBB);
896*9880d681SAndroid Build Coastguard Worker   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
897*9880d681SAndroid Build Coastguard Worker 
898*9880d681SAndroid Build Coastguard Worker   Value *NewVal = PerformOp(Builder, Loaded);
899*9880d681SAndroid Build Coastguard Worker 
900*9880d681SAndroid Build Coastguard Worker   Value *StoreSuccess =
901*9880d681SAndroid Build Coastguard Worker       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
902*9880d681SAndroid Build Coastguard Worker   Value *TryAgain = Builder.CreateICmpNE(
903*9880d681SAndroid Build Coastguard Worker       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
904*9880d681SAndroid Build Coastguard Worker   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
905*9880d681SAndroid Build Coastguard Worker 
906*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
907*9880d681SAndroid Build Coastguard Worker   return Loaded;
908*9880d681SAndroid Build Coastguard Worker }
909*9880d681SAndroid Build Coastguard Worker 
910*9880d681SAndroid Build Coastguard Worker /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
911*9880d681SAndroid Build Coastguard Worker /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
912*9880d681SAndroid Build Coastguard Worker /// IR.  As a migration step, we convert back to what use to be the standard
913*9880d681SAndroid Build Coastguard Worker /// way to represent a pointer cmpxchg so that we can update backends one by
914*9880d681SAndroid Build Coastguard Worker /// one.
convertCmpXchgToIntegerType(AtomicCmpXchgInst * CI)915*9880d681SAndroid Build Coastguard Worker AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
916*9880d681SAndroid Build Coastguard Worker   auto *M = CI->getModule();
917*9880d681SAndroid Build Coastguard Worker   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
918*9880d681SAndroid Build Coastguard Worker                                             M->getDataLayout());
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(CI);
921*9880d681SAndroid Build Coastguard Worker 
922*9880d681SAndroid Build Coastguard Worker   Value *Addr = CI->getPointerOperand();
923*9880d681SAndroid Build Coastguard Worker   Type *PT = PointerType::get(NewTy,
924*9880d681SAndroid Build Coastguard Worker                               Addr->getType()->getPointerAddressSpace());
925*9880d681SAndroid Build Coastguard Worker   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
926*9880d681SAndroid Build Coastguard Worker 
927*9880d681SAndroid Build Coastguard Worker   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
928*9880d681SAndroid Build Coastguard Worker   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
929*9880d681SAndroid Build Coastguard Worker 
930*9880d681SAndroid Build Coastguard Worker 
931*9880d681SAndroid Build Coastguard Worker   auto *NewCI = Builder.CreateAtomicCmpXchg(NewAddr, NewCmp, NewNewVal,
932*9880d681SAndroid Build Coastguard Worker                                             CI->getSuccessOrdering(),
933*9880d681SAndroid Build Coastguard Worker                                             CI->getFailureOrdering(),
934*9880d681SAndroid Build Coastguard Worker                                             CI->getSynchScope());
935*9880d681SAndroid Build Coastguard Worker   NewCI->setVolatile(CI->isVolatile());
936*9880d681SAndroid Build Coastguard Worker   NewCI->setWeak(CI->isWeak());
937*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
938*9880d681SAndroid Build Coastguard Worker 
939*9880d681SAndroid Build Coastguard Worker   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
940*9880d681SAndroid Build Coastguard Worker   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
941*9880d681SAndroid Build Coastguard Worker 
942*9880d681SAndroid Build Coastguard Worker   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
943*9880d681SAndroid Build Coastguard Worker 
944*9880d681SAndroid Build Coastguard Worker   Value *Res = UndefValue::get(CI->getType());
945*9880d681SAndroid Build Coastguard Worker   Res = Builder.CreateInsertValue(Res, OldVal, 0);
946*9880d681SAndroid Build Coastguard Worker   Res = Builder.CreateInsertValue(Res, Succ, 1);
947*9880d681SAndroid Build Coastguard Worker 
948*9880d681SAndroid Build Coastguard Worker   CI->replaceAllUsesWith(Res);
949*9880d681SAndroid Build Coastguard Worker   CI->eraseFromParent();
950*9880d681SAndroid Build Coastguard Worker   return NewCI;
951*9880d681SAndroid Build Coastguard Worker }
952*9880d681SAndroid Build Coastguard Worker 
953*9880d681SAndroid Build Coastguard Worker 
expandAtomicCmpXchg(AtomicCmpXchgInst * CI)954*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
955*9880d681SAndroid Build Coastguard Worker   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
956*9880d681SAndroid Build Coastguard Worker   AtomicOrdering FailureOrder = CI->getFailureOrdering();
957*9880d681SAndroid Build Coastguard Worker   Value *Addr = CI->getPointerOperand();
958*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = CI->getParent();
959*9880d681SAndroid Build Coastguard Worker   Function *F = BB->getParent();
960*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = F->getContext();
961*9880d681SAndroid Build Coastguard Worker   // If shouldInsertFencesForAtomic() returns true, then the target does not
962*9880d681SAndroid Build Coastguard Worker   // want to deal with memory orders, and emitLeading/TrailingFence should take
963*9880d681SAndroid Build Coastguard Worker   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
964*9880d681SAndroid Build Coastguard Worker   // should preserve the ordering.
965*9880d681SAndroid Build Coastguard Worker   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
966*9880d681SAndroid Build Coastguard Worker   AtomicOrdering MemOpOrder =
967*9880d681SAndroid Build Coastguard Worker       ShouldInsertFencesForAtomic ? AtomicOrdering::Monotonic : SuccessOrder;
968*9880d681SAndroid Build Coastguard Worker 
969*9880d681SAndroid Build Coastguard Worker   // In implementations which use a barrier to achieve release semantics, we can
970*9880d681SAndroid Build Coastguard Worker   // delay emitting this barrier until we know a store is actually going to be
971*9880d681SAndroid Build Coastguard Worker   // attempted. The cost of this delay is that we need 2 copies of the block
972*9880d681SAndroid Build Coastguard Worker   // emitting the load-linked, affecting code size.
973*9880d681SAndroid Build Coastguard Worker   //
974*9880d681SAndroid Build Coastguard Worker   // Ideally, this logic would be unconditional except for the minsize check
975*9880d681SAndroid Build Coastguard Worker   // since in other cases the extra blocks naturally collapse down to the
976*9880d681SAndroid Build Coastguard Worker   // minimal loop. Unfortunately, this puts too much stress on later
977*9880d681SAndroid Build Coastguard Worker   // optimisations so we avoid emitting the extra logic in those cases too.
978*9880d681SAndroid Build Coastguard Worker   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
979*9880d681SAndroid Build Coastguard Worker                            SuccessOrder != AtomicOrdering::Monotonic &&
980*9880d681SAndroid Build Coastguard Worker                            SuccessOrder != AtomicOrdering::Acquire &&
981*9880d681SAndroid Build Coastguard Worker                            !F->optForMinSize();
982*9880d681SAndroid Build Coastguard Worker 
983*9880d681SAndroid Build Coastguard Worker   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
984*9880d681SAndroid Build Coastguard Worker   // do it even on minsize.
985*9880d681SAndroid Build Coastguard Worker   bool UseUnconditionalReleaseBarrier = F->optForMinSize() && !CI->isWeak();
986*9880d681SAndroid Build Coastguard Worker 
987*9880d681SAndroid Build Coastguard Worker   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
988*9880d681SAndroid Build Coastguard Worker   //
989*9880d681SAndroid Build Coastguard Worker   // The full expansion we produce is:
990*9880d681SAndroid Build Coastguard Worker   //     [...]
991*9880d681SAndroid Build Coastguard Worker   // cmpxchg.start:
992*9880d681SAndroid Build Coastguard Worker   //     %unreleasedload = @load.linked(%addr)
993*9880d681SAndroid Build Coastguard Worker   //     %should_store = icmp eq %unreleasedload, %desired
994*9880d681SAndroid Build Coastguard Worker   //     br i1 %should_store, label %cmpxchg.fencedstore,
995*9880d681SAndroid Build Coastguard Worker   //                          label %cmpxchg.nostore
996*9880d681SAndroid Build Coastguard Worker   // cmpxchg.releasingstore:
997*9880d681SAndroid Build Coastguard Worker   //     fence?
998*9880d681SAndroid Build Coastguard Worker   //     br label cmpxchg.trystore
999*9880d681SAndroid Build Coastguard Worker   // cmpxchg.trystore:
1000*9880d681SAndroid Build Coastguard Worker   //     %loaded.trystore = phi [%unreleasedload, %releasingstore],
1001*9880d681SAndroid Build Coastguard Worker   //                            [%releasedload, %cmpxchg.releasedload]
1002*9880d681SAndroid Build Coastguard Worker   //     %stored = @store_conditional(%new, %addr)
1003*9880d681SAndroid Build Coastguard Worker   //     %success = icmp eq i32 %stored, 0
1004*9880d681SAndroid Build Coastguard Worker   //     br i1 %success, label %cmpxchg.success,
1005*9880d681SAndroid Build Coastguard Worker   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1006*9880d681SAndroid Build Coastguard Worker   // cmpxchg.releasedload:
1007*9880d681SAndroid Build Coastguard Worker   //     %releasedload = @load.linked(%addr)
1008*9880d681SAndroid Build Coastguard Worker   //     %should_store = icmp eq %releasedload, %desired
1009*9880d681SAndroid Build Coastguard Worker   //     br i1 %should_store, label %cmpxchg.trystore,
1010*9880d681SAndroid Build Coastguard Worker   //                          label %cmpxchg.failure
1011*9880d681SAndroid Build Coastguard Worker   // cmpxchg.success:
1012*9880d681SAndroid Build Coastguard Worker   //     fence?
1013*9880d681SAndroid Build Coastguard Worker   //     br label %cmpxchg.end
1014*9880d681SAndroid Build Coastguard Worker   // cmpxchg.nostore:
1015*9880d681SAndroid Build Coastguard Worker   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1016*9880d681SAndroid Build Coastguard Worker   //                           [%releasedload,
1017*9880d681SAndroid Build Coastguard Worker   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
1018*9880d681SAndroid Build Coastguard Worker   //     @load_linked_fail_balance()?
1019*9880d681SAndroid Build Coastguard Worker   //     br label %cmpxchg.failure
1020*9880d681SAndroid Build Coastguard Worker   // cmpxchg.failure:
1021*9880d681SAndroid Build Coastguard Worker   //     fence?
1022*9880d681SAndroid Build Coastguard Worker   //     br label %cmpxchg.end
1023*9880d681SAndroid Build Coastguard Worker   // cmpxchg.end:
1024*9880d681SAndroid Build Coastguard Worker   //     %loaded = phi [%loaded.nostore, %cmpxchg.failure],
1025*9880d681SAndroid Build Coastguard Worker   //                   [%loaded.trystore, %cmpxchg.trystore]
1026*9880d681SAndroid Build Coastguard Worker   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1027*9880d681SAndroid Build Coastguard Worker   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1028*9880d681SAndroid Build Coastguard Worker   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1029*9880d681SAndroid Build Coastguard Worker   //     [...]
1030*9880d681SAndroid Build Coastguard Worker   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1031*9880d681SAndroid Build Coastguard Worker   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1032*9880d681SAndroid Build Coastguard Worker   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1033*9880d681SAndroid Build Coastguard Worker   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1034*9880d681SAndroid Build Coastguard Worker   auto ReleasedLoadBB =
1035*9880d681SAndroid Build Coastguard Worker       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1036*9880d681SAndroid Build Coastguard Worker   auto TryStoreBB =
1037*9880d681SAndroid Build Coastguard Worker       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1038*9880d681SAndroid Build Coastguard Worker   auto ReleasingStoreBB =
1039*9880d681SAndroid Build Coastguard Worker       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1040*9880d681SAndroid Build Coastguard Worker   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
1041*9880d681SAndroid Build Coastguard Worker 
1042*9880d681SAndroid Build Coastguard Worker   // This grabs the DebugLoc from CI
1043*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(CI);
1044*9880d681SAndroid Build Coastguard Worker 
1045*9880d681SAndroid Build Coastguard Worker   // The split call above "helpfully" added a branch at the end of BB (to the
1046*9880d681SAndroid Build Coastguard Worker   // wrong place), but we might want a fence too. It's easiest to just remove
1047*9880d681SAndroid Build Coastguard Worker   // the branch entirely.
1048*9880d681SAndroid Build Coastguard Worker   std::prev(BB->end())->eraseFromParent();
1049*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(BB);
1050*9880d681SAndroid Build Coastguard Worker   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
1051*9880d681SAndroid Build Coastguard Worker     TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
1052*9880d681SAndroid Build Coastguard Worker                           /*IsLoad=*/true);
1053*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(StartBB);
1054*9880d681SAndroid Build Coastguard Worker 
1055*9880d681SAndroid Build Coastguard Worker   // Start the main loop block now that we've taken care of the preliminaries.
1056*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(StartBB);
1057*9880d681SAndroid Build Coastguard Worker   Value *UnreleasedLoad = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1058*9880d681SAndroid Build Coastguard Worker   Value *ShouldStore = Builder.CreateICmpEQ(
1059*9880d681SAndroid Build Coastguard Worker       UnreleasedLoad, CI->getCompareOperand(), "should_store");
1060*9880d681SAndroid Build Coastguard Worker 
1061*9880d681SAndroid Build Coastguard Worker   // If the cmpxchg doesn't actually need any ordering when it fails, we can
1062*9880d681SAndroid Build Coastguard Worker   // jump straight past that fence instruction (if it exists).
1063*9880d681SAndroid Build Coastguard Worker   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1064*9880d681SAndroid Build Coastguard Worker 
1065*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(ReleasingStoreBB);
1066*9880d681SAndroid Build Coastguard Worker   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
1067*9880d681SAndroid Build Coastguard Worker     TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
1068*9880d681SAndroid Build Coastguard Worker                           /*IsLoad=*/true);
1069*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(TryStoreBB);
1070*9880d681SAndroid Build Coastguard Worker 
1071*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(TryStoreBB);
1072*9880d681SAndroid Build Coastguard Worker   Value *StoreSuccess = TLI->emitStoreConditional(
1073*9880d681SAndroid Build Coastguard Worker       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
1074*9880d681SAndroid Build Coastguard Worker   StoreSuccess = Builder.CreateICmpEQ(
1075*9880d681SAndroid Build Coastguard Worker       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1076*9880d681SAndroid Build Coastguard Worker   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
1077*9880d681SAndroid Build Coastguard Worker   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1078*9880d681SAndroid Build Coastguard Worker                        CI->isWeak() ? FailureBB : RetryBB);
1079*9880d681SAndroid Build Coastguard Worker 
1080*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(ReleasedLoadBB);
1081*9880d681SAndroid Build Coastguard Worker   Value *SecondLoad;
1082*9880d681SAndroid Build Coastguard Worker   if (HasReleasedLoadBB) {
1083*9880d681SAndroid Build Coastguard Worker     SecondLoad = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1084*9880d681SAndroid Build Coastguard Worker     ShouldStore = Builder.CreateICmpEQ(SecondLoad, CI->getCompareOperand(),
1085*9880d681SAndroid Build Coastguard Worker                                        "should_store");
1086*9880d681SAndroid Build Coastguard Worker 
1087*9880d681SAndroid Build Coastguard Worker     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1088*9880d681SAndroid Build Coastguard Worker     // jump straight past that fence instruction (if it exists).
1089*9880d681SAndroid Build Coastguard Worker     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1090*9880d681SAndroid Build Coastguard Worker   } else
1091*9880d681SAndroid Build Coastguard Worker     Builder.CreateUnreachable();
1092*9880d681SAndroid Build Coastguard Worker 
1093*9880d681SAndroid Build Coastguard Worker   // Make sure later instructions don't get reordered with a fence if
1094*9880d681SAndroid Build Coastguard Worker   // necessary.
1095*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(SuccessBB);
1096*9880d681SAndroid Build Coastguard Worker   if (ShouldInsertFencesForAtomic)
1097*9880d681SAndroid Build Coastguard Worker     TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
1098*9880d681SAndroid Build Coastguard Worker                            /*IsLoad=*/true);
1099*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(ExitBB);
1100*9880d681SAndroid Build Coastguard Worker 
1101*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(NoStoreBB);
1102*9880d681SAndroid Build Coastguard Worker   // In the failing case, where we don't execute the store-conditional, the
1103*9880d681SAndroid Build Coastguard Worker   // target might want to balance out the load-linked with a dedicated
1104*9880d681SAndroid Build Coastguard Worker   // instruction (e.g., on ARM, clearing the exclusive monitor).
1105*9880d681SAndroid Build Coastguard Worker   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1106*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(FailureBB);
1107*9880d681SAndroid Build Coastguard Worker 
1108*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(FailureBB);
1109*9880d681SAndroid Build Coastguard Worker   if (ShouldInsertFencesForAtomic)
1110*9880d681SAndroid Build Coastguard Worker     TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
1111*9880d681SAndroid Build Coastguard Worker                            /*IsLoad=*/true);
1112*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(ExitBB);
1113*9880d681SAndroid Build Coastguard Worker 
1114*9880d681SAndroid Build Coastguard Worker   // Finally, we have control-flow based knowledge of whether the cmpxchg
1115*9880d681SAndroid Build Coastguard Worker   // succeeded or not. We expose this to later passes by converting any
1116*9880d681SAndroid Build Coastguard Worker   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1117*9880d681SAndroid Build Coastguard Worker   // PHI.
1118*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1119*9880d681SAndroid Build Coastguard Worker   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
1120*9880d681SAndroid Build Coastguard Worker   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1121*9880d681SAndroid Build Coastguard Worker   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1122*9880d681SAndroid Build Coastguard Worker 
1123*9880d681SAndroid Build Coastguard Worker   // Setup the builder so we can create any PHIs we need.
1124*9880d681SAndroid Build Coastguard Worker   Value *Loaded;
1125*9880d681SAndroid Build Coastguard Worker   if (!HasReleasedLoadBB)
1126*9880d681SAndroid Build Coastguard Worker     Loaded = UnreleasedLoad;
1127*9880d681SAndroid Build Coastguard Worker   else {
1128*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(TryStoreBB, TryStoreBB->begin());
1129*9880d681SAndroid Build Coastguard Worker     PHINode *TryStoreLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
1130*9880d681SAndroid Build Coastguard Worker     TryStoreLoaded->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1131*9880d681SAndroid Build Coastguard Worker     TryStoreLoaded->addIncoming(SecondLoad, ReleasedLoadBB);
1132*9880d681SAndroid Build Coastguard Worker 
1133*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(NoStoreBB, NoStoreBB->begin());
1134*9880d681SAndroid Build Coastguard Worker     PHINode *NoStoreLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
1135*9880d681SAndroid Build Coastguard Worker     NoStoreLoaded->addIncoming(UnreleasedLoad, StartBB);
1136*9880d681SAndroid Build Coastguard Worker     NoStoreLoaded->addIncoming(SecondLoad, ReleasedLoadBB);
1137*9880d681SAndroid Build Coastguard Worker 
1138*9880d681SAndroid Build Coastguard Worker     Builder.SetInsertPoint(ExitBB, ++ExitBB->begin());
1139*9880d681SAndroid Build Coastguard Worker     PHINode *ExitLoaded = Builder.CreatePHI(UnreleasedLoad->getType(), 2);
1140*9880d681SAndroid Build Coastguard Worker     ExitLoaded->addIncoming(TryStoreLoaded, SuccessBB);
1141*9880d681SAndroid Build Coastguard Worker     ExitLoaded->addIncoming(NoStoreLoaded, FailureBB);
1142*9880d681SAndroid Build Coastguard Worker 
1143*9880d681SAndroid Build Coastguard Worker     Loaded = ExitLoaded;
1144*9880d681SAndroid Build Coastguard Worker   }
1145*9880d681SAndroid Build Coastguard Worker 
1146*9880d681SAndroid Build Coastguard Worker   // Look for any users of the cmpxchg that are just comparing the loaded value
1147*9880d681SAndroid Build Coastguard Worker   // against the desired one, and replace them with the CFG-derived version.
1148*9880d681SAndroid Build Coastguard Worker   SmallVector<ExtractValueInst *, 2> PrunedInsts;
1149*9880d681SAndroid Build Coastguard Worker   for (auto User : CI->users()) {
1150*9880d681SAndroid Build Coastguard Worker     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1151*9880d681SAndroid Build Coastguard Worker     if (!EV)
1152*9880d681SAndroid Build Coastguard Worker       continue;
1153*9880d681SAndroid Build Coastguard Worker 
1154*9880d681SAndroid Build Coastguard Worker     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1155*9880d681SAndroid Build Coastguard Worker            "weird extraction from { iN, i1 }");
1156*9880d681SAndroid Build Coastguard Worker 
1157*9880d681SAndroid Build Coastguard Worker     if (EV->getIndices()[0] == 0)
1158*9880d681SAndroid Build Coastguard Worker       EV->replaceAllUsesWith(Loaded);
1159*9880d681SAndroid Build Coastguard Worker     else
1160*9880d681SAndroid Build Coastguard Worker       EV->replaceAllUsesWith(Success);
1161*9880d681SAndroid Build Coastguard Worker 
1162*9880d681SAndroid Build Coastguard Worker     PrunedInsts.push_back(EV);
1163*9880d681SAndroid Build Coastguard Worker   }
1164*9880d681SAndroid Build Coastguard Worker 
1165*9880d681SAndroid Build Coastguard Worker   // We can remove the instructions now we're no longer iterating through them.
1166*9880d681SAndroid Build Coastguard Worker   for (auto EV : PrunedInsts)
1167*9880d681SAndroid Build Coastguard Worker     EV->eraseFromParent();
1168*9880d681SAndroid Build Coastguard Worker 
1169*9880d681SAndroid Build Coastguard Worker   if (!CI->use_empty()) {
1170*9880d681SAndroid Build Coastguard Worker     // Some use of the full struct return that we don't understand has happened,
1171*9880d681SAndroid Build Coastguard Worker     // so we've got to reconstruct it properly.
1172*9880d681SAndroid Build Coastguard Worker     Value *Res;
1173*9880d681SAndroid Build Coastguard Worker     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1174*9880d681SAndroid Build Coastguard Worker     Res = Builder.CreateInsertValue(Res, Success, 1);
1175*9880d681SAndroid Build Coastguard Worker 
1176*9880d681SAndroid Build Coastguard Worker     CI->replaceAllUsesWith(Res);
1177*9880d681SAndroid Build Coastguard Worker   }
1178*9880d681SAndroid Build Coastguard Worker 
1179*9880d681SAndroid Build Coastguard Worker   CI->eraseFromParent();
1180*9880d681SAndroid Build Coastguard Worker   return true;
1181*9880d681SAndroid Build Coastguard Worker }
1182*9880d681SAndroid Build Coastguard Worker 
isIdempotentRMW(AtomicRMWInst * RMWI)1183*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
1184*9880d681SAndroid Build Coastguard Worker   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1185*9880d681SAndroid Build Coastguard Worker   if(!C)
1186*9880d681SAndroid Build Coastguard Worker     return false;
1187*9880d681SAndroid Build Coastguard Worker 
1188*9880d681SAndroid Build Coastguard Worker   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1189*9880d681SAndroid Build Coastguard Worker   switch(Op) {
1190*9880d681SAndroid Build Coastguard Worker     case AtomicRMWInst::Add:
1191*9880d681SAndroid Build Coastguard Worker     case AtomicRMWInst::Sub:
1192*9880d681SAndroid Build Coastguard Worker     case AtomicRMWInst::Or:
1193*9880d681SAndroid Build Coastguard Worker     case AtomicRMWInst::Xor:
1194*9880d681SAndroid Build Coastguard Worker       return C->isZero();
1195*9880d681SAndroid Build Coastguard Worker     case AtomicRMWInst::And:
1196*9880d681SAndroid Build Coastguard Worker       return C->isMinusOne();
1197*9880d681SAndroid Build Coastguard Worker     // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1198*9880d681SAndroid Build Coastguard Worker     default:
1199*9880d681SAndroid Build Coastguard Worker       return false;
1200*9880d681SAndroid Build Coastguard Worker   }
1201*9880d681SAndroid Build Coastguard Worker }
1202*9880d681SAndroid Build Coastguard Worker 
simplifyIdempotentRMW(AtomicRMWInst * RMWI)1203*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
1204*9880d681SAndroid Build Coastguard Worker   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1205*9880d681SAndroid Build Coastguard Worker     tryExpandAtomicLoad(ResultingLoad);
1206*9880d681SAndroid Build Coastguard Worker     return true;
1207*9880d681SAndroid Build Coastguard Worker   }
1208*9880d681SAndroid Build Coastguard Worker   return false;
1209*9880d681SAndroid Build Coastguard Worker }
1210*9880d681SAndroid Build Coastguard Worker 
insertRMWCmpXchgLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp,CreateCmpXchgInstFun CreateCmpXchg)1211*9880d681SAndroid Build Coastguard Worker Value *AtomicExpand::insertRMWCmpXchgLoop(
1212*9880d681SAndroid Build Coastguard Worker     IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
1213*9880d681SAndroid Build Coastguard Worker     AtomicOrdering MemOpOrder,
1214*9880d681SAndroid Build Coastguard Worker     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1215*9880d681SAndroid Build Coastguard Worker     CreateCmpXchgInstFun CreateCmpXchg) {
1216*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = Builder.getContext();
1217*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = Builder.GetInsertBlock();
1218*9880d681SAndroid Build Coastguard Worker   Function *F = BB->getParent();
1219*9880d681SAndroid Build Coastguard Worker 
1220*9880d681SAndroid Build Coastguard Worker   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1221*9880d681SAndroid Build Coastguard Worker   //
1222*9880d681SAndroid Build Coastguard Worker   // The standard expansion we produce is:
1223*9880d681SAndroid Build Coastguard Worker   //     [...]
1224*9880d681SAndroid Build Coastguard Worker   //     %init_loaded = load atomic iN* %addr
1225*9880d681SAndroid Build Coastguard Worker   //     br label %loop
1226*9880d681SAndroid Build Coastguard Worker   // loop:
1227*9880d681SAndroid Build Coastguard Worker   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1228*9880d681SAndroid Build Coastguard Worker   //     %new = some_op iN %loaded, %incr
1229*9880d681SAndroid Build Coastguard Worker   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1230*9880d681SAndroid Build Coastguard Worker   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1231*9880d681SAndroid Build Coastguard Worker   //     %success = extractvalue { iN, i1 } %pair, 1
1232*9880d681SAndroid Build Coastguard Worker   //     br i1 %success, label %atomicrmw.end, label %loop
1233*9880d681SAndroid Build Coastguard Worker   // atomicrmw.end:
1234*9880d681SAndroid Build Coastguard Worker   //     [...]
1235*9880d681SAndroid Build Coastguard Worker   BasicBlock *ExitBB =
1236*9880d681SAndroid Build Coastguard Worker       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1237*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1238*9880d681SAndroid Build Coastguard Worker 
1239*9880d681SAndroid Build Coastguard Worker   // The split call above "helpfully" added a branch at the end of BB (to the
1240*9880d681SAndroid Build Coastguard Worker   // wrong place), but we want a load. It's easiest to just remove
1241*9880d681SAndroid Build Coastguard Worker   // the branch entirely.
1242*9880d681SAndroid Build Coastguard Worker   std::prev(BB->end())->eraseFromParent();
1243*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(BB);
1244*9880d681SAndroid Build Coastguard Worker   LoadInst *InitLoaded = Builder.CreateLoad(ResultTy, Addr);
1245*9880d681SAndroid Build Coastguard Worker   // Atomics require at least natural alignment.
1246*9880d681SAndroid Build Coastguard Worker   InitLoaded->setAlignment(ResultTy->getPrimitiveSizeInBits() / 8);
1247*9880d681SAndroid Build Coastguard Worker   Builder.CreateBr(LoopBB);
1248*9880d681SAndroid Build Coastguard Worker 
1249*9880d681SAndroid Build Coastguard Worker   // Start the main loop block now that we've taken care of the preliminaries.
1250*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(LoopBB);
1251*9880d681SAndroid Build Coastguard Worker   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1252*9880d681SAndroid Build Coastguard Worker   Loaded->addIncoming(InitLoaded, BB);
1253*9880d681SAndroid Build Coastguard Worker 
1254*9880d681SAndroid Build Coastguard Worker   Value *NewVal = PerformOp(Builder, Loaded);
1255*9880d681SAndroid Build Coastguard Worker 
1256*9880d681SAndroid Build Coastguard Worker   Value *NewLoaded = nullptr;
1257*9880d681SAndroid Build Coastguard Worker   Value *Success = nullptr;
1258*9880d681SAndroid Build Coastguard Worker 
1259*9880d681SAndroid Build Coastguard Worker   CreateCmpXchg(Builder, Addr, Loaded, NewVal,
1260*9880d681SAndroid Build Coastguard Worker                 MemOpOrder == AtomicOrdering::Unordered
1261*9880d681SAndroid Build Coastguard Worker                     ? AtomicOrdering::Monotonic
1262*9880d681SAndroid Build Coastguard Worker                     : MemOpOrder,
1263*9880d681SAndroid Build Coastguard Worker                 Success, NewLoaded);
1264*9880d681SAndroid Build Coastguard Worker   assert(Success && NewLoaded);
1265*9880d681SAndroid Build Coastguard Worker 
1266*9880d681SAndroid Build Coastguard Worker   Loaded->addIncoming(NewLoaded, LoopBB);
1267*9880d681SAndroid Build Coastguard Worker 
1268*9880d681SAndroid Build Coastguard Worker   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1269*9880d681SAndroid Build Coastguard Worker 
1270*9880d681SAndroid Build Coastguard Worker   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1271*9880d681SAndroid Build Coastguard Worker   return NewLoaded;
1272*9880d681SAndroid Build Coastguard Worker }
1273*9880d681SAndroid Build Coastguard Worker 
1274*9880d681SAndroid Build Coastguard Worker // Note: This function is exposed externally by AtomicExpandUtils.h
expandAtomicRMWToCmpXchg(AtomicRMWInst * AI,CreateCmpXchgInstFun CreateCmpXchg)1275*9880d681SAndroid Build Coastguard Worker bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1276*9880d681SAndroid Build Coastguard Worker                                     CreateCmpXchgInstFun CreateCmpXchg) {
1277*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(AI);
1278*9880d681SAndroid Build Coastguard Worker   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1279*9880d681SAndroid Build Coastguard Worker       Builder, AI->getType(), AI->getPointerOperand(), AI->getOrdering(),
1280*9880d681SAndroid Build Coastguard Worker       [&](IRBuilder<> &Builder, Value *Loaded) {
1281*9880d681SAndroid Build Coastguard Worker         return performAtomicOp(AI->getOperation(), Builder, Loaded,
1282*9880d681SAndroid Build Coastguard Worker                                AI->getValOperand());
1283*9880d681SAndroid Build Coastguard Worker       },
1284*9880d681SAndroid Build Coastguard Worker       CreateCmpXchg);
1285*9880d681SAndroid Build Coastguard Worker 
1286*9880d681SAndroid Build Coastguard Worker   AI->replaceAllUsesWith(Loaded);
1287*9880d681SAndroid Build Coastguard Worker   AI->eraseFromParent();
1288*9880d681SAndroid Build Coastguard Worker   return true;
1289*9880d681SAndroid Build Coastguard Worker }
1290*9880d681SAndroid Build Coastguard Worker 
1291*9880d681SAndroid Build Coastguard Worker // In order to use one of the sized library calls such as
1292*9880d681SAndroid Build Coastguard Worker // __atomic_fetch_add_4, the alignment must be sufficient, the size
1293*9880d681SAndroid Build Coastguard Worker // must be one of the potentially-specialized sizes, and the value
1294*9880d681SAndroid Build Coastguard Worker // type must actually exist in C on the target (otherwise, the
1295*9880d681SAndroid Build Coastguard Worker // function wouldn't actually be defined.)
canUseSizedAtomicCall(unsigned Size,unsigned Align,const DataLayout & DL)1296*9880d681SAndroid Build Coastguard Worker static bool canUseSizedAtomicCall(unsigned Size, unsigned Align,
1297*9880d681SAndroid Build Coastguard Worker                                   const DataLayout &DL) {
1298*9880d681SAndroid Build Coastguard Worker   // TODO: "LargestSize" is an approximation for "largest type that
1299*9880d681SAndroid Build Coastguard Worker   // you can express in C". It seems to be the case that int128 is
1300*9880d681SAndroid Build Coastguard Worker   // supported on all 64-bit platforms, otherwise only up to 64-bit
1301*9880d681SAndroid Build Coastguard Worker   // integers are supported. If we get this wrong, then we'll try to
1302*9880d681SAndroid Build Coastguard Worker   // call a sized libcall that doesn't actually exist. There should
1303*9880d681SAndroid Build Coastguard Worker   // really be some more reliable way in LLVM of determining integer
1304*9880d681SAndroid Build Coastguard Worker   // sizes which are valid in the target's C ABI...
1305*9880d681SAndroid Build Coastguard Worker   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1306*9880d681SAndroid Build Coastguard Worker   return Align >= Size &&
1307*9880d681SAndroid Build Coastguard Worker          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1308*9880d681SAndroid Build Coastguard Worker          Size <= LargestSize;
1309*9880d681SAndroid Build Coastguard Worker }
1310*9880d681SAndroid Build Coastguard Worker 
expandAtomicLoadToLibcall(LoadInst * I)1311*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
1312*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall Libcalls[6] = {
1313*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1314*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1315*9880d681SAndroid Build Coastguard Worker   unsigned Size = getAtomicOpSize(I);
1316*9880d681SAndroid Build Coastguard Worker   unsigned Align = getAtomicOpAlign(I);
1317*9880d681SAndroid Build Coastguard Worker 
1318*9880d681SAndroid Build Coastguard Worker   bool expanded = expandAtomicOpToLibcall(
1319*9880d681SAndroid Build Coastguard Worker       I, Size, Align, I->getPointerOperand(), nullptr, nullptr,
1320*9880d681SAndroid Build Coastguard Worker       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1321*9880d681SAndroid Build Coastguard Worker   (void)expanded;
1322*9880d681SAndroid Build Coastguard Worker   assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Load");
1323*9880d681SAndroid Build Coastguard Worker }
1324*9880d681SAndroid Build Coastguard Worker 
expandAtomicStoreToLibcall(StoreInst * I)1325*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
1326*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall Libcalls[6] = {
1327*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1328*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1329*9880d681SAndroid Build Coastguard Worker   unsigned Size = getAtomicOpSize(I);
1330*9880d681SAndroid Build Coastguard Worker   unsigned Align = getAtomicOpAlign(I);
1331*9880d681SAndroid Build Coastguard Worker 
1332*9880d681SAndroid Build Coastguard Worker   bool expanded = expandAtomicOpToLibcall(
1333*9880d681SAndroid Build Coastguard Worker       I, Size, Align, I->getPointerOperand(), I->getValueOperand(), nullptr,
1334*9880d681SAndroid Build Coastguard Worker       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1335*9880d681SAndroid Build Coastguard Worker   (void)expanded;
1336*9880d681SAndroid Build Coastguard Worker   assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Store");
1337*9880d681SAndroid Build Coastguard Worker }
1338*9880d681SAndroid Build Coastguard Worker 
expandAtomicCASToLibcall(AtomicCmpXchgInst * I)1339*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1340*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall Libcalls[6] = {
1341*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1342*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1343*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1344*9880d681SAndroid Build Coastguard Worker   unsigned Size = getAtomicOpSize(I);
1345*9880d681SAndroid Build Coastguard Worker   unsigned Align = getAtomicOpAlign(I);
1346*9880d681SAndroid Build Coastguard Worker 
1347*9880d681SAndroid Build Coastguard Worker   bool expanded = expandAtomicOpToLibcall(
1348*9880d681SAndroid Build Coastguard Worker       I, Size, Align, I->getPointerOperand(), I->getNewValOperand(),
1349*9880d681SAndroid Build Coastguard Worker       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1350*9880d681SAndroid Build Coastguard Worker       Libcalls);
1351*9880d681SAndroid Build Coastguard Worker   (void)expanded;
1352*9880d681SAndroid Build Coastguard Worker   assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor CAS");
1353*9880d681SAndroid Build Coastguard Worker }
1354*9880d681SAndroid Build Coastguard Worker 
GetRMWLibcall(AtomicRMWInst::BinOp Op)1355*9880d681SAndroid Build Coastguard Worker static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1356*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsXchg[6] = {
1357*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1358*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1359*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1360*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsAdd[6] = {
1361*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1362*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1363*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1364*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsSub[6] = {
1365*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1366*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1367*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1368*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsAnd[6] = {
1369*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1370*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1371*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1372*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsOr[6] = {
1373*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1374*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1375*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1376*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsXor[6] = {
1377*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1378*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1379*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1380*9880d681SAndroid Build Coastguard Worker   static const RTLIB::Libcall LibcallsNand[6] = {
1381*9880d681SAndroid Build Coastguard Worker       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1382*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1383*9880d681SAndroid Build Coastguard Worker       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1384*9880d681SAndroid Build Coastguard Worker 
1385*9880d681SAndroid Build Coastguard Worker   switch (Op) {
1386*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::BAD_BINOP:
1387*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("Should not have BAD_BINOP.");
1388*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xchg:
1389*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsXchg);
1390*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Add:
1391*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsAdd);
1392*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Sub:
1393*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsSub);
1394*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::And:
1395*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsAnd);
1396*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Or:
1397*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsOr);
1398*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Xor:
1399*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsXor);
1400*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Nand:
1401*9880d681SAndroid Build Coastguard Worker     return makeArrayRef(LibcallsNand);
1402*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Max:
1403*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::Min:
1404*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMax:
1405*9880d681SAndroid Build Coastguard Worker   case AtomicRMWInst::UMin:
1406*9880d681SAndroid Build Coastguard Worker     // No atomic libcalls are available for max/min/umax/umin.
1407*9880d681SAndroid Build Coastguard Worker     return {};
1408*9880d681SAndroid Build Coastguard Worker   }
1409*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("Unexpected AtomicRMW operation.");
1410*9880d681SAndroid Build Coastguard Worker }
1411*9880d681SAndroid Build Coastguard Worker 
expandAtomicRMWToLibcall(AtomicRMWInst * I)1412*9880d681SAndroid Build Coastguard Worker void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1413*9880d681SAndroid Build Coastguard Worker   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1414*9880d681SAndroid Build Coastguard Worker 
1415*9880d681SAndroid Build Coastguard Worker   unsigned Size = getAtomicOpSize(I);
1416*9880d681SAndroid Build Coastguard Worker   unsigned Align = getAtomicOpAlign(I);
1417*9880d681SAndroid Build Coastguard Worker 
1418*9880d681SAndroid Build Coastguard Worker   bool Success = false;
1419*9880d681SAndroid Build Coastguard Worker   if (!Libcalls.empty())
1420*9880d681SAndroid Build Coastguard Worker     Success = expandAtomicOpToLibcall(
1421*9880d681SAndroid Build Coastguard Worker         I, Size, Align, I->getPointerOperand(), I->getValOperand(), nullptr,
1422*9880d681SAndroid Build Coastguard Worker         I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1423*9880d681SAndroid Build Coastguard Worker 
1424*9880d681SAndroid Build Coastguard Worker   // The expansion failed: either there were no libcalls at all for
1425*9880d681SAndroid Build Coastguard Worker   // the operation (min/max), or there were only size-specialized
1426*9880d681SAndroid Build Coastguard Worker   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1427*9880d681SAndroid Build Coastguard Worker   // CAS libcall, via a CAS loop, instead.
1428*9880d681SAndroid Build Coastguard Worker   if (!Success) {
1429*9880d681SAndroid Build Coastguard Worker     expandAtomicRMWToCmpXchg(I, [this](IRBuilder<> &Builder, Value *Addr,
1430*9880d681SAndroid Build Coastguard Worker                                        Value *Loaded, Value *NewVal,
1431*9880d681SAndroid Build Coastguard Worker                                        AtomicOrdering MemOpOrder,
1432*9880d681SAndroid Build Coastguard Worker                                        Value *&Success, Value *&NewLoaded) {
1433*9880d681SAndroid Build Coastguard Worker       // Create the CAS instruction normally...
1434*9880d681SAndroid Build Coastguard Worker       AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1435*9880d681SAndroid Build Coastguard Worker           Addr, Loaded, NewVal, MemOpOrder,
1436*9880d681SAndroid Build Coastguard Worker           AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
1437*9880d681SAndroid Build Coastguard Worker       Success = Builder.CreateExtractValue(Pair, 1, "success");
1438*9880d681SAndroid Build Coastguard Worker       NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1439*9880d681SAndroid Build Coastguard Worker 
1440*9880d681SAndroid Build Coastguard Worker       // ...and then expand the CAS into a libcall.
1441*9880d681SAndroid Build Coastguard Worker       expandAtomicCASToLibcall(Pair);
1442*9880d681SAndroid Build Coastguard Worker     });
1443*9880d681SAndroid Build Coastguard Worker   }
1444*9880d681SAndroid Build Coastguard Worker }
1445*9880d681SAndroid Build Coastguard Worker 
1446*9880d681SAndroid Build Coastguard Worker // A helper routine for the above expandAtomic*ToLibcall functions.
1447*9880d681SAndroid Build Coastguard Worker //
1448*9880d681SAndroid Build Coastguard Worker // 'Libcalls' contains an array of enum values for the particular
1449*9880d681SAndroid Build Coastguard Worker // ATOMIC libcalls to be emitted. All of the other arguments besides
1450*9880d681SAndroid Build Coastguard Worker // 'I' are extracted from the Instruction subclass by the
1451*9880d681SAndroid Build Coastguard Worker // caller. Depending on the particular call, some will be null.
expandAtomicOpToLibcall(Instruction * I,unsigned Size,unsigned Align,Value * PointerOperand,Value * ValueOperand,Value * CASExpected,AtomicOrdering Ordering,AtomicOrdering Ordering2,ArrayRef<RTLIB::Libcall> Libcalls)1452*9880d681SAndroid Build Coastguard Worker bool AtomicExpand::expandAtomicOpToLibcall(
1453*9880d681SAndroid Build Coastguard Worker     Instruction *I, unsigned Size, unsigned Align, Value *PointerOperand,
1454*9880d681SAndroid Build Coastguard Worker     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1455*9880d681SAndroid Build Coastguard Worker     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1456*9880d681SAndroid Build Coastguard Worker   assert(Libcalls.size() == 6);
1457*9880d681SAndroid Build Coastguard Worker 
1458*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = I->getContext();
1459*9880d681SAndroid Build Coastguard Worker   Module *M = I->getModule();
1460*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = M->getDataLayout();
1461*9880d681SAndroid Build Coastguard Worker   IRBuilder<> Builder(I);
1462*9880d681SAndroid Build Coastguard Worker   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1463*9880d681SAndroid Build Coastguard Worker 
1464*9880d681SAndroid Build Coastguard Worker   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Align, DL);
1465*9880d681SAndroid Build Coastguard Worker   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1466*9880d681SAndroid Build Coastguard Worker 
1467*9880d681SAndroid Build Coastguard Worker   unsigned AllocaAlignment = DL.getPrefTypeAlignment(SizedIntTy);
1468*9880d681SAndroid Build Coastguard Worker 
1469*9880d681SAndroid Build Coastguard Worker   // TODO: the "order" argument type is "int", not int32. So
1470*9880d681SAndroid Build Coastguard Worker   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1471*9880d681SAndroid Build Coastguard Worker   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1472*9880d681SAndroid Build Coastguard Worker   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1473*9880d681SAndroid Build Coastguard Worker   Constant *OrderingVal =
1474*9880d681SAndroid Build Coastguard Worker       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1475*9880d681SAndroid Build Coastguard Worker   Constant *Ordering2Val = nullptr;
1476*9880d681SAndroid Build Coastguard Worker   if (CASExpected) {
1477*9880d681SAndroid Build Coastguard Worker     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1478*9880d681SAndroid Build Coastguard Worker     Ordering2Val =
1479*9880d681SAndroid Build Coastguard Worker         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1480*9880d681SAndroid Build Coastguard Worker   }
1481*9880d681SAndroid Build Coastguard Worker   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1482*9880d681SAndroid Build Coastguard Worker 
1483*9880d681SAndroid Build Coastguard Worker   RTLIB::Libcall RTLibType;
1484*9880d681SAndroid Build Coastguard Worker   if (UseSizedLibcall) {
1485*9880d681SAndroid Build Coastguard Worker     switch (Size) {
1486*9880d681SAndroid Build Coastguard Worker     case 1: RTLibType = Libcalls[1]; break;
1487*9880d681SAndroid Build Coastguard Worker     case 2: RTLibType = Libcalls[2]; break;
1488*9880d681SAndroid Build Coastguard Worker     case 4: RTLibType = Libcalls[3]; break;
1489*9880d681SAndroid Build Coastguard Worker     case 8: RTLibType = Libcalls[4]; break;
1490*9880d681SAndroid Build Coastguard Worker     case 16: RTLibType = Libcalls[5]; break;
1491*9880d681SAndroid Build Coastguard Worker     }
1492*9880d681SAndroid Build Coastguard Worker   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1493*9880d681SAndroid Build Coastguard Worker     RTLibType = Libcalls[0];
1494*9880d681SAndroid Build Coastguard Worker   } else {
1495*9880d681SAndroid Build Coastguard Worker     // Can't use sized function, and there's no generic for this
1496*9880d681SAndroid Build Coastguard Worker     // operation, so give up.
1497*9880d681SAndroid Build Coastguard Worker     return false;
1498*9880d681SAndroid Build Coastguard Worker   }
1499*9880d681SAndroid Build Coastguard Worker 
1500*9880d681SAndroid Build Coastguard Worker   // Build up the function call. There's two kinds. First, the sized
1501*9880d681SAndroid Build Coastguard Worker   // variants.  These calls are going to be one of the following (with
1502*9880d681SAndroid Build Coastguard Worker   // N=1,2,4,8,16):
1503*9880d681SAndroid Build Coastguard Worker   //  iN    __atomic_load_N(iN *ptr, int ordering)
1504*9880d681SAndroid Build Coastguard Worker   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1505*9880d681SAndroid Build Coastguard Worker   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1506*9880d681SAndroid Build Coastguard Worker   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1507*9880d681SAndroid Build Coastguard Worker   //                                    int success_order, int failure_order)
1508*9880d681SAndroid Build Coastguard Worker   //
1509*9880d681SAndroid Build Coastguard Worker   // Note that these functions can be used for non-integer atomic
1510*9880d681SAndroid Build Coastguard Worker   // operations, the values just need to be bitcast to integers on the
1511*9880d681SAndroid Build Coastguard Worker   // way in and out.
1512*9880d681SAndroid Build Coastguard Worker   //
1513*9880d681SAndroid Build Coastguard Worker   // And, then, the generic variants. They look like the following:
1514*9880d681SAndroid Build Coastguard Worker   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1515*9880d681SAndroid Build Coastguard Worker   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1516*9880d681SAndroid Build Coastguard Worker   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1517*9880d681SAndroid Build Coastguard Worker   //                          int ordering)
1518*9880d681SAndroid Build Coastguard Worker   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1519*9880d681SAndroid Build Coastguard Worker   //                                  void *desired, int success_order,
1520*9880d681SAndroid Build Coastguard Worker   //                                  int failure_order)
1521*9880d681SAndroid Build Coastguard Worker   //
1522*9880d681SAndroid Build Coastguard Worker   // The different signatures are built up depending on the
1523*9880d681SAndroid Build Coastguard Worker   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1524*9880d681SAndroid Build Coastguard Worker   // variables.
1525*9880d681SAndroid Build Coastguard Worker 
1526*9880d681SAndroid Build Coastguard Worker   AllocaInst *AllocaCASExpected = nullptr;
1527*9880d681SAndroid Build Coastguard Worker   Value *AllocaCASExpected_i8 = nullptr;
1528*9880d681SAndroid Build Coastguard Worker   AllocaInst *AllocaValue = nullptr;
1529*9880d681SAndroid Build Coastguard Worker   Value *AllocaValue_i8 = nullptr;
1530*9880d681SAndroid Build Coastguard Worker   AllocaInst *AllocaResult = nullptr;
1531*9880d681SAndroid Build Coastguard Worker   Value *AllocaResult_i8 = nullptr;
1532*9880d681SAndroid Build Coastguard Worker 
1533*9880d681SAndroid Build Coastguard Worker   Type *ResultTy;
1534*9880d681SAndroid Build Coastguard Worker   SmallVector<Value *, 6> Args;
1535*9880d681SAndroid Build Coastguard Worker   AttributeSet Attr;
1536*9880d681SAndroid Build Coastguard Worker 
1537*9880d681SAndroid Build Coastguard Worker   // 'size' argument.
1538*9880d681SAndroid Build Coastguard Worker   if (!UseSizedLibcall) {
1539*9880d681SAndroid Build Coastguard Worker     // Note, getIntPtrType is assumed equivalent to size_t.
1540*9880d681SAndroid Build Coastguard Worker     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1541*9880d681SAndroid Build Coastguard Worker   }
1542*9880d681SAndroid Build Coastguard Worker 
1543*9880d681SAndroid Build Coastguard Worker   // 'ptr' argument.
1544*9880d681SAndroid Build Coastguard Worker   Value *PtrVal =
1545*9880d681SAndroid Build Coastguard Worker       Builder.CreateBitCast(PointerOperand, Type::getInt8PtrTy(Ctx));
1546*9880d681SAndroid Build Coastguard Worker   Args.push_back(PtrVal);
1547*9880d681SAndroid Build Coastguard Worker 
1548*9880d681SAndroid Build Coastguard Worker   // 'expected' argument, if present.
1549*9880d681SAndroid Build Coastguard Worker   if (CASExpected) {
1550*9880d681SAndroid Build Coastguard Worker     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1551*9880d681SAndroid Build Coastguard Worker     AllocaCASExpected->setAlignment(AllocaAlignment);
1552*9880d681SAndroid Build Coastguard Worker     AllocaCASExpected_i8 =
1553*9880d681SAndroid Build Coastguard Worker         Builder.CreateBitCast(AllocaCASExpected, Type::getInt8PtrTy(Ctx));
1554*9880d681SAndroid Build Coastguard Worker     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
1555*9880d681SAndroid Build Coastguard Worker     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1556*9880d681SAndroid Build Coastguard Worker     Args.push_back(AllocaCASExpected_i8);
1557*9880d681SAndroid Build Coastguard Worker   }
1558*9880d681SAndroid Build Coastguard Worker 
1559*9880d681SAndroid Build Coastguard Worker   // 'val' argument ('desired' for cas), if present.
1560*9880d681SAndroid Build Coastguard Worker   if (ValueOperand) {
1561*9880d681SAndroid Build Coastguard Worker     if (UseSizedLibcall) {
1562*9880d681SAndroid Build Coastguard Worker       Value *IntValue =
1563*9880d681SAndroid Build Coastguard Worker           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1564*9880d681SAndroid Build Coastguard Worker       Args.push_back(IntValue);
1565*9880d681SAndroid Build Coastguard Worker     } else {
1566*9880d681SAndroid Build Coastguard Worker       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1567*9880d681SAndroid Build Coastguard Worker       AllocaValue->setAlignment(AllocaAlignment);
1568*9880d681SAndroid Build Coastguard Worker       AllocaValue_i8 =
1569*9880d681SAndroid Build Coastguard Worker           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
1570*9880d681SAndroid Build Coastguard Worker       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
1571*9880d681SAndroid Build Coastguard Worker       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1572*9880d681SAndroid Build Coastguard Worker       Args.push_back(AllocaValue_i8);
1573*9880d681SAndroid Build Coastguard Worker     }
1574*9880d681SAndroid Build Coastguard Worker   }
1575*9880d681SAndroid Build Coastguard Worker 
1576*9880d681SAndroid Build Coastguard Worker   // 'ret' argument.
1577*9880d681SAndroid Build Coastguard Worker   if (!CASExpected && HasResult && !UseSizedLibcall) {
1578*9880d681SAndroid Build Coastguard Worker     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1579*9880d681SAndroid Build Coastguard Worker     AllocaResult->setAlignment(AllocaAlignment);
1580*9880d681SAndroid Build Coastguard Worker     AllocaResult_i8 =
1581*9880d681SAndroid Build Coastguard Worker         Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx));
1582*9880d681SAndroid Build Coastguard Worker     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
1583*9880d681SAndroid Build Coastguard Worker     Args.push_back(AllocaResult_i8);
1584*9880d681SAndroid Build Coastguard Worker   }
1585*9880d681SAndroid Build Coastguard Worker 
1586*9880d681SAndroid Build Coastguard Worker   // 'ordering' ('success_order' for cas) argument.
1587*9880d681SAndroid Build Coastguard Worker   Args.push_back(OrderingVal);
1588*9880d681SAndroid Build Coastguard Worker 
1589*9880d681SAndroid Build Coastguard Worker   // 'failure_order' argument, if present.
1590*9880d681SAndroid Build Coastguard Worker   if (Ordering2Val)
1591*9880d681SAndroid Build Coastguard Worker     Args.push_back(Ordering2Val);
1592*9880d681SAndroid Build Coastguard Worker 
1593*9880d681SAndroid Build Coastguard Worker   // Now, the return type.
1594*9880d681SAndroid Build Coastguard Worker   if (CASExpected) {
1595*9880d681SAndroid Build Coastguard Worker     ResultTy = Type::getInt1Ty(Ctx);
1596*9880d681SAndroid Build Coastguard Worker     Attr = Attr.addAttribute(Ctx, AttributeSet::ReturnIndex, Attribute::ZExt);
1597*9880d681SAndroid Build Coastguard Worker   } else if (HasResult && UseSizedLibcall)
1598*9880d681SAndroid Build Coastguard Worker     ResultTy = SizedIntTy;
1599*9880d681SAndroid Build Coastguard Worker   else
1600*9880d681SAndroid Build Coastguard Worker     ResultTy = Type::getVoidTy(Ctx);
1601*9880d681SAndroid Build Coastguard Worker 
1602*9880d681SAndroid Build Coastguard Worker   // Done with setting up arguments and return types, create the call:
1603*9880d681SAndroid Build Coastguard Worker   SmallVector<Type *, 6> ArgTys;
1604*9880d681SAndroid Build Coastguard Worker   for (Value *Arg : Args)
1605*9880d681SAndroid Build Coastguard Worker     ArgTys.push_back(Arg->getType());
1606*9880d681SAndroid Build Coastguard Worker   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
1607*9880d681SAndroid Build Coastguard Worker   Constant *LibcallFn =
1608*9880d681SAndroid Build Coastguard Worker       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
1609*9880d681SAndroid Build Coastguard Worker   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
1610*9880d681SAndroid Build Coastguard Worker   Call->setAttributes(Attr);
1611*9880d681SAndroid Build Coastguard Worker   Value *Result = Call;
1612*9880d681SAndroid Build Coastguard Worker 
1613*9880d681SAndroid Build Coastguard Worker   // And then, extract the results...
1614*9880d681SAndroid Build Coastguard Worker   if (ValueOperand && !UseSizedLibcall)
1615*9880d681SAndroid Build Coastguard Worker     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
1616*9880d681SAndroid Build Coastguard Worker 
1617*9880d681SAndroid Build Coastguard Worker   if (CASExpected) {
1618*9880d681SAndroid Build Coastguard Worker     // The final result from the CAS is {load of 'expected' alloca, bool result
1619*9880d681SAndroid Build Coastguard Worker     // from call}
1620*9880d681SAndroid Build Coastguard Worker     Type *FinalResultTy = I->getType();
1621*9880d681SAndroid Build Coastguard Worker     Value *V = UndefValue::get(FinalResultTy);
1622*9880d681SAndroid Build Coastguard Worker     Value *ExpectedOut =
1623*9880d681SAndroid Build Coastguard Worker         Builder.CreateAlignedLoad(AllocaCASExpected, AllocaAlignment);
1624*9880d681SAndroid Build Coastguard Worker     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
1625*9880d681SAndroid Build Coastguard Worker     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
1626*9880d681SAndroid Build Coastguard Worker     V = Builder.CreateInsertValue(V, Result, 1);
1627*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(V);
1628*9880d681SAndroid Build Coastguard Worker   } else if (HasResult) {
1629*9880d681SAndroid Build Coastguard Worker     Value *V;
1630*9880d681SAndroid Build Coastguard Worker     if (UseSizedLibcall)
1631*9880d681SAndroid Build Coastguard Worker       V = Builder.CreateBitOrPointerCast(Result, I->getType());
1632*9880d681SAndroid Build Coastguard Worker     else {
1633*9880d681SAndroid Build Coastguard Worker       V = Builder.CreateAlignedLoad(AllocaResult, AllocaAlignment);
1634*9880d681SAndroid Build Coastguard Worker       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
1635*9880d681SAndroid Build Coastguard Worker     }
1636*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(V);
1637*9880d681SAndroid Build Coastguard Worker   }
1638*9880d681SAndroid Build Coastguard Worker   I->eraseFromParent();
1639*9880d681SAndroid Build Coastguard Worker   return true;
1640*9880d681SAndroid Build Coastguard Worker }
1641