blob: fbb6e9662d63f999579b077fe636c82f1b363631 [file] [log] [blame]
Tim Northover037f26f22014-04-17 18:22:47 +00001//===-- AtomicExpandLoadLinkedPass.cpp - Expand atomic instructions -------===//
Tim Northoverc882eb02014-04-03 11:44:58 +00002//
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
Tim Northoverc882eb02014-04-03 11:44:58 +000015#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"
24using namespace llvm;
25
Chandler Carruth1b9dde02014-04-22 02:02:50 +000026#define DEBUG_TYPE "arm-atomic-expand"
27
Tim Northoverc882eb02014-04-03 11:44:58 +000028namespace {
Tim Northover037f26f22014-04-17 18:22:47 +000029 class AtomicExpandLoadLinked : public FunctionPass {
Tim Northoverc882eb02014-04-03 11:44:58 +000030 const TargetLowering *TLI;
31 public:
32 static char ID; // Pass identification, replacement for typeid
Craig Topper353eda42014-04-24 06:44:33 +000033 explicit AtomicExpandLoadLinked(const TargetMachine *TM = nullptr)
34 : FunctionPass(ID), TLI(TM ? TM->getTargetLowering() : nullptr) {
Tim Northover037f26f22014-04-17 18:22:47 +000035 initializeAtomicExpandLoadLinkedPass(*PassRegistry::getPassRegistry());
36 }
Tim Northoverc882eb02014-04-03 11:44:58 +000037
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);
Tim Northoverc882eb02014-04-03 11:44:58 +000048 };
49}
50
Tim Northover037f26f22014-04-17 18:22:47 +000051char AtomicExpandLoadLinked::ID = 0;
52char &llvm::AtomicExpandLoadLinkedID = AtomicExpandLoadLinked::ID;
Jiangning Liud623c522014-06-11 07:04:37 +000053INITIALIZE_TM_PASS(AtomicExpandLoadLinked, "atomic-ll-sc",
54 "Expand Atomic calls in terms of load-linked & store-conditional",
55 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +000056
57FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
58 return new AtomicExpandLoadLinked(TM);
59}
60
61bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
62 if (!TLI)
63 return false;
64
Tim Northoverc882eb02014-04-03 11:44:58 +000065 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) {
Tim Northover037f26f22014-04-17 18:22:47 +000079 if (!TLI->shouldExpandAtomicInIR(Inst))
Tim Northoverc882eb02014-04-03 11:44:58 +000080 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
Tim Northover037f26f22014-04-17 18:22:47 +000097bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +000098 // 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);
Tim Northover037f26f22014-04-17 18:22:47 +0000106 Value *Val =
107 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000108
109 insertTrailingFence(Builder, LI->getOrdering());
110
111 LI->replaceAllUsesWith(Val);
112 LI->eraseFromParent();
113
114 return true;
115}
116
Tim Northover037f26f22014-04-17 18:22:47 +0000117bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000118 // 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
Tim Northover037f26f22014-04-17 18:22:47 +0000131bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000132 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);
Tim Northover037f26f22014-04-17 18:22:47 +0000168 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000169
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
Tim Northover037f26f22014-04-17 18:22:47 +0000214 Value *StoreSuccess =
215 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000216 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
Tim Northover037f26f22014-04-17 18:22:47 +0000229bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +0000230 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
231 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000232 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 //
Tim Northover70450c52014-04-03 13:06:54 +0000239 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +0000240 // [...]
241 // fence?
242 // cmpxchg.start:
243 // %loaded = @load.linked(%addr)
244 // %should_store = icmp eq %loaded, %desired
Tim Northover70450c52014-04-03 13:06:54 +0000245 // br i1 %should_store, label %cmpxchg.trystore,
246 // label %cmpxchg.end/%cmpxchg.barrier
Tim Northoverc882eb02014-04-03 11:44:58 +0000247 // cmpxchg.trystore:
248 // %stored = @store_conditional(%new, %addr)
249 // %try_again = icmp i32 ne %stored, 0
250 // br i1 %try_again, label %loop, label %cmpxchg.end
Tim Northover70450c52014-04-03 13:06:54 +0000251 // cmpxchg.barrier:
Tim Northoverc882eb02014-04-03 11:44:58 +0000252 // fence?
Tim Northover70450c52014-04-03 13:06:54 +0000253 // br label %cmpxchg.end
254 // cmpxchg.end:
Tim Northoverc882eb02014-04-03 11:44:58 +0000255 // [...]
256 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
Tim Northover037f26f22014-04-17 18:22:47 +0000257 auto BarrierBB = BasicBlock::Create(Ctx, "cmpxchg.barrier", F, ExitBB);
258 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, BarrierBB);
Tim Northover70450c52014-04-03 13:06:54 +0000259 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000260
261 // This grabs the DebugLoc from CI
262 IRBuilder<> Builder(CI);
263
264 // The split call above "helpfully" added a branch at the end of BB (to the
265 // wrong place), but we might want a fence too. It's easiest to just remove
266 // the branch entirely.
267 std::prev(BB->end())->eraseFromParent();
268 Builder.SetInsertPoint(BB);
Tim Northover70450c52014-04-03 13:06:54 +0000269 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000270 Builder.CreateBr(LoopBB);
271
272 // Start the main loop block now that we've taken care of the preliminaries.
273 Builder.SetInsertPoint(LoopBB);
Tim Northover037f26f22014-04-17 18:22:47 +0000274 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000275 Value *ShouldStore =
276 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +0000277
278 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
279 // jump straight past that fence instruction (if it exists).
280 BasicBlock *FailureBB = FailureOrder == Monotonic ? ExitBB : BarrierBB;
281 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000282
283 Builder.SetInsertPoint(TryStoreBB);
Tim Northover037f26f22014-04-17 18:22:47 +0000284 Value *StoreSuccess = TLI->emitStoreConditional(
285 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000286 Value *TryAgain = Builder.CreateICmpNE(
287 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northover70450c52014-04-03 13:06:54 +0000288 Builder.CreateCondBr(TryAgain, LoopBB, BarrierBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000289
Tim Northoverb4ddc082014-05-30 10:09:59 +0000290 // Make sure later instructions don't get reordered with a fence if necessary.
Tim Northover70450c52014-04-03 13:06:54 +0000291 Builder.SetInsertPoint(BarrierBB);
292 insertTrailingFence(Builder, SuccessOrder);
293 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000294
Tim Northoverb4ddc082014-05-30 10:09:59 +0000295 // Finally, we have control-flow based knowledge of whether the cmpxchg
296 // succeeded or not. We expose this to later passes by converting any
297 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
298
299 // Setup the builder so we can create any PHIs we need.
300 Builder.SetInsertPoint(FailureBB, FailureBB->begin());
301 BasicBlock *SuccessBB = FailureOrder == Monotonic ? BarrierBB : TryStoreBB;
Craig Topper66f09ad2014-06-08 22:29:17 +0000302 PHINode *Success = nullptr, *Failure = nullptr;
Tim Northoverb4ddc082014-05-30 10:09:59 +0000303
304 // Look for any users of the cmpxchg that are just comparing the loaded value
305 // against the desired one, and replace them with the CFG-derived version.
306 for (auto User : CI->users()) {
307 ICmpInst *ICmp = dyn_cast<ICmpInst>(User);
308 if (!ICmp)
309 continue;
310
311 // Because we know ICmp uses CI, we only need one operand to be the old
312 // value.
313 if (ICmp->getOperand(0) != CI->getCompareOperand() &&
314 ICmp->getOperand(1) != CI->getCompareOperand())
315 continue;
316
317 if (ICmp->getPredicate() == CmpInst::ICMP_EQ) {
318 if (!Success) {
319 Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
320 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
321 Success->addIncoming(ConstantInt::getFalse(Ctx), LoopBB);
322 }
323 ICmp->replaceAllUsesWith(Success);
324 } else if (ICmp->getPredicate() == CmpInst::ICMP_NE) {
325 if (!Failure) {
326 Failure = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
327 Failure->addIncoming(ConstantInt::getFalse(Ctx), SuccessBB);
328 Failure->addIncoming(ConstantInt::getTrue(Ctx), LoopBB);
329 }
330 ICmp->replaceAllUsesWith(Failure);
331 }
332 }
333
Tim Northoverc882eb02014-04-03 11:44:58 +0000334 CI->replaceAllUsesWith(Loaded);
335 CI->eraseFromParent();
336
337 return true;
338}
339
Tim Northover037f26f22014-04-17 18:22:47 +0000340AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
Tim Northoverc882eb02014-04-03 11:44:58 +0000341 AtomicOrdering Ord) {
342 if (!TLI->getInsertFencesForAtomic())
343 return Ord;
344
345 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
346 Builder.CreateFence(Release);
347
348 // The exclusive operations don't need any barrier if we're adding separate
349 // fences.
350 return Monotonic;
351}
352
Tim Northover037f26f22014-04-17 18:22:47 +0000353void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
Tim Northoverc882eb02014-04-03 11:44:58 +0000354 AtomicOrdering Ord) {
355 if (!TLI->getInsertFencesForAtomic())
356 return;
357
358 if (Ord == Acquire || Ord == AcquireRelease)
359 Builder.CreateFence(Acquire);
360 else if (Ord == SequentiallyConsistent)
361 Builder.CreateFence(SequentiallyConsistent);
362}