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