1f1933329SEugene Zelenko //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
259c23cd9SRobin Morisset //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
659c23cd9SRobin Morisset //
759c23cd9SRobin Morisset //===----------------------------------------------------------------------===//
859c23cd9SRobin Morisset //
959c23cd9SRobin Morisset // This file contains a pass (at IR level) to replace atomic instructions with
1019f6cce4SJames Y Knight // __atomic_* library calls, or target specific instruction which implement the
1119f6cce4SJames Y Knight // same semantics in a way which better fits the target backend.  This can
1219f6cce4SJames Y Knight // include the use of (intrinsic-based) load-linked/store-conditional loops,
1319f6cce4SJames Y Knight // AtomicCmpXchg, or type coercions.
1459c23cd9SRobin Morisset //
1559c23cd9SRobin Morisset //===----------------------------------------------------------------------===//
1659c23cd9SRobin Morisset 
17f1933329SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
18989f1c72Sserge-sans-paille #include "llvm/ADT/STLFunctionalExtras.h"
19f1933329SEugene Zelenko #include "llvm/ADT/SmallVector.h"
20f22ba518SAnshil Gandhi #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21e8aad299SJF Bastien #include "llvm/CodeGen/AtomicExpandUtils.h"
22f1933329SEugene Zelenko #include "llvm/CodeGen/RuntimeLibcalls.h"
23b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetLowering.h"
248b61764cSFrancis Visoiu Mistrih #include "llvm/CodeGen/TargetPassConfig.h"
25b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
262fa14362SCraig Topper #include "llvm/CodeGen/ValueTypes.h"
27f1933329SEugene Zelenko #include "llvm/IR/Attributes.h"
28f1933329SEugene Zelenko #include "llvm/IR/BasicBlock.h"
29f1933329SEugene Zelenko #include "llvm/IR/Constant.h"
30f1933329SEugene Zelenko #include "llvm/IR/Constants.h"
31f1933329SEugene Zelenko #include "llvm/IR/DataLayout.h"
32f1933329SEugene Zelenko #include "llvm/IR/DerivedTypes.h"
3359c23cd9SRobin Morisset #include "llvm/IR/Function.h"
3459c23cd9SRobin Morisset #include "llvm/IR/IRBuilder.h"
35ed3d48f1SRobin Morisset #include "llvm/IR/InstIterator.h"
36f1933329SEugene Zelenko #include "llvm/IR/Instruction.h"
3759c23cd9SRobin Morisset #include "llvm/IR/Instructions.h"
3859c23cd9SRobin Morisset #include "llvm/IR/Module.h"
39f1933329SEugene Zelenko #include "llvm/IR/Type.h"
40f1933329SEugene Zelenko #include "llvm/IR/User.h"
41f1933329SEugene Zelenko #include "llvm/IR/Value.h"
4205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
43f1933329SEugene Zelenko #include "llvm/Pass.h"
44f1933329SEugene Zelenko #include "llvm/Support/AtomicOrdering.h"
45f1933329SEugene Zelenko #include "llvm/Support/Casting.h"
4659c23cd9SRobin Morisset #include "llvm/Support/Debug.h"
47f1933329SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
4823319014SPhilip Reames #include "llvm/Support/raw_ostream.h"
4959c23cd9SRobin Morisset #include "llvm/Target/TargetMachine.h"
507f14a1d4SMatt Arsenault #include "llvm/Transforms/Utils/LowerAtomic.h"
51f1933329SEugene Zelenko #include <cassert>
52f1933329SEugene Zelenko #include <cstdint>
53f1933329SEugene Zelenko #include <iterator>
5459c23cd9SRobin Morisset 
5559c23cd9SRobin Morisset using namespace llvm;
5659c23cd9SRobin Morisset 
5759c23cd9SRobin Morisset #define DEBUG_TYPE "atomic-expand"
5859c23cd9SRobin Morisset 
5959c23cd9SRobin Morisset namespace {
60f1933329SEugene Zelenko 
6159c23cd9SRobin Morisset class AtomicExpand : public FunctionPass {
62f1933329SEugene Zelenko   const TargetLowering *TLI = nullptr;
63f1933329SEugene Zelenko 
6459c23cd9SRobin Morisset public:
6559c23cd9SRobin Morisset   static char ID; // Pass identification, replacement for typeid
66f1933329SEugene Zelenko 
AtomicExpand()67f1933329SEugene Zelenko   AtomicExpand() : FunctionPass(ID) {
6859c23cd9SRobin Morisset     initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
6959c23cd9SRobin Morisset   }
7059c23cd9SRobin Morisset 
7159c23cd9SRobin Morisset   bool runOnFunction(Function &F) override;
7259c23cd9SRobin Morisset 
73ed3d48f1SRobin Morisset private:
7404de70d3STim Shen   bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
7561a24ab6SPhilip Reames   IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
7661a24ab6SPhilip Reames   LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
7752468673SAhmed Bougacha   bool tryExpandAtomicLoad(LoadInst *LI);
786dbbbc28SRobin Morisset   bool expandAtomicLoadToLL(LoadInst *LI);
796dbbbc28SRobin Morisset   bool expandAtomicLoadToCmpXchg(LoadInst *LI);
8061a24ab6SPhilip Reames   StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
81c4ea925fSMatt Arsenault   bool tryExpandAtomicStore(StoreInst *SI);
825cd9fa55SEli Friedman   void expandAtomicStore(StoreInst *SI);
83f14889eeSJF Bastien   bool tryExpandAtomicRMW(AtomicRMWInst *AI);
84b577ec49SLemonBoy   AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
85148a6469SJames Y Knight   Value *
86148a6469SJames Y Knight   insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
8724539f1eSJames Y Knight                     Align AddrAlign, AtomicOrdering MemOpOrder,
88d3f4c05aSBenjamin Kramer                     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
89b09439e2SMarco Elver   void
90b09439e2SMarco Elver   expandAtomicOpToLLSC(Instruction *I, Type *ResultTy, Value *Addr,
91b09439e2SMarco Elver                        Align AddrAlign, AtomicOrdering MemOpOrder,
92148a6469SJames Y Knight                        function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
93148a6469SJames Y Knight   void expandPartwordAtomicRMW(
94b09439e2SMarco Elver       AtomicRMWInst *I, TargetLoweringBase::AtomicExpansionKind ExpansionKind);
953291f9aaSAlex Bradbury   AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
96a60c31fdSserge-sans-paille   bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
9721aea51eSAlex Bradbury   void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
9866d9a752SAlex Bradbury   void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
99148a6469SJames Y Knight 
1001960cfd3SPhilip Reames   AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
101b09439e2SMarco Elver   static Value *
102b09439e2SMarco Elver   insertRMWCmpXchgLoop(IRBuilder<> &Builder, Type *ResultType, Value *Addr,
103b09439e2SMarco Elver                        Align AddrAlign, AtomicOrdering MemOpOrder,
104b09439e2SMarco Elver                        SyncScope::ID SSID,
105148a6469SJames Y Knight                        function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
106148a6469SJames Y Knight                        CreateCmpXchgInstFun CreateCmpXchg);
10779518b02SAlex Bradbury   bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
108148a6469SJames Y Knight 
10959c23cd9SRobin Morisset   bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
110cb0bab86SFangrui Song   bool isIdempotentRMW(AtomicRMWInst *RMWI);
111cb0bab86SFangrui Song   bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
11219f6cce4SJames Y Knight 
1132c5ff48eSGuillaume Chatelet   bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
11419f6cce4SJames Y Knight                                Value *PointerOperand, Value *ValueOperand,
11519f6cce4SJames Y Knight                                Value *CASExpected, AtomicOrdering Ordering,
11619f6cce4SJames Y Knight                                AtomicOrdering Ordering2,
11719f6cce4SJames Y Knight                                ArrayRef<RTLIB::Libcall> Libcalls);
11819f6cce4SJames Y Knight   void expandAtomicLoadToLibcall(LoadInst *LI);
11919f6cce4SJames Y Knight   void expandAtomicStoreToLibcall(StoreInst *LI);
12019f6cce4SJames Y Knight   void expandAtomicRMWToLibcall(AtomicRMWInst *I);
12119f6cce4SJames Y Knight   void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
122148a6469SJames Y Knight 
123148a6469SJames Y Knight   friend bool
124148a6469SJames Y Knight   llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
125148a6469SJames Y Knight                                  CreateCmpXchgInstFun CreateCmpXchg);
12659c23cd9SRobin Morisset };
127f1933329SEugene Zelenko 
128f1933329SEugene Zelenko } // end anonymous namespace
12959c23cd9SRobin Morisset 
13059c23cd9SRobin Morisset char AtomicExpand::ID = 0;
131f1933329SEugene Zelenko 
13259c23cd9SRobin Morisset char &llvm::AtomicExpandID = AtomicExpand::ID;
133f1933329SEugene Zelenko 
134b09439e2SMarco Elver INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions", false,
135b09439e2SMarco Elver                 false)
13659c23cd9SRobin Morisset 
createAtomicExpandPass()1378b61764cSFrancis Visoiu Mistrih FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
13859c23cd9SRobin Morisset 
13919f6cce4SJames Y Knight // Helper functions to retrieve the size of atomic instructions.
getAtomicOpSize(LoadInst * LI)140f1933329SEugene Zelenko static unsigned getAtomicOpSize(LoadInst *LI) {
14119f6cce4SJames Y Knight   const DataLayout &DL = LI->getModule()->getDataLayout();
14219f6cce4SJames Y Knight   return DL.getTypeStoreSize(LI->getType());
14319f6cce4SJames Y Knight }
14419f6cce4SJames Y Knight 
getAtomicOpSize(StoreInst * SI)145f1933329SEugene Zelenko static unsigned getAtomicOpSize(StoreInst *SI) {
14619f6cce4SJames Y Knight   const DataLayout &DL = SI->getModule()->getDataLayout();
14719f6cce4SJames Y Knight   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
14819f6cce4SJames Y Knight }
14919f6cce4SJames Y Knight 
getAtomicOpSize(AtomicRMWInst * RMWI)150f1933329SEugene Zelenko static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
15119f6cce4SJames Y Knight   const DataLayout &DL = RMWI->getModule()->getDataLayout();
15219f6cce4SJames Y Knight   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
15319f6cce4SJames Y Knight }
15419f6cce4SJames Y Knight 
getAtomicOpSize(AtomicCmpXchgInst * CASI)155f1933329SEugene Zelenko static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
15619f6cce4SJames Y Knight   const DataLayout &DL = CASI->getModule()->getDataLayout();
15719f6cce4SJames Y Knight   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
15819f6cce4SJames Y Knight }
15919f6cce4SJames Y Knight 
16019f6cce4SJames Y Knight // Determine if a particular atomic operation has a supported size,
16119f6cce4SJames Y Knight // and is of appropriate alignment, to be passed through for target
16219f6cce4SJames Y Knight // lowering. (Versus turning into a __atomic libcall)
16319f6cce4SJames Y Knight template <typename Inst>
atomicSizeSupported(const TargetLowering * TLI,Inst * I)164f1933329SEugene Zelenko static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
16519f6cce4SJames Y Knight   unsigned Size = getAtomicOpSize(I);
1662c5ff48eSGuillaume Chatelet   Align Alignment = I->getAlign();
1672c5ff48eSGuillaume Chatelet   return Alignment >= Size &&
1682c5ff48eSGuillaume Chatelet          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
16919f6cce4SJames Y Knight }
17019f6cce4SJames Y Knight 
runOnFunction(Function & F)17159c23cd9SRobin Morisset bool AtomicExpand::runOnFunction(Function &F) {
1728b61764cSFrancis Visoiu Mistrih   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1738b61764cSFrancis Visoiu Mistrih   if (!TPC)
17459c23cd9SRobin Morisset     return false;
1758b61764cSFrancis Visoiu Mistrih 
1768b61764cSFrancis Visoiu Mistrih   auto &TM = TPC->getTM<TargetMachine>();
1778b61764cSFrancis Visoiu Mistrih   if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
1788b61764cSFrancis Visoiu Mistrih     return false;
1798b61764cSFrancis Visoiu Mistrih   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
18059c23cd9SRobin Morisset 
18159c23cd9SRobin Morisset   SmallVector<Instruction *, 1> AtomicInsts;
18259c23cd9SRobin Morisset 
18359c23cd9SRobin Morisset   // Changing control-flow while iterating through it is a bad idea, so gather a
18459c23cd9SRobin Morisset   // list of all atomic instructions before we start.
185feb40a3aSKazu Hirata   for (Instruction &I : instructions(F))
186feb40a3aSKazu Hirata     if (I.isAtomic() && !isa<FenceInst>(&I))
187feb40a3aSKazu Hirata       AtomicInsts.push_back(&I);
18859c23cd9SRobin Morisset 
18959c23cd9SRobin Morisset   bool MadeChange = false;
1909e6d1f4bSKazu Hirata   for (auto *I : AtomicInsts) {
191ed3d48f1SRobin Morisset     auto LI = dyn_cast<LoadInst>(I);
192ed3d48f1SRobin Morisset     auto SI = dyn_cast<StoreInst>(I);
193ed3d48f1SRobin Morisset     auto RMWI = dyn_cast<AtomicRMWInst>(I);
194ed3d48f1SRobin Morisset     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
19501f2ca56SJames Y Knight     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
196ed3d48f1SRobin Morisset 
19719f6cce4SJames Y Knight     // If the Size/Alignment is not supported, replace with a libcall.
19819f6cce4SJames Y Knight     if (LI) {
19919f6cce4SJames Y Knight       if (!atomicSizeSupported(TLI, LI)) {
20019f6cce4SJames Y Knight         expandAtomicLoadToLibcall(LI);
20119f6cce4SJames Y Knight         MadeChange = true;
20219f6cce4SJames Y Knight         continue;
20319f6cce4SJames Y Knight       }
20419f6cce4SJames Y Knight     } else if (SI) {
20519f6cce4SJames Y Knight       if (!atomicSizeSupported(TLI, SI)) {
20619f6cce4SJames Y Knight         expandAtomicStoreToLibcall(SI);
20719f6cce4SJames Y Knight         MadeChange = true;
20819f6cce4SJames Y Knight         continue;
20919f6cce4SJames Y Knight       }
21019f6cce4SJames Y Knight     } else if (RMWI) {
21119f6cce4SJames Y Knight       if (!atomicSizeSupported(TLI, RMWI)) {
21219f6cce4SJames Y Knight         expandAtomicRMWToLibcall(RMWI);
21319f6cce4SJames Y Knight         MadeChange = true;
21419f6cce4SJames Y Knight         continue;
21519f6cce4SJames Y Knight       }
21619f6cce4SJames Y Knight     } else if (CASI) {
21719f6cce4SJames Y Knight       if (!atomicSizeSupported(TLI, CASI)) {
21819f6cce4SJames Y Knight         expandAtomicCASToLibcall(CASI);
21919f6cce4SJames Y Knight         MadeChange = true;
22019f6cce4SJames Y Knight         continue;
22119f6cce4SJames Y Knight       }
22219f6cce4SJames Y Knight     }
22319f6cce4SJames Y Knight 
224f44fc521SJames Y Knight     if (TLI->shouldInsertFencesForAtomic(I)) {
225800f87a8SJF Bastien       auto FenceOrdering = AtomicOrdering::Monotonic;
226800f87a8SJF Bastien       if (LI && isAcquireOrStronger(LI->getOrdering())) {
227dedef332SRobin Morisset         FenceOrdering = LI->getOrdering();
228800f87a8SJF Bastien         LI->setOrdering(AtomicOrdering::Monotonic);
229800f87a8SJF Bastien       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
230dedef332SRobin Morisset         FenceOrdering = SI->getOrdering();
231800f87a8SJF Bastien         SI->setOrdering(AtomicOrdering::Monotonic);
232800f87a8SJF Bastien       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
233800f87a8SJF Bastien                           isAcquireOrStronger(RMWI->getOrdering()))) {
234dedef332SRobin Morisset         FenceOrdering = RMWI->getOrdering();
235800f87a8SJF Bastien         RMWI->setOrdering(AtomicOrdering::Monotonic);
23679518b02SAlex Bradbury       } else if (CASI &&
23779518b02SAlex Bradbury                  TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
23879518b02SAlex Bradbury                      TargetLoweringBase::AtomicExpansionKind::None &&
239800f87a8SJF Bastien                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
24044cdf771SEli Friedman                   isAcquireOrStronger(CASI->getSuccessOrdering()) ||
24144cdf771SEli Friedman                   isAcquireOrStronger(CASI->getFailureOrdering()))) {
242dedef332SRobin Morisset         // If a compare and swap is lowered to LL/SC, we can do smarter fence
243dedef332SRobin Morisset         // insertion, with a stronger one on the success path than on the
244dedef332SRobin Morisset         // failure path. As a result, fence insertion is directly done by
245dedef332SRobin Morisset         // expandAtomicCmpXchg in that case.
24644cdf771SEli Friedman         FenceOrdering = CASI->getMergedOrdering();
247800f87a8SJF Bastien         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
248800f87a8SJF Bastien         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
249dedef332SRobin Morisset       }
250dedef332SRobin Morisset 
251800f87a8SJF Bastien       if (FenceOrdering != AtomicOrdering::Monotonic) {
25204de70d3STim Shen         MadeChange |= bracketInstWithFences(I, FenceOrdering);
253dedef332SRobin Morisset       }
254dedef332SRobin Morisset     }
255dedef332SRobin Morisset 
25652468673SAhmed Bougacha     if (LI) {
257ff60a0a3SShilei Tian       if (TLI->shouldCastAtomicLoadInIR(LI) ==
258ff60a0a3SShilei Tian           TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
25961a24ab6SPhilip Reames         // TODO: add a TLI hook to control this so that each target can
26061a24ab6SPhilip Reames         // convert to lowering the original type one at a time.
26161a24ab6SPhilip Reames         LI = convertAtomicLoadToIntegerType(LI);
26261a24ab6SPhilip Reames         assert(LI->getType()->isIntegerTy() && "invariant broken");
26361a24ab6SPhilip Reames         MadeChange = true;
26461a24ab6SPhilip Reames       }
26561a24ab6SPhilip Reames 
26652468673SAhmed Bougacha       MadeChange |= tryExpandAtomicLoad(LI);
26761a24ab6SPhilip Reames     } else if (SI) {
268ff60a0a3SShilei Tian       if (TLI->shouldCastAtomicStoreInIR(SI) ==
269ff60a0a3SShilei Tian           TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
27061a24ab6SPhilip Reames         // TODO: add a TLI hook to control this so that each target can
27161a24ab6SPhilip Reames         // convert to lowering the original type one at a time.
27261a24ab6SPhilip Reames         SI = convertAtomicStoreToIntegerType(SI);
27361a24ab6SPhilip Reames         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
27461a24ab6SPhilip Reames                "invariant broken");
27561a24ab6SPhilip Reames         MadeChange = true;
27661a24ab6SPhilip Reames       }
27761a24ab6SPhilip Reames 
278c4ea925fSMatt Arsenault       if (tryExpandAtomicStore(SI))
2795cd9fa55SEli Friedman         MadeChange = true;
280810739d1SRobin Morisset     } else if (RMWI) {
281810739d1SRobin Morisset       // There are two different ways of expanding RMW instructions:
282810739d1SRobin Morisset       // - into a load if it is idempotent
283810739d1SRobin Morisset       // - into a Cmpxchg/LL-SC loop otherwise
284810739d1SRobin Morisset       // we try them in that order.
285f14889eeSJF Bastien 
286f14889eeSJF Bastien       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
287f14889eeSJF Bastien         MadeChange = true;
288f14889eeSJF Bastien       } else {
289b577ec49SLemonBoy         AtomicRMWInst::BinOp Op = RMWI->getOperation();
290ff60a0a3SShilei Tian         if (TLI->shouldCastAtomicRMWIInIR(RMWI) ==
291ff60a0a3SShilei Tian             TargetLoweringBase::AtomicExpansionKind::CastToInteger) {
292b577ec49SLemonBoy           // TODO: add a TLI hook to control this so that each target can
293b577ec49SLemonBoy           // convert to lowering the original type one at a time.
294b577ec49SLemonBoy           RMWI = convertAtomicXchgToIntegerType(RMWI);
295b577ec49SLemonBoy           assert(RMWI->getValOperand()->getType()->isIntegerTy() &&
296b577ec49SLemonBoy                  "invariant broken");
297b577ec49SLemonBoy           MadeChange = true;
298b577ec49SLemonBoy         }
2993291f9aaSAlex Bradbury         unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
3003291f9aaSAlex Bradbury         unsigned ValueSize = getAtomicOpSize(RMWI);
3013291f9aaSAlex Bradbury         if (ValueSize < MinCASSize &&
3023291f9aaSAlex Bradbury             (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
3033291f9aaSAlex Bradbury              Op == AtomicRMWInst::And)) {
3043291f9aaSAlex Bradbury           RMWI = widenPartwordAtomicRMW(RMWI);
3053291f9aaSAlex Bradbury           MadeChange = true;
3063291f9aaSAlex Bradbury         }
3073291f9aaSAlex Bradbury 
308f14889eeSJF Bastien         MadeChange |= tryExpandAtomicRMW(RMWI);
309f14889eeSJF Bastien       }
3101960cfd3SPhilip Reames     } else if (CASI) {
3111960cfd3SPhilip Reames       // TODO: when we're ready to make the change at the IR level, we can
3121960cfd3SPhilip Reames       // extend convertCmpXchgToInteger for floating point too.
3131960cfd3SPhilip Reames       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
3141960cfd3SPhilip Reames              "unimplemented - floating point not legal at IR level");
3151960cfd3SPhilip Reames       if (CASI->getCompareOperand()->getType()->isPointerTy()) {
3161960cfd3SPhilip Reames         // TODO: add a TLI hook to control this so that each target can
3171960cfd3SPhilip Reames         // convert to lowering the original type one at a time.
3181960cfd3SPhilip Reames         CASI = convertCmpXchgToIntegerType(CASI);
3191960cfd3SPhilip Reames         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
3201960cfd3SPhilip Reames                "invariant broken");
3211960cfd3SPhilip Reames         MadeChange = true;
3221960cfd3SPhilip Reames       }
3231960cfd3SPhilip Reames 
32479518b02SAlex Bradbury       MadeChange |= tryExpandAtomicCmpXchg(CASI);
325ed3d48f1SRobin Morisset     }
326148a6469SJames Y Knight   }
32759c23cd9SRobin Morisset   return MadeChange;
32859c23cd9SRobin Morisset }
32959c23cd9SRobin Morisset 
bracketInstWithFences(Instruction * I,AtomicOrdering Order)33004de70d3STim Shen bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
331dedef332SRobin Morisset   IRBuilder<> Builder(I);
332dedef332SRobin Morisset 
33304de70d3STim Shen   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
334dedef332SRobin Morisset 
33504de70d3STim Shen   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
336dedef332SRobin Morisset   // We have a guard here because not every atomic operation generates a
337dedef332SRobin Morisset   // trailing fence.
338674d2c23SSanjay Patel   if (TrailingFence)
339674d2c23SSanjay Patel     TrailingFence->moveAfter(I);
340dedef332SRobin Morisset 
341dedef332SRobin Morisset   return (LeadingFence || TrailingFence);
342dedef332SRobin Morisset }
343dedef332SRobin Morisset 
34461a24ab6SPhilip Reames /// Get the iX type with the same bitwidth as T.
getCorrespondingIntegerType(Type * T,const DataLayout & DL)34561a24ab6SPhilip Reames IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
34661a24ab6SPhilip Reames                                                        const DataLayout &DL) {
347ee2474dfSTim Northover   EVT VT = TLI->getMemValueType(DL, T);
34861a24ab6SPhilip Reames   unsigned BitWidth = VT.getStoreSizeInBits();
34961a24ab6SPhilip Reames   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
35061a24ab6SPhilip Reames   return IntegerType::get(T->getContext(), BitWidth);
35161a24ab6SPhilip Reames }
35261a24ab6SPhilip Reames 
35361a24ab6SPhilip Reames /// Convert an atomic load of a non-integral type to an integer load of the
3541960cfd3SPhilip Reames /// equivalent bitwidth.  See the function comment on
35561a24ab6SPhilip Reames /// convertAtomicStoreToIntegerType for background.
convertAtomicLoadToIntegerType(LoadInst * LI)35661a24ab6SPhilip Reames LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
35761a24ab6SPhilip Reames   auto *M = LI->getModule();
358b09439e2SMarco Elver   Type *NewTy = getCorrespondingIntegerType(LI->getType(), M->getDataLayout());
35961a24ab6SPhilip Reames 
36061a24ab6SPhilip Reames   IRBuilder<> Builder(LI);
36161a24ab6SPhilip Reames 
36261a24ab6SPhilip Reames   Value *Addr = LI->getPointerOperand();
363b09439e2SMarco Elver   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
36461a24ab6SPhilip Reames   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
36561a24ab6SPhilip Reames 
36614359ef1SJames Y Knight   auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
3673f13ee8aSEli Friedman   NewLI->setAlignment(LI->getAlign());
36861a24ab6SPhilip Reames   NewLI->setVolatile(LI->isVolatile());
369bb80d3e1SKonstantin Zhuravlyov   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
370d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
37161a24ab6SPhilip Reames 
37261a24ab6SPhilip Reames   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
37361a24ab6SPhilip Reames   LI->replaceAllUsesWith(NewVal);
37461a24ab6SPhilip Reames   LI->eraseFromParent();
37561a24ab6SPhilip Reames   return NewLI;
37661a24ab6SPhilip Reames }
37761a24ab6SPhilip Reames 
378b577ec49SLemonBoy AtomicRMWInst *
convertAtomicXchgToIntegerType(AtomicRMWInst * RMWI)379b577ec49SLemonBoy AtomicExpand::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
380b577ec49SLemonBoy   auto *M = RMWI->getModule();
381b577ec49SLemonBoy   Type *NewTy =
382b577ec49SLemonBoy       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
383b577ec49SLemonBoy 
384b577ec49SLemonBoy   IRBuilder<> Builder(RMWI);
385b577ec49SLemonBoy 
386b577ec49SLemonBoy   Value *Addr = RMWI->getPointerOperand();
387b577ec49SLemonBoy   Value *Val = RMWI->getValOperand();
388b577ec49SLemonBoy   Type *PT = PointerType::get(NewTy, RMWI->getPointerAddressSpace());
389b577ec49SLemonBoy   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
39018e6b823STakafumi Arakaki   Value *NewVal = Val->getType()->isPointerTy()
39118e6b823STakafumi Arakaki                       ? Builder.CreatePtrToInt(Val, NewTy)
39218e6b823STakafumi Arakaki                       : Builder.CreateBitCast(Val, NewTy);
393b577ec49SLemonBoy 
394b577ec49SLemonBoy   auto *NewRMWI =
395b577ec49SLemonBoy       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, NewAddr, NewVal,
396b577ec49SLemonBoy                               RMWI->getAlign(), RMWI->getOrdering());
397b577ec49SLemonBoy   NewRMWI->setVolatile(RMWI->isVolatile());
398b577ec49SLemonBoy   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
399b577ec49SLemonBoy 
40018e6b823STakafumi Arakaki   Value *NewRVal = RMWI->getType()->isPointerTy()
40118e6b823STakafumi Arakaki                        ? Builder.CreateIntToPtr(NewRMWI, RMWI->getType())
40218e6b823STakafumi Arakaki                        : Builder.CreateBitCast(NewRMWI, RMWI->getType());
403b577ec49SLemonBoy   RMWI->replaceAllUsesWith(NewRVal);
404b577ec49SLemonBoy   RMWI->eraseFromParent();
405b577ec49SLemonBoy   return NewRMWI;
406b577ec49SLemonBoy }
407b577ec49SLemonBoy 
tryExpandAtomicLoad(LoadInst * LI)40852468673SAhmed Bougacha bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
40952468673SAhmed Bougacha   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
41052468673SAhmed Bougacha   case TargetLoweringBase::AtomicExpansionKind::None:
41152468673SAhmed Bougacha     return false;
412f520eff7STim Northover   case TargetLoweringBase::AtomicExpansionKind::LLSC:
413148a6469SJames Y Knight     expandAtomicOpToLLSC(
41424539f1eSJames Y Knight         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
41524539f1eSJames Y Knight         LI->getOrdering(),
416f520eff7STim Northover         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
417148a6469SJames Y Knight     return true;
418f520eff7STim Northover   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
4196dbbbc28SRobin Morisset     return expandAtomicLoadToLL(LI);
420f520eff7STim Northover   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
4216dbbbc28SRobin Morisset     return expandAtomicLoadToCmpXchg(LI);
4227f14a1d4SMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
4237f14a1d4SMatt Arsenault     LI->setAtomic(AtomicOrdering::NotAtomic);
4247f14a1d4SMatt Arsenault     return true;
42521aea51eSAlex Bradbury   default:
42652468673SAhmed Bougacha     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
42752468673SAhmed Bougacha   }
42821aea51eSAlex Bradbury }
4296dbbbc28SRobin Morisset 
tryExpandAtomicStore(StoreInst * SI)430c4ea925fSMatt Arsenault bool AtomicExpand::tryExpandAtomicStore(StoreInst *SI) {
431c4ea925fSMatt Arsenault   switch (TLI->shouldExpandAtomicStoreInIR(SI)) {
432c4ea925fSMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::None:
433c4ea925fSMatt Arsenault     return false;
434c4ea925fSMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::Expand:
435c4ea925fSMatt Arsenault     expandAtomicStore(SI);
436c4ea925fSMatt Arsenault     return true;
4377f14a1d4SMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
4387f14a1d4SMatt Arsenault     SI->setAtomic(AtomicOrdering::NotAtomic);
4397f14a1d4SMatt Arsenault     return true;
440c4ea925fSMatt Arsenault   default:
441c4ea925fSMatt Arsenault     llvm_unreachable("Unhandled case in tryExpandAtomicStore");
442c4ea925fSMatt Arsenault   }
443c4ea925fSMatt Arsenault }
444c4ea925fSMatt Arsenault 
expandAtomicLoadToLL(LoadInst * LI)4456dbbbc28SRobin Morisset bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
44659c23cd9SRobin Morisset   IRBuilder<> Builder(LI);
44759c23cd9SRobin Morisset 
448dedef332SRobin Morisset   // On some architectures, load-linked instructions are atomic for larger
449dedef332SRobin Morisset   // sizes than normal loads. For example, the only 64-bit load guaranteed
450dedef332SRobin Morisset   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
451df88c26fSKrzysztof Parzyszek   Value *Val = TLI->emitLoadLinked(Builder, LI->getType(),
452df88c26fSKrzysztof Parzyszek                                    LI->getPointerOperand(), LI->getOrdering());
453f520eff7STim Northover   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
45459c23cd9SRobin Morisset 
45559c23cd9SRobin Morisset   LI->replaceAllUsesWith(Val);
45659c23cd9SRobin Morisset   LI->eraseFromParent();
45759c23cd9SRobin Morisset 
45859c23cd9SRobin Morisset   return true;
45959c23cd9SRobin Morisset }
46059c23cd9SRobin Morisset 
expandAtomicLoadToCmpXchg(LoadInst * LI)4616dbbbc28SRobin Morisset bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
4626dbbbc28SRobin Morisset   IRBuilder<> Builder(LI);
4636dbbbc28SRobin Morisset   AtomicOrdering Order = LI->getOrdering();
4642153c4b8SPhilip Reames   if (Order == AtomicOrdering::Unordered)
4652153c4b8SPhilip Reames     Order = AtomicOrdering::Monotonic;
4662153c4b8SPhilip Reames 
4676dbbbc28SRobin Morisset   Value *Addr = LI->getPointerOperand();
46837223748SArthur Eubanks   Type *Ty = LI->getType();
4696dbbbc28SRobin Morisset   Constant *DummyVal = Constant::getNullValue(Ty);
4706dbbbc28SRobin Morisset 
4716dbbbc28SRobin Morisset   Value *Pair = Builder.CreateAtomicCmpXchg(
47224539f1eSJames Y Knight       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
4736dbbbc28SRobin Morisset       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
4746dbbbc28SRobin Morisset   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
4756dbbbc28SRobin Morisset 
4766dbbbc28SRobin Morisset   LI->replaceAllUsesWith(Loaded);
4776dbbbc28SRobin Morisset   LI->eraseFromParent();
4786dbbbc28SRobin Morisset 
4796dbbbc28SRobin Morisset   return true;
4806dbbbc28SRobin Morisset }
4816dbbbc28SRobin Morisset 
48261a24ab6SPhilip Reames /// Convert an atomic store of a non-integral type to an integer store of the
4831960cfd3SPhilip Reames /// equivalent bitwidth.  We used to not support floating point or vector
48461a24ab6SPhilip Reames /// atomics in the IR at all.  The backends learned to deal with the bitcast
48561a24ab6SPhilip Reames /// idiom because that was the only way of expressing the notion of a atomic
48661a24ab6SPhilip Reames /// float or vector store.  The long term plan is to teach each backend to
48761a24ab6SPhilip Reames /// instruction select from the original atomic store, but as a migration
48861a24ab6SPhilip Reames /// mechanism, we convert back to the old format which the backends understand.
48961a24ab6SPhilip Reames /// Each backend will need individual work to recognize the new format.
convertAtomicStoreToIntegerType(StoreInst * SI)49061a24ab6SPhilip Reames StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
49161a24ab6SPhilip Reames   IRBuilder<> Builder(SI);
49261a24ab6SPhilip Reames   auto *M = SI->getModule();
49361a24ab6SPhilip Reames   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
49461a24ab6SPhilip Reames                                             M->getDataLayout());
49561a24ab6SPhilip Reames   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
49661a24ab6SPhilip Reames 
49761a24ab6SPhilip Reames   Value *Addr = SI->getPointerOperand();
498b09439e2SMarco Elver   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
49961a24ab6SPhilip Reames   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
50061a24ab6SPhilip Reames 
50161a24ab6SPhilip Reames   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
5023f13ee8aSEli Friedman   NewSI->setAlignment(SI->getAlign());
50361a24ab6SPhilip Reames   NewSI->setVolatile(SI->isVolatile());
504bb80d3e1SKonstantin Zhuravlyov   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
505d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
50661a24ab6SPhilip Reames   SI->eraseFromParent();
50761a24ab6SPhilip Reames   return NewSI;
50861a24ab6SPhilip Reames }
50961a24ab6SPhilip Reames 
expandAtomicStore(StoreInst * SI)5105cd9fa55SEli Friedman void AtomicExpand::expandAtomicStore(StoreInst *SI) {
51125c8e318SRobin Morisset   // This function is only called on atomic stores that are too large to be
51225c8e318SRobin Morisset   // atomic if implemented as a native store. So we replace them by an
51325c8e318SRobin Morisset   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
51425c8e318SRobin Morisset   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
515f14889eeSJF Bastien   // It is the responsibility of the target to only signal expansion via
51625c8e318SRobin Morisset   // shouldExpandAtomicRMW in cases where this is required and possible.
51759c23cd9SRobin Morisset   IRBuilder<> Builder(SI);
518*1e636f26SAlexander Shaposhnikov   AtomicOrdering Ordering = SI->getOrdering();
519*1e636f26SAlexander Shaposhnikov   assert(Ordering != AtomicOrdering::NotAtomic);
520*1e636f26SAlexander Shaposhnikov   AtomicOrdering RMWOrdering = Ordering == AtomicOrdering::Unordered
521*1e636f26SAlexander Shaposhnikov                                    ? AtomicOrdering::Monotonic
522*1e636f26SAlexander Shaposhnikov                                    : Ordering;
52324539f1eSJames Y Knight   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
52424539f1eSJames Y Knight       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
525*1e636f26SAlexander Shaposhnikov       SI->getAlign(), RMWOrdering);
52659c23cd9SRobin Morisset   SI->eraseFromParent();
52759c23cd9SRobin Morisset 
52859c23cd9SRobin Morisset   // Now we have an appropriate swap instruction, lower it as usual.
5295cd9fa55SEli Friedman   tryExpandAtomicRMW(AI);
53059c23cd9SRobin Morisset }
53159c23cd9SRobin Morisset 
createCmpXchgInstFun(IRBuilder<> & Builder,Value * Addr,Value * Loaded,Value * NewVal,Align AddrAlign,AtomicOrdering MemOpOrder,SyncScope::ID SSID,Value * & Success,Value * & NewLoaded)532e8aad299SJF Bastien static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
53324539f1eSJames Y Knight                                  Value *Loaded, Value *NewVal, Align AddrAlign,
53430b3aab3SStanislav Mekhanoshin                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
53530b3aab3SStanislav Mekhanoshin                                  Value *&Success, Value *&NewLoaded) {
5360cb08e44SMatt Arsenault   Type *OrigTy = NewVal->getType();
5370cb08e44SMatt Arsenault 
5380cb08e44SMatt Arsenault   // This code can go away when cmpxchg supports FP types.
53918e6b823STakafumi Arakaki   assert(!OrigTy->isPointerTy());
5400cb08e44SMatt Arsenault   bool NeedBitcast = OrigTy->isFloatingPointTy();
5410cb08e44SMatt Arsenault   if (NeedBitcast) {
5420cb08e44SMatt Arsenault     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
5430cb08e44SMatt Arsenault     unsigned AS = Addr->getType()->getPointerAddressSpace();
5440cb08e44SMatt Arsenault     Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
5450cb08e44SMatt Arsenault     NewVal = Builder.CreateBitCast(NewVal, IntTy);
5460cb08e44SMatt Arsenault     Loaded = Builder.CreateBitCast(Loaded, IntTy);
5470cb08e44SMatt Arsenault   }
5480cb08e44SMatt Arsenault 
549e8aad299SJF Bastien   Value *Pair = Builder.CreateAtomicCmpXchg(
55024539f1eSJames Y Knight       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
55130b3aab3SStanislav Mekhanoshin       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
552e8aad299SJF Bastien   Success = Builder.CreateExtractValue(Pair, 1, "success");
553e8aad299SJF Bastien   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
5540cb08e44SMatt Arsenault 
5550cb08e44SMatt Arsenault   if (NeedBitcast)
5560cb08e44SMatt Arsenault     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
557e8aad299SJF Bastien }
558e8aad299SJF Bastien 
tryExpandAtomicRMW(AtomicRMWInst * AI)559f520eff7STim Northover bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
560f22ba518SAnshil Gandhi   LLVMContext &Ctx = AI->getModule()->getContext();
561f22ba518SAnshil Gandhi   TargetLowering::AtomicExpansionKind Kind = TLI->shouldExpandAtomicRMWInIR(AI);
562f22ba518SAnshil Gandhi   switch (Kind) {
563f520eff7STim Northover   case TargetLoweringBase::AtomicExpansionKind::None:
564f520eff7STim Northover     return false;
565148a6469SJames Y Knight   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
566148a6469SJames Y Knight     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
567148a6469SJames Y Knight     unsigned ValueSize = getAtomicOpSize(AI);
568148a6469SJames Y Knight     if (ValueSize < MinCASSize) {
56925a4b190SKrzysztof Parzyszek       expandPartwordAtomicRMW(AI,
57025a4b190SKrzysztof Parzyszek                               TargetLoweringBase::AtomicExpansionKind::LLSC);
571148a6469SJames Y Knight     } else {
572148a6469SJames Y Knight       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
5739fdd2584SMatt Arsenault         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
574f520eff7STim Northover                                    AI->getValOperand());
575148a6469SJames Y Knight       };
576148a6469SJames Y Knight       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
57724539f1eSJames Y Knight                            AI->getAlign(), AI->getOrdering(), PerformOp);
578148a6469SJames Y Knight     }
579148a6469SJames Y Knight     return true;
580148a6469SJames Y Knight   }
581148a6469SJames Y Knight   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
582148a6469SJames Y Knight     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
583148a6469SJames Y Knight     unsigned ValueSize = getAtomicOpSize(AI);
584148a6469SJames Y Knight     if (ValueSize < MinCASSize) {
585383e72fcSMatt Arsenault       // TODO: Handle atomicrmw fadd/fsub
586383e72fcSMatt Arsenault       if (AI->getType()->isFloatingPointTy())
587383e72fcSMatt Arsenault         return false;
588383e72fcSMatt Arsenault 
589148a6469SJames Y Knight       expandPartwordAtomicRMW(AI,
590148a6469SJames Y Knight                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
591148a6469SJames Y Knight     } else {
592f22ba518SAnshil Gandhi       SmallVector<StringRef> SSNs;
593f22ba518SAnshil Gandhi       Ctx.getSyncScopeNames(SSNs);
594f22ba518SAnshil Gandhi       auto MemScope = SSNs[AI->getSyncScopeID()].empty()
595f22ba518SAnshil Gandhi                           ? "system"
596f22ba518SAnshil Gandhi                           : SSNs[AI->getSyncScopeID()];
597f22ba518SAnshil Gandhi       OptimizationRemarkEmitter ORE(AI->getFunction());
598f22ba518SAnshil Gandhi       ORE.emit([&]() {
599508b0669SAnshil Gandhi         return OptimizationRemark(DEBUG_TYPE, "Passed", AI)
600f22ba518SAnshil Gandhi                << "A compare and swap loop was generated for an atomic "
601f22ba518SAnshil Gandhi                << AI->getOperationName(AI->getOperation()) << " operation at "
602f22ba518SAnshil Gandhi                << MemScope << " memory scope";
603f22ba518SAnshil Gandhi       });
604148a6469SJames Y Knight       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
605148a6469SJames Y Knight     }
606148a6469SJames Y Knight     return true;
607148a6469SJames Y Knight   }
60821aea51eSAlex Bradbury   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
60921aea51eSAlex Bradbury     expandAtomicRMWToMaskedIntrinsic(AI);
61021aea51eSAlex Bradbury     return true;
61121aea51eSAlex Bradbury   }
612e03d216cSPhoebe Wang   case TargetLoweringBase::AtomicExpansionKind::BitTestIntrinsic: {
613e03d216cSPhoebe Wang     TLI->emitBitTestAtomicRMWIntrinsic(AI);
614e03d216cSPhoebe Wang     return true;
615e03d216cSPhoebe Wang   }
6167f14a1d4SMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
6177f14a1d4SMatt Arsenault     return lowerAtomicRMWInst(AI);
618f520eff7STim Northover   default:
619f520eff7STim Northover     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
620f520eff7STim Northover   }
621f520eff7STim Northover }
622f520eff7STim Northover 
623148a6469SJames Y Knight namespace {
624148a6469SJames Y Knight 
625148a6469SJames Y Knight struct PartwordMaskValues {
62625a4b190SKrzysztof Parzyszek   // These three fields are guaranteed to be set by createMaskInstrs.
62725a4b190SKrzysztof Parzyszek   Type *WordType = nullptr;
62825a4b190SKrzysztof Parzyszek   Type *ValueType = nullptr;
62925a4b190SKrzysztof Parzyszek   Value *AlignedAddr = nullptr;
63024539f1eSJames Y Knight   Align AlignedAddrAlignment;
63125a4b190SKrzysztof Parzyszek   // The remaining fields can be null.
63225a4b190SKrzysztof Parzyszek   Value *ShiftAmt = nullptr;
63325a4b190SKrzysztof Parzyszek   Value *Mask = nullptr;
63425a4b190SKrzysztof Parzyszek   Value *Inv_Mask = nullptr;
635148a6469SJames Y Knight };
636f1933329SEugene Zelenko 
63725a4b190SKrzysztof Parzyszek LLVM_ATTRIBUTE_UNUSED
operator <<(raw_ostream & O,const PartwordMaskValues & PMV)63825a4b190SKrzysztof Parzyszek raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
63925a4b190SKrzysztof Parzyszek   auto PrintObj = [&O](auto *V) {
64025a4b190SKrzysztof Parzyszek     if (V)
64125a4b190SKrzysztof Parzyszek       O << *V;
64225a4b190SKrzysztof Parzyszek     else
64325a4b190SKrzysztof Parzyszek       O << "nullptr";
64425a4b190SKrzysztof Parzyszek     O << '\n';
64525a4b190SKrzysztof Parzyszek   };
64625a4b190SKrzysztof Parzyszek   O << "PartwordMaskValues {\n";
64725a4b190SKrzysztof Parzyszek   O << "  WordType: ";
64825a4b190SKrzysztof Parzyszek   PrintObj(PMV.WordType);
64925a4b190SKrzysztof Parzyszek   O << "  ValueType: ";
65025a4b190SKrzysztof Parzyszek   PrintObj(PMV.ValueType);
65125a4b190SKrzysztof Parzyszek   O << "  AlignedAddr: ";
65225a4b190SKrzysztof Parzyszek   PrintObj(PMV.AlignedAddr);
65324539f1eSJames Y Knight   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
65425a4b190SKrzysztof Parzyszek   O << "  ShiftAmt: ";
65525a4b190SKrzysztof Parzyszek   PrintObj(PMV.ShiftAmt);
65625a4b190SKrzysztof Parzyszek   O << "  Mask: ";
65725a4b190SKrzysztof Parzyszek   PrintObj(PMV.Mask);
65825a4b190SKrzysztof Parzyszek   O << "  Inv_Mask: ";
65925a4b190SKrzysztof Parzyszek   PrintObj(PMV.Inv_Mask);
66025a4b190SKrzysztof Parzyszek   O << "}\n";
66125a4b190SKrzysztof Parzyszek   return O;
66225a4b190SKrzysztof Parzyszek }
66325a4b190SKrzysztof Parzyszek 
664148a6469SJames Y Knight } // end anonymous namespace
665148a6469SJames Y Knight 
666148a6469SJames Y Knight /// This is a helper function which builds instructions to provide
667148a6469SJames Y Knight /// values necessary for partword atomic operations. It takes an
668148a6469SJames Y Knight /// incoming address, Addr, and ValueType, and constructs the address,
669148a6469SJames Y Knight /// shift-amounts and masks needed to work with a larger value of size
670148a6469SJames Y Knight /// WordSize.
671148a6469SJames Y Knight ///
672148a6469SJames Y Knight /// AlignedAddr: Addr rounded down to a multiple of WordSize
673148a6469SJames Y Knight ///
674148a6469SJames Y Knight /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
675148a6469SJames Y Knight ///           from AlignAddr for it to have the same value as if
676148a6469SJames Y Knight ///           ValueType was loaded from Addr.
677148a6469SJames Y Knight ///
678148a6469SJames Y Knight /// Mask: Value to mask with the value loaded from AlignAddr to
679148a6469SJames Y Knight ///       include only the part that would've been loaded from Addr.
680148a6469SJames Y Knight ///
681148a6469SJames Y Knight /// Inv_Mask: The inverse of Mask.
createMaskInstrs(IRBuilder<> & Builder,Instruction * I,Type * ValueType,Value * Addr,Align AddrAlign,unsigned MinWordSize)682148a6469SJames Y Knight static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
683148a6469SJames Y Knight                                            Type *ValueType, Value *Addr,
68424539f1eSJames Y Knight                                            Align AddrAlign,
68525a4b190SKrzysztof Parzyszek                                            unsigned MinWordSize) {
68625a4b190SKrzysztof Parzyszek   PartwordMaskValues PMV;
687148a6469SJames Y Knight 
688148a6469SJames Y Knight   Module *M = I->getModule();
68925a4b190SKrzysztof Parzyszek   LLVMContext &Ctx = M->getContext();
690148a6469SJames Y Knight   const DataLayout &DL = M->getDataLayout();
691148a6469SJames Y Knight   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
692148a6469SJames Y Knight 
69325a4b190SKrzysztof Parzyszek   PMV.ValueType = ValueType;
69425a4b190SKrzysztof Parzyszek   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
69525a4b190SKrzysztof Parzyszek                                          : ValueType;
69625a4b190SKrzysztof Parzyszek   if (PMV.ValueType == PMV.WordType) {
69725a4b190SKrzysztof Parzyszek     PMV.AlignedAddr = Addr;
69824539f1eSJames Y Knight     PMV.AlignedAddrAlignment = AddrAlign;
699b9c3941cSKai Luo     PMV.ShiftAmt = ConstantInt::get(PMV.ValueType, 0);
70031906a60SKai Luo     PMV.Mask = ConstantInt::get(PMV.ValueType, ~0, /*isSigned*/ true);
70125a4b190SKrzysztof Parzyszek     return PMV;
702148a6469SJames Y Knight   }
703148a6469SJames Y Knight 
70425a4b190SKrzysztof Parzyszek   assert(ValueSize < MinWordSize);
705148a6469SJames Y Knight 
70625a4b190SKrzysztof Parzyszek   Type *WordPtrType =
70725a4b190SKrzysztof Parzyszek       PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
70825a4b190SKrzysztof Parzyszek 
70924539f1eSJames Y Knight   // TODO: we could skip some of this if AddrAlign >= MinWordSize.
71025a4b190SKrzysztof Parzyszek   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
71125a4b190SKrzysztof Parzyszek   PMV.AlignedAddr = Builder.CreateIntToPtr(
71225a4b190SKrzysztof Parzyszek       Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
71325a4b190SKrzysztof Parzyszek       "AlignedAddr");
71424539f1eSJames Y Knight   PMV.AlignedAddrAlignment = Align(MinWordSize);
71525a4b190SKrzysztof Parzyszek 
71625a4b190SKrzysztof Parzyszek   Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
71725a4b190SKrzysztof Parzyszek   if (DL.isLittleEndian()) {
71825a4b190SKrzysztof Parzyszek     // turn bytes into bits
71925a4b190SKrzysztof Parzyszek     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
72025a4b190SKrzysztof Parzyszek   } else {
72125a4b190SKrzysztof Parzyszek     // turn bytes into bits, and count from the other side.
72225a4b190SKrzysztof Parzyszek     PMV.ShiftAmt = Builder.CreateShl(
72325a4b190SKrzysztof Parzyszek         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
72425a4b190SKrzysztof Parzyszek   }
72525a4b190SKrzysztof Parzyszek 
72625a4b190SKrzysztof Parzyszek   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
72725a4b190SKrzysztof Parzyszek   PMV.Mask = Builder.CreateShl(
72825a4b190SKrzysztof Parzyszek       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
72925a4b190SKrzysztof Parzyszek       "Mask");
73025a4b190SKrzysztof Parzyszek   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
73125a4b190SKrzysztof Parzyszek   return PMV;
73225a4b190SKrzysztof Parzyszek }
73325a4b190SKrzysztof Parzyszek 
extractMaskedValue(IRBuilder<> & Builder,Value * WideWord,const PartwordMaskValues & PMV)73425a4b190SKrzysztof Parzyszek static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
73525a4b190SKrzysztof Parzyszek                                  const PartwordMaskValues &PMV) {
73625a4b190SKrzysztof Parzyszek   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
73725a4b190SKrzysztof Parzyszek   if (PMV.WordType == PMV.ValueType)
73825a4b190SKrzysztof Parzyszek     return WideWord;
73925a4b190SKrzysztof Parzyszek 
74025a4b190SKrzysztof Parzyszek   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
74125a4b190SKrzysztof Parzyszek   Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
74225a4b190SKrzysztof Parzyszek   return Trunc;
74325a4b190SKrzysztof Parzyszek }
74425a4b190SKrzysztof Parzyszek 
insertMaskedValue(IRBuilder<> & Builder,Value * WideWord,Value * Updated,const PartwordMaskValues & PMV)74525a4b190SKrzysztof Parzyszek static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
74625a4b190SKrzysztof Parzyszek                                 Value *Updated, const PartwordMaskValues &PMV) {
74725a4b190SKrzysztof Parzyszek   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
74825a4b190SKrzysztof Parzyszek   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
74925a4b190SKrzysztof Parzyszek   if (PMV.WordType == PMV.ValueType)
75025a4b190SKrzysztof Parzyszek     return Updated;
75125a4b190SKrzysztof Parzyszek 
75225a4b190SKrzysztof Parzyszek   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
75325a4b190SKrzysztof Parzyszek   Value *Shift =
75425a4b190SKrzysztof Parzyszek       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
75525a4b190SKrzysztof Parzyszek   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
75625a4b190SKrzysztof Parzyszek   Value *Or = Builder.CreateOr(And, Shift, "inserted");
75725a4b190SKrzysztof Parzyszek   return Or;
758148a6469SJames Y Knight }
759148a6469SJames Y Knight 
760148a6469SJames Y Knight /// Emit IR to implement a masked version of a given atomicrmw
761148a6469SJames Y Knight /// operation. (That is, only the bits under the Mask should be
762148a6469SJames Y Knight /// affected by the operation)
performMaskedAtomicOp(AtomicRMWInst::BinOp Op,IRBuilder<> & Builder,Value * Loaded,Value * Shifted_Inc,Value * Inc,const PartwordMaskValues & PMV)763148a6469SJames Y Knight static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
764148a6469SJames Y Knight                                     IRBuilder<> &Builder, Value *Loaded,
765148a6469SJames Y Knight                                     Value *Shifted_Inc, Value *Inc,
766148a6469SJames Y Knight                                     const PartwordMaskValues &PMV) {
76721aea51eSAlex Bradbury   // TODO: update to use
76821aea51eSAlex Bradbury   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
76921aea51eSAlex Bradbury   // to merge bits from two values without requiring PMV.Inv_Mask.
770148a6469SJames Y Knight   switch (Op) {
771148a6469SJames Y Knight   case AtomicRMWInst::Xchg: {
772148a6469SJames Y Knight     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
773148a6469SJames Y Knight     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
774148a6469SJames Y Knight     return FinalVal;
775148a6469SJames Y Knight   }
776148a6469SJames Y Knight   case AtomicRMWInst::Or:
777148a6469SJames Y Knight   case AtomicRMWInst::Xor:
7783291f9aaSAlex Bradbury   case AtomicRMWInst::And:
7793291f9aaSAlex Bradbury     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
780148a6469SJames Y Knight   case AtomicRMWInst::Add:
781148a6469SJames Y Knight   case AtomicRMWInst::Sub:
782148a6469SJames Y Knight   case AtomicRMWInst::Nand: {
783148a6469SJames Y Knight     // The other arithmetic ops need to be masked into place.
7849fdd2584SMatt Arsenault     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded, Shifted_Inc);
785148a6469SJames Y Knight     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
786148a6469SJames Y Knight     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
787148a6469SJames Y Knight     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
788148a6469SJames Y Knight     return FinalVal;
789148a6469SJames Y Knight   }
790148a6469SJames Y Knight   case AtomicRMWInst::Max:
791148a6469SJames Y Knight   case AtomicRMWInst::Min:
792148a6469SJames Y Knight   case AtomicRMWInst::UMax:
793148a6469SJames Y Knight   case AtomicRMWInst::UMin: {
794148a6469SJames Y Knight     // Finally, comparison ops will operate on the full value, so
795148a6469SJames Y Knight     // truncate down to the original size, and expand out again after
796148a6469SJames Y Knight     // doing the operation.
79725a4b190SKrzysztof Parzyszek     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
7989fdd2584SMatt Arsenault     Value *NewVal = buildAtomicRMWValue(Op, Builder, Loaded_Extract, Inc);
79925a4b190SKrzysztof Parzyszek     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
800148a6469SJames Y Knight     return FinalVal;
801148a6469SJames Y Knight   }
802148a6469SJames Y Knight   default:
803148a6469SJames Y Knight     llvm_unreachable("Unknown atomic op");
804148a6469SJames Y Knight   }
805148a6469SJames Y Knight }
806148a6469SJames Y Knight 
807148a6469SJames Y Knight /// Expand a sub-word atomicrmw operation into an appropriate
808148a6469SJames Y Knight /// word-sized operation.
809148a6469SJames Y Knight ///
810148a6469SJames Y Knight /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
811148a6469SJames Y Knight /// way as a typical atomicrmw expansion. The only difference here is
81225a4b190SKrzysztof Parzyszek /// that the operation inside of the loop may operate upon only a
813148a6469SJames Y Knight /// part of the value.
expandPartwordAtomicRMW(AtomicRMWInst * AI,TargetLoweringBase::AtomicExpansionKind ExpansionKind)814148a6469SJames Y Knight void AtomicExpand::expandPartwordAtomicRMW(
815148a6469SJames Y Knight     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
816148a6469SJames Y Knight   AtomicOrdering MemOpOrder = AI->getOrdering();
81730b3aab3SStanislav Mekhanoshin   SyncScope::ID SSID = AI->getSyncScopeID();
818148a6469SJames Y Knight 
819148a6469SJames Y Knight   IRBuilder<> Builder(AI);
820148a6469SJames Y Knight 
821148a6469SJames Y Knight   PartwordMaskValues PMV =
822148a6469SJames Y Knight       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
82324539f1eSJames Y Knight                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
824148a6469SJames Y Knight 
825148a6469SJames Y Knight   Value *ValOperand_Shifted =
826148a6469SJames Y Knight       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
827148a6469SJames Y Knight                         PMV.ShiftAmt, "ValOperand_Shifted");
828148a6469SJames Y Knight 
829148a6469SJames Y Knight   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
830148a6469SJames Y Knight     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
831148a6469SJames Y Knight                                  ValOperand_Shifted, AI->getValOperand(), PMV);
832148a6469SJames Y Knight   };
833148a6469SJames Y Knight 
83425a4b190SKrzysztof Parzyszek   Value *OldResult;
83525a4b190SKrzysztof Parzyszek   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
83624539f1eSJames Y Knight     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
837b09439e2SMarco Elver                                      PMV.AlignedAddrAlignment, MemOpOrder, SSID,
838b09439e2SMarco Elver                                      PerformPartwordOp, createCmpXchgInstFun);
83925a4b190SKrzysztof Parzyszek   } else {
84025a4b190SKrzysztof Parzyszek     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
84125a4b190SKrzysztof Parzyszek     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
84224539f1eSJames Y Knight                                   PMV.AlignedAddrAlignment, MemOpOrder,
84324539f1eSJames Y Knight                                   PerformPartwordOp);
84425a4b190SKrzysztof Parzyszek   }
84525a4b190SKrzysztof Parzyszek 
84625a4b190SKrzysztof Parzyszek   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
847148a6469SJames Y Knight   AI->replaceAllUsesWith(FinalOldResult);
848148a6469SJames Y Knight   AI->eraseFromParent();
849148a6469SJames Y Knight }
850148a6469SJames Y Knight 
8513291f9aaSAlex Bradbury // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
widenPartwordAtomicRMW(AtomicRMWInst * AI)8523291f9aaSAlex Bradbury AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
8533291f9aaSAlex Bradbury   IRBuilder<> Builder(AI);
8543291f9aaSAlex Bradbury   AtomicRMWInst::BinOp Op = AI->getOperation();
8553291f9aaSAlex Bradbury 
8563291f9aaSAlex Bradbury   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
8573291f9aaSAlex Bradbury           Op == AtomicRMWInst::And) &&
8583291f9aaSAlex Bradbury          "Unable to widen operation");
8593291f9aaSAlex Bradbury 
8603291f9aaSAlex Bradbury   PartwordMaskValues PMV =
8613291f9aaSAlex Bradbury       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
86224539f1eSJames Y Knight                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
8633291f9aaSAlex Bradbury 
8643291f9aaSAlex Bradbury   Value *ValOperand_Shifted =
8653291f9aaSAlex Bradbury       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
8663291f9aaSAlex Bradbury                         PMV.ShiftAmt, "ValOperand_Shifted");
8673291f9aaSAlex Bradbury 
8683291f9aaSAlex Bradbury   Value *NewOperand;
8693291f9aaSAlex Bradbury 
8703291f9aaSAlex Bradbury   if (Op == AtomicRMWInst::And)
8713291f9aaSAlex Bradbury     NewOperand =
8723291f9aaSAlex Bradbury         Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
8733291f9aaSAlex Bradbury   else
8743291f9aaSAlex Bradbury     NewOperand = ValOperand_Shifted;
8753291f9aaSAlex Bradbury 
87624539f1eSJames Y Knight   AtomicRMWInst *NewAI =
87724539f1eSJames Y Knight       Builder.CreateAtomicRMW(Op, PMV.AlignedAddr, NewOperand,
87824539f1eSJames Y Knight                               PMV.AlignedAddrAlignment, AI->getOrdering());
8793291f9aaSAlex Bradbury 
88025a4b190SKrzysztof Parzyszek   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
8813291f9aaSAlex Bradbury   AI->replaceAllUsesWith(FinalOldResult);
8823291f9aaSAlex Bradbury   AI->eraseFromParent();
8833291f9aaSAlex Bradbury   return NewAI;
8843291f9aaSAlex Bradbury }
8853291f9aaSAlex Bradbury 
expandPartwordCmpXchg(AtomicCmpXchgInst * CI)886a60c31fdSserge-sans-paille bool AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
887148a6469SJames Y Knight   // The basic idea here is that we're expanding a cmpxchg of a
888148a6469SJames Y Knight   // smaller memory size up to a word-sized cmpxchg. To do this, we
889148a6469SJames Y Knight   // need to add a retry-loop for strong cmpxchg, so that
890148a6469SJames Y Knight   // modifications to other parts of the word don't cause a spurious
891148a6469SJames Y Knight   // failure.
892148a6469SJames Y Knight 
893148a6469SJames Y Knight   // This generates code like the following:
894148a6469SJames Y Knight   //     [[Setup mask values PMV.*]]
895148a6469SJames Y Knight   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
896148a6469SJames Y Knight   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
897148a6469SJames Y Knight   //     %InitLoaded = load i32* %addr
898148a6469SJames Y Knight   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
899148a6469SJames Y Knight   //     br partword.cmpxchg.loop
900148a6469SJames Y Knight   // partword.cmpxchg.loop:
901148a6469SJames Y Knight   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
902148a6469SJames Y Knight   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
903148a6469SJames Y Knight   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
904148a6469SJames Y Knight   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
905148a6469SJames Y Knight   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
906148a6469SJames Y Knight   //        i32 %FullWord_NewVal success_ordering failure_ordering
907148a6469SJames Y Knight   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
908148a6469SJames Y Knight   //     %Success = extractvalue { i32, i1 } %NewCI, 1
909148a6469SJames Y Knight   //     br i1 %Success, label %partword.cmpxchg.end,
910148a6469SJames Y Knight   //        label %partword.cmpxchg.failure
911148a6469SJames Y Knight   // partword.cmpxchg.failure:
912148a6469SJames Y Knight   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
913148a6469SJames Y Knight   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
914148a6469SJames Y Knight   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
915148a6469SJames Y Knight   //         label %partword.cmpxchg.end
916148a6469SJames Y Knight   // partword.cmpxchg.end:
917148a6469SJames Y Knight   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
918148a6469SJames Y Knight   //    %FinalOldVal = trunc i32 %tmp1 to i8
919148a6469SJames Y Knight   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
920148a6469SJames Y Knight   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
921148a6469SJames Y Knight 
922148a6469SJames Y Knight   Value *Addr = CI->getPointerOperand();
923148a6469SJames Y Knight   Value *Cmp = CI->getCompareOperand();
924148a6469SJames Y Knight   Value *NewVal = CI->getNewValOperand();
925148a6469SJames Y Knight 
926148a6469SJames Y Knight   BasicBlock *BB = CI->getParent();
927148a6469SJames Y Knight   Function *F = BB->getParent();
928148a6469SJames Y Knight   IRBuilder<> Builder(CI);
929148a6469SJames Y Knight   LLVMContext &Ctx = Builder.getContext();
930148a6469SJames Y Knight 
931148a6469SJames Y Knight   BasicBlock *EndBB =
932148a6469SJames Y Knight       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
933148a6469SJames Y Knight   auto FailureBB =
934148a6469SJames Y Knight       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
935148a6469SJames Y Knight   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
936148a6469SJames Y Knight 
937148a6469SJames Y Knight   // The split call above "helpfully" added a branch at the end of BB
938148a6469SJames Y Knight   // (to the wrong place).
939148a6469SJames Y Knight   std::prev(BB->end())->eraseFromParent();
940148a6469SJames Y Knight   Builder.SetInsertPoint(BB);
941148a6469SJames Y Knight 
94224539f1eSJames Y Knight   PartwordMaskValues PMV =
94324539f1eSJames Y Knight       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
94424539f1eSJames Y Knight                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
945148a6469SJames Y Knight 
946148a6469SJames Y Knight   // Shift the incoming values over, into the right location in the word.
947148a6469SJames Y Knight   Value *NewVal_Shifted =
948148a6469SJames Y Knight       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
949148a6469SJames Y Knight   Value *Cmp_Shifted =
950148a6469SJames Y Knight       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
951148a6469SJames Y Knight 
952148a6469SJames Y Knight   // Load the entire current word, and mask into place the expected and new
953148a6469SJames Y Knight   // values
954148a6469SJames Y Knight   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
955148a6469SJames Y Knight   InitLoaded->setVolatile(CI->isVolatile());
956148a6469SJames Y Knight   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
957148a6469SJames Y Knight   Builder.CreateBr(LoopBB);
958148a6469SJames Y Knight 
959148a6469SJames Y Knight   // partword.cmpxchg.loop:
960148a6469SJames Y Knight   Builder.SetInsertPoint(LoopBB);
961148a6469SJames Y Knight   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
962148a6469SJames Y Knight   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
963148a6469SJames Y Knight 
964148a6469SJames Y Knight   // Mask/Or the expected and new values into place in the loaded word.
965148a6469SJames Y Knight   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
966148a6469SJames Y Knight   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
967148a6469SJames Y Knight   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
96824539f1eSJames Y Knight       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
96924539f1eSJames Y Knight       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
970148a6469SJames Y Knight   NewCI->setVolatile(CI->isVolatile());
971148a6469SJames Y Knight   // When we're building a strong cmpxchg, we need a loop, so you
972148a6469SJames Y Knight   // might think we could use a weak cmpxchg inside. But, using strong
973148a6469SJames Y Knight   // allows the below comparison for ShouldContinue, and we're
974148a6469SJames Y Knight   // expecting the underlying cmpxchg to be a machine instruction,
975148a6469SJames Y Knight   // which is strong anyways.
976148a6469SJames Y Knight   NewCI->setWeak(CI->isWeak());
977148a6469SJames Y Knight 
978148a6469SJames Y Knight   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
979148a6469SJames Y Knight   Value *Success = Builder.CreateExtractValue(NewCI, 1);
980148a6469SJames Y Knight 
981148a6469SJames Y Knight   if (CI->isWeak())
982148a6469SJames Y Knight     Builder.CreateBr(EndBB);
983148a6469SJames Y Knight   else
984148a6469SJames Y Knight     Builder.CreateCondBr(Success, EndBB, FailureBB);
985148a6469SJames Y Knight 
986148a6469SJames Y Knight   // partword.cmpxchg.failure:
987148a6469SJames Y Knight   Builder.SetInsertPoint(FailureBB);
988148a6469SJames Y Knight   // Upon failure, verify that the masked-out part of the loaded value
989148a6469SJames Y Knight   // has been modified.  If it didn't, abort the cmpxchg, since the
990148a6469SJames Y Knight   // masked-in part must've.
991148a6469SJames Y Knight   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
992148a6469SJames Y Knight   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
993148a6469SJames Y Knight   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
994148a6469SJames Y Knight 
995148a6469SJames Y Knight   // Add the second value to the phi from above
996148a6469SJames Y Knight   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
997148a6469SJames Y Knight 
998148a6469SJames Y Knight   // partword.cmpxchg.end:
999148a6469SJames Y Knight   Builder.SetInsertPoint(CI);
1000148a6469SJames Y Knight 
100125a4b190SKrzysztof Parzyszek   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1002148a6469SJames Y Knight   Value *Res = UndefValue::get(CI->getType());
1003148a6469SJames Y Knight   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1004148a6469SJames Y Knight   Res = Builder.CreateInsertValue(Res, Success, 1);
1005148a6469SJames Y Knight 
1006148a6469SJames Y Knight   CI->replaceAllUsesWith(Res);
1007148a6469SJames Y Knight   CI->eraseFromParent();
1008a60c31fdSserge-sans-paille   return true;
1009148a6469SJames Y Knight }
1010148a6469SJames Y Knight 
expandAtomicOpToLLSC(Instruction * I,Type * ResultType,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)1011148a6469SJames Y Knight void AtomicExpand::expandAtomicOpToLLSC(
101224539f1eSJames Y Knight     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
101324539f1eSJames Y Knight     AtomicOrdering MemOpOrder,
1014148a6469SJames Y Knight     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1015148a6469SJames Y Knight   IRBuilder<> Builder(I);
101624539f1eSJames Y Knight   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
101724539f1eSJames Y Knight                                     MemOpOrder, PerformOp);
1018148a6469SJames Y Knight 
1019148a6469SJames Y Knight   I->replaceAllUsesWith(Loaded);
1020148a6469SJames Y Knight   I->eraseFromParent();
1021148a6469SJames Y Knight }
1022148a6469SJames Y Knight 
expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst * AI)102321aea51eSAlex Bradbury void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
102421aea51eSAlex Bradbury   IRBuilder<> Builder(AI);
102521aea51eSAlex Bradbury 
102621aea51eSAlex Bradbury   PartwordMaskValues PMV =
102721aea51eSAlex Bradbury       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
102824539f1eSJames Y Knight                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
102921aea51eSAlex Bradbury 
103021aea51eSAlex Bradbury   // The value operand must be sign-extended for signed min/max so that the
103121aea51eSAlex Bradbury   // target's signed comparison instructions can be used. Otherwise, just
103221aea51eSAlex Bradbury   // zero-ext.
103321aea51eSAlex Bradbury   Instruction::CastOps CastOp = Instruction::ZExt;
103421aea51eSAlex Bradbury   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
103521aea51eSAlex Bradbury   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
103621aea51eSAlex Bradbury     CastOp = Instruction::SExt;
103721aea51eSAlex Bradbury 
103821aea51eSAlex Bradbury   Value *ValOperand_Shifted = Builder.CreateShl(
103921aea51eSAlex Bradbury       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
104021aea51eSAlex Bradbury       PMV.ShiftAmt, "ValOperand_Shifted");
104121aea51eSAlex Bradbury   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
104221aea51eSAlex Bradbury       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
104321aea51eSAlex Bradbury       AI->getOrdering());
104425a4b190SKrzysztof Parzyszek   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
104521aea51eSAlex Bradbury   AI->replaceAllUsesWith(FinalOldResult);
104621aea51eSAlex Bradbury   AI->eraseFromParent();
104721aea51eSAlex Bradbury }
104821aea51eSAlex Bradbury 
expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst * CI)104966d9a752SAlex Bradbury void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
105066d9a752SAlex Bradbury   IRBuilder<> Builder(CI);
105166d9a752SAlex Bradbury 
105266d9a752SAlex Bradbury   PartwordMaskValues PMV = createMaskInstrs(
105366d9a752SAlex Bradbury       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
105424539f1eSJames Y Knight       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
105566d9a752SAlex Bradbury 
105666d9a752SAlex Bradbury   Value *CmpVal_Shifted = Builder.CreateShl(
105766d9a752SAlex Bradbury       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
105866d9a752SAlex Bradbury       "CmpVal_Shifted");
105966d9a752SAlex Bradbury   Value *NewVal_Shifted = Builder.CreateShl(
106066d9a752SAlex Bradbury       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
106166d9a752SAlex Bradbury       "NewVal_Shifted");
106266d9a752SAlex Bradbury   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
106366d9a752SAlex Bradbury       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
106444cdf771SEli Friedman       CI->getMergedOrdering());
106525a4b190SKrzysztof Parzyszek   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
106666d9a752SAlex Bradbury   Value *Res = UndefValue::get(CI->getType());
106766d9a752SAlex Bradbury   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
106866d9a752SAlex Bradbury   Value *Success = Builder.CreateICmpEQ(
106966d9a752SAlex Bradbury       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
107066d9a752SAlex Bradbury   Res = Builder.CreateInsertValue(Res, Success, 1);
107166d9a752SAlex Bradbury 
107266d9a752SAlex Bradbury   CI->replaceAllUsesWith(Res);
107366d9a752SAlex Bradbury   CI->eraseFromParent();
107466d9a752SAlex Bradbury }
107566d9a752SAlex Bradbury 
insertRMWLLSCLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp)1076148a6469SJames Y Knight Value *AtomicExpand::insertRMWLLSCLoop(
107724539f1eSJames Y Knight     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1078148a6469SJames Y Knight     AtomicOrdering MemOpOrder,
1079148a6469SJames Y Knight     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1080148a6469SJames Y Knight   LLVMContext &Ctx = Builder.getContext();
1081148a6469SJames Y Knight   BasicBlock *BB = Builder.GetInsertBlock();
1082148a6469SJames Y Knight   Function *F = BB->getParent();
108359c23cd9SRobin Morisset 
1084740e69b6SJames Y Knight   assert(AddrAlign >=
1085740e69b6SJames Y Knight              F->getParent()->getDataLayout().getTypeStoreSize(ResultTy) &&
108624539f1eSJames Y Knight          "Expected at least natural alignment at this point.");
108724539f1eSJames Y Knight 
108859c23cd9SRobin Morisset   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
108959c23cd9SRobin Morisset   //
109059c23cd9SRobin Morisset   // The standard expansion we produce is:
109159c23cd9SRobin Morisset   //     [...]
109259c23cd9SRobin Morisset   // atomicrmw.start:
109359c23cd9SRobin Morisset   //     %loaded = @load.linked(%addr)
109459c23cd9SRobin Morisset   //     %new = some_op iN %loaded, %incr
109559c23cd9SRobin Morisset   //     %stored = @store_conditional(%new, %addr)
109659c23cd9SRobin Morisset   //     %try_again = icmp i32 ne %stored, 0
109759c23cd9SRobin Morisset   //     br i1 %try_again, label %loop, label %atomicrmw.end
109859c23cd9SRobin Morisset   // atomicrmw.end:
109959c23cd9SRobin Morisset   //     [...]
1100148a6469SJames Y Knight   BasicBlock *ExitBB =
1101148a6469SJames Y Knight       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
110259c23cd9SRobin Morisset   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
110359c23cd9SRobin Morisset 
110459c23cd9SRobin Morisset   // The split call above "helpfully" added a branch at the end of BB (to the
1105148a6469SJames Y Knight   // wrong place).
110659c23cd9SRobin Morisset   std::prev(BB->end())->eraseFromParent();
110759c23cd9SRobin Morisset   Builder.SetInsertPoint(BB);
110859c23cd9SRobin Morisset   Builder.CreateBr(LoopBB);
110959c23cd9SRobin Morisset 
111059c23cd9SRobin Morisset   // Start the main loop block now that we've taken care of the preliminaries.
111159c23cd9SRobin Morisset   Builder.SetInsertPoint(LoopBB);
1112df88c26fSKrzysztof Parzyszek   Value *Loaded = TLI->emitLoadLinked(Builder, ResultTy, Addr, MemOpOrder);
111359c23cd9SRobin Morisset 
1114f520eff7STim Northover   Value *NewVal = PerformOp(Builder, Loaded);
111559c23cd9SRobin Morisset 
111659c23cd9SRobin Morisset   Value *StoreSuccess =
1117a47cb411SRobin Morisset       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
111859c23cd9SRobin Morisset   Value *TryAgain = Builder.CreateICmpNE(
111959c23cd9SRobin Morisset       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
112059c23cd9SRobin Morisset   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
112159c23cd9SRobin Morisset 
112259c23cd9SRobin Morisset   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1123148a6469SJames Y Knight   return Loaded;
112459c23cd9SRobin Morisset }
112559c23cd9SRobin Morisset 
11261960cfd3SPhilip Reames /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
11271960cfd3SPhilip Reames /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
11281960cfd3SPhilip Reames /// IR.  As a migration step, we convert back to what use to be the standard
11291960cfd3SPhilip Reames /// way to represent a pointer cmpxchg so that we can update backends one by
11301960cfd3SPhilip Reames /// one.
1131b09439e2SMarco Elver AtomicCmpXchgInst *
convertCmpXchgToIntegerType(AtomicCmpXchgInst * CI)1132b09439e2SMarco Elver AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
11331960cfd3SPhilip Reames   auto *M = CI->getModule();
11341960cfd3SPhilip Reames   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
11351960cfd3SPhilip Reames                                             M->getDataLayout());
11361960cfd3SPhilip Reames 
11371960cfd3SPhilip Reames   IRBuilder<> Builder(CI);
11381960cfd3SPhilip Reames 
11391960cfd3SPhilip Reames   Value *Addr = CI->getPointerOperand();
1140b09439e2SMarco Elver   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
11411960cfd3SPhilip Reames   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
11421960cfd3SPhilip Reames 
11431960cfd3SPhilip Reames   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
11441960cfd3SPhilip Reames   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
11451960cfd3SPhilip Reames 
114624539f1eSJames Y Knight   auto *NewCI = Builder.CreateAtomicCmpXchg(
114724539f1eSJames Y Knight       NewAddr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
114824539f1eSJames Y Knight       CI->getFailureOrdering(), CI->getSyncScopeID());
11491960cfd3SPhilip Reames   NewCI->setVolatile(CI->isVolatile());
11501960cfd3SPhilip Reames   NewCI->setWeak(CI->isWeak());
1151d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
11521960cfd3SPhilip Reames 
11531960cfd3SPhilip Reames   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
11541960cfd3SPhilip Reames   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
11551960cfd3SPhilip Reames 
11561960cfd3SPhilip Reames   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
11571960cfd3SPhilip Reames 
11581960cfd3SPhilip Reames   Value *Res = UndefValue::get(CI->getType());
11591960cfd3SPhilip Reames   Res = Builder.CreateInsertValue(Res, OldVal, 0);
11601960cfd3SPhilip Reames   Res = Builder.CreateInsertValue(Res, Succ, 1);
11611960cfd3SPhilip Reames 
11621960cfd3SPhilip Reames   CI->replaceAllUsesWith(Res);
11631960cfd3SPhilip Reames   CI->eraseFromParent();
11641960cfd3SPhilip Reames   return NewCI;
11651960cfd3SPhilip Reames }
11661960cfd3SPhilip Reames 
expandAtomicCmpXchg(AtomicCmpXchgInst * CI)116759c23cd9SRobin Morisset bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
116859c23cd9SRobin Morisset   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
116959c23cd9SRobin Morisset   AtomicOrdering FailureOrder = CI->getFailureOrdering();
117059c23cd9SRobin Morisset   Value *Addr = CI->getPointerOperand();
117159c23cd9SRobin Morisset   BasicBlock *BB = CI->getParent();
117259c23cd9SRobin Morisset   Function *F = BB->getParent();
117359c23cd9SRobin Morisset   LLVMContext &Ctx = F->getContext();
1174f44fc521SJames Y Knight   // If shouldInsertFencesForAtomic() returns true, then the target does not
1175f44fc521SJames Y Knight   // want to deal with memory orders, and emitLeading/TrailingFence should take
1176f44fc521SJames Y Knight   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1177ed3d48f1SRobin Morisset   // should preserve the ordering.
1178f44fc521SJames Y Knight   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
117944cdf771SEli Friedman   AtomicOrdering MemOpOrder = ShouldInsertFencesForAtomic
118044cdf771SEli Friedman                                   ? AtomicOrdering::Monotonic
118144cdf771SEli Friedman                                   : CI->getMergedOrdering();
118259c23cd9SRobin Morisset 
1183d32f8e60STim Northover   // In implementations which use a barrier to achieve release semantics, we can
1184d32f8e60STim Northover   // delay emitting this barrier until we know a store is actually going to be
1185d32f8e60STim Northover   // attempted. The cost of this delay is that we need 2 copies of the block
1186d32f8e60STim Northover   // emitting the load-linked, affecting code size.
1187d32f8e60STim Northover   //
1188d32f8e60STim Northover   // Ideally, this logic would be unconditional except for the minsize check
1189d32f8e60STim Northover   // since in other cases the extra blocks naturally collapse down to the
1190d32f8e60STim Northover   // minimal loop. Unfortunately, this puts too much stress on later
1191d32f8e60STim Northover   // optimisations so we avoid emitting the extra logic in those cases too.
1192f44fc521SJames Y Knight   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
1193800f87a8SJF Bastien                            SuccessOrder != AtomicOrdering::Monotonic &&
1194800f87a8SJF Bastien                            SuccessOrder != AtomicOrdering::Acquire &&
119585bd3978SEvandro Menezes                            !F->hasMinSize();
1196d32f8e60STim Northover 
1197d32f8e60STim Northover   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1198d32f8e60STim Northover   // do it even on minsize.
119985bd3978SEvandro Menezes   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
1200d32f8e60STim Northover 
120159c23cd9SRobin Morisset   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
120259c23cd9SRobin Morisset   //
120359c23cd9SRobin Morisset   // The full expansion we produce is:
120459c23cd9SRobin Morisset   //     [...]
120525a4b190SKrzysztof Parzyszek   // %aligned.addr = ...
120659c23cd9SRobin Morisset   // cmpxchg.start:
120725a4b190SKrzysztof Parzyszek   //     %unreleasedload = @load.linked(%aligned.addr)
120825a4b190SKrzysztof Parzyszek   //     %unreleasedload.extract = extract value from %unreleasedload
120925a4b190SKrzysztof Parzyszek   //     %should_store = icmp eq %unreleasedload.extract, %desired
121025a4b190SKrzysztof Parzyszek   //     br i1 %should_store, label %cmpxchg.releasingstore,
121107a844d7SAhmed Bougacha   //                          label %cmpxchg.nostore
1212d32f8e60STim Northover   // cmpxchg.releasingstore:
1213d32f8e60STim Northover   //     fence?
1214d32f8e60STim Northover   //     br label cmpxchg.trystore
121559c23cd9SRobin Morisset   // cmpxchg.trystore:
121625a4b190SKrzysztof Parzyszek   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
1217d32f8e60STim Northover   //                            [%releasedload, %cmpxchg.releasedload]
121825a4b190SKrzysztof Parzyszek   //     %updated.new = insert %new into %loaded.trystore
121925a4b190SKrzysztof Parzyszek   //     %stored = @store_conditional(%updated.new, %aligned.addr)
122059c23cd9SRobin Morisset   //     %success = icmp eq i32 %stored, 0
1221d32f8e60STim Northover   //     br i1 %success, label %cmpxchg.success,
1222d32f8e60STim Northover   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1223d32f8e60STim Northover   // cmpxchg.releasedload:
122425a4b190SKrzysztof Parzyszek   //     %releasedload = @load.linked(%aligned.addr)
122525a4b190SKrzysztof Parzyszek   //     %releasedload.extract = extract value from %releasedload
122625a4b190SKrzysztof Parzyszek   //     %should_store = icmp eq %releasedload.extract, %desired
1227d32f8e60STim Northover   //     br i1 %should_store, label %cmpxchg.trystore,
1228d32f8e60STim Northover   //                          label %cmpxchg.failure
122959c23cd9SRobin Morisset   // cmpxchg.success:
123059c23cd9SRobin Morisset   //     fence?
123159c23cd9SRobin Morisset   //     br label %cmpxchg.end
123207a844d7SAhmed Bougacha   // cmpxchg.nostore:
1233d32f8e60STim Northover   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1234d32f8e60STim Northover   //                           [%releasedload,
1235d32f8e60STim Northover   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
123607a844d7SAhmed Bougacha   //     @load_linked_fail_balance()?
123707a844d7SAhmed Bougacha   //     br label %cmpxchg.failure
123859c23cd9SRobin Morisset   // cmpxchg.failure:
123959c23cd9SRobin Morisset   //     fence?
124059c23cd9SRobin Morisset   //     br label %cmpxchg.end
124159c23cd9SRobin Morisset   // cmpxchg.end:
124225a4b190SKrzysztof Parzyszek   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1243d32f8e60STim Northover   //                        [%loaded.trystore, %cmpxchg.trystore]
124459c23cd9SRobin Morisset   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
124525a4b190SKrzysztof Parzyszek   //     %loaded = extract value from %loaded.exit
124659c23cd9SRobin Morisset   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
124759c23cd9SRobin Morisset   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
124859c23cd9SRobin Morisset   //     [...]
12498f11e1a7SDuncan P. N. Exon Smith   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
125059c23cd9SRobin Morisset   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
125107a844d7SAhmed Bougacha   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
125207a844d7SAhmed Bougacha   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1253d32f8e60STim Northover   auto ReleasedLoadBB =
1254d32f8e60STim Northover       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1255d32f8e60STim Northover   auto TryStoreBB =
1256d32f8e60STim Northover       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1257d32f8e60STim Northover   auto ReleasingStoreBB =
1258d32f8e60STim Northover       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1259d32f8e60STim Northover   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
126059c23cd9SRobin Morisset 
126159c23cd9SRobin Morisset   // This grabs the DebugLoc from CI
126259c23cd9SRobin Morisset   IRBuilder<> Builder(CI);
126359c23cd9SRobin Morisset 
126459c23cd9SRobin Morisset   // The split call above "helpfully" added a branch at the end of BB (to the
126559c23cd9SRobin Morisset   // wrong place), but we might want a fence too. It's easiest to just remove
126659c23cd9SRobin Morisset   // the branch entirely.
126759c23cd9SRobin Morisset   std::prev(BB->end())->eraseFromParent();
126859c23cd9SRobin Morisset   Builder.SetInsertPoint(BB);
1269f44fc521SJames Y Knight   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
127004de70d3STim Shen     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
127125a4b190SKrzysztof Parzyszek 
127225a4b190SKrzysztof Parzyszek   PartwordMaskValues PMV =
127325a4b190SKrzysztof Parzyszek       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
127424539f1eSJames Y Knight                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1275d32f8e60STim Northover   Builder.CreateBr(StartBB);
127659c23cd9SRobin Morisset 
127759c23cd9SRobin Morisset   // Start the main loop block now that we've taken care of the preliminaries.
1278d32f8e60STim Northover   Builder.SetInsertPoint(StartBB);
127925a4b190SKrzysztof Parzyszek   Value *UnreleasedLoad =
1280df88c26fSKrzysztof Parzyszek       TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
128125a4b190SKrzysztof Parzyszek   Value *UnreleasedLoadExtract =
128225a4b190SKrzysztof Parzyszek       extractMaskedValue(Builder, UnreleasedLoad, PMV);
1283d32f8e60STim Northover   Value *ShouldStore = Builder.CreateICmpEQ(
128425a4b190SKrzysztof Parzyszek       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
128559c23cd9SRobin Morisset 
1286572e03a3SEric Christopher   // If the cmpxchg doesn't actually need any ordering when it fails, we can
128759c23cd9SRobin Morisset   // jump straight past that fence instruction (if it exists).
1288d32f8e60STim Northover   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1289d32f8e60STim Northover 
1290d32f8e60STim Northover   Builder.SetInsertPoint(ReleasingStoreBB);
1291f44fc521SJames Y Knight   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
129204de70d3STim Shen     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1293d32f8e60STim Northover   Builder.CreateBr(TryStoreBB);
129459c23cd9SRobin Morisset 
129559c23cd9SRobin Morisset   Builder.SetInsertPoint(TryStoreBB);
129625a4b190SKrzysztof Parzyszek   PHINode *LoadedTryStore =
129725a4b190SKrzysztof Parzyszek       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
129825a4b190SKrzysztof Parzyszek   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
129925a4b190SKrzysztof Parzyszek   Value *NewValueInsert =
130025a4b190SKrzysztof Parzyszek       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1301b09439e2SMarco Elver   Value *StoreSuccess = TLI->emitStoreConditional(Builder, NewValueInsert,
1302b09439e2SMarco Elver                                                   PMV.AlignedAddr, MemOpOrder);
130359c23cd9SRobin Morisset   StoreSuccess = Builder.CreateICmpEQ(
130459c23cd9SRobin Morisset       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1305d32f8e60STim Northover   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
130659c23cd9SRobin Morisset   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1307d32f8e60STim Northover                        CI->isWeak() ? FailureBB : RetryBB);
130859c23cd9SRobin Morisset 
1309d32f8e60STim Northover   Builder.SetInsertPoint(ReleasedLoadBB);
1310d32f8e60STim Northover   Value *SecondLoad;
1311d32f8e60STim Northover   if (HasReleasedLoadBB) {
1312df88c26fSKrzysztof Parzyszek     SecondLoad =
1313df88c26fSKrzysztof Parzyszek         TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
131425a4b190SKrzysztof Parzyszek     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
131525a4b190SKrzysztof Parzyszek     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
131625a4b190SKrzysztof Parzyszek                                        CI->getCompareOperand(), "should_store");
1317d32f8e60STim Northover 
1318d32f8e60STim Northover     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1319d32f8e60STim Northover     // jump straight past that fence instruction (if it exists).
1320d32f8e60STim Northover     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
132125a4b190SKrzysztof Parzyszek     // Update PHI node in TryStoreBB.
132225a4b190SKrzysztof Parzyszek     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
1323d32f8e60STim Northover   } else
1324d32f8e60STim Northover     Builder.CreateUnreachable();
1325d32f8e60STim Northover 
1326d32f8e60STim Northover   // Make sure later instructions don't get reordered with a fence if
1327d32f8e60STim Northover   // necessary.
132859c23cd9SRobin Morisset   Builder.SetInsertPoint(SuccessBB);
1329f44fc521SJames Y Knight   if (ShouldInsertFencesForAtomic)
133004de70d3STim Shen     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
133159c23cd9SRobin Morisset   Builder.CreateBr(ExitBB);
133259c23cd9SRobin Morisset 
133307a844d7SAhmed Bougacha   Builder.SetInsertPoint(NoStoreBB);
133425a4b190SKrzysztof Parzyszek   PHINode *LoadedNoStore =
133525a4b190SKrzysztof Parzyszek       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
133625a4b190SKrzysztof Parzyszek   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
133725a4b190SKrzysztof Parzyszek   if (HasReleasedLoadBB)
133825a4b190SKrzysztof Parzyszek     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
133925a4b190SKrzysztof Parzyszek 
134007a844d7SAhmed Bougacha   // In the failing case, where we don't execute the store-conditional, the
134107a844d7SAhmed Bougacha   // target might want to balance out the load-linked with a dedicated
134207a844d7SAhmed Bougacha   // instruction (e.g., on ARM, clearing the exclusive monitor).
134307a844d7SAhmed Bougacha   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
134407a844d7SAhmed Bougacha   Builder.CreateBr(FailureBB);
134507a844d7SAhmed Bougacha 
134659c23cd9SRobin Morisset   Builder.SetInsertPoint(FailureBB);
134725a4b190SKrzysztof Parzyszek   PHINode *LoadedFailure =
134825a4b190SKrzysztof Parzyszek       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
134925a4b190SKrzysztof Parzyszek   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
135025a4b190SKrzysztof Parzyszek   if (CI->isWeak())
135125a4b190SKrzysztof Parzyszek     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
1352f44fc521SJames Y Knight   if (ShouldInsertFencesForAtomic)
135304de70d3STim Shen     TLI->emitTrailingFence(Builder, CI, FailureOrder);
135459c23cd9SRobin Morisset   Builder.CreateBr(ExitBB);
135559c23cd9SRobin Morisset 
135659c23cd9SRobin Morisset   // Finally, we have control-flow based knowledge of whether the cmpxchg
135759c23cd9SRobin Morisset   // succeeded or not. We expose this to later passes by converting any
1358d32f8e60STim Northover   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1359d32f8e60STim Northover   // PHI.
136059c23cd9SRobin Morisset   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
136125a4b190SKrzysztof Parzyszek   PHINode *LoadedExit =
136225a4b190SKrzysztof Parzyszek       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
136325a4b190SKrzysztof Parzyszek   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
136425a4b190SKrzysztof Parzyszek   LoadedExit->addIncoming(LoadedFailure, FailureBB);
136525a4b190SKrzysztof Parzyszek   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
136659c23cd9SRobin Morisset   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
136759c23cd9SRobin Morisset   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
136859c23cd9SRobin Morisset 
136925a4b190SKrzysztof Parzyszek   // This is the "exit value" from the cmpxchg expansion. It may be of
137025a4b190SKrzysztof Parzyszek   // a type wider than the one in the cmpxchg instruction.
137125a4b190SKrzysztof Parzyszek   Value *LoadedFull = LoadedExit;
1372d32f8e60STim Northover 
137325a4b190SKrzysztof Parzyszek   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
137425a4b190SKrzysztof Parzyszek   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
1375d32f8e60STim Northover 
137659c23cd9SRobin Morisset   // Look for any users of the cmpxchg that are just comparing the loaded value
137759c23cd9SRobin Morisset   // against the desired one, and replace them with the CFG-derived version.
137859c23cd9SRobin Morisset   SmallVector<ExtractValueInst *, 2> PrunedInsts;
13799e6d1f4bSKazu Hirata   for (auto *User : CI->users()) {
138059c23cd9SRobin Morisset     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
138159c23cd9SRobin Morisset     if (!EV)
138259c23cd9SRobin Morisset       continue;
138359c23cd9SRobin Morisset 
138459c23cd9SRobin Morisset     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
138559c23cd9SRobin Morisset            "weird extraction from { iN, i1 }");
138659c23cd9SRobin Morisset 
138759c23cd9SRobin Morisset     if (EV->getIndices()[0] == 0)
138859c23cd9SRobin Morisset       EV->replaceAllUsesWith(Loaded);
138959c23cd9SRobin Morisset     else
139059c23cd9SRobin Morisset       EV->replaceAllUsesWith(Success);
139159c23cd9SRobin Morisset 
139259c23cd9SRobin Morisset     PrunedInsts.push_back(EV);
139359c23cd9SRobin Morisset   }
139459c23cd9SRobin Morisset 
139559c23cd9SRobin Morisset   // We can remove the instructions now we're no longer iterating through them.
13969e6d1f4bSKazu Hirata   for (auto *EV : PrunedInsts)
139759c23cd9SRobin Morisset     EV->eraseFromParent();
139859c23cd9SRobin Morisset 
139959c23cd9SRobin Morisset   if (!CI->use_empty()) {
140059c23cd9SRobin Morisset     // Some use of the full struct return that we don't understand has happened,
140159c23cd9SRobin Morisset     // so we've got to reconstruct it properly.
140259c23cd9SRobin Morisset     Value *Res;
140359c23cd9SRobin Morisset     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
140459c23cd9SRobin Morisset     Res = Builder.CreateInsertValue(Res, Success, 1);
140559c23cd9SRobin Morisset 
140659c23cd9SRobin Morisset     CI->replaceAllUsesWith(Res);
140759c23cd9SRobin Morisset   }
140859c23cd9SRobin Morisset 
140959c23cd9SRobin Morisset   CI->eraseFromParent();
141059c23cd9SRobin Morisset   return true;
141159c23cd9SRobin Morisset }
1412810739d1SRobin Morisset 
isIdempotentRMW(AtomicRMWInst * RMWI)1413810739d1SRobin Morisset bool AtomicExpand::isIdempotentRMW(AtomicRMWInst *RMWI) {
1414810739d1SRobin Morisset   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1415810739d1SRobin Morisset   if (!C)
1416810739d1SRobin Morisset     return false;
1417810739d1SRobin Morisset 
1418810739d1SRobin Morisset   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1419810739d1SRobin Morisset   switch (Op) {
1420810739d1SRobin Morisset   case AtomicRMWInst::Add:
1421810739d1SRobin Morisset   case AtomicRMWInst::Sub:
1422810739d1SRobin Morisset   case AtomicRMWInst::Or:
1423810739d1SRobin Morisset   case AtomicRMWInst::Xor:
1424810739d1SRobin Morisset     return C->isZero();
1425810739d1SRobin Morisset   case AtomicRMWInst::And:
1426810739d1SRobin Morisset     return C->isMinusOne();
1427810739d1SRobin Morisset   // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1428810739d1SRobin Morisset   default:
1429810739d1SRobin Morisset     return false;
1430810739d1SRobin Morisset   }
1431810739d1SRobin Morisset }
1432810739d1SRobin Morisset 
simplifyIdempotentRMW(AtomicRMWInst * RMWI)1433810739d1SRobin Morisset bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst *RMWI) {
143449b531a0SAhmed Bougacha   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
143549b531a0SAhmed Bougacha     tryExpandAtomicLoad(ResultingLoad);
143649b531a0SAhmed Bougacha     return true;
143749b531a0SAhmed Bougacha   }
1438810739d1SRobin Morisset   return false;
1439810739d1SRobin Morisset }
1440e8aad299SJF Bastien 
insertRMWCmpXchgLoop(IRBuilder<> & Builder,Type * ResultTy,Value * Addr,Align AddrAlign,AtomicOrdering MemOpOrder,SyncScope::ID SSID,function_ref<Value * (IRBuilder<> &,Value *)> PerformOp,CreateCmpXchgInstFun CreateCmpXchg)1441148a6469SJames Y Knight Value *AtomicExpand::insertRMWCmpXchgLoop(
144224539f1eSJames Y Knight     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
144330b3aab3SStanislav Mekhanoshin     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
1444148a6469SJames Y Knight     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1445e8aad299SJF Bastien     CreateCmpXchgInstFun CreateCmpXchg) {
1446148a6469SJames Y Knight   LLVMContext &Ctx = Builder.getContext();
1447148a6469SJames Y Knight   BasicBlock *BB = Builder.GetInsertBlock();
1448e8aad299SJF Bastien   Function *F = BB->getParent();
1449e8aad299SJF Bastien 
1450e8aad299SJF Bastien   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1451e8aad299SJF Bastien   //
1452e8aad299SJF Bastien   // The standard expansion we produce is:
1453e8aad299SJF Bastien   //     [...]
1454e8aad299SJF Bastien   //     %init_loaded = load atomic iN* %addr
1455e8aad299SJF Bastien   //     br label %loop
1456e8aad299SJF Bastien   // loop:
1457e8aad299SJF Bastien   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1458e8aad299SJF Bastien   //     %new = some_op iN %loaded, %incr
1459e8aad299SJF Bastien   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1460e8aad299SJF Bastien   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1461e8aad299SJF Bastien   //     %success = extractvalue { iN, i1 } %pair, 1
1462e8aad299SJF Bastien   //     br i1 %success, label %atomicrmw.end, label %loop
1463e8aad299SJF Bastien   // atomicrmw.end:
1464e8aad299SJF Bastien   //     [...]
1465148a6469SJames Y Knight   BasicBlock *ExitBB =
1466148a6469SJames Y Knight       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1467e8aad299SJF Bastien   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1468e8aad299SJF Bastien 
1469e8aad299SJF Bastien   // The split call above "helpfully" added a branch at the end of BB (to the
1470e8aad299SJF Bastien   // wrong place), but we want a load. It's easiest to just remove
1471e8aad299SJF Bastien   // the branch entirely.
1472e8aad299SJF Bastien   std::prev(BB->end())->eraseFromParent();
1473e8aad299SJF Bastien   Builder.SetInsertPoint(BB);
147424539f1eSJames Y Knight   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
1475e8aad299SJF Bastien   Builder.CreateBr(LoopBB);
1476e8aad299SJF Bastien 
1477e8aad299SJF Bastien   // Start the main loop block now that we've taken care of the preliminaries.
1478e8aad299SJF Bastien   Builder.SetInsertPoint(LoopBB);
1479148a6469SJames Y Knight   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1480e8aad299SJF Bastien   Loaded->addIncoming(InitLoaded, BB);
1481e8aad299SJF Bastien 
1482148a6469SJames Y Knight   Value *NewVal = PerformOp(Builder, Loaded);
1483e8aad299SJF Bastien 
1484e8aad299SJF Bastien   Value *NewLoaded = nullptr;
1485e8aad299SJF Bastien   Value *Success = nullptr;
1486e8aad299SJF Bastien 
148724539f1eSJames Y Knight   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
1488148a6469SJames Y Knight                 MemOpOrder == AtomicOrdering::Unordered
1489148a6469SJames Y Knight                     ? AtomicOrdering::Monotonic
1490148a6469SJames Y Knight                     : MemOpOrder,
149130b3aab3SStanislav Mekhanoshin                 SSID, Success, NewLoaded);
1492e8aad299SJF Bastien   assert(Success && NewLoaded);
1493e8aad299SJF Bastien 
1494e8aad299SJF Bastien   Loaded->addIncoming(NewLoaded, LoopBB);
1495e8aad299SJF Bastien 
1496e8aad299SJF Bastien   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1497e8aad299SJF Bastien 
1498e8aad299SJF Bastien   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1499148a6469SJames Y Knight   return NewLoaded;
1500148a6469SJames Y Knight }
1501e8aad299SJF Bastien 
tryExpandAtomicCmpXchg(AtomicCmpXchgInst * CI)150279518b02SAlex Bradbury bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
150379518b02SAlex Bradbury   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
150479518b02SAlex Bradbury   unsigned ValueSize = getAtomicOpSize(CI);
150579518b02SAlex Bradbury 
150679518b02SAlex Bradbury   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
150779518b02SAlex Bradbury   default:
150879518b02SAlex Bradbury     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
150979518b02SAlex Bradbury   case TargetLoweringBase::AtomicExpansionKind::None:
151079518b02SAlex Bradbury     if (ValueSize < MinCASSize)
1511a60c31fdSserge-sans-paille       return expandPartwordCmpXchg(CI);
151279518b02SAlex Bradbury     return false;
151379518b02SAlex Bradbury   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
151479518b02SAlex Bradbury     return expandAtomicCmpXchg(CI);
151579518b02SAlex Bradbury   }
151679518b02SAlex Bradbury   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
151766d9a752SAlex Bradbury     expandAtomicCmpXchgToMaskedIntrinsic(CI);
151866d9a752SAlex Bradbury     return true;
15197f14a1d4SMatt Arsenault   case TargetLoweringBase::AtomicExpansionKind::NotAtomic:
15207f14a1d4SMatt Arsenault     return lowerAtomicCmpXchgInst(CI);
152179518b02SAlex Bradbury   }
152279518b02SAlex Bradbury }
152379518b02SAlex Bradbury 
1524148a6469SJames Y Knight // Note: This function is exposed externally by AtomicExpandUtils.h
expandAtomicRMWToCmpXchg(AtomicRMWInst * AI,CreateCmpXchgInstFun CreateCmpXchg)1525148a6469SJames Y Knight bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1526148a6469SJames Y Knight                                     CreateCmpXchgInstFun CreateCmpXchg) {
1527148a6469SJames Y Knight   IRBuilder<> Builder(AI);
1528148a6469SJames Y Knight   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
152924539f1eSJames Y Knight       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
153030b3aab3SStanislav Mekhanoshin       AI->getOrdering(), AI->getSyncScopeID(),
1531148a6469SJames Y Knight       [&](IRBuilder<> &Builder, Value *Loaded) {
15329fdd2584SMatt Arsenault         return buildAtomicRMWValue(AI->getOperation(), Builder, Loaded,
1533148a6469SJames Y Knight                                    AI->getValOperand());
1534148a6469SJames Y Knight       },
1535148a6469SJames Y Knight       CreateCmpXchg);
1536148a6469SJames Y Knight 
1537148a6469SJames Y Knight   AI->replaceAllUsesWith(Loaded);
1538e8aad299SJF Bastien   AI->eraseFromParent();
1539e8aad299SJF Bastien   return true;
1540e8aad299SJF Bastien }
154119f6cce4SJames Y Knight 
154219f6cce4SJames Y Knight // In order to use one of the sized library calls such as
154319f6cce4SJames Y Knight // __atomic_fetch_add_4, the alignment must be sufficient, the size
154419f6cce4SJames Y Knight // must be one of the potentially-specialized sizes, and the value
154519f6cce4SJames Y Knight // type must actually exist in C on the target (otherwise, the
154619f6cce4SJames Y Knight // function wouldn't actually be defined.)
canUseSizedAtomicCall(unsigned Size,Align Alignment,const DataLayout & DL)15472c5ff48eSGuillaume Chatelet static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
154819f6cce4SJames Y Knight                                   const DataLayout &DL) {
154919f6cce4SJames Y Knight   // TODO: "LargestSize" is an approximation for "largest type that
155019f6cce4SJames Y Knight   // you can express in C". It seems to be the case that int128 is
155119f6cce4SJames Y Knight   // supported on all 64-bit platforms, otherwise only up to 64-bit
155219f6cce4SJames Y Knight   // integers are supported. If we get this wrong, then we'll try to
155319f6cce4SJames Y Knight   // call a sized libcall that doesn't actually exist. There should
155419f6cce4SJames Y Knight   // really be some more reliable way in LLVM of determining integer
155519f6cce4SJames Y Knight   // sizes which are valid in the target's C ABI...
1556be11bdc4SJun Bum Lim   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
15572c5ff48eSGuillaume Chatelet   return Alignment >= Size &&
155819f6cce4SJames Y Knight          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
155919f6cce4SJames Y Knight          Size <= LargestSize;
156019f6cce4SJames Y Knight }
156119f6cce4SJames Y Knight 
expandAtomicLoadToLibcall(LoadInst * I)156219f6cce4SJames Y Knight void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
156319f6cce4SJames Y Knight   static const RTLIB::Libcall Libcalls[6] = {
156419f6cce4SJames Y Knight       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
156519f6cce4SJames Y Knight       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
156619f6cce4SJames Y Knight   unsigned Size = getAtomicOpSize(I);
156719f6cce4SJames Y Knight 
156819f6cce4SJames Y Knight   bool expanded = expandAtomicOpToLibcall(
15692c5ff48eSGuillaume Chatelet       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
157019f6cce4SJames Y Knight       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
15715bc438efSAlex Richardson   if (!expanded)
15725bc438efSAlex Richardson     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
157319f6cce4SJames Y Knight }
157419f6cce4SJames Y Knight 
expandAtomicStoreToLibcall(StoreInst * I)157519f6cce4SJames Y Knight void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
157619f6cce4SJames Y Knight   static const RTLIB::Libcall Libcalls[6] = {
157719f6cce4SJames Y Knight       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
157819f6cce4SJames Y Knight       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
157919f6cce4SJames Y Knight   unsigned Size = getAtomicOpSize(I);
158019f6cce4SJames Y Knight 
158119f6cce4SJames Y Knight   bool expanded = expandAtomicOpToLibcall(
15822c5ff48eSGuillaume Chatelet       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
15832c5ff48eSGuillaume Chatelet       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
15845bc438efSAlex Richardson   if (!expanded)
15855bc438efSAlex Richardson     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
158619f6cce4SJames Y Knight }
158719f6cce4SJames Y Knight 
expandAtomicCASToLibcall(AtomicCmpXchgInst * I)158819f6cce4SJames Y Knight void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
158919f6cce4SJames Y Knight   static const RTLIB::Libcall Libcalls[6] = {
159019f6cce4SJames Y Knight       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
159119f6cce4SJames Y Knight       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
159219f6cce4SJames Y Knight       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
159319f6cce4SJames Y Knight   unsigned Size = getAtomicOpSize(I);
159419f6cce4SJames Y Knight 
159519f6cce4SJames Y Knight   bool expanded = expandAtomicOpToLibcall(
15962c5ff48eSGuillaume Chatelet       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
159719f6cce4SJames Y Knight       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
159819f6cce4SJames Y Knight       Libcalls);
15995bc438efSAlex Richardson   if (!expanded)
16005bc438efSAlex Richardson     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
160119f6cce4SJames Y Knight }
160219f6cce4SJames Y Knight 
GetRMWLibcall(AtomicRMWInst::BinOp Op)160319f6cce4SJames Y Knight static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
160419f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsXchg[6] = {
160519f6cce4SJames Y Knight       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
160619f6cce4SJames Y Knight       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
160719f6cce4SJames Y Knight       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
160819f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsAdd[6] = {
160919f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
161019f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
161119f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
161219f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsSub[6] = {
161319f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
161419f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
161519f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
161619f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsAnd[6] = {
161719f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
161819f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
161919f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
162019f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsOr[6] = {
162119f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
162219f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
162319f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
162419f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsXor[6] = {
162519f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
162619f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
162719f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
162819f6cce4SJames Y Knight   static const RTLIB::Libcall LibcallsNand[6] = {
162919f6cce4SJames Y Knight       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
163019f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
163119f6cce4SJames Y Knight       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
163219f6cce4SJames Y Knight 
163319f6cce4SJames Y Knight   switch (Op) {
163419f6cce4SJames Y Knight   case AtomicRMWInst::BAD_BINOP:
163519f6cce4SJames Y Knight     llvm_unreachable("Should not have BAD_BINOP.");
163619f6cce4SJames Y Knight   case AtomicRMWInst::Xchg:
163719f6cce4SJames Y Knight     return makeArrayRef(LibcallsXchg);
163819f6cce4SJames Y Knight   case AtomicRMWInst::Add:
163919f6cce4SJames Y Knight     return makeArrayRef(LibcallsAdd);
164019f6cce4SJames Y Knight   case AtomicRMWInst::Sub:
164119f6cce4SJames Y Knight     return makeArrayRef(LibcallsSub);
164219f6cce4SJames Y Knight   case AtomicRMWInst::And:
164319f6cce4SJames Y Knight     return makeArrayRef(LibcallsAnd);
164419f6cce4SJames Y Knight   case AtomicRMWInst::Or:
164519f6cce4SJames Y Knight     return makeArrayRef(LibcallsOr);
164619f6cce4SJames Y Knight   case AtomicRMWInst::Xor:
164719f6cce4SJames Y Knight     return makeArrayRef(LibcallsXor);
164819f6cce4SJames Y Knight   case AtomicRMWInst::Nand:
164919f6cce4SJames Y Knight     return makeArrayRef(LibcallsNand);
165019f6cce4SJames Y Knight   case AtomicRMWInst::Max:
165119f6cce4SJames Y Knight   case AtomicRMWInst::Min:
165219f6cce4SJames Y Knight   case AtomicRMWInst::UMax:
165319f6cce4SJames Y Knight   case AtomicRMWInst::UMin:
16541023ddafSShilei Tian   case AtomicRMWInst::FMax:
16551023ddafSShilei Tian   case AtomicRMWInst::FMin:
165639508331SMatt Arsenault   case AtomicRMWInst::FAdd:
165739508331SMatt Arsenault   case AtomicRMWInst::FSub:
165819f6cce4SJames Y Knight     // No atomic libcalls are available for max/min/umax/umin.
165919f6cce4SJames Y Knight     return {};
166019f6cce4SJames Y Knight   }
166119f6cce4SJames Y Knight   llvm_unreachable("Unexpected AtomicRMW operation.");
166219f6cce4SJames Y Knight }
166319f6cce4SJames Y Knight 
expandAtomicRMWToLibcall(AtomicRMWInst * I)166419f6cce4SJames Y Knight void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
166519f6cce4SJames Y Knight   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
166619f6cce4SJames Y Knight 
166719f6cce4SJames Y Knight   unsigned Size = getAtomicOpSize(I);
166819f6cce4SJames Y Knight 
166919f6cce4SJames Y Knight   bool Success = false;
167019f6cce4SJames Y Knight   if (!Libcalls.empty())
167119f6cce4SJames Y Knight     Success = expandAtomicOpToLibcall(
16722c5ff48eSGuillaume Chatelet         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
16732c5ff48eSGuillaume Chatelet         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
167419f6cce4SJames Y Knight 
167519f6cce4SJames Y Knight   // The expansion failed: either there were no libcalls at all for
167619f6cce4SJames Y Knight   // the operation (min/max), or there were only size-specialized
167719f6cce4SJames Y Knight   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
167819f6cce4SJames Y Knight   // CAS libcall, via a CAS loop, instead.
167919f6cce4SJames Y Knight   if (!Success) {
168024539f1eSJames Y Knight     expandAtomicRMWToCmpXchg(
168124539f1eSJames Y Knight         I, [this](IRBuilder<> &Builder, Value *Addr, Value *Loaded,
168224539f1eSJames Y Knight                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
168330b3aab3SStanislav Mekhanoshin                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
168419f6cce4SJames Y Knight           // Create the CAS instruction normally...
168519f6cce4SJames Y Knight           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
168624539f1eSJames Y Knight               Addr, Loaded, NewVal, Alignment, MemOpOrder,
168730b3aab3SStanislav Mekhanoshin               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
168819f6cce4SJames Y Knight           Success = Builder.CreateExtractValue(Pair, 1, "success");
168919f6cce4SJames Y Knight           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
169019f6cce4SJames Y Knight 
169119f6cce4SJames Y Knight           // ...and then expand the CAS into a libcall.
169219f6cce4SJames Y Knight           expandAtomicCASToLibcall(Pair);
169319f6cce4SJames Y Knight         });
169419f6cce4SJames Y Knight   }
169519f6cce4SJames Y Knight }
169619f6cce4SJames Y Knight 
169719f6cce4SJames Y Knight // A helper routine for the above expandAtomic*ToLibcall functions.
169819f6cce4SJames Y Knight //
169919f6cce4SJames Y Knight // 'Libcalls' contains an array of enum values for the particular
170019f6cce4SJames Y Knight // ATOMIC libcalls to be emitted. All of the other arguments besides
170119f6cce4SJames Y Knight // 'I' are extracted from the Instruction subclass by the
170219f6cce4SJames Y Knight // caller. Depending on the particular call, some will be null.
expandAtomicOpToLibcall(Instruction * I,unsigned Size,Align Alignment,Value * PointerOperand,Value * ValueOperand,Value * CASExpected,AtomicOrdering Ordering,AtomicOrdering Ordering2,ArrayRef<RTLIB::Libcall> Libcalls)170319f6cce4SJames Y Knight bool AtomicExpand::expandAtomicOpToLibcall(
17042c5ff48eSGuillaume Chatelet     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
170519f6cce4SJames Y Knight     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
170619f6cce4SJames Y Knight     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
170719f6cce4SJames Y Knight   assert(Libcalls.size() == 6);
170819f6cce4SJames Y Knight 
170919f6cce4SJames Y Knight   LLVMContext &Ctx = I->getContext();
171019f6cce4SJames Y Knight   Module *M = I->getModule();
171119f6cce4SJames Y Knight   const DataLayout &DL = M->getDataLayout();
171219f6cce4SJames Y Knight   IRBuilder<> Builder(I);
171319f6cce4SJames Y Knight   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
171419f6cce4SJames Y Knight 
17152c5ff48eSGuillaume Chatelet   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
171619f6cce4SJames Y Knight   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
171719f6cce4SJames Y Knight 
17182c5ff48eSGuillaume Chatelet   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
171919f6cce4SJames Y Knight 
172019f6cce4SJames Y Knight   // TODO: the "order" argument type is "int", not int32. So
172119f6cce4SJames Y Knight   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
172219f6cce4SJames Y Knight   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1723bbb0aee6SJF Bastien   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
172419f6cce4SJames Y Knight   Constant *OrderingVal =
1725bbb0aee6SJF Bastien       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1726bbb0aee6SJF Bastien   Constant *Ordering2Val = nullptr;
1727bbb0aee6SJF Bastien   if (CASExpected) {
1728bbb0aee6SJF Bastien     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1729bbb0aee6SJF Bastien     Ordering2Val =
1730bbb0aee6SJF Bastien         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1731bbb0aee6SJF Bastien   }
173219f6cce4SJames Y Knight   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
173319f6cce4SJames Y Knight 
173419f6cce4SJames Y Knight   RTLIB::Libcall RTLibType;
173519f6cce4SJames Y Knight   if (UseSizedLibcall) {
173619f6cce4SJames Y Knight     switch (Size) {
1737b09439e2SMarco Elver     case 1:
1738b09439e2SMarco Elver       RTLibType = Libcalls[1];
1739b09439e2SMarco Elver       break;
1740b09439e2SMarco Elver     case 2:
1741b09439e2SMarco Elver       RTLibType = Libcalls[2];
1742b09439e2SMarco Elver       break;
1743b09439e2SMarco Elver     case 4:
1744b09439e2SMarco Elver       RTLibType = Libcalls[3];
1745b09439e2SMarco Elver       break;
1746b09439e2SMarco Elver     case 8:
1747b09439e2SMarco Elver       RTLibType = Libcalls[4];
1748b09439e2SMarco Elver       break;
1749b09439e2SMarco Elver     case 16:
1750b09439e2SMarco Elver       RTLibType = Libcalls[5];
1751b09439e2SMarco Elver       break;
175219f6cce4SJames Y Knight     }
175319f6cce4SJames Y Knight   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
175419f6cce4SJames Y Knight     RTLibType = Libcalls[0];
175519f6cce4SJames Y Knight   } else {
175619f6cce4SJames Y Knight     // Can't use sized function, and there's no generic for this
175719f6cce4SJames Y Knight     // operation, so give up.
175819f6cce4SJames Y Knight     return false;
175919f6cce4SJames Y Knight   }
176019f6cce4SJames Y Knight 
17615bc438efSAlex Richardson   if (!TLI->getLibcallName(RTLibType)) {
17625bc438efSAlex Richardson     // This target does not implement the requested atomic libcall so give up.
17635bc438efSAlex Richardson     return false;
17645bc438efSAlex Richardson   }
17655bc438efSAlex Richardson 
176619f6cce4SJames Y Knight   // Build up the function call. There's two kinds. First, the sized
176719f6cce4SJames Y Knight   // variants.  These calls are going to be one of the following (with
176819f6cce4SJames Y Knight   // N=1,2,4,8,16):
176919f6cce4SJames Y Knight   //  iN    __atomic_load_N(iN *ptr, int ordering)
177019f6cce4SJames Y Knight   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
177119f6cce4SJames Y Knight   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
177219f6cce4SJames Y Knight   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
177319f6cce4SJames Y Knight   //                                    int success_order, int failure_order)
177419f6cce4SJames Y Knight   //
177519f6cce4SJames Y Knight   // Note that these functions can be used for non-integer atomic
177619f6cce4SJames Y Knight   // operations, the values just need to be bitcast to integers on the
177719f6cce4SJames Y Knight   // way in and out.
177819f6cce4SJames Y Knight   //
177919f6cce4SJames Y Knight   // And, then, the generic variants. They look like the following:
178019f6cce4SJames Y Knight   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
178119f6cce4SJames Y Knight   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
178219f6cce4SJames Y Knight   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
178319f6cce4SJames Y Knight   //                          int ordering)
178419f6cce4SJames Y Knight   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
178519f6cce4SJames Y Knight   //                                  void *desired, int success_order,
178619f6cce4SJames Y Knight   //                                  int failure_order)
178719f6cce4SJames Y Knight   //
178819f6cce4SJames Y Knight   // The different signatures are built up depending on the
178919f6cce4SJames Y Knight   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
179019f6cce4SJames Y Knight   // variables.
179119f6cce4SJames Y Knight 
179219f6cce4SJames Y Knight   AllocaInst *AllocaCASExpected = nullptr;
179319f6cce4SJames Y Knight   Value *AllocaCASExpected_i8 = nullptr;
179419f6cce4SJames Y Knight   AllocaInst *AllocaValue = nullptr;
179519f6cce4SJames Y Knight   Value *AllocaValue_i8 = nullptr;
179619f6cce4SJames Y Knight   AllocaInst *AllocaResult = nullptr;
179719f6cce4SJames Y Knight   Value *AllocaResult_i8 = nullptr;
179819f6cce4SJames Y Knight 
179919f6cce4SJames Y Knight   Type *ResultTy;
180019f6cce4SJames Y Knight   SmallVector<Value *, 6> Args;
1801b518054bSReid Kleckner   AttributeList Attr;
180219f6cce4SJames Y Knight 
180319f6cce4SJames Y Knight   // 'size' argument.
180419f6cce4SJames Y Knight   if (!UseSizedLibcall) {
180519f6cce4SJames Y Knight     // Note, getIntPtrType is assumed equivalent to size_t.
180619f6cce4SJames Y Knight     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
180719f6cce4SJames Y Knight   }
180819f6cce4SJames Y Knight 
180919f6cce4SJames Y Knight   // 'ptr' argument.
18109549f756SPhilip Reames   // note: This assumes all address spaces share a common libfunc
18119549f756SPhilip Reames   // implementation and that addresses are convertable.  For systems without
18129549f756SPhilip Reames   // that property, we'd need to extend this mechanism to support AS-specific
18139549f756SPhilip Reames   // families of atomic intrinsics.
18149549f756SPhilip Reames   auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
1815b09439e2SMarco Elver   Value *PtrVal =
1816b09439e2SMarco Elver       Builder.CreateBitCast(PointerOperand, Type::getInt8PtrTy(Ctx, PtrTypeAS));
18179549f756SPhilip Reames   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
181819f6cce4SJames Y Knight   Args.push_back(PtrVal);
181919f6cce4SJames Y Knight 
182019f6cce4SJames Y Knight   // 'expected' argument, if present.
182119f6cce4SJames Y Knight   if (CASExpected) {
182219f6cce4SJames Y Knight     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1823279fa8e0SGuillaume Chatelet     AllocaCASExpected->setAlignment(AllocaAlignment);
1824c5830f5fSMatt Arsenault     unsigned AllocaAS = AllocaCASExpected->getType()->getPointerAddressSpace();
1825c5830f5fSMatt Arsenault 
1826b09439e2SMarco Elver     AllocaCASExpected_i8 = Builder.CreateBitCast(
1827b09439e2SMarco Elver         AllocaCASExpected, Type::getInt8PtrTy(Ctx, AllocaAS));
182819f6cce4SJames Y Knight     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
182919f6cce4SJames Y Knight     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
183019f6cce4SJames Y Knight     Args.push_back(AllocaCASExpected_i8);
183119f6cce4SJames Y Knight   }
183219f6cce4SJames Y Knight 
183319f6cce4SJames Y Knight   // 'val' argument ('desired' for cas), if present.
183419f6cce4SJames Y Knight   if (ValueOperand) {
183519f6cce4SJames Y Knight     if (UseSizedLibcall) {
183619f6cce4SJames Y Knight       Value *IntValue =
183719f6cce4SJames Y Knight           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
183819f6cce4SJames Y Knight       Args.push_back(IntValue);
183919f6cce4SJames Y Knight     } else {
184019f6cce4SJames Y Knight       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1841279fa8e0SGuillaume Chatelet       AllocaValue->setAlignment(AllocaAlignment);
184219f6cce4SJames Y Knight       AllocaValue_i8 =
184319f6cce4SJames Y Knight           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
184419f6cce4SJames Y Knight       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
184519f6cce4SJames Y Knight       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
184619f6cce4SJames Y Knight       Args.push_back(AllocaValue_i8);
184719f6cce4SJames Y Knight     }
184819f6cce4SJames Y Knight   }
184919f6cce4SJames Y Knight 
185019f6cce4SJames Y Knight   // 'ret' argument.
185119f6cce4SJames Y Knight   if (!CASExpected && HasResult && !UseSizedLibcall) {
185219f6cce4SJames Y Knight     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1853279fa8e0SGuillaume Chatelet     AllocaResult->setAlignment(AllocaAlignment);
1854c5830f5fSMatt Arsenault     unsigned AllocaAS = AllocaResult->getType()->getPointerAddressSpace();
185519f6cce4SJames Y Knight     AllocaResult_i8 =
1856c5830f5fSMatt Arsenault         Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
185719f6cce4SJames Y Knight     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
185819f6cce4SJames Y Knight     Args.push_back(AllocaResult_i8);
185919f6cce4SJames Y Knight   }
186019f6cce4SJames Y Knight 
186119f6cce4SJames Y Knight   // 'ordering' ('success_order' for cas) argument.
186219f6cce4SJames Y Knight   Args.push_back(OrderingVal);
186319f6cce4SJames Y Knight 
186419f6cce4SJames Y Knight   // 'failure_order' argument, if present.
186519f6cce4SJames Y Knight   if (Ordering2Val)
186619f6cce4SJames Y Knight     Args.push_back(Ordering2Val);
186719f6cce4SJames Y Knight 
186819f6cce4SJames Y Knight   // Now, the return type.
186919f6cce4SJames Y Knight   if (CASExpected) {
187019f6cce4SJames Y Knight     ResultTy = Type::getInt1Ty(Ctx);
1871de0ae9e8SArthur Eubanks     Attr = Attr.addRetAttribute(Ctx, Attribute::ZExt);
187219f6cce4SJames Y Knight   } else if (HasResult && UseSizedLibcall)
187319f6cce4SJames Y Knight     ResultTy = SizedIntTy;
187419f6cce4SJames Y Knight   else
187519f6cce4SJames Y Knight     ResultTy = Type::getVoidTy(Ctx);
187619f6cce4SJames Y Knight 
187719f6cce4SJames Y Knight   // Done with setting up arguments and return types, create the call:
187819f6cce4SJames Y Knight   SmallVector<Type *, 6> ArgTys;
187919f6cce4SJames Y Knight   for (Value *Arg : Args)
188019f6cce4SJames Y Knight     ArgTys.push_back(Arg->getType());
188119f6cce4SJames Y Knight   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
188213680223SJames Y Knight   FunctionCallee LibcallFn =
188319f6cce4SJames Y Knight       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
188419f6cce4SJames Y Knight   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
188519f6cce4SJames Y Knight   Call->setAttributes(Attr);
188619f6cce4SJames Y Knight   Value *Result = Call;
188719f6cce4SJames Y Knight 
188819f6cce4SJames Y Knight   // And then, extract the results...
188919f6cce4SJames Y Knight   if (ValueOperand && !UseSizedLibcall)
189019f6cce4SJames Y Knight     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
189119f6cce4SJames Y Knight 
189219f6cce4SJames Y Knight   if (CASExpected) {
189319f6cce4SJames Y Knight     // The final result from the CAS is {load of 'expected' alloca, bool result
189419f6cce4SJames Y Knight     // from call}
189519f6cce4SJames Y Knight     Type *FinalResultTy = I->getType();
189619f6cce4SJames Y Knight     Value *V = UndefValue::get(FinalResultTy);
189714359ef1SJames Y Knight     Value *ExpectedOut = Builder.CreateAlignedLoad(
189814359ef1SJames Y Knight         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
189919f6cce4SJames Y Knight     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
190019f6cce4SJames Y Knight     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
190119f6cce4SJames Y Knight     V = Builder.CreateInsertValue(V, Result, 1);
190219f6cce4SJames Y Knight     I->replaceAllUsesWith(V);
190319f6cce4SJames Y Knight   } else if (HasResult) {
190419f6cce4SJames Y Knight     Value *V;
190519f6cce4SJames Y Knight     if (UseSizedLibcall)
190619f6cce4SJames Y Knight       V = Builder.CreateBitOrPointerCast(Result, I->getType());
190719f6cce4SJames Y Knight     else {
190814359ef1SJames Y Knight       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
190914359ef1SJames Y Knight                                     AllocaAlignment);
191019f6cce4SJames Y Knight       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
191119f6cce4SJames Y Knight     }
191219f6cce4SJames Y Knight     I->replaceAllUsesWith(V);
191319f6cce4SJames Y Knight   }
191419f6cce4SJames Y Knight   I->eraseFromParent();
191519f6cce4SJames Y Knight   return true;
191619f6cce4SJames Y Knight }
1917