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