blob: 03b0ff32f15c3a9f61274a1e80bd631d400635ff [file] [log] [blame]
Robin Morisset59c23cd2014-08-21 21:50:01 +00001//===-- AtomicExpandPass.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
Richard Diamond7ef94562015-08-05 19:40:39 +000011// either (intrinsic-based) load-linked/store-conditional loops or
12// AtomicCmpXchg.
Tim Northoverc882eb02014-04-03 11:44:58 +000013//
14//===----------------------------------------------------------------------===//
15
JF Bastiene8aad292015-08-03 15:29:47 +000016#include "llvm/CodeGen/AtomicExpandUtils.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000017#include "llvm/CodeGen/Passes.h"
18#include "llvm/IR/Function.h"
19#include "llvm/IR/IRBuilder.h"
Robin Morisseted3d48f2014-09-03 21:29:59 +000020#include "llvm/IR/InstIterator.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000021#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Target/TargetLowering.h"
26#include "llvm/Target/TargetMachine.h"
Eric Christopherc40e5ed2014-06-19 21:03:04 +000027#include "llvm/Target/TargetSubtargetInfo.h"
28
Tim Northoverc882eb02014-04-03 11:44:58 +000029using namespace llvm;
30
Robin Morisset59c23cd2014-08-21 21:50:01 +000031#define DEBUG_TYPE "atomic-expand"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000032
Tim Northoverc882eb02014-04-03 11:44:58 +000033namespace {
Robin Morisset59c23cd2014-08-21 21:50:01 +000034 class AtomicExpand: public FunctionPass {
Eric Christopherc40e5ed2014-06-19 21:03:04 +000035 const TargetMachine *TM;
Eric Christopherb11a1b72015-01-26 19:45:40 +000036 const TargetLowering *TLI;
Tim Northoverc882eb02014-04-03 11:44:58 +000037 public:
38 static char ID; // Pass identification, replacement for typeid
Robin Morisset59c23cd2014-08-21 21:50:01 +000039 explicit AtomicExpand(const TargetMachine *TM = nullptr)
Eric Christopherb11a1b72015-01-26 19:45:40 +000040 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Robin Morisset59c23cd2014-08-21 21:50:01 +000041 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
Tim Northover037f26f22014-04-17 18:22:47 +000042 }
Tim Northoverc882eb02014-04-03 11:44:58 +000043
44 bool runOnFunction(Function &F) override;
Tim Northoverc882eb02014-04-03 11:44:58 +000045
Robin Morisseted3d48f2014-09-03 21:29:59 +000046 private:
Robin Morissetdedef332014-09-23 20:31:14 +000047 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
48 bool IsStore, bool IsLoad);
Tim Northoverc882eb02014-04-03 11:44:58 +000049 bool expandAtomicLoad(LoadInst *LI);
Robin Morisset6dbbbc22014-09-23 20:59:25 +000050 bool expandAtomicLoadToLL(LoadInst *LI);
51 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
Robin Morisseted3d48f2014-09-03 21:29:59 +000052 bool expandAtomicStore(StoreInst *SI);
JF Bastienf14889e2015-03-04 15:47:57 +000053 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
Robin Morisset25c8e312014-09-17 00:06:58 +000054 bool expandAtomicRMWToLLSC(AtomicRMWInst *AI);
Tim Northoverc882eb02014-04-03 11:44:58 +000055 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
Robin Morisset810739d2014-09-25 17:27:43 +000056 bool isIdempotentRMW(AtomicRMWInst *AI);
57 bool simplifyIdempotentRMW(AtomicRMWInst *AI);
Tim Northoverc882eb02014-04-03 11:44:58 +000058 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000059}
Tim Northoverc882eb02014-04-03 11:44:58 +000060
Robin Morisset59c23cd2014-08-21 21:50:01 +000061char AtomicExpand::ID = 0;
62char &llvm::AtomicExpandID = AtomicExpand::ID;
63INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
64 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
Jiangning Liud623c522014-06-11 07:04:37 +000065 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +000066
Robin Morisset59c23cd2014-08-21 21:50:01 +000067FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
68 return new AtomicExpand(TM);
Tim Northover037f26f22014-04-17 18:22:47 +000069}
70
Robin Morisset59c23cd2014-08-21 21:50:01 +000071bool AtomicExpand::runOnFunction(Function &F) {
Eric Christopher4e048eeb2015-01-27 01:04:42 +000072 if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
Tim Northover037f26f22014-04-17 18:22:47 +000073 return false;
Eric Christopher4e048eeb2015-01-27 01:04:42 +000074 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Tim Northover037f26f22014-04-17 18:22:47 +000075
Tim Northoverc882eb02014-04-03 11:44:58 +000076 SmallVector<Instruction *, 1> AtomicInsts;
77
78 // Changing control-flow while iterating through it is a bad idea, so gather a
79 // list of all atomic instructions before we start.
Robin Morisseted3d48f2014-09-03 21:29:59 +000080 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
81 if (I->isAtomic())
82 AtomicInsts.push_back(&*I);
Tim Northoverc882eb02014-04-03 11:44:58 +000083 }
84
Robin Morisseted3d48f2014-09-03 21:29:59 +000085 bool MadeChange = false;
86 for (auto I : AtomicInsts) {
87 auto LI = dyn_cast<LoadInst>(I);
88 auto SI = dyn_cast<StoreInst>(I);
89 auto RMWI = dyn_cast<AtomicRMWInst>(I);
90 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
Robin Morisseted3d48f2014-09-03 21:29:59 +000091 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
92 "Unknown atomic instruction");
93
Robin Morissetdedef332014-09-23 20:31:14 +000094 auto FenceOrdering = Monotonic;
95 bool IsStore, IsLoad;
Eric Christopherb11a1b72015-01-26 19:45:40 +000096 if (TLI->getInsertFencesForAtomic()) {
Robin Morissetdedef332014-09-23 20:31:14 +000097 if (LI && isAtLeastAcquire(LI->getOrdering())) {
98 FenceOrdering = LI->getOrdering();
99 LI->setOrdering(Monotonic);
100 IsStore = false;
101 IsLoad = true;
102 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
103 FenceOrdering = SI->getOrdering();
104 SI->setOrdering(Monotonic);
105 IsStore = true;
106 IsLoad = false;
107 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
108 isAtLeastAcquire(RMWI->getOrdering()))) {
109 FenceOrdering = RMWI->getOrdering();
110 RMWI->setOrdering(Monotonic);
111 IsStore = IsLoad = true;
Eric Christopherb11a1b72015-01-26 19:45:40 +0000112 } else if (CASI && !TLI->hasLoadLinkedStoreConditional() &&
113 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
114 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
Robin Morissetdedef332014-09-23 20:31:14 +0000115 // If a compare and swap is lowered to LL/SC, we can do smarter fence
116 // insertion, with a stronger one on the success path than on the
117 // failure path. As a result, fence insertion is directly done by
118 // expandAtomicCmpXchg in that case.
119 FenceOrdering = CASI->getSuccessOrdering();
120 CASI->setSuccessOrdering(Monotonic);
121 CASI->setFailureOrdering(Monotonic);
122 IsStore = IsLoad = true;
123 }
124
125 if (FenceOrdering != Monotonic) {
126 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
127 }
128 }
129
Eric Christopherb11a1b72015-01-26 19:45:40 +0000130 if (LI && TLI->shouldExpandAtomicLoadInIR(LI)) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000131 MadeChange |= expandAtomicLoad(LI);
Eric Christopherb11a1b72015-01-26 19:45:40 +0000132 } else if (SI && TLI->shouldExpandAtomicStoreInIR(SI)) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000133 MadeChange |= expandAtomicStore(SI);
Robin Morisset810739d2014-09-25 17:27:43 +0000134 } else if (RMWI) {
135 // There are two different ways of expanding RMW instructions:
136 // - into a load if it is idempotent
137 // - into a Cmpxchg/LL-SC loop otherwise
138 // we try them in that order.
JF Bastienf14889e2015-03-04 15:47:57 +0000139
140 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
141 MadeChange = true;
142 } else {
143 MadeChange |= tryExpandAtomicRMW(RMWI);
144 }
Eric Christopherb11a1b72015-01-26 19:45:40 +0000145 } else if (CASI && TLI->hasLoadLinkedStoreConditional()) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000146 MadeChange |= expandAtomicCmpXchg(CASI);
147 }
148 }
Tim Northoverc882eb02014-04-03 11:44:58 +0000149 return MadeChange;
150}
151
Robin Morissetdedef332014-09-23 20:31:14 +0000152bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
153 bool IsStore, bool IsLoad) {
154 IRBuilder<> Builder(I);
155
Eric Christopherb11a1b72015-01-26 19:45:40 +0000156 auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000157
Eric Christopherb11a1b72015-01-26 19:45:40 +0000158 auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000159 // The trailing fence is emitted before the instruction instead of after
160 // because there is no easy way of setting Builder insertion point after
161 // an instruction. So we must erase it from the BB, and insert it back
162 // in the right place.
163 // We have a guard here because not every atomic operation generates a
164 // trailing fence.
165 if (TrailingFence) {
166 TrailingFence->removeFromParent();
167 TrailingFence->insertAfter(I);
168 }
169
170 return (LeadingFence || TrailingFence);
171}
172
Robin Morisset59c23cd2014-08-21 21:50:01 +0000173bool AtomicExpand::expandAtomicLoad(LoadInst *LI) {
Eric Christopherb11a1b72015-01-26 19:45:40 +0000174 if (TLI->hasLoadLinkedStoreConditional())
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000175 return expandAtomicLoadToLL(LI);
176 else
177 return expandAtomicLoadToCmpXchg(LI);
178}
179
180bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000181 IRBuilder<> Builder(LI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000182
Robin Morissetdedef332014-09-23 20:31:14 +0000183 // On some architectures, load-linked instructions are atomic for larger
184 // sizes than normal loads. For example, the only 64-bit load guaranteed
185 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
Robin Morisseta47cb412014-09-03 21:01:03 +0000186 Value *Val =
Robin Morissetdedef332014-09-23 20:31:14 +0000187 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
Tim Northoverc882eb02014-04-03 11:44:58 +0000188
189 LI->replaceAllUsesWith(Val);
190 LI->eraseFromParent();
191
192 return true;
193}
194
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000195bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
196 IRBuilder<> Builder(LI);
197 AtomicOrdering Order = LI->getOrdering();
198 Value *Addr = LI->getPointerOperand();
199 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
200 Constant *DummyVal = Constant::getNullValue(Ty);
201
202 Value *Pair = Builder.CreateAtomicCmpXchg(
203 Addr, DummyVal, DummyVal, Order,
204 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
205 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
206
207 LI->replaceAllUsesWith(Loaded);
208 LI->eraseFromParent();
209
210 return true;
211}
212
Robin Morisset59c23cd2014-08-21 21:50:01 +0000213bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
Robin Morisset25c8e312014-09-17 00:06:58 +0000214 // This function is only called on atomic stores that are too large to be
215 // atomic if implemented as a native store. So we replace them by an
216 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
217 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
JF Bastienf14889e2015-03-04 15:47:57 +0000218 // It is the responsibility of the target to only signal expansion via
Robin Morisset25c8e312014-09-17 00:06:58 +0000219 // shouldExpandAtomicRMW in cases where this is required and possible.
Tim Northoverc882eb02014-04-03 11:44:58 +0000220 IRBuilder<> Builder(SI);
221 AtomicRMWInst *AI =
222 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
223 SI->getValueOperand(), SI->getOrdering());
224 SI->eraseFromParent();
225
226 // Now we have an appropriate swap instruction, lower it as usual.
JF Bastienf14889e2015-03-04 15:47:57 +0000227 return tryExpandAtomicRMW(AI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000228}
229
JF Bastiene8aad292015-08-03 15:29:47 +0000230static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
231 Value *Loaded, Value *NewVal,
232 AtomicOrdering MemOpOrder,
233 Value *&Success, Value *&NewLoaded) {
234 Value* Pair = Builder.CreateAtomicCmpXchg(
235 Addr, Loaded, NewVal, MemOpOrder,
236 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
237 Success = Builder.CreateExtractValue(Pair, 1, "success");
238 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
239}
240
JF Bastienf14889e2015-03-04 15:47:57 +0000241bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
242 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
243 case TargetLoweringBase::AtomicRMWExpansionKind::None:
244 return false;
245 case TargetLoweringBase::AtomicRMWExpansionKind::LLSC: {
246 assert(TLI->hasLoadLinkedStoreConditional() &&
247 "TargetLowering requested we expand AtomicRMW instruction into "
248 "load-linked/store-conditional combos, but such instructions aren't "
249 "supported");
250
Robin Morisset25c8e312014-09-17 00:06:58 +0000251 return expandAtomicRMWToLLSC(AI);
JF Bastienf14889e2015-03-04 15:47:57 +0000252 }
253 case TargetLoweringBase::AtomicRMWExpansionKind::CmpXChg: {
JF Bastiene8aad292015-08-03 15:29:47 +0000254 return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
JF Bastienf14889e2015-03-04 15:47:57 +0000255 }
256 }
257 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
Robin Morisset25c8e312014-09-17 00:06:58 +0000258}
259
260/// Emit IR to implement the given atomicrmw operation on values in registers,
261/// returning the new value.
262static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
263 Value *Loaded, Value *Inc) {
264 Value *NewVal;
265 switch (Op) {
266 case AtomicRMWInst::Xchg:
267 return Inc;
268 case AtomicRMWInst::Add:
269 return Builder.CreateAdd(Loaded, Inc, "new");
270 case AtomicRMWInst::Sub:
271 return Builder.CreateSub(Loaded, Inc, "new");
272 case AtomicRMWInst::And:
273 return Builder.CreateAnd(Loaded, Inc, "new");
274 case AtomicRMWInst::Nand:
275 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
276 case AtomicRMWInst::Or:
277 return Builder.CreateOr(Loaded, Inc, "new");
278 case AtomicRMWInst::Xor:
279 return Builder.CreateXor(Loaded, Inc, "new");
280 case AtomicRMWInst::Max:
281 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
282 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
283 case AtomicRMWInst::Min:
284 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
285 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
286 case AtomicRMWInst::UMax:
287 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
288 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
289 case AtomicRMWInst::UMin:
290 NewVal = Builder.CreateICmpULE(Loaded, Inc);
291 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
292 default:
293 llvm_unreachable("Unknown atomic op");
294 }
295}
296
297bool AtomicExpand::expandAtomicRMWToLLSC(AtomicRMWInst *AI) {
Robin Morissetdedef332014-09-23 20:31:14 +0000298 AtomicOrdering MemOpOrder = AI->getOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000299 Value *Addr = AI->getPointerOperand();
300 BasicBlock *BB = AI->getParent();
301 Function *F = BB->getParent();
302 LLVMContext &Ctx = F->getContext();
303
304 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
305 //
306 // The standard expansion we produce is:
307 // [...]
308 // fence?
309 // atomicrmw.start:
310 // %loaded = @load.linked(%addr)
311 // %new = some_op iN %loaded, %incr
312 // %stored = @store_conditional(%new, %addr)
313 // %try_again = icmp i32 ne %stored, 0
314 // br i1 %try_again, label %loop, label %atomicrmw.end
315 // atomicrmw.end:
316 // fence?
317 // [...]
318 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
319 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
320
321 // This grabs the DebugLoc from AI.
322 IRBuilder<> Builder(AI);
323
324 // The split call above "helpfully" added a branch at the end of BB (to the
325 // wrong place), but we might want a fence too. It's easiest to just remove
326 // the branch entirely.
327 std::prev(BB->end())->eraseFromParent();
328 Builder.SetInsertPoint(BB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000329 Builder.CreateBr(LoopBB);
330
331 // Start the main loop block now that we've taken care of the preliminaries.
332 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000333 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000334
Robin Morisset25c8e312014-09-17 00:06:58 +0000335 Value *NewVal =
336 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
Tim Northoverc882eb02014-04-03 11:44:58 +0000337
Eric Christopherd9134482014-08-04 21:25:23 +0000338 Value *StoreSuccess =
Robin Morisseta47cb412014-09-03 21:01:03 +0000339 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000340 Value *TryAgain = Builder.CreateICmpNE(
341 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
342 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
343
344 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northoverc882eb02014-04-03 11:44:58 +0000345
346 AI->replaceAllUsesWith(Loaded);
347 AI->eraseFromParent();
348
349 return true;
350}
351
Robin Morisset59c23cd2014-08-21 21:50:01 +0000352bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +0000353 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
354 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000355 Value *Addr = CI->getPointerOperand();
356 BasicBlock *BB = CI->getParent();
357 Function *F = BB->getParent();
358 LLVMContext &Ctx = F->getContext();
Robin Morisseted3d48f2014-09-03 21:29:59 +0000359 // If getInsertFencesForAtomic() returns true, then the target does not want
360 // to deal with memory orders, and emitLeading/TrailingFence should take care
361 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
362 // should preserve the ordering.
Robin Morisseta47cb412014-09-03 21:01:03 +0000363 AtomicOrdering MemOpOrder =
364 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
Tim Northoverc882eb02014-04-03 11:44:58 +0000365
366 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
367 //
Tim Northover70450c52014-04-03 13:06:54 +0000368 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +0000369 // [...]
370 // fence?
371 // cmpxchg.start:
372 // %loaded = @load.linked(%addr)
373 // %should_store = icmp eq %loaded, %desired
Tim Northover70450c52014-04-03 13:06:54 +0000374 // br i1 %should_store, label %cmpxchg.trystore,
Tim Northover20b9f732014-06-13 16:45:52 +0000375 // label %cmpxchg.failure
Tim Northoverc882eb02014-04-03 11:44:58 +0000376 // cmpxchg.trystore:
377 // %stored = @store_conditional(%new, %addr)
Tim Northover20b9f732014-06-13 16:45:52 +0000378 // %success = icmp eq i32 %stored, 0
379 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
380 // cmpxchg.success:
381 // fence?
382 // br label %cmpxchg.end
383 // cmpxchg.failure:
Tim Northoverc882eb02014-04-03 11:44:58 +0000384 // fence?
Tim Northover70450c52014-04-03 13:06:54 +0000385 // br label %cmpxchg.end
386 // cmpxchg.end:
Tim Northover20b9f732014-06-13 16:45:52 +0000387 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
388 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
389 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
Tim Northoverc882eb02014-04-03 11:44:58 +0000390 // [...]
391 BasicBlock *ExitBB = BB->splitBasicBlock(CI, "cmpxchg.end");
Tim Northover20b9f732014-06-13 16:45:52 +0000392 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
393 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, FailureBB);
394 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
Tim Northover70450c52014-04-03 13:06:54 +0000395 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000396
397 // This grabs the DebugLoc from CI
398 IRBuilder<> Builder(CI);
399
400 // The split call above "helpfully" added a branch at the end of BB (to the
401 // wrong place), but we might want a fence too. It's easiest to just remove
402 // the branch entirely.
403 std::prev(BB->end())->eraseFromParent();
404 Builder.SetInsertPoint(BB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000405 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
406 /*IsLoad=*/true);
Tim Northoverc882eb02014-04-03 11:44:58 +0000407 Builder.CreateBr(LoopBB);
408
409 // Start the main loop block now that we've taken care of the preliminaries.
410 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000411 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000412 Value *ShouldStore =
413 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +0000414
Eric Christopher572e03a2015-06-19 01:53:21 +0000415 // If the cmpxchg doesn't actually need any ordering when it fails, we can
Tim Northover70450c52014-04-03 13:06:54 +0000416 // jump straight past that fence instruction (if it exists).
Tim Northover70450c52014-04-03 13:06:54 +0000417 Builder.CreateCondBr(ShouldStore, TryStoreBB, FailureBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000418
419 Builder.SetInsertPoint(TryStoreBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000420 Value *StoreSuccess = TLI->emitStoreConditional(
421 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
Tim Northoverd039abd2014-06-13 16:45:36 +0000422 StoreSuccess = Builder.CreateICmpEQ(
Tim Northoverc882eb02014-04-03 11:44:58 +0000423 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northover20b9f732014-06-13 16:45:52 +0000424 Builder.CreateCondBr(StoreSuccess, SuccessBB,
425 CI->isWeak() ? FailureBB : LoopBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000426
Tim Northoverb4ddc082014-05-30 10:09:59 +0000427 // Make sure later instructions don't get reordered with a fence if necessary.
Tim Northover20b9f732014-06-13 16:45:52 +0000428 Builder.SetInsertPoint(SuccessBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000429 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
430 /*IsLoad=*/true);
Tim Northover70450c52014-04-03 13:06:54 +0000431 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000432
Tim Northover20b9f732014-06-13 16:45:52 +0000433 Builder.SetInsertPoint(FailureBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000434 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
435 /*IsLoad=*/true);
Tim Northover20b9f732014-06-13 16:45:52 +0000436 Builder.CreateBr(ExitBB);
437
Tim Northoverb4ddc082014-05-30 10:09:59 +0000438 // Finally, we have control-flow based knowledge of whether the cmpxchg
439 // succeeded or not. We expose this to later passes by converting any
440 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
441
442 // Setup the builder so we can create any PHIs we need.
Tim Northover20b9f732014-06-13 16:45:52 +0000443 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northover420a2162014-06-13 14:24:07 +0000444 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
445 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
Tim Northover20b9f732014-06-13 16:45:52 +0000446 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000447
448 // Look for any users of the cmpxchg that are just comparing the loaded value
449 // against the desired one, and replace them with the CFG-derived version.
Tim Northover420a2162014-06-13 14:24:07 +0000450 SmallVector<ExtractValueInst *, 2> PrunedInsts;
Tim Northoverb4ddc082014-05-30 10:09:59 +0000451 for (auto User : CI->users()) {
Tim Northover420a2162014-06-13 14:24:07 +0000452 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
453 if (!EV)
Tim Northoverb4ddc082014-05-30 10:09:59 +0000454 continue;
455
Tim Northover420a2162014-06-13 14:24:07 +0000456 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
457 "weird extraction from { iN, i1 }");
Tim Northoverb4ddc082014-05-30 10:09:59 +0000458
Tim Northover420a2162014-06-13 14:24:07 +0000459 if (EV->getIndices()[0] == 0)
460 EV->replaceAllUsesWith(Loaded);
461 else
462 EV->replaceAllUsesWith(Success);
463
464 PrunedInsts.push_back(EV);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000465 }
466
Tim Northover420a2162014-06-13 14:24:07 +0000467 // We can remove the instructions now we're no longer iterating through them.
468 for (auto EV : PrunedInsts)
469 EV->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000470
Tim Northover420a2162014-06-13 14:24:07 +0000471 if (!CI->use_empty()) {
472 // Some use of the full struct return that we don't understand has happened,
473 // so we've got to reconstruct it properly.
474 Value *Res;
475 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
476 Res = Builder.CreateInsertValue(Res, Success, 1);
477
478 CI->replaceAllUsesWith(Res);
479 }
480
481 CI->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000482 return true;
483}
Robin Morisset810739d2014-09-25 17:27:43 +0000484
485bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
486 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
487 if(!C)
488 return false;
489
490 AtomicRMWInst::BinOp Op = RMWI->getOperation();
491 switch(Op) {
492 case AtomicRMWInst::Add:
493 case AtomicRMWInst::Sub:
494 case AtomicRMWInst::Or:
495 case AtomicRMWInst::Xor:
496 return C->isZero();
497 case AtomicRMWInst::And:
498 return C->isMinusOne();
499 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
500 default:
501 return false;
502 }
503}
504
505bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
Robin Morisset810739d2014-09-25 17:27:43 +0000506 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
507 if (TLI->shouldExpandAtomicLoadInIR(ResultingLoad))
508 expandAtomicLoad(ResultingLoad);
509 return true;
510 }
Robin Morisset810739d2014-09-25 17:27:43 +0000511 return false;
512}
JF Bastiene8aad292015-08-03 15:29:47 +0000513
514bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
515 CreateCmpXchgInstFun CreateCmpXchg) {
516 assert(AI);
517
518 AtomicOrdering MemOpOrder =
519 AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
520 Value *Addr = AI->getPointerOperand();
521 BasicBlock *BB = AI->getParent();
522 Function *F = BB->getParent();
523 LLVMContext &Ctx = F->getContext();
524
525 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
526 //
527 // The standard expansion we produce is:
528 // [...]
529 // %init_loaded = load atomic iN* %addr
530 // br label %loop
531 // loop:
532 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
533 // %new = some_op iN %loaded, %incr
534 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
535 // %new_loaded = extractvalue { iN, i1 } %pair, 0
536 // %success = extractvalue { iN, i1 } %pair, 1
537 // br i1 %success, label %atomicrmw.end, label %loop
538 // atomicrmw.end:
539 // [...]
540 BasicBlock *ExitBB = BB->splitBasicBlock(AI, "atomicrmw.end");
541 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
542
543 // This grabs the DebugLoc from AI.
544 IRBuilder<> Builder(AI);
545
546 // The split call above "helpfully" added a branch at the end of BB (to the
547 // wrong place), but we want a load. It's easiest to just remove
548 // the branch entirely.
549 std::prev(BB->end())->eraseFromParent();
550 Builder.SetInsertPoint(BB);
551 LoadInst *InitLoaded = Builder.CreateLoad(Addr);
552 // Atomics require at least natural alignment.
553 InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits());
554 Builder.CreateBr(LoopBB);
555
556 // Start the main loop block now that we've taken care of the preliminaries.
557 Builder.SetInsertPoint(LoopBB);
558 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
559 Loaded->addIncoming(InitLoaded, BB);
560
561 Value *NewVal =
562 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
563
564 Value *NewLoaded = nullptr;
565 Value *Success = nullptr;
566
567 CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
568 Success, NewLoaded);
569 assert(Success && NewLoaded);
570
571 Loaded->addIncoming(NewLoaded, LoopBB);
572
573 Builder.CreateCondBr(Success, ExitBB, LoopBB);
574
575 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
576
577 AI->replaceAllUsesWith(NewLoaded);
578 AI->eraseFromParent();
579
580 return true;
581}