1 //===-- AtomicExpandLoadLinkedPass.cpp - Expand atomic instructions -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass (at IR level) to replace atomic instructions with
11 // appropriate (intrinsic-based) ldrex/strex loops.
13 //===----------------------------------------------------------------------===//
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"
28 #define DEBUG_TYPE "arm-atomic-expand"
31 class AtomicExpandLoadLinked : public FunctionPass {
32 const TargetMachine *TM;
34 static char ID; // Pass identification, replacement for typeid
35 explicit AtomicExpandLoadLinked(const TargetMachine *TM = nullptr)
36 : FunctionPass(ID), TM(TM) {
37 initializeAtomicExpandLoadLinkedPass(*PassRegistry::getPassRegistry());
40 bool runOnFunction(Function &F) override;
41 bool expandAtomicInsts(Function &F);
43 bool expandAtomicLoad(LoadInst *LI);
44 bool expandAtomicStore(StoreInst *LI);
45 bool expandAtomicRMW(AtomicRMWInst *AI);
46 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
48 AtomicOrdering insertLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
49 void insertTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
53 char AtomicExpandLoadLinked::ID = 0;
54 char &llvm::AtomicExpandLoadLinkedID = AtomicExpandLoadLinked::ID;
55 INITIALIZE_TM_PASS(AtomicExpandLoadLinked, "atomic-ll-sc",
56 "Expand Atomic calls in terms of load-linked & store-conditional",
59 FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
60 return new AtomicExpandLoadLinked(TM);
63 bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
64 if (!TM || !TM->getSubtargetImpl()->enableAtomicExpandLoadLinked())
67 SmallVector<Instruction *, 1> AtomicInsts;
69 // Changing control-flow while iterating through it is a bad idea, so gather a
70 // list of all atomic instructions before we start.
71 for (BasicBlock &BB : F)
72 for (Instruction &Inst : BB) {
73 if (isa<AtomicRMWInst>(&Inst) || isa<AtomicCmpXchgInst>(&Inst) ||
74 (isa<LoadInst>(&Inst) && cast<LoadInst>(&Inst)->isAtomic()) ||
75 (isa<StoreInst>(&Inst) && cast<StoreInst>(&Inst)->isAtomic()))
76 AtomicInsts.push_back(&Inst);
79 bool MadeChange = false;
80 for (Instruction *Inst : AtomicInsts) {
81 if (!TM->getSubtargetImpl()->getTargetLowering()->shouldExpandAtomicInIR(
85 if (AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Inst))
86 MadeChange |= expandAtomicRMW(AI);
87 else if (AtomicCmpXchgInst *CI = dyn_cast<AtomicCmpXchgInst>(Inst))
88 MadeChange |= expandAtomicCmpXchg(CI);
89 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
90 MadeChange |= expandAtomicLoad(LI);
91 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
92 MadeChange |= expandAtomicStore(SI);
94 llvm_unreachable("Unknown atomic instruction");
100 bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
101 // Load instructions don't actually need a leading fence, even in the
102 // SequentiallyConsistent case.
103 AtomicOrdering MemOpOrder =
104 TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic()
108 // The only 64-bit load guaranteed to be single-copy atomic by the ARM is
109 // an ldrexd (A3.5.3).
110 IRBuilder<> Builder(LI);
111 Value *Val = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
112 Builder, LI->getPointerOperand(), MemOpOrder);
114 insertTrailingFence(Builder, LI->getOrdering());
116 LI->replaceAllUsesWith(Val);
117 LI->eraseFromParent();
122 bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
123 // The only atomic 64-bit store on ARM is an strexd that succeeds, which means
124 // we need a loop and the entire instruction is essentially an "atomicrmw
125 // xchg" that ignores the value loaded.
126 IRBuilder<> Builder(SI);
128 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
129 SI->getValueOperand(), SI->getOrdering());
130 SI->eraseFromParent();
132 // Now we have an appropriate swap instruction, lower it as usual.
133 return expandAtomicRMW(AI);
136 bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
137 AtomicOrdering Order = AI->getOrdering();
138 Value *Addr = AI->getPointerOperand();
139 BasicBlock *BB = AI->getParent();
140 Function *F = BB->getParent();
141 LLVMContext &Ctx = F->getContext();
143 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
145 // The standard expansion we produce is:
149 // %loaded = @load.linked(%addr)
150 // %new = some_op iN %loaded, %incr
151 // %stored = @store_conditional(%new, %addr)
152 // %try_again = icmp i32 ne %stored, 0
153 // br i1 %try_again, label %loop, label %atomicrmw.end
157 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
158 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
160 // This grabs the DebugLoc from AI.
161 IRBuilder<> Builder(AI);
163 // The split call above "helpfully" added a branch at the end of BB (to the
164 // wrong place), but we might want a fence too. It's easiest to just remove
165 // the branch entirely.
166 std::prev(BB->end())->eraseFromParent();
167 Builder.SetInsertPoint(BB);
168 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, Order);
169 Builder.CreateBr(LoopBB);
171 // Start the main loop block now that we've taken care of the preliminaries.
172 Builder.SetInsertPoint(LoopBB);
173 Value *Loaded = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
174 Builder, Addr, MemOpOrder);
177 switch (AI->getOperation()) {
178 case AtomicRMWInst::Xchg:
179 NewVal = AI->getValOperand();
181 case AtomicRMWInst::Add:
182 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
184 case AtomicRMWInst::Sub:
185 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
187 case AtomicRMWInst::And:
188 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
190 case AtomicRMWInst::Nand:
191 NewVal = Builder.CreateNot(Builder.CreateAnd(Loaded, AI->getValOperand()),
194 case AtomicRMWInst::Or:
195 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
197 case AtomicRMWInst::Xor:
198 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
200 case AtomicRMWInst::Max:
201 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
202 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
204 case AtomicRMWInst::Min:
205 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
206 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
208 case AtomicRMWInst::UMax:
209 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
210 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
212 case AtomicRMWInst::UMin:
213 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
214 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
217 llvm_unreachable("Unknown atomic op");
220 Value *StoreSuccess =
221 TM->getSubtargetImpl()->getTargetLowering()->emitStoreConditional(
222 Builder, NewVal, Addr, MemOpOrder);
223 Value *TryAgain = Builder.CreateICmpNE(
224 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
225 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
227 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
228 insertTrailingFence(Builder, Order);
230 AI->replaceAllUsesWith(Loaded);
231 AI->eraseFromParent();
236 bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
237 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
238 AtomicOrdering FailureOrder = CI->getFailureOrdering();
239 Value *Addr = CI->getPointerOperand();
240 BasicBlock *BB = CI->getParent();
241 Function *F = BB->getParent();
242 LLVMContext &Ctx = F->getContext();
244 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
246 // The full expansion we produce is:
250 // %loaded = @load.linked(%addr)
251 // %should_store = icmp eq %loaded, %desired
252 // br i1 %should_store, label %cmpxchg.trystore,
253 // label %cmpxchg.failure
255 // %stored = @store_conditional(%new, %addr)
256 // %success = icmp eq i32 %stored, 0
257 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
260 // br label %cmpxchg.end
263 // br label %cmpxchg.end
265 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
266 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
267 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
269 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
270 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
271 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
272 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
273 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
275 // This grabs the DebugLoc from CI
276 IRBuilder<> Builder(CI);
278 // The split call above "helpfully" added a branch at the end of BB (to the
279 // wrong place), but we might want a fence too. It's easiest to just remove
280 // the branch entirely.
281 std::prev(BB->end())->eraseFromParent();
282 Builder.SetInsertPoint(BB);
283 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
284 Builder.CreateBr(LoopBB);
286 // Start the main loop block now that we've taken care of the preliminaries.
287 Builder.SetInsertPoint(LoopBB);
288 Value *Loaded = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
289 Builder, Addr, MemOpOrder);
291 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
293 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
294 // jump straight past that fence instruction (if it exists).
295 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
297 Builder.SetInsertPoint(TryStoreBB);
298 Value *StoreSuccess =
299 TM->getSubtargetImpl()->getTargetLowering()->emitStoreConditional(
300 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
301 StoreSuccess = Builder.CreateICmpEQ(
302 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
303 Builder.CreateCondBr(StoreSuccess, SuccessBB,
304 CI->isWeak() ? FailureBB : LoopBB);
306 // Make sure later instructions don't get reordered with a fence if necessary.
307 Builder.SetInsertPoint(SuccessBB);
308 insertTrailingFence(Builder, SuccessOrder);
309 Builder.CreateBr(ExitBB);
311 Builder.SetInsertPoint(FailureBB);
312 insertTrailingFence(Builder, FailureOrder);
313 Builder.CreateBr(ExitBB);
315 // Finally, we have control-flow based knowledge of whether the cmpxchg
316 // succeeded or not. We expose this to later passes by converting any
317 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
319 // Setup the builder so we can create any PHIs we need.
320 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
321 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
322 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
323 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
325 // Look for any users of the cmpxchg that are just comparing the loaded value
326 // against the desired one, and replace them with the CFG-derived version.
327 SmallVector<ExtractValueInst *, 2> PrunedInsts;
328 for (auto User : CI->users()) {
329 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
333 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
334 "weird extraction from { iN, i1 }");
336 if (EV->getIndices()[0] == 0)
337 EV->replaceAllUsesWith(Loaded);
339 EV->replaceAllUsesWith(Success);
341 PrunedInsts.push_back(EV);
344 // We can remove the instructions now we're no longer iterating through them.
345 for (auto EV : PrunedInsts)
346 EV->eraseFromParent();
348 if (!CI->use_empty()) {
349 // Some use of the full struct return that we don't understand has happened,
350 // so we've got to reconstruct it properly.
352 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
353 Res = Builder.CreateInsertValue(Res, Success, 1);
355 CI->replaceAllUsesWith(Res);
358 CI->eraseFromParent();
362 AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
363 AtomicOrdering Ord) {
364 if (!TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic())
367 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
368 Builder.CreateFence(Release);
370 // The exclusive operations don't need any barrier if we're adding separate
375 void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
376 AtomicOrdering Ord) {
377 if (!TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic())
380 if (Ord == Acquire || Ord == AcquireRelease)
381 Builder.CreateFence(Acquire);
382 else if (Ord == SequentiallyConsistent)
383 Builder.CreateFence(SequentiallyConsistent);