1 //===-- AtomicExpandPass.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 "atomic-expand"
31 class AtomicExpand: public FunctionPass {
32 const TargetMachine *TM;
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());
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);
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",
56 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
57 return new AtomicExpand(TM);
60 bool AtomicExpand::runOnFunction(Function &F) {
61 if (!TM || !TM->getSubtargetImpl()->enableAtomicExpand())
64 SmallVector<Instruction *, 1> AtomicInsts;
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);
76 bool MadeChange = false;
77 for (Instruction *Inst : AtomicInsts) {
78 if (!TM->getSubtargetImpl()->getTargetLowering()->shouldExpandAtomicInIR(
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);
91 llvm_unreachable("Unknown atomic instruction");
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);
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);
114 // The only 64-bit load guaranteed to be single-copy atomic by ARM is
115 // an ldrexd (A3.5.3).
117 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), MemOpOrder);
119 TLI->emitTrailingFence(Builder, LI->getOrdering(),
120 /*IsStore=*/false, /*IsLoad=*/true);
122 LI->replaceAllUsesWith(Val);
123 LI->eraseFromParent();
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);
134 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
135 SI->getValueOperand(), SI->getOrdering());
136 SI->eraseFromParent();
138 // Now we have an appropriate swap instruction, lower it as usual.
139 return expandAtomicRMW(AI);
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;
156 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
158 // The standard expansion we produce is:
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
170 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
171 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
173 // This grabs the DebugLoc from AI.
174 IRBuilder<> Builder(AI);
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);
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);
189 switch (AI->getOperation()) {
190 case AtomicRMWInst::Xchg:
191 NewVal = AI->getValOperand();
193 case AtomicRMWInst::Add:
194 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
196 case AtomicRMWInst::Sub:
197 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
199 case AtomicRMWInst::And:
200 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
202 case AtomicRMWInst::Nand:
203 NewVal = Builder.CreateNot(Builder.CreateAnd(Loaded, AI->getValOperand()),
206 case AtomicRMWInst::Or:
207 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
209 case AtomicRMWInst::Xor:
210 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
212 case AtomicRMWInst::Max:
213 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
214 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
216 case AtomicRMWInst::Min:
217 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
218 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
220 case AtomicRMWInst::UMax:
221 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
222 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
224 case AtomicRMWInst::UMin:
225 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
226 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
229 llvm_unreachable("Unknown atomic op");
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);
238 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
239 TLI->emitTrailingFence(Builder, Order, /*IsStore=*/true, /*IsLoad=*/true);
241 AI->replaceAllUsesWith(Loaded);
242 AI->eraseFromParent();
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;
262 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
264 // The full expansion we produce is:
268 // %loaded = @load.linked(%addr)
269 // %should_store = icmp eq %loaded, %desired
270 // br i1 %should_store, label %cmpxchg.trystore,
271 // label %cmpxchg.failure
273 // %stored = @store_conditional(%new, %addr)
274 // %success = icmp eq i32 %stored, 0
275 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
278 // br label %cmpxchg.end
281 // br label %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
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);
293 // This grabs the DebugLoc from CI
294 IRBuilder<> Builder(CI);
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,
303 Builder.CreateBr(LoopBB);
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);
309 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
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);
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);
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,
327 Builder.CreateBr(ExitBB);
329 Builder.SetInsertPoint(FailureBB);
330 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
332 Builder.CreateBr(ExitBB);
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.
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);
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);
352 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
353 "weird extraction from { iN, i1 }");
355 if (EV->getIndices()[0] == 0)
356 EV->replaceAllUsesWith(Loaded);
358 EV->replaceAllUsesWith(Success);
360 PrunedInsts.push_back(EV);
363 // We can remove the instructions now we're no longer iterating through them.
364 for (auto EV : PrunedInsts)
365 EV->eraseFromParent();
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.
371 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
372 Res = Builder.CreateInsertValue(Res, Success, 1);
374 CI->replaceAllUsesWith(Res);
377 CI->eraseFromParent();