4c4150bfec90abc1830a0cb2e1b85267a695c7d1
[oota-llvm.git] / lib / CodeGen / AtomicExpandLoadLinkedPass.cpp
1 //===-- AtomicExpandLoadLinkedPass.cpp - Expand atomic instructions -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass (at IR level) to replace atomic instructions with
11 // appropriate (intrinsic-based) ldrex/strex loops.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetMachine.h"
24 using namespace llvm;
25
26 #define DEBUG_TYPE "arm-atomic-expand"
27
28 namespace {
29   class AtomicExpandLoadLinked : public FunctionPass {
30     const TargetLowering *TLI;
31   public:
32     static char ID; // Pass identification, replacement for typeid
33     explicit AtomicExpandLoadLinked(const TargetMachine *TM = nullptr)
34       : FunctionPass(ID), TLI(TM ? TM->getTargetLowering() : nullptr) {
35       initializeAtomicExpandLoadLinkedPass(*PassRegistry::getPassRegistry());
36     }
37
38     bool runOnFunction(Function &F) override;
39     bool expandAtomicInsts(Function &F);
40
41     bool expandAtomicLoad(LoadInst *LI);
42     bool expandAtomicStore(StoreInst *LI);
43     bool expandAtomicRMW(AtomicRMWInst *AI);
44     bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
45
46     AtomicOrdering insertLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
47     void insertTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
48   };
49 }
50
51 char AtomicExpandLoadLinked::ID = 0;
52 char &llvm::AtomicExpandLoadLinkedID = AtomicExpandLoadLinked::ID;
53 INITIALIZE_TM_PASS(AtomicExpandLoadLinked, "atomic-ll-sc",
54     "Expand Atomic calls in terms of load-linked & store-conditional",
55     false, false)
56
57 FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
58   return new AtomicExpandLoadLinked(TM);
59 }
60
61 bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
62   if (!TLI)
63     return false;
64
65   SmallVector<Instruction *, 1> AtomicInsts;
66
67   // Changing control-flow while iterating through it is a bad idea, so gather a
68   // list of all atomic instructions before we start.
69   for (BasicBlock &BB : F)
70     for (Instruction &Inst : BB) {
71       if (isa<AtomicRMWInst>(&Inst) || isa<AtomicCmpXchgInst>(&Inst) ||
72           (isa<LoadInst>(&Inst) && cast<LoadInst>(&Inst)->isAtomic()) ||
73           (isa<StoreInst>(&Inst) && cast<StoreInst>(&Inst)->isAtomic()))
74         AtomicInsts.push_back(&Inst);
75     }
76
77   bool MadeChange = false;
78   for (Instruction *Inst : AtomicInsts) {
79     if (!TLI->shouldExpandAtomicInIR(Inst))
80       continue;
81
82     if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst))
83       MadeChange |= expandAtomicRMW(AI);
84     else if (AtomicCmpXchgInst *CI = dyn_cast<AtomicCmpXchgInst>(Inst))
85       MadeChange |= expandAtomicCmpXchg(CI);
86     else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
87       MadeChange |= expandAtomicLoad(LI);
88     else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
89       MadeChange |= expandAtomicStore(SI);
90     else
91       llvm_unreachable("Unknown atomic instruction");
92   }
93
94   return MadeChange;
95 }
96
97 bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
98   // Load instructions don't actually need a leading fence, even in the
99   // SequentiallyConsistent case.
100   AtomicOrdering MemOpOrder =
101     TLI->getInsertFencesForAtomic() ? Monotonic : LI->getOrdering();
102
103   // The only 64-bit load guaranteed to be single-copy atomic by the ARM ARM is
104   // an ldrexd (A3.5.3).
105   IRBuilder<> Builder(LI);
106   Value *Val =
107       TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
108
109   insertTrailingFence(Builder, LI->getOrdering());
110
111   LI->replaceAllUsesWith(Val);
112   LI->eraseFromParent();
113
114   return true;
115 }
116
117 bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
118   // The only atomic 64-bit store on ARM is an strexd that succeeds, which means
119   // we need a loop and the entire instruction is essentially an "atomicrmw
120   // xchg" that ignores the value loaded.
121   IRBuilder<> Builder(SI);
122   AtomicRMWInst *AI =
123       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
124                               SI->getValueOperand(), SI->getOrdering());
125   SI->eraseFromParent();
126
127   // Now we have an appropriate swap instruction, lower it as usual.
128   return expandAtomicRMW(AI);
129 }
130
131 bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
132   AtomicOrdering Order = AI->getOrdering();
133   Value *Addr = AI->getPointerOperand();
134   BasicBlock *BB = AI->getParent();
135   Function *F = BB->getParent();
136   LLVMContext &Ctx = F->getContext();
137
138   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
139   //
140   // The standard expansion we produce is:
141   //     [...]
142   //     fence?
143   // atomicrmw.start:
144   //     %loaded = @load.linked(%addr)
145   //     %new = some_op iN %loaded, %incr
146   //     %stored = @store_conditional(%new, %addr)
147   //     %try_again = icmp i32 ne %stored, 0
148   //     br i1 %try_again, label %loop, label %atomicrmw.end
149   // atomicrmw.end:
150   //     fence?
151   //     [...]
152   BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
153   BasicBlock *LoopBB =  BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
154
155   // This grabs the DebugLoc from AI.
156   IRBuilder<> Builder(AI);
157
158   // The split call above "helpfully" added a branch at the end of BB (to the
159   // wrong place), but we might want a fence too. It's easiest to just remove
160   // the branch entirely.
161   std::prev(BB->end())->eraseFromParent();
162   Builder.SetInsertPoint(BB);
163   AtomicOrdering MemOpOrder = insertLeadingFence(Builder, Order);
164   Builder.CreateBr(LoopBB);
165
166   // Start the main loop block now that we've taken care of the preliminaries.
167   Builder.SetInsertPoint(LoopBB);
168   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
169
170   Value *NewVal;
171   switch (AI->getOperation()) {
172   case AtomicRMWInst::Xchg:
173     NewVal = AI->getValOperand();
174     break;
175   case AtomicRMWInst::Add:
176     NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
177     break;
178   case AtomicRMWInst::Sub:
179     NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
180     break;
181   case AtomicRMWInst::And:
182     NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
183     break;
184   case AtomicRMWInst::Nand:
185     NewVal = Builder.CreateAnd(Loaded, Builder.CreateNot(AI->getValOperand()),
186                                "new");
187     break;
188   case AtomicRMWInst::Or:
189     NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
190     break;
191   case AtomicRMWInst::Xor:
192     NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
193     break;
194   case AtomicRMWInst::Max:
195     NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
196     NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
197     break;
198   case AtomicRMWInst::Min:
199     NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
200     NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
201     break;
202   case AtomicRMWInst::UMax:
203     NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
204     NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
205     break;
206   case AtomicRMWInst::UMin:
207     NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
208     NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
209     break;
210   default:
211     llvm_unreachable("Unknown atomic op");
212   }
213
214   Value *StoreSuccess =
215       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
216   Value *TryAgain = Builder.CreateICmpNE(
217       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
218   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
219
220   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
221   insertTrailingFence(Builder, Order);
222
223   AI->replaceAllUsesWith(Loaded);
224   AI->eraseFromParent();
225
226   return true;
227 }
228
229 bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
230   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
231   AtomicOrdering FailureOrder = CI->getFailureOrdering();
232   Value *Addr = CI->getPointerOperand();
233   BasicBlock *BB = CI->getParent();
234   Function *F = BB->getParent();
235   LLVMContext &Ctx = F->getContext();
236
237   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
238   //
239   // The full expansion we produce is:
240   //     [...]
241   //     fence?
242   // cmpxchg.start:
243   //     %loaded = @load.linked(%addr)
244   //     %should_store = icmp eq %loaded, %desired
245   //     br i1 %should_store, label %cmpxchg.trystore,
246   //                          label %cmpxchg.failure
247   // cmpxchg.trystore:
248   //     %stored = @store_conditional(%new, %addr)
249   //     %success = icmp eq i32 %stored, 0
250   //     br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
251   // cmpxchg.success:
252   //     fence?
253   //     br label %cmpxchg.end
254   // cmpxchg.failure:
255   //     fence?
256   //     br label %cmpxchg.end
257   // cmpxchg.end:
258   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
259   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
260   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
261   //     [...]
262   BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
263   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
264   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
265   auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
266   auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
267
268   // This grabs the DebugLoc from CI
269   IRBuilder<> Builder(CI);
270
271   // The split call above "helpfully" added a branch at the end of BB (to the
272   // wrong place), but we might want a fence too. It's easiest to just remove
273   // the branch entirely.
274   std::prev(BB->end())->eraseFromParent();
275   Builder.SetInsertPoint(BB);
276   AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
277   Builder.CreateBr(LoopBB);
278
279   // Start the main loop block now that we've taken care of the preliminaries.
280   Builder.SetInsertPoint(LoopBB);
281   Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
282   Value *ShouldStore =
283       Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
284
285   // If the the cmpxchg doesn't actually need any ordering when it fails, we can
286   // jump straight past that fence instruction (if it exists).
287   Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
288
289   Builder.SetInsertPoint(TryStoreBB);
290   Value *StoreSuccess = TLI->emitStoreConditional(
291       Builder, CI->getNewValOperand(), Addr, MemOpOrder);
292   StoreSuccess = Builder.CreateICmpEQ(
293       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
294   Builder.CreateCondBr(StoreSuccess, SuccessBB,
295                        CI->isWeak() ? FailureBB : LoopBB);
296
297   // Make sure later instructions don't get reordered with a fence if necessary.
298   Builder.SetInsertPoint(SuccessBB);
299   insertTrailingFence(Builder, SuccessOrder);
300   Builder.CreateBr(ExitBB);
301
302   Builder.SetInsertPoint(FailureBB);
303   insertTrailingFence(Builder, FailureOrder);
304   Builder.CreateBr(ExitBB);
305
306   // Finally, we have control-flow based knowledge of whether the cmpxchg
307   // succeeded or not. We expose this to later passes by converting any
308   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
309
310   // Setup the builder so we can create any PHIs we need.
311   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
312   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
313   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
314   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
315
316   // Look for any users of the cmpxchg that are just comparing the loaded value
317   // against the desired one, and replace them with the CFG-derived version.
318   SmallVector<ExtractValueInst *, 2> PrunedInsts;
319   for (auto User : CI->users()) {
320     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
321     if (!EV)
322       continue;
323
324     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
325            "weird extraction from { iN, i1 }");
326
327     if (EV->getIndices()[0] == 0)
328       EV->replaceAllUsesWith(Loaded);
329     else
330       EV->replaceAllUsesWith(Success);
331
332     PrunedInsts.push_back(EV);
333   }
334
335   // We can remove the instructions now we're no longer iterating through them.
336   for (auto EV : PrunedInsts)
337     EV->eraseFromParent();
338
339   if (!CI->use_empty()) {
340     // Some use of the full struct return that we don't understand has happened,
341     // so we've got to reconstruct it properly.
342     Value *Res;
343     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
344     Res = Builder.CreateInsertValue(Res, Success, 1);
345
346     CI->replaceAllUsesWith(Res);
347   }
348
349   CI->eraseFromParent();
350   return true;
351 }
352
353 AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
354                                                        AtomicOrdering Ord) {
355   if (!TLI->getInsertFencesForAtomic())
356     return Ord;
357
358   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
359     Builder.CreateFence(Release);
360
361   // The exclusive operations don't need any barrier if we're adding separate
362   // fences.
363   return Monotonic;
364 }
365
366 void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
367                                               AtomicOrdering Ord) {
368   if (!TLI->getInsertFencesForAtomic())
369     return;
370
371   if (Ord == Acquire || Ord == AcquireRelease)
372     Builder.CreateFence(Acquire);
373   else if (Ord == SequentiallyConsistent)
374     Builder.CreateFence(SequentiallyConsistent);
375 }