blob: 0c37c45b3af7c5f3f1044c745e3df29753ce44db [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"
Eric Christopherc40e5ed2014-06-19 21:03:04 +000024#include "llvm/Target/TargetSubtargetInfo.h"
25
Tim Northoverc882eb02014-04-03 11:44:58 +000026using namespace llvm;
27
Chandler Carruth1b9dde02014-04-22 02:02:50 +000028#define DEBUG_TYPE "arm-atomic-expand"
29
Tim Northoverc882eb02014-04-03 11:44:58 +000030namespace {
Tim Northover037f26f22014-04-17 18:22:47 +000031 class AtomicExpandLoadLinked : public FunctionPass {
Eric Christopherc40e5ed2014-06-19 21:03:04 +000032 const TargetMachine *TM;
Tim Northoverc882eb02014-04-03 11:44:58 +000033 public:
34 static char ID; // Pass identification, replacement for typeid
Craig Topper353eda42014-04-24 06:44:33 +000035 explicit AtomicExpandLoadLinked(const TargetMachine *TM = nullptr)
Eric Christopherc40e5ed2014-06-19 21:03:04 +000036 : FunctionPass(ID), TM(TM) {
Tim Northover037f26f22014-04-17 18:22:47 +000037 initializeAtomicExpandLoadLinkedPass(*PassRegistry::getPassRegistry());
38 }
Tim Northoverc882eb02014-04-03 11:44:58 +000039
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 AtomicOrdering insertLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
49 void insertTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord);
Tim Northoverc882eb02014-04-03 11:44:58 +000050 };
51}
52
Tim Northover037f26f22014-04-17 18:22:47 +000053char AtomicExpandLoadLinked::ID = 0;
54char &llvm::AtomicExpandLoadLinkedID = AtomicExpandLoadLinked::ID;
Jiangning Liud623c522014-06-11 07:04:37 +000055INITIALIZE_TM_PASS(AtomicExpandLoadLinked, "atomic-ll-sc",
56 "Expand Atomic calls in terms of load-linked & store-conditional",
57 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +000058
59FunctionPass *llvm::createAtomicExpandLoadLinkedPass(const TargetMachine *TM) {
60 return new AtomicExpandLoadLinked(TM);
61}
62
63bool AtomicExpandLoadLinked::runOnFunction(Function &F) {
Eric Christopherc40e5ed2014-06-19 21:03:04 +000064 if (!TM || !TM->getSubtargetImpl()->enableAtomicExpandLoadLinked())
Tim Northover037f26f22014-04-17 18:22:47 +000065 return false;
66
Tim Northoverc882eb02014-04-03 11:44:58 +000067 SmallVector<Instruction *, 1> AtomicInsts;
68
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);
77 }
78
79 bool MadeChange = false;
80 for (Instruction *Inst : AtomicInsts) {
Eric Christopherd9134482014-08-04 21:25:23 +000081 if (!TM->getSubtargetImpl()->getTargetLowering()->shouldExpandAtomicInIR(
82 Inst))
Tim Northoverc882eb02014-04-03 11:44:58 +000083 continue;
84
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);
93 else
94 llvm_unreachable("Unknown atomic instruction");
95 }
96
97 return MadeChange;
98}
99
Tim Northover037f26f22014-04-17 18:22:47 +0000100bool AtomicExpandLoadLinked::expandAtomicLoad(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000101 // Load instructions don't actually need a leading fence, even in the
102 // SequentiallyConsistent case.
103 AtomicOrdering MemOpOrder =
Eric Christopherd9134482014-08-04 21:25:23 +0000104 TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic()
105 ? Monotonic
106 : LI->getOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000107
108 // The only 64-bit load guaranteed to be single-copy atomic by the ARM ARM is
109 // an ldrexd (A3.5.3).
110 IRBuilder<> Builder(LI);
Eric Christopherd9134482014-08-04 21:25:23 +0000111 Value *Val = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
Eric Christopherc40e5ed2014-06-19 21:03:04 +0000112 Builder, LI->getPointerOperand(), MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000113
114 insertTrailingFence(Builder, LI->getOrdering());
115
116 LI->replaceAllUsesWith(Val);
117 LI->eraseFromParent();
118
119 return true;
120}
121
Tim Northover037f26f22014-04-17 18:22:47 +0000122bool AtomicExpandLoadLinked::expandAtomicStore(StoreInst *SI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000123 // 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);
127 AtomicRMWInst *AI =
128 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
129 SI->getValueOperand(), SI->getOrdering());
130 SI->eraseFromParent();
131
132 // Now we have an appropriate swap instruction, lower it as usual.
133 return expandAtomicRMW(AI);
134}
135
Tim Northover037f26f22014-04-17 18:22:47 +0000136bool AtomicExpandLoadLinked::expandAtomicRMW(AtomicRMWInst *AI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000137 AtomicOrdering Order = AI->getOrdering();
138 Value *Addr = AI->getPointerOperand();
139 BasicBlock *BB = AI->getParent();
140 Function *F = BB->getParent();
141 LLVMContext &Ctx = F->getContext();
142
143 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
144 //
145 // The standard expansion we produce is:
146 // [...]
147 // fence?
148 // atomicrmw.start:
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
154 // atomicrmw.end:
155 // fence?
156 // [...]
157 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
158 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
159
160 // This grabs the DebugLoc from AI.
161 IRBuilder<> Builder(AI);
162
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);
170
171 // Start the main loop block now that we've taken care of the preliminaries.
172 Builder.SetInsertPoint(LoopBB);
Eric Christopherd9134482014-08-04 21:25:23 +0000173 Value *Loaded = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
174 Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000175
176 Value *NewVal;
177 switch (AI->getOperation()) {
178 case AtomicRMWInst::Xchg:
179 NewVal = AI->getValOperand();
180 break;
181 case AtomicRMWInst::Add:
182 NewVal = Builder.CreateAdd(Loaded, AI->getValOperand(), "new");
183 break;
184 case AtomicRMWInst::Sub:
185 NewVal = Builder.CreateSub(Loaded, AI->getValOperand(), "new");
186 break;
187 case AtomicRMWInst::And:
188 NewVal = Builder.CreateAnd(Loaded, AI->getValOperand(), "new");
189 break;
190 case AtomicRMWInst::Nand:
Tim Northover55beb642014-07-07 09:06:35 +0000191 NewVal = Builder.CreateNot(Builder.CreateAnd(Loaded, AI->getValOperand()),
Tim Northoverc882eb02014-04-03 11:44:58 +0000192 "new");
193 break;
194 case AtomicRMWInst::Or:
195 NewVal = Builder.CreateOr(Loaded, AI->getValOperand(), "new");
196 break;
197 case AtomicRMWInst::Xor:
198 NewVal = Builder.CreateXor(Loaded, AI->getValOperand(), "new");
199 break;
200 case AtomicRMWInst::Max:
201 NewVal = Builder.CreateICmpSGT(Loaded, AI->getValOperand());
202 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
203 break;
204 case AtomicRMWInst::Min:
205 NewVal = Builder.CreateICmpSLE(Loaded, AI->getValOperand());
206 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
207 break;
208 case AtomicRMWInst::UMax:
209 NewVal = Builder.CreateICmpUGT(Loaded, AI->getValOperand());
210 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
211 break;
212 case AtomicRMWInst::UMin:
213 NewVal = Builder.CreateICmpULE(Loaded, AI->getValOperand());
214 NewVal = Builder.CreateSelect(NewVal, Loaded, AI->getValOperand(), "new");
215 break;
216 default:
217 llvm_unreachable("Unknown atomic op");
218 }
219
Eric Christopherd9134482014-08-04 21:25:23 +0000220 Value *StoreSuccess =
221 TM->getSubtargetImpl()->getTargetLowering()->emitStoreConditional(
222 Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000223 Value *TryAgain = Builder.CreateICmpNE(
224 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
225 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
226
227 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
228 insertTrailingFence(Builder, Order);
229
230 AI->replaceAllUsesWith(Loaded);
231 AI->eraseFromParent();
232
233 return true;
234}
235
Tim Northover037f26f22014-04-17 18:22:47 +0000236bool AtomicExpandLoadLinked::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +0000237 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
238 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000239 Value *Addr = CI->getPointerOperand();
240 BasicBlock *BB = CI->getParent();
241 Function *F = BB->getParent();
242 LLVMContext &Ctx = F->getContext();
243
244 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
245 //
Tim Northover70450c52014-04-03 13:06:54 +0000246 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +0000247 // [...]
248 // fence?
249 // cmpxchg.start:
250 // %loaded = @load.linked(%addr)
251 // %should_store = icmp eq %loaded, %desired
Tim Northover70450c52014-04-03 13:06:54 +0000252 // br i1 %should_store, label %cmpxchg.trystore,
Tim Northover20b9f732014-06-13 16:45:52 +0000253 // label %cmpxchg.failure
Tim Northoverc882eb02014-04-03 11:44:58 +0000254 // cmpxchg.trystore:
255 // %stored = @store_conditional(%new, %addr)
Tim Northover20b9f732014-06-13 16:45:52 +0000256 // %success = icmp eq i32 %stored, 0
257 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
258 // cmpxchg.success:
259 // fence?
260 // br label %cmpxchg.end
261 // cmpxchg.failure:
Tim Northoverc882eb02014-04-03 11:44:58 +0000262 // fence?
Tim Northover70450c52014-04-03 13:06:54 +0000263 // br label %cmpxchg.end
264 // cmpxchg.end:
Tim Northover20b9f732014-06-13 16:45:52 +0000265 // %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
Tim Northoverc882eb02014-04-03 11:44:58 +0000268 // [...]
269 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
Tim Northover20b9f732014-06-13 16:45:52 +0000270 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);
Tim Northover70450c52014-04-03 13:06:54 +0000273 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000274
275 // This grabs the DebugLoc from CI
276 IRBuilder<> Builder(CI);
277
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);
Tim Northover70450c52014-04-03 13:06:54 +0000283 AtomicOrdering MemOpOrder = insertLeadingFence(Builder, SuccessOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000284 Builder.CreateBr(LoopBB);
285
286 // Start the main loop block now that we've taken care of the preliminaries.
287 Builder.SetInsertPoint(LoopBB);
Eric Christopherd9134482014-08-04 21:25:23 +0000288 Value *Loaded = TM->getSubtargetImpl()->getTargetLowering()->emitLoadLinked(
289 Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000290 Value *ShouldStore =
291 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +0000292
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).
Tim Northover70450c52014-04-03 13:06:54 +0000295 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000296
297 Builder.SetInsertPoint(TryStoreBB);
Eric Christopherd9134482014-08-04 21:25:23 +0000298 Value *StoreSuccess =
299 TM->getSubtargetImpl()->getTargetLowering()->emitStoreConditional(
300 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
Tim Northoverd039abd2014-06-13 16:45:36 +0000301 StoreSuccess = Builder.CreateICmpEQ(
Tim Northoverc882eb02014-04-03 11:44:58 +0000302 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northover20b9f732014-06-13 16:45:52 +0000303 Builder.CreateCondBr(StoreSuccess, SuccessBB,
304 CI->isWeak() ? FailureBB : LoopBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000305
Tim Northoverb4ddc082014-05-30 10:09:59 +0000306 // Make sure later instructions don't get reordered with a fence if necessary.
Tim Northover20b9f732014-06-13 16:45:52 +0000307 Builder.SetInsertPoint(SuccessBB);
Tim Northover70450c52014-04-03 13:06:54 +0000308 insertTrailingFence(Builder, SuccessOrder);
309 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000310
Tim Northover20b9f732014-06-13 16:45:52 +0000311 Builder.SetInsertPoint(FailureBB);
312 insertTrailingFence(Builder, FailureOrder);
313 Builder.CreateBr(ExitBB);
314
Tim Northoverb4ddc082014-05-30 10:09:59 +0000315 // 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.
318
319 // Setup the builder so we can create any PHIs we need.
Tim Northover20b9f732014-06-13 16:45:52 +0000320 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northover420a2162014-06-13 14:24:07 +0000321 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
322 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
Tim Northover20b9f732014-06-13 16:45:52 +0000323 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000324
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.
Tim Northover420a2162014-06-13 14:24:07 +0000327 SmallVector<ExtractValueInst *, 2> PrunedInsts;
Tim Northoverb4ddc082014-05-30 10:09:59 +0000328 for (auto User : CI->users()) {
Tim Northover420a2162014-06-13 14:24:07 +0000329 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
330 if (!EV)
Tim Northoverb4ddc082014-05-30 10:09:59 +0000331 continue;
332
Tim Northover420a2162014-06-13 14:24:07 +0000333 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
334 "weird extraction from { iN, i1 }");
Tim Northoverb4ddc082014-05-30 10:09:59 +0000335
Tim Northover420a2162014-06-13 14:24:07 +0000336 if (EV->getIndices()[0] == 0)
337 EV->replaceAllUsesWith(Loaded);
338 else
339 EV->replaceAllUsesWith(Success);
340
341 PrunedInsts.push_back(EV);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000342 }
343
Tim Northover420a2162014-06-13 14:24:07 +0000344 // We can remove the instructions now we're no longer iterating through them.
345 for (auto EV : PrunedInsts)
346 EV->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000347
Tim Northover420a2162014-06-13 14:24:07 +0000348 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.
351 Value *Res;
352 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
353 Res = Builder.CreateInsertValue(Res, Success, 1);
354
355 CI->replaceAllUsesWith(Res);
356 }
357
358 CI->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000359 return true;
360}
361
Tim Northover037f26f22014-04-17 18:22:47 +0000362AtomicOrdering AtomicExpandLoadLinked::insertLeadingFence(IRBuilder<> &Builder,
Tim Northoverc882eb02014-04-03 11:44:58 +0000363 AtomicOrdering Ord) {
Eric Christopherd9134482014-08-04 21:25:23 +0000364 if (!TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic())
Tim Northoverc882eb02014-04-03 11:44:58 +0000365 return Ord;
366
367 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
368 Builder.CreateFence(Release);
369
370 // The exclusive operations don't need any barrier if we're adding separate
371 // fences.
372 return Monotonic;
373}
374
Tim Northover037f26f22014-04-17 18:22:47 +0000375void AtomicExpandLoadLinked::insertTrailingFence(IRBuilder<> &Builder,
Tim Northoverc882eb02014-04-03 11:44:58 +0000376 AtomicOrdering Ord) {
Eric Christopherd9134482014-08-04 21:25:23 +0000377 if (!TM->getSubtargetImpl()->getTargetLowering()->getInsertFencesForAtomic())
Tim Northoverc882eb02014-04-03 11:44:58 +0000378 return;
379
380 if (Ord == Acquire || Ord == AcquireRelease)
381 Builder.CreateFence(Acquire);
382 else if (Ord == SequentiallyConsistent)
383 Builder.CreateFence(SequentiallyConsistent);
384}