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 // either (intrinsic-based) load-linked/store-conditional loops or AtomicCmpXchg.
13 //===----------------------------------------------------------------------===//
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"
29 #define DEBUG_TYPE "atomic-expand"
32 class AtomicExpand: public FunctionPass {
33 const TargetMachine *TM;
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());
41 bool runOnFunction(Function &F) override;
44 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
45 bool IsStore, bool IsLoad);
46 bool expandAtomicLoad(LoadInst *LI);
47 bool expandAtomicStore(StoreInst *SI);
48 bool expandAtomicRMW(AtomicRMWInst *AI);
49 bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
50 bool expandAtomicRMWToCmpXchg(AtomicRMWInst *AI);
51 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
55 char AtomicExpand::ID = 0;
56 char &llvm::AtomicExpandID = AtomicExpand::ID;
57 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
58 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
61 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
62 return new AtomicExpand(TM);
65 bool AtomicExpand::runOnFunction(Function &F) {
66 if (!TM || !TM->getSubtargetImpl()->enableAtomicExpand())
68 auto TargetLowering = TM->getSubtargetImpl()->getTargetLowering();
70 SmallVector<Instruction *, 1> AtomicInsts;
72 // Changing control-flow while iterating through it is a bad idea, so gather a
73 // list of all atomic instructions before we start.
74 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
76 AtomicInsts.push_back(&*I);
79 bool MadeChange = false;
80 for (auto I : AtomicInsts) {
81 auto LI = dyn_cast<LoadInst>(I);
82 auto SI = dyn_cast<StoreInst>(I);
83 auto RMWI = dyn_cast<AtomicRMWInst>(I);
84 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
85 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
86 "Unknown atomic instruction");
88 auto FenceOrdering = Monotonic;
90 if (TargetLowering->getInsertFencesForAtomic()) {
91 if (LI && isAtLeastAcquire(LI->getOrdering())) {
92 FenceOrdering = LI->getOrdering();
93 LI->setOrdering(Monotonic);
96 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
97 FenceOrdering = SI->getOrdering();
98 SI->setOrdering(Monotonic);
101 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
102 isAtLeastAcquire(RMWI->getOrdering()))) {
103 FenceOrdering = RMWI->getOrdering();
104 RMWI->setOrdering(Monotonic);
105 IsStore = IsLoad = true;
106 } else if (CASI && !TargetLowering->hasLoadLinkedStoreConditional() &&
107 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
108 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
109 // If a compare and swap is lowered to LL/SC, we can do smarter fence
110 // insertion, with a stronger one on the success path than on the
111 // failure path. As a result, fence insertion is directly done by
112 // expandAtomicCmpXchg in that case.
113 FenceOrdering = CASI->getSuccessOrdering();
114 CASI->setSuccessOrdering(Monotonic);
115 CASI->setFailureOrdering(Monotonic);
116 IsStore = IsLoad = true;
119 if (FenceOrdering != Monotonic) {
120 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
124 if (LI && TargetLowering->shouldExpandAtomicLoadInIR(LI)) {
125 MadeChange |= expandAtomicLoad(LI);
126 } else if (SI && TargetLowering->shouldExpandAtomicStoreInIR(SI)) {
127 MadeChange |= expandAtomicStore(SI);
128 } else if (RMWI && TargetLowering->shouldExpandAtomicRMWInIR(RMWI)) {
129 MadeChange |= expandAtomicRMW(RMWI);
130 } else if (CASI && TargetLowering->hasLoadLinkedStoreConditional()) {
131 MadeChange |= expandAtomicCmpXchg(CASI);
137 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
138 bool IsStore, bool IsLoad) {
139 IRBuilder<> Builder(I);
142 TM->getSubtargetImpl()->getTargetLowering()->emitLeadingFence(
143 Builder, Order, IsStore, IsLoad);
146 TM->getSubtargetImpl()->getTargetLowering()->emitTrailingFence(
147 Builder, Order, IsStore, IsLoad);
148 // The trailing fence is emitted before the instruction instead of after
149 // because there is no easy way of setting Builder insertion point after
150 // an instruction. So we must erase it from the BB, and insert it back
151 // in the right place.
152 // We have a guard here because not every atomic operation generates a
155 TrailingFence->removeFromParent();
156 TrailingFence->insertAfter(I);
159 return (LeadingFence || TrailingFence);
162 bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
163 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
164 IRBuilder<> Builder(LI);
166 // On some architectures, load-linked instructions are atomic for larger
167 // sizes than normal loads. For example, the only 64-bit load guaranteed
168 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
170 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
172 LI->replaceAllUsesWith(Val);
173 LI->eraseFromParent();
178 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
179 // This function is only called on atomic stores that are too large to be
180 // atomic if implemented as a native store. So we replace them by an
181 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
182 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
183 // It is the responsibility of the target to only return true in
184 // shouldExpandAtomicRMW in cases where this is required and possible.
185 IRBuilder<> Builder(SI);
187 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
188 SI->getValueOperand(), SI->getOrdering());
189 SI->eraseFromParent();
191 // Now we have an appropriate swap instruction, lower it as usual.
192 return expandAtomicRMW(AI);
195 bool AtomicExpand::expandAtomicRMW(AtomicRMWInst *AI) {
196 if (TM->getSubtargetImpl()
197 ->getTargetLowering()
198 ->hasLoadLinkedStoreConditional())
199 return expandAtomicRMWToLLSC(AI);
201 return expandAtomicRMWToCmpXchg(AI);
204 /// Emit IR to implement the given atomicrmw operation on values in registers,
205 /// returning the new value.
206 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
207 Value *Loaded, Value *Inc) {
210 case AtomicRMWInst::Xchg:
212 case AtomicRMWInst::Add:
213 return Builder.CreateAdd(Loaded, Inc, "new");
214 case AtomicRMWInst::Sub:
215 return Builder.CreateSub(Loaded, Inc, "new");
216 case AtomicRMWInst::And:
217 return Builder.CreateAnd(Loaded, Inc, "new");
218 case AtomicRMWInst::Nand:
219 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
220 case AtomicRMWInst::Or:
221 return Builder.CreateOr(Loaded, Inc, "new");
222 case AtomicRMWInst::Xor:
223 return Builder.CreateXor(Loaded, Inc, "new");
224 case AtomicRMWInst::Max:
225 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
226 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
227 case AtomicRMWInst::Min:
228 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
229 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
230 case AtomicRMWInst::UMax:
231 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
232 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
233 case AtomicRMWInst::UMin:
234 NewVal = Builder.CreateICmpULE(Loaded, Inc);
235 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
237 llvm_unreachable("Unknown atomic op");
241 bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
242 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
243 AtomicOrdering MemOpOrder = AI->getOrdering();
244 Value *Addr = AI->getPointerOperand();
245 BasicBlock *BB = AI->getParent();
246 Function *F = BB->getParent();
247 LLVMContext &Ctx = F->getContext();
249 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
251 // The standard expansion we produce is:
255 // %loaded = @load.linked(%addr)
256 // %new = some_op iN %loaded, %incr
257 // %stored = @store_conditional(%new, %addr)
258 // %try_again = icmp i32 ne %stored, 0
259 // br i1 %try_again, label %loop, label %atomicrmw.end
263 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
264 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
266 // This grabs the DebugLoc from AI.
267 IRBuilder<> Builder(AI);
269 // The split call above "helpfully" added a branch at the end of BB (to the
270 // wrong place), but we might want a fence too. It's easiest to just remove
271 // the branch entirely.
272 std::prev(BB->end())->eraseFromParent();
273 Builder.SetInsertPoint(BB);
274 Builder.CreateBr(LoopBB);
276 // Start the main loop block now that we've taken care of the preliminaries.
277 Builder.SetInsertPoint(LoopBB);
278 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
281 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
283 Value *StoreSuccess =
284 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
285 Value *TryAgain = Builder.CreateICmpNE(
286 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
287 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
289 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
291 AI->replaceAllUsesWith(Loaded);
292 AI->eraseFromParent();
297 bool AtomicExpand::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI) {
298 AtomicOrdering MemOpOrder =
299 AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
300 Value *Addr = AI->getPointerOperand();
301 BasicBlock *BB = AI->getParent();
302 Function *F = BB->getParent();
303 LLVMContext &Ctx = F->getContext();
305 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
307 // The standard expansion we produce is:
309 // %init_loaded = load atomic iN* %addr
312 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
313 // %new = some_op iN %loaded, %incr
314 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
315 // %new_loaded = extractvalue { iN, i1 } %pair, 0
316 // %success = extractvalue { iN, i1 } %pair, 1
317 // br i1 %success, label %atomicrmw.end, label %loop
320 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
321 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
323 // This grabs the DebugLoc from AI.
324 IRBuilder<> Builder(AI);
326 // The split call above "helpfully" added a branch at the end of BB (to the
327 // wrong place), but we want a load. It's easiest to just remove
328 // the branch entirely.
329 std::prev(BB->end())->eraseFromParent();
330 Builder.SetInsertPoint(BB);
331 LoadInst *InitLoaded = Builder.CreateLoad(Addr);
332 // Atomics require at least natural alignment.
333 InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits());
334 Builder.CreateBr(LoopBB);
336 // Start the main loop block now that we've taken care of the preliminaries.
337 Builder.SetInsertPoint(LoopBB);
338 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
339 Loaded->addIncoming(InitLoaded, BB);
342 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
344 Value *Pair = Builder.CreateAtomicCmpXchg(
345 Addr, Loaded, NewVal, MemOpOrder,
346 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
347 Value *NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
348 Loaded->addIncoming(NewLoaded, LoopBB);
350 Value *Success = Builder.CreateExtractValue(Pair, 1, "success");
351 Builder.CreateCondBr(Success, ExitBB, LoopBB);
353 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
355 AI->replaceAllUsesWith(NewLoaded);
356 AI->eraseFromParent();
361 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
362 auto TLI = TM->getSubtargetImpl()->getTargetLowering();
363 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
364 AtomicOrdering FailureOrder = CI->getFailureOrdering();
365 Value *Addr = CI->getPointerOperand();
366 BasicBlock *BB = CI->getParent();
367 Function *F = BB->getParent();
368 LLVMContext &Ctx = F->getContext();
369 // If getInsertFencesForAtomic() returns true, then the target does not want
370 // to deal with memory orders, and emitLeading/TrailingFence should take care
371 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
372 // should preserve the ordering.
373 AtomicOrdering MemOpOrder =
374 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
376 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
378 // The full expansion we produce is:
382 // %loaded = @load.linked(%addr)
383 // %should_store = icmp eq %loaded, %desired
384 // br i1 %should_store, label %cmpxchg.trystore,
385 // label %cmpxchg.failure
387 // %stored = @store_conditional(%new, %addr)
388 // %success = icmp eq i32 %stored, 0
389 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
392 // br label %cmpxchg.end
395 // br label %cmpxchg.end
397 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
398 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
399 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
401 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
402 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
403 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
404 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
405 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
407 // This grabs the DebugLoc from CI
408 IRBuilder<> Builder(CI);
410 // The split call above "helpfully" added a branch at the end of BB (to the
411 // wrong place), but we might want a fence too. It's easiest to just remove
412 // the branch entirely.
413 std::prev(BB->end())->eraseFromParent();
414 Builder.SetInsertPoint(BB);
415 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
417 Builder.CreateBr(LoopBB);
419 // Start the main loop block now that we've taken care of the preliminaries.
420 Builder.SetInsertPoint(LoopBB);
421 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
423 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
425 // If the the cmpxchg doesn't actually need any ordering when it fails, we can
426 // jump straight past that fence instruction (if it exists).
427 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
429 Builder.SetInsertPoint(TryStoreBB);
430 Value *StoreSuccess = TLI->emitStoreConditional(
431 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
432 StoreSuccess = Builder.CreateICmpEQ(
433 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
434 Builder.CreateCondBr(StoreSuccess, SuccessBB,
435 CI->isWeak() ? FailureBB : LoopBB);
437 // Make sure later instructions don't get reordered with a fence if necessary.
438 Builder.SetInsertPoint(SuccessBB);
439 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
441 Builder.CreateBr(ExitBB);
443 Builder.SetInsertPoint(FailureBB);
444 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
446 Builder.CreateBr(ExitBB);
448 // Finally, we have control-flow based knowledge of whether the cmpxchg
449 // succeeded or not. We expose this to later passes by converting any
450 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
452 // Setup the builder so we can create any PHIs we need.
453 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
454 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
455 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
456 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
458 // Look for any users of the cmpxchg that are just comparing the loaded value
459 // against the desired one, and replace them with the CFG-derived version.
460 SmallVector<ExtractValueInst *, 2> PrunedInsts;
461 for (auto User : CI->users()) {
462 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
466 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
467 "weird extraction from { iN, i1 }");
469 if (EV->getIndices()[0] == 0)
470 EV->replaceAllUsesWith(Loaded);
472 EV->replaceAllUsesWith(Success);
474 PrunedInsts.push_back(EV);
477 // We can remove the instructions now we're no longer iterating through them.
478 for (auto EV : PrunedInsts)
479 EV->eraseFromParent();
481 if (!CI->use_empty()) {
482 // Some use of the full struct return that we don't understand has happened,
483 // so we've got to reconstruct it properly.
485 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
486 Res = Builder.CreateInsertValue(Res, Success, 1);
488 CI->replaceAllUsesWith(Res);
491 CI->eraseFromParent();