blob: d0615aeca143a1c2ea9425d7862ab8bb4b2a5371 [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
Philip Reames61a24ab2015-12-16 00:49:36 +000011// target specific instruction which implement the same semantics in a way
12// which better fits the target backend. This can include the use of either
13// (intrinsic-based) load-linked/store-conditional loops, AtomicCmpXchg, or
14// type coercions.
Tim Northoverc882eb02014-04-03 11:44:58 +000015//
16//===----------------------------------------------------------------------===//
17
JF Bastiene8aad292015-08-03 15:29:47 +000018#include "llvm/CodeGen/AtomicExpandUtils.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000019#include "llvm/CodeGen/Passes.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
Robin Morisseted3d48f2014-09-03 21:29:59 +000022#include "llvm/IR/InstIterator.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000023#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
Eric Christopherc40e5ed2014-06-19 21:03:04 +000029#include "llvm/Target/TargetSubtargetInfo.h"
30
Tim Northoverc882eb02014-04-03 11:44:58 +000031using namespace llvm;
32
Robin Morisset59c23cd2014-08-21 21:50:01 +000033#define DEBUG_TYPE "atomic-expand"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000034
Tim Northoverc882eb02014-04-03 11:44:58 +000035namespace {
Robin Morisset59c23cd2014-08-21 21:50:01 +000036 class AtomicExpand: public FunctionPass {
Eric Christopherc40e5ed2014-06-19 21:03:04 +000037 const TargetMachine *TM;
Eric Christopherb11a1b72015-01-26 19:45:40 +000038 const TargetLowering *TLI;
Tim Northoverc882eb02014-04-03 11:44:58 +000039 public:
40 static char ID; // Pass identification, replacement for typeid
Robin Morisset59c23cd2014-08-21 21:50:01 +000041 explicit AtomicExpand(const TargetMachine *TM = nullptr)
Eric Christopherb11a1b72015-01-26 19:45:40 +000042 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Robin Morisset59c23cd2014-08-21 21:50:01 +000043 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
Tim Northover037f26f22014-04-17 18:22:47 +000044 }
Tim Northoverc882eb02014-04-03 11:44:58 +000045
46 bool runOnFunction(Function &F) override;
Tim Northoverc882eb02014-04-03 11:44:58 +000047
Robin Morisseted3d48f2014-09-03 21:29:59 +000048 private:
Robin Morissetdedef332014-09-23 20:31:14 +000049 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
50 bool IsStore, bool IsLoad);
Philip Reames61a24ab2015-12-16 00:49:36 +000051 IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
52 LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
Ahmed Bougacha52468672015-09-11 17:08:28 +000053 bool tryExpandAtomicLoad(LoadInst *LI);
Robin Morisset6dbbbc22014-09-23 20:59:25 +000054 bool expandAtomicLoadToLL(LoadInst *LI);
55 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
Philip Reames61a24ab2015-12-16 00:49:36 +000056 StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
Robin Morisseted3d48f2014-09-03 21:29:59 +000057 bool expandAtomicStore(StoreInst *SI);
JF Bastienf14889e2015-03-04 15:47:57 +000058 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
Tim Northoverf520eff2015-12-02 18:12:57 +000059 bool expandAtomicOpToLLSC(
60 Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
61 std::function<Value *(IRBuilder<> &, Value *)> PerformOp);
Tim Northoverc882eb02014-04-03 11:44:58 +000062 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
Robin Morisset810739d2014-09-25 17:27:43 +000063 bool isIdempotentRMW(AtomicRMWInst *AI);
64 bool simplifyIdempotentRMW(AtomicRMWInst *AI);
Tim Northoverc882eb02014-04-03 11:44:58 +000065 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000066}
Tim Northoverc882eb02014-04-03 11:44:58 +000067
Robin Morisset59c23cd2014-08-21 21:50:01 +000068char AtomicExpand::ID = 0;
69char &llvm::AtomicExpandID = AtomicExpand::ID;
70INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
71 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
Jiangning Liud623c522014-06-11 07:04:37 +000072 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +000073
Robin Morisset59c23cd2014-08-21 21:50:01 +000074FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
75 return new AtomicExpand(TM);
Tim Northover037f26f22014-04-17 18:22:47 +000076}
77
Robin Morisset59c23cd2014-08-21 21:50:01 +000078bool AtomicExpand::runOnFunction(Function &F) {
Eric Christopher4e048eeb2015-01-27 01:04:42 +000079 if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
Tim Northover037f26f22014-04-17 18:22:47 +000080 return false;
Eric Christopher4e048eeb2015-01-27 01:04:42 +000081 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Tim Northover037f26f22014-04-17 18:22:47 +000082
Tim Northoverc882eb02014-04-03 11:44:58 +000083 SmallVector<Instruction *, 1> AtomicInsts;
84
85 // Changing control-flow while iterating through it is a bad idea, so gather a
86 // list of all atomic instructions before we start.
Robin Morisseted3d48f2014-09-03 21:29:59 +000087 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
88 if (I->isAtomic())
89 AtomicInsts.push_back(&*I);
Tim Northoverc882eb02014-04-03 11:44:58 +000090 }
91
Robin Morisseted3d48f2014-09-03 21:29:59 +000092 bool MadeChange = false;
93 for (auto I : AtomicInsts) {
94 auto LI = dyn_cast<LoadInst>(I);
95 auto SI = dyn_cast<StoreInst>(I);
96 auto RMWI = dyn_cast<AtomicRMWInst>(I);
97 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
Robin Morisseted3d48f2014-09-03 21:29:59 +000098 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
99 "Unknown atomic instruction");
100
Robin Morissetdedef332014-09-23 20:31:14 +0000101 auto FenceOrdering = Monotonic;
102 bool IsStore, IsLoad;
Eric Christopherb11a1b72015-01-26 19:45:40 +0000103 if (TLI->getInsertFencesForAtomic()) {
Robin Morissetdedef332014-09-23 20:31:14 +0000104 if (LI && isAtLeastAcquire(LI->getOrdering())) {
105 FenceOrdering = LI->getOrdering();
106 LI->setOrdering(Monotonic);
107 IsStore = false;
108 IsLoad = true;
109 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
110 FenceOrdering = SI->getOrdering();
111 SI->setOrdering(Monotonic);
112 IsStore = true;
113 IsLoad = false;
114 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
115 isAtLeastAcquire(RMWI->getOrdering()))) {
116 FenceOrdering = RMWI->getOrdering();
117 RMWI->setOrdering(Monotonic);
118 IsStore = IsLoad = true;
Ahmed Bougacha52468672015-09-11 17:08:28 +0000119 } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
Eric Christopherb11a1b72015-01-26 19:45:40 +0000120 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
121 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
Robin Morissetdedef332014-09-23 20:31:14 +0000122 // If a compare and swap is lowered to LL/SC, we can do smarter fence
123 // insertion, with a stronger one on the success path than on the
124 // failure path. As a result, fence insertion is directly done by
125 // expandAtomicCmpXchg in that case.
126 FenceOrdering = CASI->getSuccessOrdering();
127 CASI->setSuccessOrdering(Monotonic);
128 CASI->setFailureOrdering(Monotonic);
129 IsStore = IsLoad = true;
130 }
131
132 if (FenceOrdering != Monotonic) {
133 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
134 }
135 }
136
Ahmed Bougacha52468672015-09-11 17:08:28 +0000137 if (LI) {
Philip Reames61a24ab2015-12-16 00:49:36 +0000138 if (LI->getType()->isFloatingPointTy()) {
139 // TODO: add a TLI hook to control this so that each target can
140 // convert to lowering the original type one at a time.
141 LI = convertAtomicLoadToIntegerType(LI);
142 assert(LI->getType()->isIntegerTy() && "invariant broken");
143 MadeChange = true;
144 }
145
Ahmed Bougacha52468672015-09-11 17:08:28 +0000146 MadeChange |= tryExpandAtomicLoad(LI);
Philip Reames61a24ab2015-12-16 00:49:36 +0000147 } else if (SI) {
148 if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
149 // TODO: add a TLI hook to control this so that each target can
150 // convert to lowering the original type one at a time.
151 SI = convertAtomicStoreToIntegerType(SI);
152 assert(SI->getValueOperand()->getType()->isIntegerTy() &&
153 "invariant broken");
154 MadeChange = true;
155 }
156
157 if (TLI->shouldExpandAtomicStoreInIR(SI))
158 MadeChange |= expandAtomicStore(SI);
Robin Morisset810739d2014-09-25 17:27:43 +0000159 } else if (RMWI) {
160 // There are two different ways of expanding RMW instructions:
161 // - into a load if it is idempotent
162 // - into a Cmpxchg/LL-SC loop otherwise
163 // we try them in that order.
JF Bastienf14889e2015-03-04 15:47:57 +0000164
165 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
166 MadeChange = true;
167 } else {
168 MadeChange |= tryExpandAtomicRMW(RMWI);
169 }
Ahmed Bougacha52468672015-09-11 17:08:28 +0000170 } else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI)) {
Robin Morisseted3d48f2014-09-03 21:29:59 +0000171 MadeChange |= expandAtomicCmpXchg(CASI);
172 }
173 }
Tim Northoverc882eb02014-04-03 11:44:58 +0000174 return MadeChange;
175}
176
Robin Morissetdedef332014-09-23 20:31:14 +0000177bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
178 bool IsStore, bool IsLoad) {
179 IRBuilder<> Builder(I);
180
Eric Christopherb11a1b72015-01-26 19:45:40 +0000181 auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000182
Eric Christopherb11a1b72015-01-26 19:45:40 +0000183 auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
Robin Morissetdedef332014-09-23 20:31:14 +0000184 // The trailing fence is emitted before the instruction instead of after
185 // because there is no easy way of setting Builder insertion point after
186 // an instruction. So we must erase it from the BB, and insert it back
187 // in the right place.
188 // We have a guard here because not every atomic operation generates a
189 // trailing fence.
190 if (TrailingFence) {
191 TrailingFence->removeFromParent();
192 TrailingFence->insertAfter(I);
193 }
194
195 return (LeadingFence || TrailingFence);
196}
197
Philip Reames61a24ab2015-12-16 00:49:36 +0000198/// Get the iX type with the same bitwidth as T.
199IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
200 const DataLayout &DL) {
201 EVT VT = TLI->getValueType(DL, T);
202 unsigned BitWidth = VT.getStoreSizeInBits();
203 assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
204 return IntegerType::get(T->getContext(), BitWidth);
205}
206
207/// Convert an atomic load of a non-integral type to an integer load of the
208/// equivelent bitwidth. See the function comment on
209/// convertAtomicStoreToIntegerType for background.
210LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
211 auto *M = LI->getModule();
212 Type *NewTy = getCorrespondingIntegerType(LI->getType(),
213 M->getDataLayout());
214
215 IRBuilder<> Builder(LI);
216
217 Value *Addr = LI->getPointerOperand();
218 Type *PT = PointerType::get(NewTy,
219 Addr->getType()->getPointerAddressSpace());
220 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
221
222 auto *NewLI = Builder.CreateLoad(NewAddr);
223 NewLI->setAlignment(LI->getAlignment());
224 NewLI->setVolatile(LI->isVolatile());
225 NewLI->setAtomic(LI->getOrdering(), LI->getSynchScope());
226 DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
227
228 Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
229 LI->replaceAllUsesWith(NewVal);
230 LI->eraseFromParent();
231 return NewLI;
232}
233
Ahmed Bougacha52468672015-09-11 17:08:28 +0000234bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
235 switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
236 case TargetLoweringBase::AtomicExpansionKind::None:
237 return false;
Tim Northoverf520eff2015-12-02 18:12:57 +0000238 case TargetLoweringBase::AtomicExpansionKind::LLSC:
239 return expandAtomicOpToLLSC(
240 LI, LI->getPointerOperand(), LI->getOrdering(),
241 [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
242 case TargetLoweringBase::AtomicExpansionKind::LLOnly:
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000243 return expandAtomicLoadToLL(LI);
Tim Northoverf520eff2015-12-02 18:12:57 +0000244 case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000245 return expandAtomicLoadToCmpXchg(LI);
Ahmed Bougacha52468672015-09-11 17:08:28 +0000246 }
Ahmed Bougacha52468672015-09-11 17:08:28 +0000247 llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000248}
249
250bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000251 IRBuilder<> Builder(LI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000252
Robin Morissetdedef332014-09-23 20:31:14 +0000253 // On some architectures, load-linked instructions are atomic for larger
254 // sizes than normal loads. For example, the only 64-bit load guaranteed
255 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
Robin Morisseta47cb412014-09-03 21:01:03 +0000256 Value *Val =
Robin Morissetdedef332014-09-23 20:31:14 +0000257 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
Tim Northoverf520eff2015-12-02 18:12:57 +0000258 TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000259
260 LI->replaceAllUsesWith(Val);
261 LI->eraseFromParent();
262
263 return true;
264}
265
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000266bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
267 IRBuilder<> Builder(LI);
268 AtomicOrdering Order = LI->getOrdering();
269 Value *Addr = LI->getPointerOperand();
270 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
271 Constant *DummyVal = Constant::getNullValue(Ty);
272
273 Value *Pair = Builder.CreateAtomicCmpXchg(
274 Addr, DummyVal, DummyVal, Order,
275 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
276 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
277
278 LI->replaceAllUsesWith(Loaded);
279 LI->eraseFromParent();
280
281 return true;
282}
283
Philip Reames61a24ab2015-12-16 00:49:36 +0000284/// Convert an atomic store of a non-integral type to an integer store of the
285/// equivelent bitwidth. We used to not support floating point or vector
286/// atomics in the IR at all. The backends learned to deal with the bitcast
287/// idiom because that was the only way of expressing the notion of a atomic
288/// float or vector store. The long term plan is to teach each backend to
289/// instruction select from the original atomic store, but as a migration
290/// mechanism, we convert back to the old format which the backends understand.
291/// Each backend will need individual work to recognize the new format.
292StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
293 IRBuilder<> Builder(SI);
294 auto *M = SI->getModule();
295 Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
296 M->getDataLayout());
297 Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
298
299 Value *Addr = SI->getPointerOperand();
300 Type *PT = PointerType::get(NewTy,
301 Addr->getType()->getPointerAddressSpace());
302 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
303
304 StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
305 NewSI->setAlignment(SI->getAlignment());
306 NewSI->setVolatile(SI->isVolatile());
307 NewSI->setAtomic(SI->getOrdering(), SI->getSynchScope());
308 DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
309 SI->eraseFromParent();
310 return NewSI;
311}
312
Robin Morisset59c23cd2014-08-21 21:50:01 +0000313bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
Robin Morisset25c8e312014-09-17 00:06:58 +0000314 // This function is only called on atomic stores that are too large to be
315 // atomic if implemented as a native store. So we replace them by an
316 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
317 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
JF Bastienf14889e2015-03-04 15:47:57 +0000318 // It is the responsibility of the target to only signal expansion via
Robin Morisset25c8e312014-09-17 00:06:58 +0000319 // shouldExpandAtomicRMW in cases where this is required and possible.
Tim Northoverc882eb02014-04-03 11:44:58 +0000320 IRBuilder<> Builder(SI);
321 AtomicRMWInst *AI =
322 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
323 SI->getValueOperand(), SI->getOrdering());
324 SI->eraseFromParent();
325
326 // Now we have an appropriate swap instruction, lower it as usual.
JF Bastienf14889e2015-03-04 15:47:57 +0000327 return tryExpandAtomicRMW(AI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000328}
329
JF Bastiene8aad292015-08-03 15:29:47 +0000330static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
331 Value *Loaded, Value *NewVal,
332 AtomicOrdering MemOpOrder,
333 Value *&Success, Value *&NewLoaded) {
334 Value* Pair = Builder.CreateAtomicCmpXchg(
335 Addr, Loaded, NewVal, MemOpOrder,
336 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
337 Success = Builder.CreateExtractValue(Pair, 1, "success");
338 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
339}
340
Robin Morisset25c8e312014-09-17 00:06:58 +0000341/// Emit IR to implement the given atomicrmw operation on values in registers,
342/// returning the new value.
343static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
344 Value *Loaded, Value *Inc) {
345 Value *NewVal;
346 switch (Op) {
347 case AtomicRMWInst::Xchg:
348 return Inc;
349 case AtomicRMWInst::Add:
350 return Builder.CreateAdd(Loaded, Inc, "new");
351 case AtomicRMWInst::Sub:
352 return Builder.CreateSub(Loaded, Inc, "new");
353 case AtomicRMWInst::And:
354 return Builder.CreateAnd(Loaded, Inc, "new");
355 case AtomicRMWInst::Nand:
356 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
357 case AtomicRMWInst::Or:
358 return Builder.CreateOr(Loaded, Inc, "new");
359 case AtomicRMWInst::Xor:
360 return Builder.CreateXor(Loaded, Inc, "new");
361 case AtomicRMWInst::Max:
362 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
363 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
364 case AtomicRMWInst::Min:
365 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
366 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
367 case AtomicRMWInst::UMax:
368 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
369 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
370 case AtomicRMWInst::UMin:
371 NewVal = Builder.CreateICmpULE(Loaded, Inc);
372 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
373 default:
374 llvm_unreachable("Unknown atomic op");
375 }
376}
377
Tim Northoverf520eff2015-12-02 18:12:57 +0000378bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
379 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
380 case TargetLoweringBase::AtomicExpansionKind::None:
381 return false;
382 case TargetLoweringBase::AtomicExpansionKind::LLSC:
383 return expandAtomicOpToLLSC(AI, AI->getPointerOperand(), AI->getOrdering(),
384 [&](IRBuilder<> &Builder, Value *Loaded) {
385 return performAtomicOp(AI->getOperation(),
386 Builder, Loaded,
387 AI->getValOperand());
388 });
389 case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
390 return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
391 default:
392 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
393 }
394}
395
396bool AtomicExpand::expandAtomicOpToLLSC(
397 Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
398 std::function<Value *(IRBuilder<> &, Value *)> PerformOp) {
399 BasicBlock *BB = I->getParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000400 Function *F = BB->getParent();
401 LLVMContext &Ctx = F->getContext();
402
403 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
404 //
405 // The standard expansion we produce is:
406 // [...]
407 // fence?
408 // atomicrmw.start:
409 // %loaded = @load.linked(%addr)
410 // %new = some_op iN %loaded, %incr
411 // %stored = @store_conditional(%new, %addr)
412 // %try_again = icmp i32 ne %stored, 0
413 // br i1 %try_again, label %loop, label %atomicrmw.end
414 // atomicrmw.end:
415 // fence?
416 // [...]
Tim Northoverf520eff2015-12-02 18:12:57 +0000417 BasicBlock *ExitBB = BB->splitBasicBlock(I->getIterator(), "atomicrmw.end");
Tim Northoverc882eb02014-04-03 11:44:58 +0000418 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
419
Tim Northoverf520eff2015-12-02 18:12:57 +0000420 // This grabs the DebugLoc from I.
421 IRBuilder<> Builder(I);
Tim Northoverc882eb02014-04-03 11:44:58 +0000422
423 // The split call above "helpfully" added a branch at the end of BB (to the
424 // wrong place), but we might want a fence too. It's easiest to just remove
425 // the branch entirely.
426 std::prev(BB->end())->eraseFromParent();
427 Builder.SetInsertPoint(BB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000428 Builder.CreateBr(LoopBB);
429
430 // Start the main loop block now that we've taken care of the preliminaries.
431 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000432 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000433
Tim Northoverf520eff2015-12-02 18:12:57 +0000434 Value *NewVal = PerformOp(Builder, Loaded);
Tim Northoverc882eb02014-04-03 11:44:58 +0000435
Eric Christopherd9134482014-08-04 21:25:23 +0000436 Value *StoreSuccess =
Robin Morisseta47cb412014-09-03 21:01:03 +0000437 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000438 Value *TryAgain = Builder.CreateICmpNE(
439 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
440 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
441
442 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northoverc882eb02014-04-03 11:44:58 +0000443
Tim Northoverf520eff2015-12-02 18:12:57 +0000444 I->replaceAllUsesWith(Loaded);
445 I->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000446
447 return true;
448}
449
Robin Morisset59c23cd2014-08-21 21:50:01 +0000450bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +0000451 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
452 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +0000453 Value *Addr = CI->getPointerOperand();
454 BasicBlock *BB = CI->getParent();
455 Function *F = BB->getParent();
456 LLVMContext &Ctx = F->getContext();
Robin Morisseted3d48f2014-09-03 21:29:59 +0000457 // If getInsertFencesForAtomic() returns true, then the target does not want
458 // to deal with memory orders, and emitLeading/TrailingFence should take care
459 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
460 // should preserve the ordering.
Robin Morisseta47cb412014-09-03 21:01:03 +0000461 AtomicOrdering MemOpOrder =
462 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
Tim Northoverc882eb02014-04-03 11:44:58 +0000463
464 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
465 //
Tim Northover70450c52014-04-03 13:06:54 +0000466 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +0000467 // [...]
468 // fence?
469 // cmpxchg.start:
470 // %loaded = @load.linked(%addr)
471 // %should_store = icmp eq %loaded, %desired
Tim Northover70450c52014-04-03 13:06:54 +0000472 // br i1 %should_store, label %cmpxchg.trystore,
Ahmed Bougacha07a844d2015-09-22 17:21:44 +0000473 // label %cmpxchg.nostore
Tim Northoverc882eb02014-04-03 11:44:58 +0000474 // cmpxchg.trystore:
475 // %stored = @store_conditional(%new, %addr)
Tim Northover20b9f732014-06-13 16:45:52 +0000476 // %success = icmp eq i32 %stored, 0
477 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
478 // cmpxchg.success:
479 // fence?
480 // br label %cmpxchg.end
Ahmed Bougacha07a844d2015-09-22 17:21:44 +0000481 // cmpxchg.nostore:
482 // @load_linked_fail_balance()?
483 // br label %cmpxchg.failure
Tim Northover20b9f732014-06-13 16:45:52 +0000484 // cmpxchg.failure:
Tim Northoverc882eb02014-04-03 11:44:58 +0000485 // fence?
Tim Northover70450c52014-04-03 13:06:54 +0000486 // br label %cmpxchg.end
487 // cmpxchg.end:
Tim Northover20b9f732014-06-13 16:45:52 +0000488 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
489 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
490 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
Tim Northoverc882eb02014-04-03 11:44:58 +0000491 // [...]
Duncan P. N. Exon Smith8f11e1a2015-10-09 16:54:49 +0000492 BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
Tim Northover20b9f732014-06-13 16:45:52 +0000493 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
Ahmed Bougacha07a844d2015-09-22 17:21:44 +0000494 auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
495 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
Tim Northover20b9f732014-06-13 16:45:52 +0000496 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
Tim Northover70450c52014-04-03 13:06:54 +0000497 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000498
499 // This grabs the DebugLoc from CI
500 IRBuilder<> Builder(CI);
501
502 // The split call above "helpfully" added a branch at the end of BB (to the
503 // wrong place), but we might want a fence too. It's easiest to just remove
504 // the branch entirely.
505 std::prev(BB->end())->eraseFromParent();
506 Builder.SetInsertPoint(BB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000507 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
508 /*IsLoad=*/true);
Tim Northoverc882eb02014-04-03 11:44:58 +0000509 Builder.CreateBr(LoopBB);
510
511 // Start the main loop block now that we've taken care of the preliminaries.
512 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000513 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000514 Value *ShouldStore =
515 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +0000516
Eric Christopher572e03a2015-06-19 01:53:21 +0000517 // If the cmpxchg doesn't actually need any ordering when it fails, we can
Tim Northover70450c52014-04-03 13:06:54 +0000518 // jump straight past that fence instruction (if it exists).
Ahmed Bougacha07a844d2015-09-22 17:21:44 +0000519 Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000520
521 Builder.SetInsertPoint(TryStoreBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000522 Value *StoreSuccess = TLI->emitStoreConditional(
523 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
Tim Northoverd039abd2014-06-13 16:45:36 +0000524 StoreSuccess = Builder.CreateICmpEQ(
Tim Northoverc882eb02014-04-03 11:44:58 +0000525 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northover20b9f732014-06-13 16:45:52 +0000526 Builder.CreateCondBr(StoreSuccess, SuccessBB,
527 CI->isWeak() ? FailureBB : LoopBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000528
Tim Northoverb4ddc082014-05-30 10:09:59 +0000529 // Make sure later instructions don't get reordered with a fence if necessary.
Tim Northover20b9f732014-06-13 16:45:52 +0000530 Builder.SetInsertPoint(SuccessBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000531 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
532 /*IsLoad=*/true);
Tim Northover70450c52014-04-03 13:06:54 +0000533 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +0000534
Ahmed Bougacha07a844d2015-09-22 17:21:44 +0000535 Builder.SetInsertPoint(NoStoreBB);
536 // In the failing case, where we don't execute the store-conditional, the
537 // target might want to balance out the load-linked with a dedicated
538 // instruction (e.g., on ARM, clearing the exclusive monitor).
539 TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
540 Builder.CreateBr(FailureBB);
541
Tim Northover20b9f732014-06-13 16:45:52 +0000542 Builder.SetInsertPoint(FailureBB);
Robin Morisseta47cb412014-09-03 21:01:03 +0000543 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
544 /*IsLoad=*/true);
Tim Northover20b9f732014-06-13 16:45:52 +0000545 Builder.CreateBr(ExitBB);
546
Tim Northoverb4ddc082014-05-30 10:09:59 +0000547 // Finally, we have control-flow based knowledge of whether the cmpxchg
548 // succeeded or not. We expose this to later passes by converting any
549 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
550
551 // Setup the builder so we can create any PHIs we need.
Tim Northover20b9f732014-06-13 16:45:52 +0000552 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Tim Northover420a2162014-06-13 14:24:07 +0000553 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
554 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
Tim Northover20b9f732014-06-13 16:45:52 +0000555 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000556
557 // Look for any users of the cmpxchg that are just comparing the loaded value
558 // against the desired one, and replace them with the CFG-derived version.
Tim Northover420a2162014-06-13 14:24:07 +0000559 SmallVector<ExtractValueInst *, 2> PrunedInsts;
Tim Northoverb4ddc082014-05-30 10:09:59 +0000560 for (auto User : CI->users()) {
Tim Northover420a2162014-06-13 14:24:07 +0000561 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
562 if (!EV)
Tim Northoverb4ddc082014-05-30 10:09:59 +0000563 continue;
564
Tim Northover420a2162014-06-13 14:24:07 +0000565 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
566 "weird extraction from { iN, i1 }");
Tim Northoverb4ddc082014-05-30 10:09:59 +0000567
Tim Northover420a2162014-06-13 14:24:07 +0000568 if (EV->getIndices()[0] == 0)
569 EV->replaceAllUsesWith(Loaded);
570 else
571 EV->replaceAllUsesWith(Success);
572
573 PrunedInsts.push_back(EV);
Tim Northoverb4ddc082014-05-30 10:09:59 +0000574 }
575
Tim Northover420a2162014-06-13 14:24:07 +0000576 // We can remove the instructions now we're no longer iterating through them.
577 for (auto EV : PrunedInsts)
578 EV->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000579
Tim Northover420a2162014-06-13 14:24:07 +0000580 if (!CI->use_empty()) {
581 // Some use of the full struct return that we don't understand has happened,
582 // so we've got to reconstruct it properly.
583 Value *Res;
584 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
585 Res = Builder.CreateInsertValue(Res, Success, 1);
586
587 CI->replaceAllUsesWith(Res);
588 }
589
590 CI->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +0000591 return true;
592}
Robin Morisset810739d2014-09-25 17:27:43 +0000593
594bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
595 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
596 if(!C)
597 return false;
598
599 AtomicRMWInst::BinOp Op = RMWI->getOperation();
600 switch(Op) {
601 case AtomicRMWInst::Add:
602 case AtomicRMWInst::Sub:
603 case AtomicRMWInst::Or:
604 case AtomicRMWInst::Xor:
605 return C->isZero();
606 case AtomicRMWInst::And:
607 return C->isMinusOne();
608 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
609 default:
610 return false;
611 }
612}
613
614bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
Ahmed Bougacha49b531a2015-09-12 18:51:23 +0000615 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
616 tryExpandAtomicLoad(ResultingLoad);
617 return true;
618 }
Robin Morisset810739d2014-09-25 17:27:43 +0000619 return false;
620}
JF Bastiene8aad292015-08-03 15:29:47 +0000621
622bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
623 CreateCmpXchgInstFun CreateCmpXchg) {
624 assert(AI);
625
626 AtomicOrdering MemOpOrder =
627 AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
628 Value *Addr = AI->getPointerOperand();
629 BasicBlock *BB = AI->getParent();
630 Function *F = BB->getParent();
631 LLVMContext &Ctx = F->getContext();
632
633 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
634 //
635 // The standard expansion we produce is:
636 // [...]
637 // %init_loaded = load atomic iN* %addr
638 // br label %loop
639 // loop:
640 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
641 // %new = some_op iN %loaded, %incr
642 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
643 // %new_loaded = extractvalue { iN, i1 } %pair, 0
644 // %success = extractvalue { iN, i1 } %pair, 1
645 // br i1 %success, label %atomicrmw.end, label %loop
646 // atomicrmw.end:
647 // [...]
Duncan P. N. Exon Smith8f11e1a2015-10-09 16:54:49 +0000648 BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
JF Bastiene8aad292015-08-03 15:29:47 +0000649 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
650
651 // This grabs the DebugLoc from AI.
652 IRBuilder<> Builder(AI);
653
654 // The split call above "helpfully" added a branch at the end of BB (to the
655 // wrong place), but we want a load. It's easiest to just remove
656 // the branch entirely.
657 std::prev(BB->end())->eraseFromParent();
658 Builder.SetInsertPoint(BB);
659 LoadInst *InitLoaded = Builder.CreateLoad(Addr);
660 // Atomics require at least natural alignment.
Richard Diamondbd753c92015-08-06 16:55:03 +0000661 InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits() / 8);
JF Bastiene8aad292015-08-03 15:29:47 +0000662 Builder.CreateBr(LoopBB);
663
664 // Start the main loop block now that we've taken care of the preliminaries.
665 Builder.SetInsertPoint(LoopBB);
666 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
667 Loaded->addIncoming(InitLoaded, BB);
668
669 Value *NewVal =
670 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
671
672 Value *NewLoaded = nullptr;
673 Value *Success = nullptr;
674
675 CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
676 Success, NewLoaded);
677 assert(Success && NewLoaded);
678
679 Loaded->addIncoming(NewLoaded, LoopBB);
680
681 Builder.CreateCondBr(Success, ExitBB, LoopBB);
682
683 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
684
685 AI->replaceAllUsesWith(NewLoaded);
686 AI->eraseFromParent();
687
688 return true;
689}