blob: 9bec110604d9b5c287376ea46b788c6297b1e11c [file] [log] [blame]
Eugene Zelenkof1933322017-09-22 23:46:57 +00001//===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
Tim Northoverc882eb02014-04-03 11:44:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northoverc882eb02014-04-03 11:44:58 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass (at IR level) to replace atomic instructions with
James Y Knight19f6cce2016-04-12 20:18:48 +000010// __atomic_* library calls, or target specific instruction which implement the
11// same semantics in a way which better fits the target backend. This can
12// include the use of (intrinsic-based) load-linked/store-conditional loops,
13// AtomicCmpXchg, or type coercions.
Tim Northoverc882eb02014-04-03 11:44:58 +000014//
15//===----------------------------------------------------------------------===//
16
Eugene Zelenkof1933322017-09-22 23:46:57 +000017#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
JF Bastiene8aad292015-08-03 15:29:47 +000020#include "llvm/CodeGen/AtomicExpandUtils.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000021#include "llvm/CodeGen/RuntimeLibcalls.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000022#include "llvm/CodeGen/TargetLowering.h"
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000023#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000024#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000025#include "llvm/CodeGen/ValueTypes.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000026#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/Constant.h"
29#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
Robin Morisseted3d48f2014-09-03 21:29:59 +000034#include "llvm/IR/InstIterator.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000035#include "llvm/IR/Instruction.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000036#include "llvm/IR/Instructions.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000037#include "llvm/IR/Module.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000038#include "llvm/IR/Type.h"
39#include "llvm/IR/User.h"
40#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080041#include "llvm/InitializePasses.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000042#include "llvm/Pass.h"
43#include "llvm/Support/AtomicOrdering.h"
44#include "llvm/Support/Casting.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000045#include "llvm/Support/Debug.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000046#include "llvm/Support/ErrorHandling.h"
Philip Reames23319012015-12-16 01:24:05 +000047#include "llvm/Support/raw_ostream.h"
Tim Northoverc882eb02014-04-03 11:44:58 +000048#include "llvm/Target/TargetMachine.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000049#include <cassert>
50#include <cstdint>
51#include <iterator>
Eric Christopherc40e5ed2014-06-19 21:03:04 +000052
Tim Northoverc882eb02014-04-03 11:44:58 +000053using namespace llvm;
54
Robin Morisset59c23cd2014-08-21 21:50:01 +000055#define DEBUG_TYPE "atomic-expand"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000056
Tim Northoverc882eb02014-04-03 11:44:58 +000057namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000058
Robin Morisset59c23cd2014-08-21 21:50:01 +000059 class AtomicExpand: public FunctionPass {
Eugene Zelenkof1933322017-09-22 23:46:57 +000060 const TargetLowering *TLI = nullptr;
61
Tim Northoverc882eb02014-04-03 11:44:58 +000062 public:
63 static char ID; // Pass identification, replacement for typeid
Eugene Zelenkof1933322017-09-22 23:46:57 +000064
65 AtomicExpand() : FunctionPass(ID) {
Robin Morisset59c23cd2014-08-21 21:50:01 +000066 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
Tim Northover037f26f22014-04-17 18:22:47 +000067 }
Tim Northoverc882eb02014-04-03 11:44:58 +000068
69 bool runOnFunction(Function &F) override;
Tim Northoverc882eb02014-04-03 11:44:58 +000070
Robin Morisseted3d48f2014-09-03 21:29:59 +000071 private:
Tim Shen04de70d2017-05-09 15:27:17 +000072 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
Philip Reames61a24ab2015-12-16 00:49:36 +000073 IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
74 LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
Ahmed Bougacha52468672015-09-11 17:08:28 +000075 bool tryExpandAtomicLoad(LoadInst *LI);
Robin Morisset6dbbbc22014-09-23 20:59:25 +000076 bool expandAtomicLoadToLL(LoadInst *LI);
77 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
Philip Reames61a24ab2015-12-16 00:49:36 +000078 StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
Robin Morisseted3d48f2014-09-03 21:29:59 +000079 bool expandAtomicStore(StoreInst *SI);
JF Bastienf14889e2015-03-04 15:47:57 +000080 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
James Y Knight148a6462016-06-17 18:11:48 +000081 Value *
82 insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
83 AtomicOrdering MemOpOrder,
84 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
85 void expandAtomicOpToLLSC(
86 Instruction *I, Type *ResultTy, Value *Addr, AtomicOrdering MemOpOrder,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +000087 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
James Y Knight148a6462016-06-17 18:11:48 +000088 void expandPartwordAtomicRMW(
89 AtomicRMWInst *I,
90 TargetLoweringBase::AtomicExpansionKind ExpansionKind);
Alex Bradbury3291f9a2018-08-17 14:03:37 +000091 AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
James Y Knight148a6462016-06-17 18:11:48 +000092 void expandPartwordCmpXchg(AtomicCmpXchgInst *I);
Alex Bradbury21aea512018-09-19 10:54:22 +000093 void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
Alex Bradbury66d9a752018-11-29 20:43:42 +000094 void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
James Y Knight148a6462016-06-17 18:11:48 +000095
Philip Reames1960cfd2016-02-19 00:06:41 +000096 AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
James Y Knight148a6462016-06-17 18:11:48 +000097 static Value *insertRMWCmpXchgLoop(
98 IRBuilder<> &Builder, Type *ResultType, Value *Addr,
99 AtomicOrdering MemOpOrder,
100 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
101 CreateCmpXchgInstFun CreateCmpXchg);
Alex Bradbury79518b02018-09-19 14:51:42 +0000102 bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
James Y Knight148a6462016-06-17 18:11:48 +0000103
Tim Northoverc882eb02014-04-03 11:44:58 +0000104 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000105 bool isIdempotentRMW(AtomicRMWInst *RMWI);
106 bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
James Y Knight19f6cce2016-04-12 20:18:48 +0000107
108 bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, unsigned Align,
109 Value *PointerOperand, Value *ValueOperand,
110 Value *CASExpected, AtomicOrdering Ordering,
111 AtomicOrdering Ordering2,
112 ArrayRef<RTLIB::Libcall> Libcalls);
113 void expandAtomicLoadToLibcall(LoadInst *LI);
114 void expandAtomicStoreToLibcall(StoreInst *LI);
115 void expandAtomicRMWToLibcall(AtomicRMWInst *I);
116 void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
James Y Knight148a6462016-06-17 18:11:48 +0000117
118 friend bool
119 llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
120 CreateCmpXchgInstFun CreateCmpXchg);
Tim Northoverc882eb02014-04-03 11:44:58 +0000121 };
Eugene Zelenkof1933322017-09-22 23:46:57 +0000122
123} // end anonymous namespace
Tim Northoverc882eb02014-04-03 11:44:58 +0000124
Robin Morisset59c23cd2014-08-21 21:50:01 +0000125char AtomicExpand::ID = 0;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000126
Robin Morisset59c23cd2014-08-21 21:50:01 +0000127char &llvm::AtomicExpandID = AtomicExpand::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000128
Matthias Braun1527baa2017-05-25 21:26:32 +0000129INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions",
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000130 false, false)
Tim Northover037f26f22014-04-17 18:22:47 +0000131
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000132FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
Tim Northover037f26f22014-04-17 18:22:47 +0000133
James Y Knight19f6cce2016-04-12 20:18:48 +0000134// Helper functions to retrieve the size of atomic instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000135static unsigned getAtomicOpSize(LoadInst *LI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000136 const DataLayout &DL = LI->getModule()->getDataLayout();
137 return DL.getTypeStoreSize(LI->getType());
138}
139
Eugene Zelenkof1933322017-09-22 23:46:57 +0000140static unsigned getAtomicOpSize(StoreInst *SI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000141 const DataLayout &DL = SI->getModule()->getDataLayout();
142 return DL.getTypeStoreSize(SI->getValueOperand()->getType());
143}
144
Eugene Zelenkof1933322017-09-22 23:46:57 +0000145static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000146 const DataLayout &DL = RMWI->getModule()->getDataLayout();
147 return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
148}
149
Eugene Zelenkof1933322017-09-22 23:46:57 +0000150static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000151 const DataLayout &DL = CASI->getModule()->getDataLayout();
152 return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
153}
154
155// Helper functions to retrieve the alignment of atomic instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000156static unsigned getAtomicOpAlign(LoadInst *LI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000157 unsigned Align = LI->getAlignment();
158 // In the future, if this IR restriction is relaxed, we should
159 // return DataLayout::getABITypeAlignment when there's no align
160 // value.
161 assert(Align != 0 && "An atomic LoadInst always has an explicit alignment");
162 return Align;
163}
164
Eugene Zelenkof1933322017-09-22 23:46:57 +0000165static unsigned getAtomicOpAlign(StoreInst *SI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000166 unsigned Align = SI->getAlignment();
167 // In the future, if this IR restriction is relaxed, we should
168 // return DataLayout::getABITypeAlignment when there's no align
169 // value.
170 assert(Align != 0 && "An atomic StoreInst always has an explicit alignment");
171 return Align;
172}
173
Eugene Zelenkof1933322017-09-22 23:46:57 +0000174static unsigned getAtomicOpAlign(AtomicRMWInst *RMWI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000175 // TODO(PR27168): This instruction has no alignment attribute, but unlike the
176 // default alignment for load/store, the default here is to assume
177 // it has NATURAL alignment, not DataLayout-specified alignment.
178 const DataLayout &DL = RMWI->getModule()->getDataLayout();
179 return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
180}
181
Eugene Zelenkof1933322017-09-22 23:46:57 +0000182static unsigned getAtomicOpAlign(AtomicCmpXchgInst *CASI) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000183 // TODO(PR27168): same comment as above.
184 const DataLayout &DL = CASI->getModule()->getDataLayout();
185 return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
186}
187
188// Determine if a particular atomic operation has a supported size,
189// and is of appropriate alignment, to be passed through for target
190// lowering. (Versus turning into a __atomic libcall)
191template <typename Inst>
Eugene Zelenkof1933322017-09-22 23:46:57 +0000192static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
James Y Knight19f6cce2016-04-12 20:18:48 +0000193 unsigned Size = getAtomicOpSize(I);
194 unsigned Align = getAtomicOpAlign(I);
195 return Align >= Size && Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
196}
197
Robin Morisset59c23cd2014-08-21 21:50:01 +0000198bool AtomicExpand::runOnFunction(Function &F) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000199 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
200 if (!TPC)
Tim Northover037f26f22014-04-17 18:22:47 +0000201 return false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000202
203 auto &TM = TPC->getTM<TargetMachine>();
204 if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
205 return false;
206 TLI = TM.getSubtargetImpl(F)->getTargetLowering();
Tim Northover037f26f22014-04-17 18:22:47 +0000207
Tim Northoverc882eb02014-04-03 11:44:58 +0000208 SmallVector<Instruction *, 1> AtomicInsts;
209
210 // Changing control-flow while iterating through it is a bad idea, so gather a
211 // list of all atomic instructions before we start.
James Y Knight01f2ca52016-03-28 15:05:30 +0000212 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
213 Instruction *I = &*II;
214 if (I->isAtomic() && !isa<FenceInst>(I))
215 AtomicInsts.push_back(I);
Tim Northoverc882eb02014-04-03 11:44:58 +0000216 }
217
Robin Morisseted3d48f2014-09-03 21:29:59 +0000218 bool MadeChange = false;
219 for (auto I : AtomicInsts) {
220 auto LI = dyn_cast<LoadInst>(I);
221 auto SI = dyn_cast<StoreInst>(I);
222 auto RMWI = dyn_cast<AtomicRMWInst>(I);
223 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
James Y Knight01f2ca52016-03-28 15:05:30 +0000224 assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
Robin Morisseted3d48f2014-09-03 21:29:59 +0000225
James Y Knight19f6cce2016-04-12 20:18:48 +0000226 // If the Size/Alignment is not supported, replace with a libcall.
227 if (LI) {
228 if (!atomicSizeSupported(TLI, LI)) {
229 expandAtomicLoadToLibcall(LI);
230 MadeChange = true;
231 continue;
232 }
233 } else if (SI) {
234 if (!atomicSizeSupported(TLI, SI)) {
235 expandAtomicStoreToLibcall(SI);
236 MadeChange = true;
237 continue;
238 }
239 } else if (RMWI) {
240 if (!atomicSizeSupported(TLI, RMWI)) {
241 expandAtomicRMWToLibcall(RMWI);
242 MadeChange = true;
243 continue;
244 }
245 } else if (CASI) {
246 if (!atomicSizeSupported(TLI, CASI)) {
247 expandAtomicCASToLibcall(CASI);
248 MadeChange = true;
249 continue;
250 }
251 }
252
James Y Knightf44fc522016-03-16 22:12:04 +0000253 if (TLI->shouldInsertFencesForAtomic(I)) {
JF Bastien800f87a2016-04-06 21:19:33 +0000254 auto FenceOrdering = AtomicOrdering::Monotonic;
JF Bastien800f87a2016-04-06 21:19:33 +0000255 if (LI && isAcquireOrStronger(LI->getOrdering())) {
Robin Morissetdedef332014-09-23 20:31:14 +0000256 FenceOrdering = LI->getOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +0000257 LI->setOrdering(AtomicOrdering::Monotonic);
JF Bastien800f87a2016-04-06 21:19:33 +0000258 } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
Robin Morissetdedef332014-09-23 20:31:14 +0000259 FenceOrdering = SI->getOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +0000260 SI->setOrdering(AtomicOrdering::Monotonic);
JF Bastien800f87a2016-04-06 21:19:33 +0000261 } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
262 isAcquireOrStronger(RMWI->getOrdering()))) {
Robin Morissetdedef332014-09-23 20:31:14 +0000263 FenceOrdering = RMWI->getOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +0000264 RMWI->setOrdering(AtomicOrdering::Monotonic);
Alex Bradbury79518b02018-09-19 14:51:42 +0000265 } else if (CASI &&
266 TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
267 TargetLoweringBase::AtomicExpansionKind::None &&
JF Bastien800f87a2016-04-06 21:19:33 +0000268 (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
269 isAcquireOrStronger(CASI->getSuccessOrdering()))) {
Robin Morissetdedef332014-09-23 20:31:14 +0000270 // If a compare and swap is lowered to LL/SC, we can do smarter fence
271 // insertion, with a stronger one on the success path than on the
272 // failure path. As a result, fence insertion is directly done by
273 // expandAtomicCmpXchg in that case.
274 FenceOrdering = CASI->getSuccessOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +0000275 CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
276 CASI->setFailureOrdering(AtomicOrdering::Monotonic);
Robin Morissetdedef332014-09-23 20:31:14 +0000277 }
278
JF Bastien800f87a2016-04-06 21:19:33 +0000279 if (FenceOrdering != AtomicOrdering::Monotonic) {
Tim Shen04de70d2017-05-09 15:27:17 +0000280 MadeChange |= bracketInstWithFences(I, FenceOrdering);
Robin Morissetdedef332014-09-23 20:31:14 +0000281 }
282 }
283
Ahmed Bougacha52468672015-09-11 17:08:28 +0000284 if (LI) {
Philip Reames61a24ab2015-12-16 00:49:36 +0000285 if (LI->getType()->isFloatingPointTy()) {
286 // TODO: add a TLI hook to control this so that each target can
287 // convert to lowering the original type one at a time.
288 LI = convertAtomicLoadToIntegerType(LI);
289 assert(LI->getType()->isIntegerTy() && "invariant broken");
290 MadeChange = true;
291 }
James Y Knight19f6cce2016-04-12 20:18:48 +0000292
Ahmed Bougacha52468672015-09-11 17:08:28 +0000293 MadeChange |= tryExpandAtomicLoad(LI);
Philip Reames61a24ab2015-12-16 00:49:36 +0000294 } else if (SI) {
295 if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
296 // TODO: add a TLI hook to control this so that each target can
297 // convert to lowering the original type one at a time.
298 SI = convertAtomicStoreToIntegerType(SI);
299 assert(SI->getValueOperand()->getType()->isIntegerTy() &&
300 "invariant broken");
301 MadeChange = true;
302 }
303
304 if (TLI->shouldExpandAtomicStoreInIR(SI))
305 MadeChange |= expandAtomicStore(SI);
Robin Morisset810739d2014-09-25 17:27:43 +0000306 } else if (RMWI) {
307 // There are two different ways of expanding RMW instructions:
308 // - into a load if it is idempotent
309 // - into a Cmpxchg/LL-SC loop otherwise
310 // we try them in that order.
JF Bastienf14889e2015-03-04 15:47:57 +0000311
312 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
313 MadeChange = true;
314 } else {
Alex Bradbury3291f9a2018-08-17 14:03:37 +0000315 unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
316 unsigned ValueSize = getAtomicOpSize(RMWI);
317 AtomicRMWInst::BinOp Op = RMWI->getOperation();
318 if (ValueSize < MinCASSize &&
319 (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
320 Op == AtomicRMWInst::And)) {
321 RMWI = widenPartwordAtomicRMW(RMWI);
322 MadeChange = true;
323 }
324
JF Bastienf14889e2015-03-04 15:47:57 +0000325 MadeChange |= tryExpandAtomicRMW(RMWI);
326 }
Philip Reames1960cfd2016-02-19 00:06:41 +0000327 } else if (CASI) {
328 // TODO: when we're ready to make the change at the IR level, we can
329 // extend convertCmpXchgToInteger for floating point too.
330 assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
331 "unimplemented - floating point not legal at IR level");
332 if (CASI->getCompareOperand()->getType()->isPointerTy() ) {
333 // TODO: add a TLI hook to control this so that each target can
334 // convert to lowering the original type one at a time.
335 CASI = convertCmpXchgToIntegerType(CASI);
336 assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
337 "invariant broken");
338 MadeChange = true;
339 }
James Y Knight148a6462016-06-17 18:11:48 +0000340
Alex Bradbury79518b02018-09-19 14:51:42 +0000341 MadeChange |= tryExpandAtomicCmpXchg(CASI);
Robin Morisseted3d48f2014-09-03 21:29:59 +0000342 }
343 }
Tim Northoverc882eb02014-04-03 11:44:58 +0000344 return MadeChange;
345}
346
Tim Shen04de70d2017-05-09 15:27:17 +0000347bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
Robin Morissetdedef332014-09-23 20:31:14 +0000348 IRBuilder<> Builder(I);
349
Tim Shen04de70d2017-05-09 15:27:17 +0000350 auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
Robin Morissetdedef332014-09-23 20:31:14 +0000351
Tim Shen04de70d2017-05-09 15:27:17 +0000352 auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
Robin Morissetdedef332014-09-23 20:31:14 +0000353 // We have a guard here because not every atomic operation generates a
354 // trailing fence.
Sanjay Patel674d2c22017-08-29 14:07:48 +0000355 if (TrailingFence)
356 TrailingFence->moveAfter(I);
Robin Morissetdedef332014-09-23 20:31:14 +0000357
358 return (LeadingFence || TrailingFence);
359}
360
Philip Reames61a24ab2015-12-16 00:49:36 +0000361/// Get the iX type with the same bitwidth as T.
362IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
363 const DataLayout &DL) {
Tim Northoveree2474d2019-05-01 12:37:30 +0000364 EVT VT = TLI->getMemValueType(DL, T);
Philip Reames61a24ab2015-12-16 00:49:36 +0000365 unsigned BitWidth = VT.getStoreSizeInBits();
366 assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
367 return IntegerType::get(T->getContext(), BitWidth);
368}
369
370/// Convert an atomic load of a non-integral type to an integer load of the
Philip Reames1960cfd2016-02-19 00:06:41 +0000371/// equivalent bitwidth. See the function comment on
Fangrui Songf78650a2018-07-30 19:41:25 +0000372/// convertAtomicStoreToIntegerType for background.
Philip Reames61a24ab2015-12-16 00:49:36 +0000373LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
374 auto *M = LI->getModule();
375 Type *NewTy = getCorrespondingIntegerType(LI->getType(),
376 M->getDataLayout());
377
378 IRBuilder<> Builder(LI);
Fangrui Songf78650a2018-07-30 19:41:25 +0000379
Philip Reames61a24ab2015-12-16 00:49:36 +0000380 Value *Addr = LI->getPointerOperand();
381 Type *PT = PointerType::get(NewTy,
382 Addr->getType()->getPointerAddressSpace());
383 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
Fangrui Songf78650a2018-07-30 19:41:25 +0000384
James Y Knight14359ef2019-02-01 20:44:24 +0000385 auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
Eli Friedman3f13ee82020-04-06 17:29:25 -0700386 NewLI->setAlignment(LI->getAlign());
Philip Reames61a24ab2015-12-16 00:49:36 +0000387 NewLI->setVolatile(LI->isVolatile());
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000388 NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000389 LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
390
Philip Reames61a24ab2015-12-16 00:49:36 +0000391 Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
392 LI->replaceAllUsesWith(NewVal);
393 LI->eraseFromParent();
394 return NewLI;
395}
396
Ahmed Bougacha52468672015-09-11 17:08:28 +0000397bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
398 switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
399 case TargetLoweringBase::AtomicExpansionKind::None:
400 return false;
Tim Northoverf520eff2015-12-02 18:12:57 +0000401 case TargetLoweringBase::AtomicExpansionKind::LLSC:
James Y Knight148a6462016-06-17 18:11:48 +0000402 expandAtomicOpToLLSC(
403 LI, LI->getType(), LI->getPointerOperand(), LI->getOrdering(),
Tim Northoverf520eff2015-12-02 18:12:57 +0000404 [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
James Y Knight148a6462016-06-17 18:11:48 +0000405 return true;
Tim Northoverf520eff2015-12-02 18:12:57 +0000406 case TargetLoweringBase::AtomicExpansionKind::LLOnly:
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000407 return expandAtomicLoadToLL(LI);
Tim Northoverf520eff2015-12-02 18:12:57 +0000408 case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000409 return expandAtomicLoadToCmpXchg(LI);
Alex Bradbury21aea512018-09-19 10:54:22 +0000410 default:
411 llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
Ahmed Bougacha52468672015-09-11 17:08:28 +0000412 }
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000413}
414
415bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
Tim Northoverc882eb02014-04-03 11:44:58 +0000416 IRBuilder<> Builder(LI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000417
Robin Morissetdedef332014-09-23 20:31:14 +0000418 // On some architectures, load-linked instructions are atomic for larger
419 // sizes than normal loads. For example, the only 64-bit load guaranteed
420 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
Robin Morisseta47cb412014-09-03 21:01:03 +0000421 Value *Val =
Robin Morissetdedef332014-09-23 20:31:14 +0000422 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
Tim Northoverf520eff2015-12-02 18:12:57 +0000423 TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
Tim Northoverc882eb02014-04-03 11:44:58 +0000424
425 LI->replaceAllUsesWith(Val);
426 LI->eraseFromParent();
427
428 return true;
429}
430
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000431bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
432 IRBuilder<> Builder(LI);
433 AtomicOrdering Order = LI->getOrdering();
Philip Reames2153c4b2019-03-19 17:20:49 +0000434 if (Order == AtomicOrdering::Unordered)
435 Order = AtomicOrdering::Monotonic;
436
Robin Morisset6dbbbc22014-09-23 20:59:25 +0000437 Value *Addr = LI->getPointerOperand();
438 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
439 Constant *DummyVal = Constant::getNullValue(Ty);
440
441 Value *Pair = Builder.CreateAtomicCmpXchg(
442 Addr, DummyVal, DummyVal, Order,
443 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
444 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
445
446 LI->replaceAllUsesWith(Loaded);
447 LI->eraseFromParent();
448
449 return true;
450}
451
Philip Reames61a24ab2015-12-16 00:49:36 +0000452/// Convert an atomic store of a non-integral type to an integer store of the
Philip Reames1960cfd2016-02-19 00:06:41 +0000453/// equivalent bitwidth. We used to not support floating point or vector
Philip Reames61a24ab2015-12-16 00:49:36 +0000454/// atomics in the IR at all. The backends learned to deal with the bitcast
455/// idiom because that was the only way of expressing the notion of a atomic
456/// float or vector store. The long term plan is to teach each backend to
457/// instruction select from the original atomic store, but as a migration
458/// mechanism, we convert back to the old format which the backends understand.
459/// Each backend will need individual work to recognize the new format.
460StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
461 IRBuilder<> Builder(SI);
462 auto *M = SI->getModule();
463 Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
464 M->getDataLayout());
465 Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
Fangrui Songf78650a2018-07-30 19:41:25 +0000466
Philip Reames61a24ab2015-12-16 00:49:36 +0000467 Value *Addr = SI->getPointerOperand();
468 Type *PT = PointerType::get(NewTy,
469 Addr->getType()->getPointerAddressSpace());
470 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
471
472 StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
Eli Friedman3f13ee82020-04-06 17:29:25 -0700473 NewSI->setAlignment(SI->getAlign());
Philip Reames61a24ab2015-12-16 00:49:36 +0000474 NewSI->setVolatile(SI->isVolatile());
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000475 NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000476 LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
Philip Reames61a24ab2015-12-16 00:49:36 +0000477 SI->eraseFromParent();
478 return NewSI;
479}
480
Robin Morisset59c23cd2014-08-21 21:50:01 +0000481bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
Robin Morisset25c8e312014-09-17 00:06:58 +0000482 // This function is only called on atomic stores that are too large to be
483 // atomic if implemented as a native store. So we replace them by an
484 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
485 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
JF Bastienf14889e2015-03-04 15:47:57 +0000486 // It is the responsibility of the target to only signal expansion via
Robin Morisset25c8e312014-09-17 00:06:58 +0000487 // shouldExpandAtomicRMW in cases where this is required and possible.
Tim Northoverc882eb02014-04-03 11:44:58 +0000488 IRBuilder<> Builder(SI);
489 AtomicRMWInst *AI =
490 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
491 SI->getValueOperand(), SI->getOrdering());
492 SI->eraseFromParent();
493
494 // Now we have an appropriate swap instruction, lower it as usual.
JF Bastienf14889e2015-03-04 15:47:57 +0000495 return tryExpandAtomicRMW(AI);
Tim Northoverc882eb02014-04-03 11:44:58 +0000496}
497
JF Bastiene8aad292015-08-03 15:29:47 +0000498static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
499 Value *Loaded, Value *NewVal,
500 AtomicOrdering MemOpOrder,
501 Value *&Success, Value *&NewLoaded) {
Matt Arsenault0cb08e42019-01-17 10:49:01 +0000502 Type *OrigTy = NewVal->getType();
503
504 // This code can go away when cmpxchg supports FP types.
505 bool NeedBitcast = OrigTy->isFloatingPointTy();
506 if (NeedBitcast) {
507 IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
508 unsigned AS = Addr->getType()->getPointerAddressSpace();
509 Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
510 NewVal = Builder.CreateBitCast(NewVal, IntTy);
511 Loaded = Builder.CreateBitCast(Loaded, IntTy);
512 }
513
JF Bastiene8aad292015-08-03 15:29:47 +0000514 Value* Pair = Builder.CreateAtomicCmpXchg(
515 Addr, Loaded, NewVal, MemOpOrder,
516 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
517 Success = Builder.CreateExtractValue(Pair, 1, "success");
518 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
Matt Arsenault0cb08e42019-01-17 10:49:01 +0000519
520 if (NeedBitcast)
521 NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
JF Bastiene8aad292015-08-03 15:29:47 +0000522}
523
Robin Morisset25c8e312014-09-17 00:06:58 +0000524/// Emit IR to implement the given atomicrmw operation on values in registers,
525/// returning the new value.
526static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
527 Value *Loaded, Value *Inc) {
528 Value *NewVal;
529 switch (Op) {
530 case AtomicRMWInst::Xchg:
531 return Inc;
532 case AtomicRMWInst::Add:
533 return Builder.CreateAdd(Loaded, Inc, "new");
534 case AtomicRMWInst::Sub:
535 return Builder.CreateSub(Loaded, Inc, "new");
536 case AtomicRMWInst::And:
537 return Builder.CreateAnd(Loaded, Inc, "new");
538 case AtomicRMWInst::Nand:
539 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
540 case AtomicRMWInst::Or:
541 return Builder.CreateOr(Loaded, Inc, "new");
542 case AtomicRMWInst::Xor:
543 return Builder.CreateXor(Loaded, Inc, "new");
544 case AtomicRMWInst::Max:
545 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
546 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
547 case AtomicRMWInst::Min:
548 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
549 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
550 case AtomicRMWInst::UMax:
551 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
552 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
553 case AtomicRMWInst::UMin:
554 NewVal = Builder.CreateICmpULE(Loaded, Inc);
555 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
Matt Arsenault39508332019-01-22 18:18:02 +0000556 case AtomicRMWInst::FAdd:
557 return Builder.CreateFAdd(Loaded, Inc, "new");
558 case AtomicRMWInst::FSub:
559 return Builder.CreateFSub(Loaded, Inc, "new");
Robin Morisset25c8e312014-09-17 00:06:58 +0000560 default:
561 llvm_unreachable("Unknown atomic op");
562 }
563}
564
Tim Northoverf520eff2015-12-02 18:12:57 +0000565bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
566 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
567 case TargetLoweringBase::AtomicExpansionKind::None:
568 return false;
James Y Knight148a6462016-06-17 18:11:48 +0000569 case TargetLoweringBase::AtomicExpansionKind::LLSC: {
570 unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
571 unsigned ValueSize = getAtomicOpSize(AI);
572 if (ValueSize < MinCASSize) {
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500573 expandPartwordAtomicRMW(AI,
574 TargetLoweringBase::AtomicExpansionKind::LLSC);
James Y Knight148a6462016-06-17 18:11:48 +0000575 } else {
576 auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
577 return performAtomicOp(AI->getOperation(), Builder, Loaded,
578 AI->getValOperand());
579 };
580 expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
581 AI->getOrdering(), PerformOp);
582 }
583 return true;
584 }
585 case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
586 unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
587 unsigned ValueSize = getAtomicOpSize(AI);
588 if (ValueSize < MinCASSize) {
Matt Arsenault383e72f2019-06-11 01:35:00 +0000589 // TODO: Handle atomicrmw fadd/fsub
590 if (AI->getType()->isFloatingPointTy())
591 return false;
592
James Y Knight148a6462016-06-17 18:11:48 +0000593 expandPartwordAtomicRMW(AI,
594 TargetLoweringBase::AtomicExpansionKind::CmpXChg);
595 } else {
596 expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
597 }
598 return true;
599 }
Alex Bradbury21aea512018-09-19 10:54:22 +0000600 case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
601 expandAtomicRMWToMaskedIntrinsic(AI);
602 return true;
603 }
Tim Northoverf520eff2015-12-02 18:12:57 +0000604 default:
605 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
606 }
607}
608
James Y Knight148a6462016-06-17 18:11:48 +0000609namespace {
610
James Y Knight148a6462016-06-17 18:11:48 +0000611struct PartwordMaskValues {
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500612 // These three fields are guaranteed to be set by createMaskInstrs.
613 Type *WordType = nullptr;
614 Type *ValueType = nullptr;
615 Value *AlignedAddr = nullptr;
616 // The remaining fields can be null.
617 Value *ShiftAmt = nullptr;
618 Value *Mask = nullptr;
619 Value *Inv_Mask = nullptr;
James Y Knight148a6462016-06-17 18:11:48 +0000620};
Eugene Zelenkof1933322017-09-22 23:46:57 +0000621
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500622LLVM_ATTRIBUTE_UNUSED
623raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
624 auto PrintObj = [&O](auto *V) {
625 if (V)
626 O << *V;
627 else
628 O << "nullptr";
629 O << '\n';
630 };
631 O << "PartwordMaskValues {\n";
632 O << " WordType: ";
633 PrintObj(PMV.WordType);
634 O << " ValueType: ";
635 PrintObj(PMV.ValueType);
636 O << " AlignedAddr: ";
637 PrintObj(PMV.AlignedAddr);
638 O << " ShiftAmt: ";
639 PrintObj(PMV.ShiftAmt);
640 O << " Mask: ";
641 PrintObj(PMV.Mask);
642 O << " Inv_Mask: ";
643 PrintObj(PMV.Inv_Mask);
644 O << "}\n";
645 return O;
646}
647
James Y Knight148a6462016-06-17 18:11:48 +0000648} // end anonymous namespace
649
650/// This is a helper function which builds instructions to provide
651/// values necessary for partword atomic operations. It takes an
652/// incoming address, Addr, and ValueType, and constructs the address,
653/// shift-amounts and masks needed to work with a larger value of size
654/// WordSize.
655///
656/// AlignedAddr: Addr rounded down to a multiple of WordSize
657///
658/// ShiftAmt: Number of bits to right-shift a WordSize value loaded
659/// from AlignAddr for it to have the same value as if
660/// ValueType was loaded from Addr.
661///
662/// Mask: Value to mask with the value loaded from AlignAddr to
663/// include only the part that would've been loaded from Addr.
664///
665/// Inv_Mask: The inverse of Mask.
James Y Knight148a6462016-06-17 18:11:48 +0000666static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
667 Type *ValueType, Value *Addr,
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500668 unsigned MinWordSize) {
669 PartwordMaskValues PMV;
James Y Knight148a6462016-06-17 18:11:48 +0000670
James Y Knight148a6462016-06-17 18:11:48 +0000671 Module *M = I->getModule();
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500672 LLVMContext &Ctx = M->getContext();
James Y Knight148a6462016-06-17 18:11:48 +0000673 const DataLayout &DL = M->getDataLayout();
James Y Knight148a6462016-06-17 18:11:48 +0000674 unsigned ValueSize = DL.getTypeStoreSize(ValueType);
675
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500676 PMV.ValueType = ValueType;
677 PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
678 : ValueType;
679 if (PMV.ValueType == PMV.WordType) {
680 PMV.AlignedAddr = Addr;
681 return PMV;
James Y Knight148a6462016-06-17 18:11:48 +0000682 }
683
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500684 assert(ValueSize < MinWordSize);
James Y Knight148a6462016-06-17 18:11:48 +0000685
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500686 Type *WordPtrType =
687 PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
688
689 Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
690 PMV.AlignedAddr = Builder.CreateIntToPtr(
691 Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
692 "AlignedAddr");
693
694 Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
695 if (DL.isLittleEndian()) {
696 // turn bytes into bits
697 PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
698 } else {
699 // turn bytes into bits, and count from the other side.
700 PMV.ShiftAmt = Builder.CreateShl(
701 Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
702 }
703
704 PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
705 PMV.Mask = Builder.CreateShl(
706 ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
707 "Mask");
708 PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
709 return PMV;
710}
711
712static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
713 const PartwordMaskValues &PMV) {
714 assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
715 if (PMV.WordType == PMV.ValueType)
716 return WideWord;
717
718 Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
719 Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
720 return Trunc;
721}
722
723static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
724 Value *Updated, const PartwordMaskValues &PMV) {
725 assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
726 assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
727 if (PMV.WordType == PMV.ValueType)
728 return Updated;
729
730 Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
731 Value *Shift =
732 Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
733 Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
734 Value *Or = Builder.CreateOr(And, Shift, "inserted");
735 return Or;
James Y Knight148a6462016-06-17 18:11:48 +0000736}
737
738/// Emit IR to implement a masked version of a given atomicrmw
739/// operation. (That is, only the bits under the Mask should be
740/// affected by the operation)
741static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
742 IRBuilder<> &Builder, Value *Loaded,
743 Value *Shifted_Inc, Value *Inc,
744 const PartwordMaskValues &PMV) {
Alex Bradbury21aea512018-09-19 10:54:22 +0000745 // TODO: update to use
746 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
747 // to merge bits from two values without requiring PMV.Inv_Mask.
James Y Knight148a6462016-06-17 18:11:48 +0000748 switch (Op) {
749 case AtomicRMWInst::Xchg: {
750 Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
751 Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
752 return FinalVal;
753 }
754 case AtomicRMWInst::Or:
755 case AtomicRMWInst::Xor:
Alex Bradbury3291f9a2018-08-17 14:03:37 +0000756 case AtomicRMWInst::And:
757 llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
James Y Knight148a6462016-06-17 18:11:48 +0000758 case AtomicRMWInst::Add:
759 case AtomicRMWInst::Sub:
James Y Knight148a6462016-06-17 18:11:48 +0000760 case AtomicRMWInst::Nand: {
761 // The other arithmetic ops need to be masked into place.
762 Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
763 Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
764 Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
765 Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
766 return FinalVal;
767 }
768 case AtomicRMWInst::Max:
769 case AtomicRMWInst::Min:
770 case AtomicRMWInst::UMax:
771 case AtomicRMWInst::UMin: {
772 // Finally, comparison ops will operate on the full value, so
773 // truncate down to the original size, and expand out again after
774 // doing the operation.
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500775 Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
776 Value *NewVal = performAtomicOp(Op, Builder, Loaded_Extract, Inc);
777 Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
James Y Knight148a6462016-06-17 18:11:48 +0000778 return FinalVal;
779 }
780 default:
781 llvm_unreachable("Unknown atomic op");
782 }
783}
784
785/// Expand a sub-word atomicrmw operation into an appropriate
786/// word-sized operation.
787///
788/// It will create an LL/SC or cmpxchg loop, as appropriate, the same
789/// way as a typical atomicrmw expansion. The only difference here is
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500790/// that the operation inside of the loop may operate upon only a
James Y Knight148a6462016-06-17 18:11:48 +0000791/// part of the value.
792void AtomicExpand::expandPartwordAtomicRMW(
793 AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
James Y Knight148a6462016-06-17 18:11:48 +0000794 AtomicOrdering MemOpOrder = AI->getOrdering();
795
796 IRBuilder<> Builder(AI);
797
798 PartwordMaskValues PMV =
799 createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
800 TLI->getMinCmpXchgSizeInBits() / 8);
801
802 Value *ValOperand_Shifted =
803 Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
804 PMV.ShiftAmt, "ValOperand_Shifted");
805
806 auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
807 return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
808 ValOperand_Shifted, AI->getValOperand(), PMV);
809 };
810
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500811 Value *OldResult;
812 if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
813 OldResult =
814 insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder,
815 PerformPartwordOp, createCmpXchgInstFun);
816 } else {
817 assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
818 OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
819 MemOpOrder, PerformPartwordOp);
820 }
821
822 Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
James Y Knight148a6462016-06-17 18:11:48 +0000823 AI->replaceAllUsesWith(FinalOldResult);
824 AI->eraseFromParent();
825}
826
Alex Bradbury3291f9a2018-08-17 14:03:37 +0000827// Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
828AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
829 IRBuilder<> Builder(AI);
830 AtomicRMWInst::BinOp Op = AI->getOperation();
831
832 assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
833 Op == AtomicRMWInst::And) &&
834 "Unable to widen operation");
835
836 PartwordMaskValues PMV =
837 createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
838 TLI->getMinCmpXchgSizeInBits() / 8);
839
840 Value *ValOperand_Shifted =
841 Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
842 PMV.ShiftAmt, "ValOperand_Shifted");
843
844 Value *NewOperand;
845
846 if (Op == AtomicRMWInst::And)
847 NewOperand =
848 Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
849 else
850 NewOperand = ValOperand_Shifted;
851
852 AtomicRMWInst *NewAI = Builder.CreateAtomicRMW(Op, PMV.AlignedAddr,
853 NewOperand, AI->getOrdering());
854
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500855 Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
Alex Bradbury3291f9a2018-08-17 14:03:37 +0000856 AI->replaceAllUsesWith(FinalOldResult);
857 AI->eraseFromParent();
858 return NewAI;
859}
860
James Y Knight148a6462016-06-17 18:11:48 +0000861void AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
862 // The basic idea here is that we're expanding a cmpxchg of a
863 // smaller memory size up to a word-sized cmpxchg. To do this, we
864 // need to add a retry-loop for strong cmpxchg, so that
865 // modifications to other parts of the word don't cause a spurious
866 // failure.
867
868 // This generates code like the following:
869 // [[Setup mask values PMV.*]]
870 // %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
871 // %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
872 // %InitLoaded = load i32* %addr
873 // %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
874 // br partword.cmpxchg.loop
875 // partword.cmpxchg.loop:
876 // %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
877 // [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
878 // %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
879 // %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
880 // %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
881 // i32 %FullWord_NewVal success_ordering failure_ordering
882 // %OldVal = extractvalue { i32, i1 } %NewCI, 0
883 // %Success = extractvalue { i32, i1 } %NewCI, 1
884 // br i1 %Success, label %partword.cmpxchg.end,
885 // label %partword.cmpxchg.failure
886 // partword.cmpxchg.failure:
887 // %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
888 // %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
889 // br i1 %ShouldContinue, label %partword.cmpxchg.loop,
890 // label %partword.cmpxchg.end
891 // partword.cmpxchg.end:
892 // %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
893 // %FinalOldVal = trunc i32 %tmp1 to i8
894 // %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
895 // %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
896
897 Value *Addr = CI->getPointerOperand();
898 Value *Cmp = CI->getCompareOperand();
899 Value *NewVal = CI->getNewValOperand();
900
901 BasicBlock *BB = CI->getParent();
902 Function *F = BB->getParent();
903 IRBuilder<> Builder(CI);
904 LLVMContext &Ctx = Builder.getContext();
905
906 const int WordSize = TLI->getMinCmpXchgSizeInBits() / 8;
907
908 BasicBlock *EndBB =
909 BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
910 auto FailureBB =
911 BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
912 auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
913
914 // The split call above "helpfully" added a branch at the end of BB
915 // (to the wrong place).
916 std::prev(BB->end())->eraseFromParent();
917 Builder.SetInsertPoint(BB);
918
919 PartwordMaskValues PMV = createMaskInstrs(
920 Builder, CI, CI->getCompareOperand()->getType(), Addr, WordSize);
921
922 // Shift the incoming values over, into the right location in the word.
923 Value *NewVal_Shifted =
924 Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
925 Value *Cmp_Shifted =
926 Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
927
928 // Load the entire current word, and mask into place the expected and new
929 // values
930 LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
931 InitLoaded->setVolatile(CI->isVolatile());
932 Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
933 Builder.CreateBr(LoopBB);
934
935 // partword.cmpxchg.loop:
936 Builder.SetInsertPoint(LoopBB);
937 PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
938 Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
939
940 // Mask/Or the expected and new values into place in the loaded word.
941 Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
942 Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
943 AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
944 PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, CI->getSuccessOrdering(),
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000945 CI->getFailureOrdering(), CI->getSyncScopeID());
James Y Knight148a6462016-06-17 18:11:48 +0000946 NewCI->setVolatile(CI->isVolatile());
947 // When we're building a strong cmpxchg, we need a loop, so you
948 // might think we could use a weak cmpxchg inside. But, using strong
949 // allows the below comparison for ShouldContinue, and we're
950 // expecting the underlying cmpxchg to be a machine instruction,
951 // which is strong anyways.
952 NewCI->setWeak(CI->isWeak());
953
954 Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
955 Value *Success = Builder.CreateExtractValue(NewCI, 1);
956
957 if (CI->isWeak())
958 Builder.CreateBr(EndBB);
959 else
960 Builder.CreateCondBr(Success, EndBB, FailureBB);
961
962 // partword.cmpxchg.failure:
963 Builder.SetInsertPoint(FailureBB);
964 // Upon failure, verify that the masked-out part of the loaded value
965 // has been modified. If it didn't, abort the cmpxchg, since the
966 // masked-in part must've.
967 Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
968 Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
969 Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
970
971 // Add the second value to the phi from above
972 Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
973
974 // partword.cmpxchg.end:
975 Builder.SetInsertPoint(CI);
976
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -0500977 Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
James Y Knight148a6462016-06-17 18:11:48 +0000978 Value *Res = UndefValue::get(CI->getType());
979 Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
980 Res = Builder.CreateInsertValue(Res, Success, 1);
981
982 CI->replaceAllUsesWith(Res);
983 CI->eraseFromParent();
984}
985
986void AtomicExpand::expandAtomicOpToLLSC(
987 Instruction *I, Type *ResultType, Value *Addr, AtomicOrdering MemOpOrder,
988 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
989 IRBuilder<> Builder(I);
990 Value *Loaded =
991 insertRMWLLSCLoop(Builder, ResultType, Addr, MemOpOrder, PerformOp);
992
993 I->replaceAllUsesWith(Loaded);
994 I->eraseFromParent();
995}
996
Alex Bradbury21aea512018-09-19 10:54:22 +0000997void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
998 IRBuilder<> Builder(AI);
999
1000 PartwordMaskValues PMV =
1001 createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1002 TLI->getMinCmpXchgSizeInBits() / 8);
1003
1004 // The value operand must be sign-extended for signed min/max so that the
1005 // target's signed comparison instructions can be used. Otherwise, just
1006 // zero-ext.
1007 Instruction::CastOps CastOp = Instruction::ZExt;
1008 AtomicRMWInst::BinOp RMWOp = AI->getOperation();
1009 if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
1010 CastOp = Instruction::SExt;
1011
1012 Value *ValOperand_Shifted = Builder.CreateShl(
1013 Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
1014 PMV.ShiftAmt, "ValOperand_Shifted");
1015 Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
1016 Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
1017 AI->getOrdering());
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001018 Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
Alex Bradbury21aea512018-09-19 10:54:22 +00001019 AI->replaceAllUsesWith(FinalOldResult);
1020 AI->eraseFromParent();
1021}
1022
Alex Bradbury66d9a752018-11-29 20:43:42 +00001023void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
1024 IRBuilder<> Builder(CI);
1025
1026 PartwordMaskValues PMV = createMaskInstrs(
1027 Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1028 TLI->getMinCmpXchgSizeInBits() / 8);
1029
1030 Value *CmpVal_Shifted = Builder.CreateShl(
1031 Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
1032 "CmpVal_Shifted");
1033 Value *NewVal_Shifted = Builder.CreateShl(
1034 Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
1035 "NewVal_Shifted");
1036 Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
1037 Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
1038 CI->getSuccessOrdering());
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001039 Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
Alex Bradbury66d9a752018-11-29 20:43:42 +00001040 Value *Res = UndefValue::get(CI->getType());
1041 Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1042 Value *Success = Builder.CreateICmpEQ(
1043 CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
1044 Res = Builder.CreateInsertValue(Res, Success, 1);
1045
1046 CI->replaceAllUsesWith(Res);
1047 CI->eraseFromParent();
1048}
1049
James Y Knight148a6462016-06-17 18:11:48 +00001050Value *AtomicExpand::insertRMWLLSCLoop(
1051 IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
1052 AtomicOrdering MemOpOrder,
1053 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1054 LLVMContext &Ctx = Builder.getContext();
1055 BasicBlock *BB = Builder.GetInsertBlock();
1056 Function *F = BB->getParent();
Tim Northoverc882eb02014-04-03 11:44:58 +00001057
1058 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1059 //
1060 // The standard expansion we produce is:
1061 // [...]
Tim Northoverc882eb02014-04-03 11:44:58 +00001062 // atomicrmw.start:
1063 // %loaded = @load.linked(%addr)
1064 // %new = some_op iN %loaded, %incr
1065 // %stored = @store_conditional(%new, %addr)
1066 // %try_again = icmp i32 ne %stored, 0
1067 // br i1 %try_again, label %loop, label %atomicrmw.end
1068 // atomicrmw.end:
Tim Northoverc882eb02014-04-03 11:44:58 +00001069 // [...]
James Y Knight148a6462016-06-17 18:11:48 +00001070 BasicBlock *ExitBB =
1071 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
Tim Northoverc882eb02014-04-03 11:44:58 +00001072 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1073
Tim Northoverc882eb02014-04-03 11:44:58 +00001074 // The split call above "helpfully" added a branch at the end of BB (to the
James Y Knight148a6462016-06-17 18:11:48 +00001075 // wrong place).
Tim Northoverc882eb02014-04-03 11:44:58 +00001076 std::prev(BB->end())->eraseFromParent();
1077 Builder.SetInsertPoint(BB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001078 Builder.CreateBr(LoopBB);
1079
1080 // Start the main loop block now that we've taken care of the preliminaries.
1081 Builder.SetInsertPoint(LoopBB);
Robin Morisseta47cb412014-09-03 21:01:03 +00001082 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +00001083
Tim Northoverf520eff2015-12-02 18:12:57 +00001084 Value *NewVal = PerformOp(Builder, Loaded);
Tim Northoverc882eb02014-04-03 11:44:58 +00001085
Eric Christopherd9134482014-08-04 21:25:23 +00001086 Value *StoreSuccess =
Robin Morisseta47cb412014-09-03 21:01:03 +00001087 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
Tim Northoverc882eb02014-04-03 11:44:58 +00001088 Value *TryAgain = Builder.CreateICmpNE(
1089 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1090 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1091
1092 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
James Y Knight148a6462016-06-17 18:11:48 +00001093 return Loaded;
Tim Northoverc882eb02014-04-03 11:44:58 +00001094}
1095
Philip Reames1960cfd2016-02-19 00:06:41 +00001096/// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
1097/// the equivalent bitwidth. We used to not support pointer cmpxchg in the
1098/// IR. As a migration step, we convert back to what use to be the standard
1099/// way to represent a pointer cmpxchg so that we can update backends one by
Fangrui Songf78650a2018-07-30 19:41:25 +00001100/// one.
Philip Reames1960cfd2016-02-19 00:06:41 +00001101AtomicCmpXchgInst *AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
1102 auto *M = CI->getModule();
1103 Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
1104 M->getDataLayout());
1105
1106 IRBuilder<> Builder(CI);
Fangrui Songf78650a2018-07-30 19:41:25 +00001107
Philip Reames1960cfd2016-02-19 00:06:41 +00001108 Value *Addr = CI->getPointerOperand();
1109 Type *PT = PointerType::get(NewTy,
1110 Addr->getType()->getPointerAddressSpace());
1111 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1112
1113 Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
1114 Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
Fangrui Songf78650a2018-07-30 19:41:25 +00001115
1116
Philip Reames1960cfd2016-02-19 00:06:41 +00001117 auto *NewCI = Builder.CreateAtomicCmpXchg(NewAddr, NewCmp, NewNewVal,
1118 CI->getSuccessOrdering(),
1119 CI->getFailureOrdering(),
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001120 CI->getSyncScopeID());
Philip Reames1960cfd2016-02-19 00:06:41 +00001121 NewCI->setVolatile(CI->isVolatile());
1122 NewCI->setWeak(CI->isWeak());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001123 LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
Philip Reames1960cfd2016-02-19 00:06:41 +00001124
1125 Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1126 Value *Succ = Builder.CreateExtractValue(NewCI, 1);
1127
1128 OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
1129
1130 Value *Res = UndefValue::get(CI->getType());
1131 Res = Builder.CreateInsertValue(Res, OldVal, 0);
1132 Res = Builder.CreateInsertValue(Res, Succ, 1);
1133
1134 CI->replaceAllUsesWith(Res);
1135 CI->eraseFromParent();
1136 return NewCI;
1137}
1138
Robin Morisset59c23cd2014-08-21 21:50:01 +00001139bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
Tim Northover70450c52014-04-03 13:06:54 +00001140 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1141 AtomicOrdering FailureOrder = CI->getFailureOrdering();
Tim Northoverc882eb02014-04-03 11:44:58 +00001142 Value *Addr = CI->getPointerOperand();
1143 BasicBlock *BB = CI->getParent();
1144 Function *F = BB->getParent();
1145 LLVMContext &Ctx = F->getContext();
James Y Knightf44fc522016-03-16 22:12:04 +00001146 // If shouldInsertFencesForAtomic() returns true, then the target does not
1147 // want to deal with memory orders, and emitLeading/TrailingFence should take
1148 // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
Robin Morisseted3d48f2014-09-03 21:29:59 +00001149 // should preserve the ordering.
James Y Knightf44fc522016-03-16 22:12:04 +00001150 bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
Robin Morisseta47cb412014-09-03 21:01:03 +00001151 AtomicOrdering MemOpOrder =
JF Bastien800f87a2016-04-06 21:19:33 +00001152 ShouldInsertFencesForAtomic ? AtomicOrdering::Monotonic : SuccessOrder;
Tim Northoverc882eb02014-04-03 11:44:58 +00001153
Tim Northoverd32f8e62016-02-22 20:55:50 +00001154 // In implementations which use a barrier to achieve release semantics, we can
1155 // delay emitting this barrier until we know a store is actually going to be
1156 // attempted. The cost of this delay is that we need 2 copies of the block
1157 // emitting the load-linked, affecting code size.
1158 //
1159 // Ideally, this logic would be unconditional except for the minsize check
1160 // since in other cases the extra blocks naturally collapse down to the
1161 // minimal loop. Unfortunately, this puts too much stress on later
1162 // optimisations so we avoid emitting the extra logic in those cases too.
James Y Knightf44fc522016-03-16 22:12:04 +00001163 bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
JF Bastien800f87a2016-04-06 21:19:33 +00001164 SuccessOrder != AtomicOrdering::Monotonic &&
1165 SuccessOrder != AtomicOrdering::Acquire &&
Evandro Menezes85bd3972019-04-04 22:40:06 +00001166 !F->hasMinSize();
Tim Northoverd32f8e62016-02-22 20:55:50 +00001167
1168 // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1169 // do it even on minsize.
Evandro Menezes85bd3972019-04-04 22:40:06 +00001170 bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
Tim Northoverd32f8e62016-02-22 20:55:50 +00001171
Tim Northoverc882eb02014-04-03 11:44:58 +00001172 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1173 //
Tim Northover70450c52014-04-03 13:06:54 +00001174 // The full expansion we produce is:
Tim Northoverc882eb02014-04-03 11:44:58 +00001175 // [...]
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001176 // %aligned.addr = ...
Tim Northoverc882eb02014-04-03 11:44:58 +00001177 // cmpxchg.start:
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001178 // %unreleasedload = @load.linked(%aligned.addr)
1179 // %unreleasedload.extract = extract value from %unreleasedload
1180 // %should_store = icmp eq %unreleasedload.extract, %desired
1181 // br i1 %should_store, label %cmpxchg.releasingstore,
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001182 // label %cmpxchg.nostore
Tim Northoverd32f8e62016-02-22 20:55:50 +00001183 // cmpxchg.releasingstore:
1184 // fence?
1185 // br label cmpxchg.trystore
Tim Northoverc882eb02014-04-03 11:44:58 +00001186 // cmpxchg.trystore:
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001187 // %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
Tim Northoverd32f8e62016-02-22 20:55:50 +00001188 // [%releasedload, %cmpxchg.releasedload]
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001189 // %updated.new = insert %new into %loaded.trystore
1190 // %stored = @store_conditional(%updated.new, %aligned.addr)
Tim Northover20b9f732014-06-13 16:45:52 +00001191 // %success = icmp eq i32 %stored, 0
Tim Northoverd32f8e62016-02-22 20:55:50 +00001192 // br i1 %success, label %cmpxchg.success,
1193 // label %cmpxchg.releasedload/%cmpxchg.failure
1194 // cmpxchg.releasedload:
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001195 // %releasedload = @load.linked(%aligned.addr)
1196 // %releasedload.extract = extract value from %releasedload
1197 // %should_store = icmp eq %releasedload.extract, %desired
Tim Northoverd32f8e62016-02-22 20:55:50 +00001198 // br i1 %should_store, label %cmpxchg.trystore,
1199 // label %cmpxchg.failure
Tim Northover20b9f732014-06-13 16:45:52 +00001200 // cmpxchg.success:
1201 // fence?
1202 // br label %cmpxchg.end
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001203 // cmpxchg.nostore:
Tim Northoverd32f8e62016-02-22 20:55:50 +00001204 // %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1205 // [%releasedload,
1206 // %cmpxchg.releasedload/%cmpxchg.trystore]
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001207 // @load_linked_fail_balance()?
1208 // br label %cmpxchg.failure
Tim Northover20b9f732014-06-13 16:45:52 +00001209 // cmpxchg.failure:
Tim Northoverc882eb02014-04-03 11:44:58 +00001210 // fence?
Tim Northover70450c52014-04-03 13:06:54 +00001211 // br label %cmpxchg.end
1212 // cmpxchg.end:
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001213 // %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1214 // [%loaded.trystore, %cmpxchg.trystore]
Tim Northover20b9f732014-06-13 16:45:52 +00001215 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001216 // %loaded = extract value from %loaded.exit
Tim Northover20b9f732014-06-13 16:45:52 +00001217 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1218 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
Tim Northoverc882eb02014-04-03 11:44:58 +00001219 // [...]
Duncan P. N. Exon Smith8f11e1a2015-10-09 16:54:49 +00001220 BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
Tim Northover20b9f732014-06-13 16:45:52 +00001221 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001222 auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1223 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001224 auto ReleasedLoadBB =
1225 BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1226 auto TryStoreBB =
1227 BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1228 auto ReleasingStoreBB =
1229 BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1230 auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001231
1232 // This grabs the DebugLoc from CI
1233 IRBuilder<> Builder(CI);
1234
1235 // The split call above "helpfully" added a branch at the end of BB (to the
1236 // wrong place), but we might want a fence too. It's easiest to just remove
1237 // the branch entirely.
1238 std::prev(BB->end())->eraseFromParent();
1239 Builder.SetInsertPoint(BB);
James Y Knightf44fc522016-03-16 22:12:04 +00001240 if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
Tim Shen04de70d2017-05-09 15:27:17 +00001241 TLI->emitLeadingFence(Builder, CI, SuccessOrder);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001242
1243 PartwordMaskValues PMV =
1244 createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1245 TLI->getMinCmpXchgSizeInBits() / 8);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001246 Builder.CreateBr(StartBB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001247
1248 // Start the main loop block now that we've taken care of the preliminaries.
Tim Northoverd32f8e62016-02-22 20:55:50 +00001249 Builder.SetInsertPoint(StartBB);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001250 Value *UnreleasedLoad =
1251 TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1252 Value *UnreleasedLoadExtract =
1253 extractMaskedValue(Builder, UnreleasedLoad, PMV);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001254 Value *ShouldStore = Builder.CreateICmpEQ(
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001255 UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
Tim Northover70450c52014-04-03 13:06:54 +00001256
Eric Christopher572e03a2015-06-19 01:53:21 +00001257 // If the cmpxchg doesn't actually need any ordering when it fails, we can
Tim Northover70450c52014-04-03 13:06:54 +00001258 // jump straight past that fence instruction (if it exists).
Tim Northoverd32f8e62016-02-22 20:55:50 +00001259 Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1260
1261 Builder.SetInsertPoint(ReleasingStoreBB);
James Y Knightf44fc522016-03-16 22:12:04 +00001262 if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
Tim Shen04de70d2017-05-09 15:27:17 +00001263 TLI->emitLeadingFence(Builder, CI, SuccessOrder);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001264 Builder.CreateBr(TryStoreBB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001265
1266 Builder.SetInsertPoint(TryStoreBB);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001267 PHINode *LoadedTryStore =
1268 Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1269 LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1270 Value *NewValueInsert =
1271 insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1272 Value *StoreSuccess =
1273 TLI->emitStoreConditional(Builder, NewValueInsert, Addr, MemOpOrder);
Tim Northoverd039abd2014-06-13 16:45:36 +00001274 StoreSuccess = Builder.CreateICmpEQ(
Tim Northoverc882eb02014-04-03 11:44:58 +00001275 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
Tim Northoverd32f8e62016-02-22 20:55:50 +00001276 BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
Tim Northover20b9f732014-06-13 16:45:52 +00001277 Builder.CreateCondBr(StoreSuccess, SuccessBB,
Tim Northoverd32f8e62016-02-22 20:55:50 +00001278 CI->isWeak() ? FailureBB : RetryBB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001279
Tim Northoverd32f8e62016-02-22 20:55:50 +00001280 Builder.SetInsertPoint(ReleasedLoadBB);
1281 Value *SecondLoad;
1282 if (HasReleasedLoadBB) {
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001283 SecondLoad = TLI->emitLoadLinked(Builder, PMV.AlignedAddr, MemOpOrder);
1284 Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1285 ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1286 CI->getCompareOperand(), "should_store");
Tim Northoverd32f8e62016-02-22 20:55:50 +00001287
1288 // If the cmpxchg doesn't actually need any ordering when it fails, we can
1289 // jump straight past that fence instruction (if it exists).
1290 Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001291 // Update PHI node in TryStoreBB.
1292 LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001293 } else
1294 Builder.CreateUnreachable();
1295
1296 // Make sure later instructions don't get reordered with a fence if
1297 // necessary.
Tim Northover20b9f732014-06-13 16:45:52 +00001298 Builder.SetInsertPoint(SuccessBB);
James Y Knightf44fc522016-03-16 22:12:04 +00001299 if (ShouldInsertFencesForAtomic)
Tim Shen04de70d2017-05-09 15:27:17 +00001300 TLI->emitTrailingFence(Builder, CI, SuccessOrder);
Tim Northover70450c52014-04-03 13:06:54 +00001301 Builder.CreateBr(ExitBB);
Tim Northoverc882eb02014-04-03 11:44:58 +00001302
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001303 Builder.SetInsertPoint(NoStoreBB);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001304 PHINode *LoadedNoStore =
1305 Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1306 LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1307 if (HasReleasedLoadBB)
1308 LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1309
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00001310 // In the failing case, where we don't execute the store-conditional, the
1311 // target might want to balance out the load-linked with a dedicated
1312 // instruction (e.g., on ARM, clearing the exclusive monitor).
1313 TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1314 Builder.CreateBr(FailureBB);
1315
Tim Northover20b9f732014-06-13 16:45:52 +00001316 Builder.SetInsertPoint(FailureBB);
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001317 PHINode *LoadedFailure =
1318 Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1319 LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1320 if (CI->isWeak())
1321 LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
James Y Knightf44fc522016-03-16 22:12:04 +00001322 if (ShouldInsertFencesForAtomic)
Tim Shen04de70d2017-05-09 15:27:17 +00001323 TLI->emitTrailingFence(Builder, CI, FailureOrder);
Tim Northover20b9f732014-06-13 16:45:52 +00001324 Builder.CreateBr(ExitBB);
1325
Tim Northoverb4ddc082014-05-30 10:09:59 +00001326 // Finally, we have control-flow based knowledge of whether the cmpxchg
1327 // succeeded or not. We expose this to later passes by converting any
Tim Northoverd32f8e62016-02-22 20:55:50 +00001328 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1329 // PHI.
Tim Northover20b9f732014-06-13 16:45:52 +00001330 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001331 PHINode *LoadedExit =
1332 Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1333 LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1334 LoadedExit->addIncoming(LoadedFailure, FailureBB);
1335 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
Tim Northover420a2162014-06-13 14:24:07 +00001336 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
Tim Northover20b9f732014-06-13 16:45:52 +00001337 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
Tim Northoverb4ddc082014-05-30 10:09:59 +00001338
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001339 // This is the "exit value" from the cmpxchg expansion. It may be of
1340 // a type wider than the one in the cmpxchg instruction.
1341 Value *LoadedFull = LoadedExit;
Tim Northoverd32f8e62016-02-22 20:55:50 +00001342
Krzysztof Parzyszek25a4b192020-03-23 12:47:32 -05001343 Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1344 Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
Tim Northoverd32f8e62016-02-22 20:55:50 +00001345
Tim Northoverb4ddc082014-05-30 10:09:59 +00001346 // Look for any users of the cmpxchg that are just comparing the loaded value
1347 // against the desired one, and replace them with the CFG-derived version.
Tim Northover420a2162014-06-13 14:24:07 +00001348 SmallVector<ExtractValueInst *, 2> PrunedInsts;
Tim Northoverb4ddc082014-05-30 10:09:59 +00001349 for (auto User : CI->users()) {
Tim Northover420a2162014-06-13 14:24:07 +00001350 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1351 if (!EV)
Tim Northoverb4ddc082014-05-30 10:09:59 +00001352 continue;
1353
Tim Northover420a2162014-06-13 14:24:07 +00001354 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1355 "weird extraction from { iN, i1 }");
Tim Northoverb4ddc082014-05-30 10:09:59 +00001356
Tim Northover420a2162014-06-13 14:24:07 +00001357 if (EV->getIndices()[0] == 0)
1358 EV->replaceAllUsesWith(Loaded);
1359 else
1360 EV->replaceAllUsesWith(Success);
1361
1362 PrunedInsts.push_back(EV);
Tim Northoverb4ddc082014-05-30 10:09:59 +00001363 }
1364
Tim Northover420a2162014-06-13 14:24:07 +00001365 // We can remove the instructions now we're no longer iterating through them.
1366 for (auto EV : PrunedInsts)
1367 EV->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +00001368
Tim Northover420a2162014-06-13 14:24:07 +00001369 if (!CI->use_empty()) {
1370 // Some use of the full struct return that we don't understand has happened,
1371 // so we've got to reconstruct it properly.
1372 Value *Res;
1373 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1374 Res = Builder.CreateInsertValue(Res, Success, 1);
1375
1376 CI->replaceAllUsesWith(Res);
1377 }
1378
1379 CI->eraseFromParent();
Tim Northoverc882eb02014-04-03 11:44:58 +00001380 return true;
1381}
Robin Morisset810739d2014-09-25 17:27:43 +00001382
1383bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
1384 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1385 if(!C)
1386 return false;
1387
1388 AtomicRMWInst::BinOp Op = RMWI->getOperation();
1389 switch(Op) {
1390 case AtomicRMWInst::Add:
1391 case AtomicRMWInst::Sub:
1392 case AtomicRMWInst::Or:
1393 case AtomicRMWInst::Xor:
1394 return C->isZero();
1395 case AtomicRMWInst::And:
1396 return C->isMinusOne();
1397 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1398 default:
1399 return false;
1400 }
1401}
1402
1403bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
Ahmed Bougacha49b531a2015-09-12 18:51:23 +00001404 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1405 tryExpandAtomicLoad(ResultingLoad);
1406 return true;
1407 }
Robin Morisset810739d2014-09-25 17:27:43 +00001408 return false;
1409}
JF Bastiene8aad292015-08-03 15:29:47 +00001410
James Y Knight148a6462016-06-17 18:11:48 +00001411Value *AtomicExpand::insertRMWCmpXchgLoop(
1412 IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
1413 AtomicOrdering MemOpOrder,
1414 function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1415 CreateCmpXchgInstFun CreateCmpXchg) {
1416 LLVMContext &Ctx = Builder.getContext();
1417 BasicBlock *BB = Builder.GetInsertBlock();
JF Bastiene8aad292015-08-03 15:29:47 +00001418 Function *F = BB->getParent();
JF Bastiene8aad292015-08-03 15:29:47 +00001419
1420 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1421 //
1422 // The standard expansion we produce is:
1423 // [...]
1424 // %init_loaded = load atomic iN* %addr
1425 // br label %loop
1426 // loop:
1427 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1428 // %new = some_op iN %loaded, %incr
1429 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1430 // %new_loaded = extractvalue { iN, i1 } %pair, 0
1431 // %success = extractvalue { iN, i1 } %pair, 1
1432 // br i1 %success, label %atomicrmw.end, label %loop
1433 // atomicrmw.end:
1434 // [...]
James Y Knight148a6462016-06-17 18:11:48 +00001435 BasicBlock *ExitBB =
1436 BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
JF Bastiene8aad292015-08-03 15:29:47 +00001437 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1438
JF Bastiene8aad292015-08-03 15:29:47 +00001439 // The split call above "helpfully" added a branch at the end of BB (to the
1440 // wrong place), but we want a load. It's easiest to just remove
1441 // the branch entirely.
1442 std::prev(BB->end())->eraseFromParent();
1443 Builder.SetInsertPoint(BB);
James Y Knight148a6462016-06-17 18:11:48 +00001444 LoadInst *InitLoaded = Builder.CreateLoad(ResultTy, Addr);
JF Bastiene8aad292015-08-03 15:29:47 +00001445 // Atomics require at least natural alignment.
Eli Friedman3f13ee82020-04-06 17:29:25 -07001446 InitLoaded->setAlignment(Align(ResultTy->getPrimitiveSizeInBits() / 8));
JF Bastiene8aad292015-08-03 15:29:47 +00001447 Builder.CreateBr(LoopBB);
1448
1449 // Start the main loop block now that we've taken care of the preliminaries.
1450 Builder.SetInsertPoint(LoopBB);
James Y Knight148a6462016-06-17 18:11:48 +00001451 PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
JF Bastiene8aad292015-08-03 15:29:47 +00001452 Loaded->addIncoming(InitLoaded, BB);
1453
James Y Knight148a6462016-06-17 18:11:48 +00001454 Value *NewVal = PerformOp(Builder, Loaded);
JF Bastiene8aad292015-08-03 15:29:47 +00001455
1456 Value *NewLoaded = nullptr;
1457 Value *Success = nullptr;
1458
James Y Knight148a6462016-06-17 18:11:48 +00001459 CreateCmpXchg(Builder, Addr, Loaded, NewVal,
1460 MemOpOrder == AtomicOrdering::Unordered
1461 ? AtomicOrdering::Monotonic
1462 : MemOpOrder,
JF Bastiene8aad292015-08-03 15:29:47 +00001463 Success, NewLoaded);
1464 assert(Success && NewLoaded);
1465
1466 Loaded->addIncoming(NewLoaded, LoopBB);
1467
1468 Builder.CreateCondBr(Success, ExitBB, LoopBB);
1469
1470 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
James Y Knight148a6462016-06-17 18:11:48 +00001471 return NewLoaded;
1472}
JF Bastiene8aad292015-08-03 15:29:47 +00001473
Alex Bradbury79518b02018-09-19 14:51:42 +00001474bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1475 unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1476 unsigned ValueSize = getAtomicOpSize(CI);
1477
1478 switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1479 default:
1480 llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1481 case TargetLoweringBase::AtomicExpansionKind::None:
1482 if (ValueSize < MinCASSize)
1483 expandPartwordCmpXchg(CI);
1484 return false;
1485 case TargetLoweringBase::AtomicExpansionKind::LLSC: {
Alex Bradbury79518b02018-09-19 14:51:42 +00001486 return expandAtomicCmpXchg(CI);
1487 }
1488 case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
Alex Bradbury66d9a752018-11-29 20:43:42 +00001489 expandAtomicCmpXchgToMaskedIntrinsic(CI);
1490 return true;
Alex Bradbury79518b02018-09-19 14:51:42 +00001491 }
1492}
1493
James Y Knight148a6462016-06-17 18:11:48 +00001494// Note: This function is exposed externally by AtomicExpandUtils.h
1495bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1496 CreateCmpXchgInstFun CreateCmpXchg) {
1497 IRBuilder<> Builder(AI);
1498 Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1499 Builder, AI->getType(), AI->getPointerOperand(), AI->getOrdering(),
1500 [&](IRBuilder<> &Builder, Value *Loaded) {
1501 return performAtomicOp(AI->getOperation(), Builder, Loaded,
1502 AI->getValOperand());
1503 },
1504 CreateCmpXchg);
1505
1506 AI->replaceAllUsesWith(Loaded);
JF Bastiene8aad292015-08-03 15:29:47 +00001507 AI->eraseFromParent();
JF Bastiene8aad292015-08-03 15:29:47 +00001508 return true;
1509}
James Y Knight19f6cce2016-04-12 20:18:48 +00001510
James Y Knight19f6cce2016-04-12 20:18:48 +00001511// In order to use one of the sized library calls such as
1512// __atomic_fetch_add_4, the alignment must be sufficient, the size
1513// must be one of the potentially-specialized sizes, and the value
1514// type must actually exist in C on the target (otherwise, the
1515// function wouldn't actually be defined.)
1516static bool canUseSizedAtomicCall(unsigned Size, unsigned Align,
1517 const DataLayout &DL) {
1518 // TODO: "LargestSize" is an approximation for "largest type that
1519 // you can express in C". It seems to be the case that int128 is
1520 // supported on all 64-bit platforms, otherwise only up to 64-bit
1521 // integers are supported. If we get this wrong, then we'll try to
1522 // call a sized libcall that doesn't actually exist. There should
1523 // really be some more reliable way in LLVM of determining integer
1524 // sizes which are valid in the target's C ABI...
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001525 unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
James Y Knight19f6cce2016-04-12 20:18:48 +00001526 return Align >= Size &&
1527 (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1528 Size <= LargestSize;
1529}
1530
1531void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
1532 static const RTLIB::Libcall Libcalls[6] = {
1533 RTLIB::ATOMIC_LOAD, RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1534 RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1535 unsigned Size = getAtomicOpSize(I);
1536 unsigned Align = getAtomicOpAlign(I);
1537
1538 bool expanded = expandAtomicOpToLibcall(
1539 I, Size, Align, I->getPointerOperand(), nullptr, nullptr,
1540 I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1541 (void)expanded;
1542 assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Load");
1543}
1544
1545void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
1546 static const RTLIB::Libcall Libcalls[6] = {
1547 RTLIB::ATOMIC_STORE, RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1548 RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1549 unsigned Size = getAtomicOpSize(I);
1550 unsigned Align = getAtomicOpAlign(I);
1551
1552 bool expanded = expandAtomicOpToLibcall(
1553 I, Size, Align, I->getPointerOperand(), I->getValueOperand(), nullptr,
1554 I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1555 (void)expanded;
1556 assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor Store");
1557}
1558
1559void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1560 static const RTLIB::Libcall Libcalls[6] = {
1561 RTLIB::ATOMIC_COMPARE_EXCHANGE, RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1562 RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1563 RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1564 unsigned Size = getAtomicOpSize(I);
1565 unsigned Align = getAtomicOpAlign(I);
1566
1567 bool expanded = expandAtomicOpToLibcall(
1568 I, Size, Align, I->getPointerOperand(), I->getNewValOperand(),
1569 I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1570 Libcalls);
1571 (void)expanded;
1572 assert(expanded && "expandAtomicOpToLibcall shouldn't fail tor CAS");
1573}
1574
1575static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1576 static const RTLIB::Libcall LibcallsXchg[6] = {
1577 RTLIB::ATOMIC_EXCHANGE, RTLIB::ATOMIC_EXCHANGE_1,
1578 RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1579 RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1580 static const RTLIB::Libcall LibcallsAdd[6] = {
1581 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_ADD_1,
1582 RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1583 RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1584 static const RTLIB::Libcall LibcallsSub[6] = {
1585 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_SUB_1,
1586 RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1587 RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1588 static const RTLIB::Libcall LibcallsAnd[6] = {
1589 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_AND_1,
1590 RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1591 RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1592 static const RTLIB::Libcall LibcallsOr[6] = {
1593 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_OR_1,
1594 RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1595 RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1596 static const RTLIB::Libcall LibcallsXor[6] = {
1597 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_XOR_1,
1598 RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1599 RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1600 static const RTLIB::Libcall LibcallsNand[6] = {
1601 RTLIB::UNKNOWN_LIBCALL, RTLIB::ATOMIC_FETCH_NAND_1,
1602 RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1603 RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1604
1605 switch (Op) {
1606 case AtomicRMWInst::BAD_BINOP:
1607 llvm_unreachable("Should not have BAD_BINOP.");
1608 case AtomicRMWInst::Xchg:
1609 return makeArrayRef(LibcallsXchg);
1610 case AtomicRMWInst::Add:
1611 return makeArrayRef(LibcallsAdd);
1612 case AtomicRMWInst::Sub:
1613 return makeArrayRef(LibcallsSub);
1614 case AtomicRMWInst::And:
1615 return makeArrayRef(LibcallsAnd);
1616 case AtomicRMWInst::Or:
1617 return makeArrayRef(LibcallsOr);
1618 case AtomicRMWInst::Xor:
1619 return makeArrayRef(LibcallsXor);
1620 case AtomicRMWInst::Nand:
1621 return makeArrayRef(LibcallsNand);
1622 case AtomicRMWInst::Max:
1623 case AtomicRMWInst::Min:
1624 case AtomicRMWInst::UMax:
1625 case AtomicRMWInst::UMin:
Matt Arsenault39508332019-01-22 18:18:02 +00001626 case AtomicRMWInst::FAdd:
1627 case AtomicRMWInst::FSub:
James Y Knight19f6cce2016-04-12 20:18:48 +00001628 // No atomic libcalls are available for max/min/umax/umin.
1629 return {};
1630 }
1631 llvm_unreachable("Unexpected AtomicRMW operation.");
1632}
1633
1634void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1635 ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1636
1637 unsigned Size = getAtomicOpSize(I);
1638 unsigned Align = getAtomicOpAlign(I);
1639
1640 bool Success = false;
1641 if (!Libcalls.empty())
1642 Success = expandAtomicOpToLibcall(
1643 I, Size, Align, I->getPointerOperand(), I->getValOperand(), nullptr,
1644 I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1645
1646 // The expansion failed: either there were no libcalls at all for
1647 // the operation (min/max), or there were only size-specialized
1648 // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1649 // CAS libcall, via a CAS loop, instead.
1650 if (!Success) {
1651 expandAtomicRMWToCmpXchg(I, [this](IRBuilder<> &Builder, Value *Addr,
1652 Value *Loaded, Value *NewVal,
1653 AtomicOrdering MemOpOrder,
1654 Value *&Success, Value *&NewLoaded) {
1655 // Create the CAS instruction normally...
1656 AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1657 Addr, Loaded, NewVal, MemOpOrder,
1658 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
1659 Success = Builder.CreateExtractValue(Pair, 1, "success");
1660 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1661
1662 // ...and then expand the CAS into a libcall.
1663 expandAtomicCASToLibcall(Pair);
1664 });
1665 }
1666}
1667
1668// A helper routine for the above expandAtomic*ToLibcall functions.
1669//
1670// 'Libcalls' contains an array of enum values for the particular
1671// ATOMIC libcalls to be emitted. All of the other arguments besides
1672// 'I' are extracted from the Instruction subclass by the
1673// caller. Depending on the particular call, some will be null.
1674bool AtomicExpand::expandAtomicOpToLibcall(
1675 Instruction *I, unsigned Size, unsigned Align, Value *PointerOperand,
1676 Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1677 AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1678 assert(Libcalls.size() == 6);
1679
1680 LLVMContext &Ctx = I->getContext();
1681 Module *M = I->getModule();
1682 const DataLayout &DL = M->getDataLayout();
1683 IRBuilder<> Builder(I);
1684 IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1685
1686 bool UseSizedLibcall = canUseSizedAtomicCall(Size, Align, DL);
1687 Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1688
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001689 const llvm::Align AllocaAlignment(DL.getPrefTypeAlignment(SizedIntTy));
James Y Knight19f6cce2016-04-12 20:18:48 +00001690
1691 // TODO: the "order" argument type is "int", not int32. So
1692 // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1693 ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
JF Bastienbbb0aee62016-04-18 18:01:43 +00001694 assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
James Y Knight19f6cce2016-04-12 20:18:48 +00001695 Constant *OrderingVal =
JF Bastienbbb0aee62016-04-18 18:01:43 +00001696 ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1697 Constant *Ordering2Val = nullptr;
1698 if (CASExpected) {
1699 assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1700 Ordering2Val =
1701 ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1702 }
James Y Knight19f6cce2016-04-12 20:18:48 +00001703 bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1704
1705 RTLIB::Libcall RTLibType;
1706 if (UseSizedLibcall) {
1707 switch (Size) {
1708 case 1: RTLibType = Libcalls[1]; break;
1709 case 2: RTLibType = Libcalls[2]; break;
1710 case 4: RTLibType = Libcalls[3]; break;
1711 case 8: RTLibType = Libcalls[4]; break;
1712 case 16: RTLibType = Libcalls[5]; break;
1713 }
1714 } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1715 RTLibType = Libcalls[0];
1716 } else {
1717 // Can't use sized function, and there's no generic for this
1718 // operation, so give up.
1719 return false;
1720 }
1721
1722 // Build up the function call. There's two kinds. First, the sized
1723 // variants. These calls are going to be one of the following (with
1724 // N=1,2,4,8,16):
1725 // iN __atomic_load_N(iN *ptr, int ordering)
1726 // void __atomic_store_N(iN *ptr, iN val, int ordering)
1727 // iN __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1728 // bool __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1729 // int success_order, int failure_order)
1730 //
1731 // Note that these functions can be used for non-integer atomic
1732 // operations, the values just need to be bitcast to integers on the
1733 // way in and out.
1734 //
1735 // And, then, the generic variants. They look like the following:
1736 // void __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1737 // void __atomic_store(size_t size, void *ptr, void *val, int ordering)
1738 // void __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1739 // int ordering)
1740 // bool __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1741 // void *desired, int success_order,
1742 // int failure_order)
1743 //
1744 // The different signatures are built up depending on the
1745 // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1746 // variables.
1747
1748 AllocaInst *AllocaCASExpected = nullptr;
1749 Value *AllocaCASExpected_i8 = nullptr;
1750 AllocaInst *AllocaValue = nullptr;
1751 Value *AllocaValue_i8 = nullptr;
1752 AllocaInst *AllocaResult = nullptr;
1753 Value *AllocaResult_i8 = nullptr;
1754
1755 Type *ResultTy;
1756 SmallVector<Value *, 6> Args;
Reid Klecknerb5180542017-03-21 16:57:19 +00001757 AttributeList Attr;
James Y Knight19f6cce2016-04-12 20:18:48 +00001758
1759 // 'size' argument.
1760 if (!UseSizedLibcall) {
1761 // Note, getIntPtrType is assumed equivalent to size_t.
1762 Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1763 }
1764
1765 // 'ptr' argument.
Philip Reames9549f752019-03-06 19:27:13 +00001766 // note: This assumes all address spaces share a common libfunc
1767 // implementation and that addresses are convertable. For systems without
1768 // that property, we'd need to extend this mechanism to support AS-specific
1769 // families of atomic intrinsics.
1770 auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
1771 Value *PtrVal = Builder.CreateBitCast(PointerOperand,
1772 Type::getInt8PtrTy(Ctx, PtrTypeAS));
1773 PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
James Y Knight19f6cce2016-04-12 20:18:48 +00001774 Args.push_back(PtrVal);
1775
1776 // 'expected' argument, if present.
1777 if (CASExpected) {
1778 AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001779 AllocaCASExpected->setAlignment(AllocaAlignment);
Matt Arsenaultc5830f52019-06-11 01:35:07 +00001780 unsigned AllocaAS = AllocaCASExpected->getType()->getPointerAddressSpace();
1781
James Y Knight19f6cce2016-04-12 20:18:48 +00001782 AllocaCASExpected_i8 =
Matt Arsenaultc5830f52019-06-11 01:35:07 +00001783 Builder.CreateBitCast(AllocaCASExpected,
1784 Type::getInt8PtrTy(Ctx, AllocaAS));
James Y Knight19f6cce2016-04-12 20:18:48 +00001785 Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
1786 Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1787 Args.push_back(AllocaCASExpected_i8);
1788 }
1789
1790 // 'val' argument ('desired' for cas), if present.
1791 if (ValueOperand) {
1792 if (UseSizedLibcall) {
1793 Value *IntValue =
1794 Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1795 Args.push_back(IntValue);
1796 } else {
1797 AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001798 AllocaValue->setAlignment(AllocaAlignment);
James Y Knight19f6cce2016-04-12 20:18:48 +00001799 AllocaValue_i8 =
1800 Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
1801 Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
1802 Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1803 Args.push_back(AllocaValue_i8);
1804 }
1805 }
1806
1807 // 'ret' argument.
1808 if (!CASExpected && HasResult && !UseSizedLibcall) {
1809 AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
Guillaume Chatelet279fa8e2020-01-23 11:33:12 +01001810 AllocaResult->setAlignment(AllocaAlignment);
Matt Arsenaultc5830f52019-06-11 01:35:07 +00001811 unsigned AllocaAS = AllocaResult->getType()->getPointerAddressSpace();
James Y Knight19f6cce2016-04-12 20:18:48 +00001812 AllocaResult_i8 =
Matt Arsenaultc5830f52019-06-11 01:35:07 +00001813 Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
James Y Knight19f6cce2016-04-12 20:18:48 +00001814 Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
1815 Args.push_back(AllocaResult_i8);
1816 }
1817
1818 // 'ordering' ('success_order' for cas) argument.
1819 Args.push_back(OrderingVal);
1820
1821 // 'failure_order' argument, if present.
1822 if (Ordering2Val)
1823 Args.push_back(Ordering2Val);
1824
1825 // Now, the return type.
1826 if (CASExpected) {
1827 ResultTy = Type::getInt1Ty(Ctx);
Reid Klecknerb5180542017-03-21 16:57:19 +00001828 Attr = Attr.addAttribute(Ctx, AttributeList::ReturnIndex, Attribute::ZExt);
James Y Knight19f6cce2016-04-12 20:18:48 +00001829 } else if (HasResult && UseSizedLibcall)
1830 ResultTy = SizedIntTy;
1831 else
1832 ResultTy = Type::getVoidTy(Ctx);
1833
1834 // Done with setting up arguments and return types, create the call:
1835 SmallVector<Type *, 6> ArgTys;
1836 for (Value *Arg : Args)
1837 ArgTys.push_back(Arg->getType());
1838 FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
James Y Knight13680222019-02-01 02:28:03 +00001839 FunctionCallee LibcallFn =
James Y Knight19f6cce2016-04-12 20:18:48 +00001840 M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
1841 CallInst *Call = Builder.CreateCall(LibcallFn, Args);
1842 Call->setAttributes(Attr);
1843 Value *Result = Call;
1844
1845 // And then, extract the results...
1846 if (ValueOperand && !UseSizedLibcall)
1847 Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
1848
1849 if (CASExpected) {
1850 // The final result from the CAS is {load of 'expected' alloca, bool result
1851 // from call}
1852 Type *FinalResultTy = I->getType();
1853 Value *V = UndefValue::get(FinalResultTy);
James Y Knight14359ef2019-02-01 20:44:24 +00001854 Value *ExpectedOut = Builder.CreateAlignedLoad(
1855 CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
James Y Knight19f6cce2016-04-12 20:18:48 +00001856 Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
1857 V = Builder.CreateInsertValue(V, ExpectedOut, 0);
1858 V = Builder.CreateInsertValue(V, Result, 1);
1859 I->replaceAllUsesWith(V);
1860 } else if (HasResult) {
1861 Value *V;
1862 if (UseSizedLibcall)
1863 V = Builder.CreateBitOrPointerCast(Result, I->getType());
1864 else {
James Y Knight14359ef2019-02-01 20:44:24 +00001865 V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
1866 AllocaAlignment);
James Y Knight19f6cce2016-04-12 20:18:48 +00001867 Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
1868 }
1869 I->replaceAllUsesWith(V);
1870 }
1871 I->eraseFromParent();
1872 return true;
1873}