1 //===- AtomicExpandPass.cpp - Expand atomic instructions ------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass (at IR level) to replace atomic instructions with
10 // __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.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/STLFunctionalExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/CodeGen/AtomicExpandUtils.h"
22 #include "llvm/CodeGen/RuntimeLibcalls.h"
23 #include "llvm/CodeGen/TargetLowering.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/User.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/InitializePasses.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/AtomicOrdering.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "atomic-expand"
57 
58 namespace {
59 
60 class AtomicExpand : public FunctionPass {
61   const TargetLowering *TLI = nullptr;
62 
63 public:
64   static char ID; // Pass identification, replacement for typeid
65 
66   AtomicExpand() : FunctionPass(ID) {
67     initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
68   }
69 
70   bool runOnFunction(Function &F) override;
71 
72 private:
73   bool bracketInstWithFences(Instruction *I, AtomicOrdering Order);
74   IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
75   LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
76   bool tryExpandAtomicLoad(LoadInst *LI);
77   bool expandAtomicLoadToLL(LoadInst *LI);
78   bool expandAtomicLoadToCmpXchg(LoadInst *LI);
79   StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
80   void expandAtomicStore(StoreInst *SI);
81   bool tryExpandAtomicRMW(AtomicRMWInst *AI);
82   AtomicRMWInst *convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI);
83   Value *
84   insertRMWLLSCLoop(IRBuilder<> &Builder, Type *ResultTy, Value *Addr,
85                     Align AddrAlign, AtomicOrdering MemOpOrder,
86                     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
87   void
88   expandAtomicOpToLLSC(Instruction *I, Type *ResultTy, Value *Addr,
89                        Align AddrAlign, AtomicOrdering MemOpOrder,
90                        function_ref<Value *(IRBuilder<> &, Value *)> PerformOp);
91   void expandPartwordAtomicRMW(
92       AtomicRMWInst *I, TargetLoweringBase::AtomicExpansionKind ExpansionKind);
93   AtomicRMWInst *widenPartwordAtomicRMW(AtomicRMWInst *AI);
94   bool expandPartwordCmpXchg(AtomicCmpXchgInst *I);
95   void expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI);
96   void expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI);
97 
98   AtomicCmpXchgInst *convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI);
99   static Value *
100   insertRMWCmpXchgLoop(IRBuilder<> &Builder, Type *ResultType, Value *Addr,
101                        Align AddrAlign, AtomicOrdering MemOpOrder,
102                        SyncScope::ID SSID,
103                        function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
104                        CreateCmpXchgInstFun CreateCmpXchg);
105   bool tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI);
106 
107   bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
108   bool isIdempotentRMW(AtomicRMWInst *RMWI);
109   bool simplifyIdempotentRMW(AtomicRMWInst *RMWI);
110 
111   bool expandAtomicOpToLibcall(Instruction *I, unsigned Size, Align Alignment,
112                                Value *PointerOperand, Value *ValueOperand,
113                                Value *CASExpected, AtomicOrdering Ordering,
114                                AtomicOrdering Ordering2,
115                                ArrayRef<RTLIB::Libcall> Libcalls);
116   void expandAtomicLoadToLibcall(LoadInst *LI);
117   void expandAtomicStoreToLibcall(StoreInst *LI);
118   void expandAtomicRMWToLibcall(AtomicRMWInst *I);
119   void expandAtomicCASToLibcall(AtomicCmpXchgInst *I);
120 
121   friend bool
122   llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
123                                  CreateCmpXchgInstFun CreateCmpXchg);
124 };
125 
126 } // end anonymous namespace
127 
128 char AtomicExpand::ID = 0;
129 
130 char &llvm::AtomicExpandID = AtomicExpand::ID;
131 
132 INITIALIZE_PASS(AtomicExpand, DEBUG_TYPE, "Expand Atomic instructions", false,
133                 false)
134 
135 FunctionPass *llvm::createAtomicExpandPass() { return new AtomicExpand(); }
136 
137 // Helper functions to retrieve the size of atomic instructions.
138 static unsigned getAtomicOpSize(LoadInst *LI) {
139   const DataLayout &DL = LI->getModule()->getDataLayout();
140   return DL.getTypeStoreSize(LI->getType());
141 }
142 
143 static unsigned getAtomicOpSize(StoreInst *SI) {
144   const DataLayout &DL = SI->getModule()->getDataLayout();
145   return DL.getTypeStoreSize(SI->getValueOperand()->getType());
146 }
147 
148 static unsigned getAtomicOpSize(AtomicRMWInst *RMWI) {
149   const DataLayout &DL = RMWI->getModule()->getDataLayout();
150   return DL.getTypeStoreSize(RMWI->getValOperand()->getType());
151 }
152 
153 static unsigned getAtomicOpSize(AtomicCmpXchgInst *CASI) {
154   const DataLayout &DL = CASI->getModule()->getDataLayout();
155   return DL.getTypeStoreSize(CASI->getCompareOperand()->getType());
156 }
157 
158 // Determine if a particular atomic operation has a supported size,
159 // and is of appropriate alignment, to be passed through for target
160 // lowering. (Versus turning into a __atomic libcall)
161 template <typename Inst>
162 static bool atomicSizeSupported(const TargetLowering *TLI, Inst *I) {
163   unsigned Size = getAtomicOpSize(I);
164   Align Alignment = I->getAlign();
165   return Alignment >= Size &&
166          Size <= TLI->getMaxAtomicSizeInBitsSupported() / 8;
167 }
168 
169 bool AtomicExpand::runOnFunction(Function &F) {
170   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
171   if (!TPC)
172     return false;
173 
174   auto &TM = TPC->getTM<TargetMachine>();
175   if (!TM.getSubtargetImpl(F)->enableAtomicExpand())
176     return false;
177   TLI = TM.getSubtargetImpl(F)->getTargetLowering();
178 
179   SmallVector<Instruction *, 1> AtomicInsts;
180 
181   // Changing control-flow while iterating through it is a bad idea, so gather a
182   // list of all atomic instructions before we start.
183   for (Instruction &I : instructions(F))
184     if (I.isAtomic() && !isa<FenceInst>(&I))
185       AtomicInsts.push_back(&I);
186 
187   bool MadeChange = false;
188   for (auto I : AtomicInsts) {
189     auto LI = dyn_cast<LoadInst>(I);
190     auto SI = dyn_cast<StoreInst>(I);
191     auto RMWI = dyn_cast<AtomicRMWInst>(I);
192     auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
193     assert((LI || SI || RMWI || CASI) && "Unknown atomic instruction");
194 
195     // If the Size/Alignment is not supported, replace with a libcall.
196     if (LI) {
197       if (!atomicSizeSupported(TLI, LI)) {
198         expandAtomicLoadToLibcall(LI);
199         MadeChange = true;
200         continue;
201       }
202     } else if (SI) {
203       if (!atomicSizeSupported(TLI, SI)) {
204         expandAtomicStoreToLibcall(SI);
205         MadeChange = true;
206         continue;
207       }
208     } else if (RMWI) {
209       if (!atomicSizeSupported(TLI, RMWI)) {
210         expandAtomicRMWToLibcall(RMWI);
211         MadeChange = true;
212         continue;
213       }
214     } else if (CASI) {
215       if (!atomicSizeSupported(TLI, CASI)) {
216         expandAtomicCASToLibcall(CASI);
217         MadeChange = true;
218         continue;
219       }
220     }
221 
222     if (TLI->shouldInsertFencesForAtomic(I)) {
223       auto FenceOrdering = AtomicOrdering::Monotonic;
224       if (LI && isAcquireOrStronger(LI->getOrdering())) {
225         FenceOrdering = LI->getOrdering();
226         LI->setOrdering(AtomicOrdering::Monotonic);
227       } else if (SI && isReleaseOrStronger(SI->getOrdering())) {
228         FenceOrdering = SI->getOrdering();
229         SI->setOrdering(AtomicOrdering::Monotonic);
230       } else if (RMWI && (isReleaseOrStronger(RMWI->getOrdering()) ||
231                           isAcquireOrStronger(RMWI->getOrdering()))) {
232         FenceOrdering = RMWI->getOrdering();
233         RMWI->setOrdering(AtomicOrdering::Monotonic);
234       } else if (CASI &&
235                  TLI->shouldExpandAtomicCmpXchgInIR(CASI) ==
236                      TargetLoweringBase::AtomicExpansionKind::None &&
237                  (isReleaseOrStronger(CASI->getSuccessOrdering()) ||
238                   isAcquireOrStronger(CASI->getSuccessOrdering()) ||
239                   isAcquireOrStronger(CASI->getFailureOrdering()))) {
240         // If a compare and swap is lowered to LL/SC, we can do smarter fence
241         // insertion, with a stronger one on the success path than on the
242         // failure path. As a result, fence insertion is directly done by
243         // expandAtomicCmpXchg in that case.
244         FenceOrdering = CASI->getMergedOrdering();
245         CASI->setSuccessOrdering(AtomicOrdering::Monotonic);
246         CASI->setFailureOrdering(AtomicOrdering::Monotonic);
247       }
248 
249       if (FenceOrdering != AtomicOrdering::Monotonic) {
250         MadeChange |= bracketInstWithFences(I, FenceOrdering);
251       }
252     }
253 
254     if (LI) {
255       if (LI->getType()->isFloatingPointTy()) {
256         // TODO: add a TLI hook to control this so that each target can
257         // convert to lowering the original type one at a time.
258         LI = convertAtomicLoadToIntegerType(LI);
259         assert(LI->getType()->isIntegerTy() && "invariant broken");
260         MadeChange = true;
261       }
262 
263       MadeChange |= tryExpandAtomicLoad(LI);
264     } else if (SI) {
265       if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
266         // TODO: add a TLI hook to control this so that each target can
267         // convert to lowering the original type one at a time.
268         SI = convertAtomicStoreToIntegerType(SI);
269         assert(SI->getValueOperand()->getType()->isIntegerTy() &&
270                "invariant broken");
271         MadeChange = true;
272       }
273 
274       if (TLI->shouldExpandAtomicStoreInIR(SI)) {
275         expandAtomicStore(SI);
276         MadeChange = true;
277       }
278     } else if (RMWI) {
279       // There are two different ways of expanding RMW instructions:
280       // - into a load if it is idempotent
281       // - into a Cmpxchg/LL-SC loop otherwise
282       // we try them in that order.
283 
284       if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
285         MadeChange = true;
286       } else {
287         AtomicRMWInst::BinOp Op = RMWI->getOperation();
288         if (Op == AtomicRMWInst::Xchg &&
289             RMWI->getValOperand()->getType()->isFloatingPointTy()) {
290           // TODO: add a TLI hook to control this so that each target can
291           // convert to lowering the original type one at a time.
292           RMWI = convertAtomicXchgToIntegerType(RMWI);
293           assert(RMWI->getValOperand()->getType()->isIntegerTy() &&
294                  "invariant broken");
295           MadeChange = true;
296         }
297         unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
298         unsigned ValueSize = getAtomicOpSize(RMWI);
299         if (ValueSize < MinCASSize &&
300             (Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
301              Op == AtomicRMWInst::And)) {
302           RMWI = widenPartwordAtomicRMW(RMWI);
303           MadeChange = true;
304         }
305 
306         MadeChange |= tryExpandAtomicRMW(RMWI);
307       }
308     } else if (CASI) {
309       // TODO: when we're ready to make the change at the IR level, we can
310       // extend convertCmpXchgToInteger for floating point too.
311       assert(!CASI->getCompareOperand()->getType()->isFloatingPointTy() &&
312              "unimplemented - floating point not legal at IR level");
313       if (CASI->getCompareOperand()->getType()->isPointerTy()) {
314         // TODO: add a TLI hook to control this so that each target can
315         // convert to lowering the original type one at a time.
316         CASI = convertCmpXchgToIntegerType(CASI);
317         assert(CASI->getCompareOperand()->getType()->isIntegerTy() &&
318                "invariant broken");
319         MadeChange = true;
320       }
321 
322       MadeChange |= tryExpandAtomicCmpXchg(CASI);
323     }
324   }
325   return MadeChange;
326 }
327 
328 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order) {
329   IRBuilder<> Builder(I);
330 
331   auto LeadingFence = TLI->emitLeadingFence(Builder, I, Order);
332 
333   auto TrailingFence = TLI->emitTrailingFence(Builder, I, Order);
334   // We have a guard here because not every atomic operation generates a
335   // trailing fence.
336   if (TrailingFence)
337     TrailingFence->moveAfter(I);
338 
339   return (LeadingFence || TrailingFence);
340 }
341 
342 /// Get the iX type with the same bitwidth as T.
343 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
344                                                        const DataLayout &DL) {
345   EVT VT = TLI->getMemValueType(DL, T);
346   unsigned BitWidth = VT.getStoreSizeInBits();
347   assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
348   return IntegerType::get(T->getContext(), BitWidth);
349 }
350 
351 /// Convert an atomic load of a non-integral type to an integer load of the
352 /// equivalent bitwidth.  See the function comment on
353 /// convertAtomicStoreToIntegerType for background.
354 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
355   auto *M = LI->getModule();
356   Type *NewTy = getCorrespondingIntegerType(LI->getType(), M->getDataLayout());
357 
358   IRBuilder<> Builder(LI);
359 
360   Value *Addr = LI->getPointerOperand();
361   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
362   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
363 
364   auto *NewLI = Builder.CreateLoad(NewTy, NewAddr);
365   NewLI->setAlignment(LI->getAlign());
366   NewLI->setVolatile(LI->isVolatile());
367   NewLI->setAtomic(LI->getOrdering(), LI->getSyncScopeID());
368   LLVM_DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
369 
370   Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
371   LI->replaceAllUsesWith(NewVal);
372   LI->eraseFromParent();
373   return NewLI;
374 }
375 
376 AtomicRMWInst *
377 AtomicExpand::convertAtomicXchgToIntegerType(AtomicRMWInst *RMWI) {
378   auto *M = RMWI->getModule();
379   Type *NewTy =
380       getCorrespondingIntegerType(RMWI->getType(), M->getDataLayout());
381 
382   IRBuilder<> Builder(RMWI);
383 
384   Value *Addr = RMWI->getPointerOperand();
385   Value *Val = RMWI->getValOperand();
386   Type *PT = PointerType::get(NewTy, RMWI->getPointerAddressSpace());
387   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
388   Value *NewVal = Builder.CreateBitCast(Val, NewTy);
389 
390   auto *NewRMWI =
391       Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, NewAddr, NewVal,
392                               RMWI->getAlign(), RMWI->getOrdering());
393   NewRMWI->setVolatile(RMWI->isVolatile());
394   LLVM_DEBUG(dbgs() << "Replaced " << *RMWI << " with " << *NewRMWI << "\n");
395 
396   Value *NewRVal = Builder.CreateBitCast(NewRMWI, RMWI->getType());
397   RMWI->replaceAllUsesWith(NewRVal);
398   RMWI->eraseFromParent();
399   return NewRMWI;
400 }
401 
402 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
403   switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
404   case TargetLoweringBase::AtomicExpansionKind::None:
405     return false;
406   case TargetLoweringBase::AtomicExpansionKind::LLSC:
407     expandAtomicOpToLLSC(
408         LI, LI->getType(), LI->getPointerOperand(), LI->getAlign(),
409         LI->getOrdering(),
410         [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
411     return true;
412   case TargetLoweringBase::AtomicExpansionKind::LLOnly:
413     return expandAtomicLoadToLL(LI);
414   case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
415     return expandAtomicLoadToCmpXchg(LI);
416   default:
417     llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
418   }
419 }
420 
421 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
422   IRBuilder<> Builder(LI);
423 
424   // On some architectures, load-linked instructions are atomic for larger
425   // sizes than normal loads. For example, the only 64-bit load guaranteed
426   // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
427   Value *Val = TLI->emitLoadLinked(Builder, LI->getType(),
428                                    LI->getPointerOperand(), LI->getOrdering());
429   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
430 
431   LI->replaceAllUsesWith(Val);
432   LI->eraseFromParent();
433 
434   return true;
435 }
436 
437 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
438   IRBuilder<> Builder(LI);
439   AtomicOrdering Order = LI->getOrdering();
440   if (Order == AtomicOrdering::Unordered)
441     Order = AtomicOrdering::Monotonic;
442 
443   Value *Addr = LI->getPointerOperand();
444   Type *Ty = LI->getType();
445   Constant *DummyVal = Constant::getNullValue(Ty);
446 
447   Value *Pair = Builder.CreateAtomicCmpXchg(
448       Addr, DummyVal, DummyVal, LI->getAlign(), Order,
449       AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
450   Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
451 
452   LI->replaceAllUsesWith(Loaded);
453   LI->eraseFromParent();
454 
455   return true;
456 }
457 
458 /// Convert an atomic store of a non-integral type to an integer store of the
459 /// equivalent bitwidth.  We used to not support floating point or vector
460 /// atomics in the IR at all.  The backends learned to deal with the bitcast
461 /// idiom because that was the only way of expressing the notion of a atomic
462 /// float or vector store.  The long term plan is to teach each backend to
463 /// instruction select from the original atomic store, but as a migration
464 /// mechanism, we convert back to the old format which the backends understand.
465 /// Each backend will need individual work to recognize the new format.
466 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
467   IRBuilder<> Builder(SI);
468   auto *M = SI->getModule();
469   Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
470                                             M->getDataLayout());
471   Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
472 
473   Value *Addr = SI->getPointerOperand();
474   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
475   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
476 
477   StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
478   NewSI->setAlignment(SI->getAlign());
479   NewSI->setVolatile(SI->isVolatile());
480   NewSI->setAtomic(SI->getOrdering(), SI->getSyncScopeID());
481   LLVM_DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
482   SI->eraseFromParent();
483   return NewSI;
484 }
485 
486 void AtomicExpand::expandAtomicStore(StoreInst *SI) {
487   // This function is only called on atomic stores that are too large to be
488   // atomic if implemented as a native store. So we replace them by an
489   // atomic swap, that can be implemented for example as a ldrex/strex on ARM
490   // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
491   // It is the responsibility of the target to only signal expansion via
492   // shouldExpandAtomicRMW in cases where this is required and possible.
493   IRBuilder<> Builder(SI);
494   AtomicRMWInst *AI = Builder.CreateAtomicRMW(
495       AtomicRMWInst::Xchg, SI->getPointerOperand(), SI->getValueOperand(),
496       SI->getAlign(), SI->getOrdering());
497   SI->eraseFromParent();
498 
499   // Now we have an appropriate swap instruction, lower it as usual.
500   tryExpandAtomicRMW(AI);
501 }
502 
503 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
504                                  Value *Loaded, Value *NewVal, Align AddrAlign,
505                                  AtomicOrdering MemOpOrder, SyncScope::ID SSID,
506                                  Value *&Success, Value *&NewLoaded) {
507   Type *OrigTy = NewVal->getType();
508 
509   // This code can go away when cmpxchg supports FP types.
510   bool NeedBitcast = OrigTy->isFloatingPointTy();
511   if (NeedBitcast) {
512     IntegerType *IntTy = Builder.getIntNTy(OrigTy->getPrimitiveSizeInBits());
513     unsigned AS = Addr->getType()->getPointerAddressSpace();
514     Addr = Builder.CreateBitCast(Addr, IntTy->getPointerTo(AS));
515     NewVal = Builder.CreateBitCast(NewVal, IntTy);
516     Loaded = Builder.CreateBitCast(Loaded, IntTy);
517   }
518 
519   Value *Pair = Builder.CreateAtomicCmpXchg(
520       Addr, Loaded, NewVal, AddrAlign, MemOpOrder,
521       AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
522   Success = Builder.CreateExtractValue(Pair, 1, "success");
523   NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
524 
525   if (NeedBitcast)
526     NewLoaded = Builder.CreateBitCast(NewLoaded, OrigTy);
527 }
528 
529 /// Emit IR to implement the given atomicrmw operation on values in registers,
530 /// returning the new value.
531 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
532                               Value *Loaded, Value *Inc) {
533   Value *NewVal;
534   switch (Op) {
535   case AtomicRMWInst::Xchg:
536     return Inc;
537   case AtomicRMWInst::Add:
538     return Builder.CreateAdd(Loaded, Inc, "new");
539   case AtomicRMWInst::Sub:
540     return Builder.CreateSub(Loaded, Inc, "new");
541   case AtomicRMWInst::And:
542     return Builder.CreateAnd(Loaded, Inc, "new");
543   case AtomicRMWInst::Nand:
544     return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
545   case AtomicRMWInst::Or:
546     return Builder.CreateOr(Loaded, Inc, "new");
547   case AtomicRMWInst::Xor:
548     return Builder.CreateXor(Loaded, Inc, "new");
549   case AtomicRMWInst::Max:
550     NewVal = Builder.CreateICmpSGT(Loaded, Inc);
551     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
552   case AtomicRMWInst::Min:
553     NewVal = Builder.CreateICmpSLE(Loaded, Inc);
554     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
555   case AtomicRMWInst::UMax:
556     NewVal = Builder.CreateICmpUGT(Loaded, Inc);
557     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
558   case AtomicRMWInst::UMin:
559     NewVal = Builder.CreateICmpULE(Loaded, Inc);
560     return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
561   case AtomicRMWInst::FAdd:
562     return Builder.CreateFAdd(Loaded, Inc, "new");
563   case AtomicRMWInst::FSub:
564     return Builder.CreateFSub(Loaded, Inc, "new");
565   default:
566     llvm_unreachable("Unknown atomic op");
567   }
568 }
569 
570 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
571   LLVMContext &Ctx = AI->getModule()->getContext();
572   TargetLowering::AtomicExpansionKind Kind = TLI->shouldExpandAtomicRMWInIR(AI);
573   switch (Kind) {
574   case TargetLoweringBase::AtomicExpansionKind::None:
575     return false;
576   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
577     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
578     unsigned ValueSize = getAtomicOpSize(AI);
579     if (ValueSize < MinCASSize) {
580       expandPartwordAtomicRMW(AI,
581                               TargetLoweringBase::AtomicExpansionKind::LLSC);
582     } else {
583       auto PerformOp = [&](IRBuilder<> &Builder, Value *Loaded) {
584         return performAtomicOp(AI->getOperation(), Builder, Loaded,
585                                AI->getValOperand());
586       };
587       expandAtomicOpToLLSC(AI, AI->getType(), AI->getPointerOperand(),
588                            AI->getAlign(), AI->getOrdering(), PerformOp);
589     }
590     return true;
591   }
592   case TargetLoweringBase::AtomicExpansionKind::CmpXChg: {
593     unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
594     unsigned ValueSize = getAtomicOpSize(AI);
595     if (ValueSize < MinCASSize) {
596       // TODO: Handle atomicrmw fadd/fsub
597       if (AI->getType()->isFloatingPointTy())
598         return false;
599 
600       expandPartwordAtomicRMW(AI,
601                               TargetLoweringBase::AtomicExpansionKind::CmpXChg);
602     } else {
603       SmallVector<StringRef> SSNs;
604       Ctx.getSyncScopeNames(SSNs);
605       auto MemScope = SSNs[AI->getSyncScopeID()].empty()
606                           ? "system"
607                           : SSNs[AI->getSyncScopeID()];
608       OptimizationRemarkEmitter ORE(AI->getFunction());
609       ORE.emit([&]() {
610         return OptimizationRemark(DEBUG_TYPE, "Passed", AI)
611                << "A compare and swap loop was generated for an atomic "
612                << AI->getOperationName(AI->getOperation()) << " operation at "
613                << MemScope << " memory scope";
614       });
615       expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
616     }
617     return true;
618   }
619   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic: {
620     expandAtomicRMWToMaskedIntrinsic(AI);
621     return true;
622   }
623   case TargetLoweringBase::AtomicExpansionKind::BitTestIntrinsic: {
624     TLI->emitBitTestAtomicRMWIntrinsic(AI);
625     return true;
626   }
627   default:
628     llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
629   }
630 }
631 
632 namespace {
633 
634 struct PartwordMaskValues {
635   // These three fields are guaranteed to be set by createMaskInstrs.
636   Type *WordType = nullptr;
637   Type *ValueType = nullptr;
638   Value *AlignedAddr = nullptr;
639   Align AlignedAddrAlignment;
640   // The remaining fields can be null.
641   Value *ShiftAmt = nullptr;
642   Value *Mask = nullptr;
643   Value *Inv_Mask = nullptr;
644 };
645 
646 LLVM_ATTRIBUTE_UNUSED
647 raw_ostream &operator<<(raw_ostream &O, const PartwordMaskValues &PMV) {
648   auto PrintObj = [&O](auto *V) {
649     if (V)
650       O << *V;
651     else
652       O << "nullptr";
653     O << '\n';
654   };
655   O << "PartwordMaskValues {\n";
656   O << "  WordType: ";
657   PrintObj(PMV.WordType);
658   O << "  ValueType: ";
659   PrintObj(PMV.ValueType);
660   O << "  AlignedAddr: ";
661   PrintObj(PMV.AlignedAddr);
662   O << "  AlignedAddrAlignment: " << PMV.AlignedAddrAlignment.value() << '\n';
663   O << "  ShiftAmt: ";
664   PrintObj(PMV.ShiftAmt);
665   O << "  Mask: ";
666   PrintObj(PMV.Mask);
667   O << "  Inv_Mask: ";
668   PrintObj(PMV.Inv_Mask);
669   O << "}\n";
670   return O;
671 }
672 
673 } // end anonymous namespace
674 
675 /// This is a helper function which builds instructions to provide
676 /// values necessary for partword atomic operations. It takes an
677 /// incoming address, Addr, and ValueType, and constructs the address,
678 /// shift-amounts and masks needed to work with a larger value of size
679 /// WordSize.
680 ///
681 /// AlignedAddr: Addr rounded down to a multiple of WordSize
682 ///
683 /// ShiftAmt: Number of bits to right-shift a WordSize value loaded
684 ///           from AlignAddr for it to have the same value as if
685 ///           ValueType was loaded from Addr.
686 ///
687 /// Mask: Value to mask with the value loaded from AlignAddr to
688 ///       include only the part that would've been loaded from Addr.
689 ///
690 /// Inv_Mask: The inverse of Mask.
691 static PartwordMaskValues createMaskInstrs(IRBuilder<> &Builder, Instruction *I,
692                                            Type *ValueType, Value *Addr,
693                                            Align AddrAlign,
694                                            unsigned MinWordSize) {
695   PartwordMaskValues PMV;
696 
697   Module *M = I->getModule();
698   LLVMContext &Ctx = M->getContext();
699   const DataLayout &DL = M->getDataLayout();
700   unsigned ValueSize = DL.getTypeStoreSize(ValueType);
701 
702   PMV.ValueType = ValueType;
703   PMV.WordType = MinWordSize > ValueSize ? Type::getIntNTy(Ctx, MinWordSize * 8)
704                                          : ValueType;
705   if (PMV.ValueType == PMV.WordType) {
706     PMV.AlignedAddr = Addr;
707     PMV.AlignedAddrAlignment = AddrAlign;
708     PMV.ShiftAmt = ConstantInt::get(PMV.ValueType, 0);
709     PMV.Mask = ConstantInt::get(PMV.ValueType, ~0, /*isSigned*/ true);
710     return PMV;
711   }
712 
713   assert(ValueSize < MinWordSize);
714 
715   Type *WordPtrType =
716       PMV.WordType->getPointerTo(Addr->getType()->getPointerAddressSpace());
717 
718   // TODO: we could skip some of this if AddrAlign >= MinWordSize.
719   Value *AddrInt = Builder.CreatePtrToInt(Addr, DL.getIntPtrType(Ctx));
720   PMV.AlignedAddr = Builder.CreateIntToPtr(
721       Builder.CreateAnd(AddrInt, ~(uint64_t)(MinWordSize - 1)), WordPtrType,
722       "AlignedAddr");
723   PMV.AlignedAddrAlignment = Align(MinWordSize);
724 
725   Value *PtrLSB = Builder.CreateAnd(AddrInt, MinWordSize - 1, "PtrLSB");
726   if (DL.isLittleEndian()) {
727     // turn bytes into bits
728     PMV.ShiftAmt = Builder.CreateShl(PtrLSB, 3);
729   } else {
730     // turn bytes into bits, and count from the other side.
731     PMV.ShiftAmt = Builder.CreateShl(
732         Builder.CreateXor(PtrLSB, MinWordSize - ValueSize), 3);
733   }
734 
735   PMV.ShiftAmt = Builder.CreateTrunc(PMV.ShiftAmt, PMV.WordType, "ShiftAmt");
736   PMV.Mask = Builder.CreateShl(
737       ConstantInt::get(PMV.WordType, (1 << (ValueSize * 8)) - 1), PMV.ShiftAmt,
738       "Mask");
739   PMV.Inv_Mask = Builder.CreateNot(PMV.Mask, "Inv_Mask");
740   return PMV;
741 }
742 
743 static Value *extractMaskedValue(IRBuilder<> &Builder, Value *WideWord,
744                                  const PartwordMaskValues &PMV) {
745   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
746   if (PMV.WordType == PMV.ValueType)
747     return WideWord;
748 
749   Value *Shift = Builder.CreateLShr(WideWord, PMV.ShiftAmt, "shifted");
750   Value *Trunc = Builder.CreateTrunc(Shift, PMV.ValueType, "extracted");
751   return Trunc;
752 }
753 
754 static Value *insertMaskedValue(IRBuilder<> &Builder, Value *WideWord,
755                                 Value *Updated, const PartwordMaskValues &PMV) {
756   assert(WideWord->getType() == PMV.WordType && "Widened type mismatch");
757   assert(Updated->getType() == PMV.ValueType && "Value type mismatch");
758   if (PMV.WordType == PMV.ValueType)
759     return Updated;
760 
761   Value *ZExt = Builder.CreateZExt(Updated, PMV.WordType, "extended");
762   Value *Shift =
763       Builder.CreateShl(ZExt, PMV.ShiftAmt, "shifted", /*HasNUW*/ true);
764   Value *And = Builder.CreateAnd(WideWord, PMV.Inv_Mask, "unmasked");
765   Value *Or = Builder.CreateOr(And, Shift, "inserted");
766   return Or;
767 }
768 
769 /// Emit IR to implement a masked version of a given atomicrmw
770 /// operation. (That is, only the bits under the Mask should be
771 /// affected by the operation)
772 static Value *performMaskedAtomicOp(AtomicRMWInst::BinOp Op,
773                                     IRBuilder<> &Builder, Value *Loaded,
774                                     Value *Shifted_Inc, Value *Inc,
775                                     const PartwordMaskValues &PMV) {
776   // TODO: update to use
777   // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge in order
778   // to merge bits from two values without requiring PMV.Inv_Mask.
779   switch (Op) {
780   case AtomicRMWInst::Xchg: {
781     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
782     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, Shifted_Inc);
783     return FinalVal;
784   }
785   case AtomicRMWInst::Or:
786   case AtomicRMWInst::Xor:
787   case AtomicRMWInst::And:
788     llvm_unreachable("Or/Xor/And handled by widenPartwordAtomicRMW");
789   case AtomicRMWInst::Add:
790   case AtomicRMWInst::Sub:
791   case AtomicRMWInst::Nand: {
792     // The other arithmetic ops need to be masked into place.
793     Value *NewVal = performAtomicOp(Op, Builder, Loaded, Shifted_Inc);
794     Value *NewVal_Masked = Builder.CreateAnd(NewVal, PMV.Mask);
795     Value *Loaded_MaskOut = Builder.CreateAnd(Loaded, PMV.Inv_Mask);
796     Value *FinalVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Masked);
797     return FinalVal;
798   }
799   case AtomicRMWInst::Max:
800   case AtomicRMWInst::Min:
801   case AtomicRMWInst::UMax:
802   case AtomicRMWInst::UMin: {
803     // Finally, comparison ops will operate on the full value, so
804     // truncate down to the original size, and expand out again after
805     // doing the operation.
806     Value *Loaded_Extract = extractMaskedValue(Builder, Loaded, PMV);
807     Value *NewVal = performAtomicOp(Op, Builder, Loaded_Extract, Inc);
808     Value *FinalVal = insertMaskedValue(Builder, Loaded, NewVal, PMV);
809     return FinalVal;
810   }
811   default:
812     llvm_unreachable("Unknown atomic op");
813   }
814 }
815 
816 /// Expand a sub-word atomicrmw operation into an appropriate
817 /// word-sized operation.
818 ///
819 /// It will create an LL/SC or cmpxchg loop, as appropriate, the same
820 /// way as a typical atomicrmw expansion. The only difference here is
821 /// that the operation inside of the loop may operate upon only a
822 /// part of the value.
823 void AtomicExpand::expandPartwordAtomicRMW(
824     AtomicRMWInst *AI, TargetLoweringBase::AtomicExpansionKind ExpansionKind) {
825   AtomicOrdering MemOpOrder = AI->getOrdering();
826   SyncScope::ID SSID = AI->getSyncScopeID();
827 
828   IRBuilder<> Builder(AI);
829 
830   PartwordMaskValues PMV =
831       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
832                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
833 
834   Value *ValOperand_Shifted =
835       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
836                         PMV.ShiftAmt, "ValOperand_Shifted");
837 
838   auto PerformPartwordOp = [&](IRBuilder<> &Builder, Value *Loaded) {
839     return performMaskedAtomicOp(AI->getOperation(), Builder, Loaded,
840                                  ValOperand_Shifted, AI->getValOperand(), PMV);
841   };
842 
843   Value *OldResult;
844   if (ExpansionKind == TargetLoweringBase::AtomicExpansionKind::CmpXChg) {
845     OldResult = insertRMWCmpXchgLoop(Builder, PMV.WordType, PMV.AlignedAddr,
846                                      PMV.AlignedAddrAlignment, MemOpOrder, SSID,
847                                      PerformPartwordOp, createCmpXchgInstFun);
848   } else {
849     assert(ExpansionKind == TargetLoweringBase::AtomicExpansionKind::LLSC);
850     OldResult = insertRMWLLSCLoop(Builder, PMV.WordType, PMV.AlignedAddr,
851                                   PMV.AlignedAddrAlignment, MemOpOrder,
852                                   PerformPartwordOp);
853   }
854 
855   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
856   AI->replaceAllUsesWith(FinalOldResult);
857   AI->eraseFromParent();
858 }
859 
860 // Widen the bitwise atomicrmw (or/xor/and) to the minimum supported width.
861 AtomicRMWInst *AtomicExpand::widenPartwordAtomicRMW(AtomicRMWInst *AI) {
862   IRBuilder<> Builder(AI);
863   AtomicRMWInst::BinOp Op = AI->getOperation();
864 
865   assert((Op == AtomicRMWInst::Or || Op == AtomicRMWInst::Xor ||
866           Op == AtomicRMWInst::And) &&
867          "Unable to widen operation");
868 
869   PartwordMaskValues PMV =
870       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
871                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
872 
873   Value *ValOperand_Shifted =
874       Builder.CreateShl(Builder.CreateZExt(AI->getValOperand(), PMV.WordType),
875                         PMV.ShiftAmt, "ValOperand_Shifted");
876 
877   Value *NewOperand;
878 
879   if (Op == AtomicRMWInst::And)
880     NewOperand =
881         Builder.CreateOr(PMV.Inv_Mask, ValOperand_Shifted, "AndOperand");
882   else
883     NewOperand = ValOperand_Shifted;
884 
885   AtomicRMWInst *NewAI =
886       Builder.CreateAtomicRMW(Op, PMV.AlignedAddr, NewOperand,
887                               PMV.AlignedAddrAlignment, AI->getOrdering());
888 
889   Value *FinalOldResult = extractMaskedValue(Builder, NewAI, PMV);
890   AI->replaceAllUsesWith(FinalOldResult);
891   AI->eraseFromParent();
892   return NewAI;
893 }
894 
895 bool AtomicExpand::expandPartwordCmpXchg(AtomicCmpXchgInst *CI) {
896   // The basic idea here is that we're expanding a cmpxchg of a
897   // smaller memory size up to a word-sized cmpxchg. To do this, we
898   // need to add a retry-loop for strong cmpxchg, so that
899   // modifications to other parts of the word don't cause a spurious
900   // failure.
901 
902   // This generates code like the following:
903   //     [[Setup mask values PMV.*]]
904   //     %NewVal_Shifted = shl i32 %NewVal, %PMV.ShiftAmt
905   //     %Cmp_Shifted = shl i32 %Cmp, %PMV.ShiftAmt
906   //     %InitLoaded = load i32* %addr
907   //     %InitLoaded_MaskOut = and i32 %InitLoaded, %PMV.Inv_Mask
908   //     br partword.cmpxchg.loop
909   // partword.cmpxchg.loop:
910   //     %Loaded_MaskOut = phi i32 [ %InitLoaded_MaskOut, %entry ],
911   //        [ %OldVal_MaskOut, %partword.cmpxchg.failure ]
912   //     %FullWord_NewVal = or i32 %Loaded_MaskOut, %NewVal_Shifted
913   //     %FullWord_Cmp = or i32 %Loaded_MaskOut, %Cmp_Shifted
914   //     %NewCI = cmpxchg i32* %PMV.AlignedAddr, i32 %FullWord_Cmp,
915   //        i32 %FullWord_NewVal success_ordering failure_ordering
916   //     %OldVal = extractvalue { i32, i1 } %NewCI, 0
917   //     %Success = extractvalue { i32, i1 } %NewCI, 1
918   //     br i1 %Success, label %partword.cmpxchg.end,
919   //        label %partword.cmpxchg.failure
920   // partword.cmpxchg.failure:
921   //     %OldVal_MaskOut = and i32 %OldVal, %PMV.Inv_Mask
922   //     %ShouldContinue = icmp ne i32 %Loaded_MaskOut, %OldVal_MaskOut
923   //     br i1 %ShouldContinue, label %partword.cmpxchg.loop,
924   //         label %partword.cmpxchg.end
925   // partword.cmpxchg.end:
926   //    %tmp1 = lshr i32 %OldVal, %PMV.ShiftAmt
927   //    %FinalOldVal = trunc i32 %tmp1 to i8
928   //    %tmp2 = insertvalue { i8, i1 } undef, i8 %FinalOldVal, 0
929   //    %Res = insertvalue { i8, i1 } %25, i1 %Success, 1
930 
931   Value *Addr = CI->getPointerOperand();
932   Value *Cmp = CI->getCompareOperand();
933   Value *NewVal = CI->getNewValOperand();
934 
935   BasicBlock *BB = CI->getParent();
936   Function *F = BB->getParent();
937   IRBuilder<> Builder(CI);
938   LLVMContext &Ctx = Builder.getContext();
939 
940   BasicBlock *EndBB =
941       BB->splitBasicBlock(CI->getIterator(), "partword.cmpxchg.end");
942   auto FailureBB =
943       BasicBlock::Create(Ctx, "partword.cmpxchg.failure", F, EndBB);
944   auto LoopBB = BasicBlock::Create(Ctx, "partword.cmpxchg.loop", F, FailureBB);
945 
946   // The split call above "helpfully" added a branch at the end of BB
947   // (to the wrong place).
948   std::prev(BB->end())->eraseFromParent();
949   Builder.SetInsertPoint(BB);
950 
951   PartwordMaskValues PMV =
952       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
953                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
954 
955   // Shift the incoming values over, into the right location in the word.
956   Value *NewVal_Shifted =
957       Builder.CreateShl(Builder.CreateZExt(NewVal, PMV.WordType), PMV.ShiftAmt);
958   Value *Cmp_Shifted =
959       Builder.CreateShl(Builder.CreateZExt(Cmp, PMV.WordType), PMV.ShiftAmt);
960 
961   // Load the entire current word, and mask into place the expected and new
962   // values
963   LoadInst *InitLoaded = Builder.CreateLoad(PMV.WordType, PMV.AlignedAddr);
964   InitLoaded->setVolatile(CI->isVolatile());
965   Value *InitLoaded_MaskOut = Builder.CreateAnd(InitLoaded, PMV.Inv_Mask);
966   Builder.CreateBr(LoopBB);
967 
968   // partword.cmpxchg.loop:
969   Builder.SetInsertPoint(LoopBB);
970   PHINode *Loaded_MaskOut = Builder.CreatePHI(PMV.WordType, 2);
971   Loaded_MaskOut->addIncoming(InitLoaded_MaskOut, BB);
972 
973   // Mask/Or the expected and new values into place in the loaded word.
974   Value *FullWord_NewVal = Builder.CreateOr(Loaded_MaskOut, NewVal_Shifted);
975   Value *FullWord_Cmp = Builder.CreateOr(Loaded_MaskOut, Cmp_Shifted);
976   AtomicCmpXchgInst *NewCI = Builder.CreateAtomicCmpXchg(
977       PMV.AlignedAddr, FullWord_Cmp, FullWord_NewVal, PMV.AlignedAddrAlignment,
978       CI->getSuccessOrdering(), CI->getFailureOrdering(), CI->getSyncScopeID());
979   NewCI->setVolatile(CI->isVolatile());
980   // When we're building a strong cmpxchg, we need a loop, so you
981   // might think we could use a weak cmpxchg inside. But, using strong
982   // allows the below comparison for ShouldContinue, and we're
983   // expecting the underlying cmpxchg to be a machine instruction,
984   // which is strong anyways.
985   NewCI->setWeak(CI->isWeak());
986 
987   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
988   Value *Success = Builder.CreateExtractValue(NewCI, 1);
989 
990   if (CI->isWeak())
991     Builder.CreateBr(EndBB);
992   else
993     Builder.CreateCondBr(Success, EndBB, FailureBB);
994 
995   // partword.cmpxchg.failure:
996   Builder.SetInsertPoint(FailureBB);
997   // Upon failure, verify that the masked-out part of the loaded value
998   // has been modified.  If it didn't, abort the cmpxchg, since the
999   // masked-in part must've.
1000   Value *OldVal_MaskOut = Builder.CreateAnd(OldVal, PMV.Inv_Mask);
1001   Value *ShouldContinue = Builder.CreateICmpNE(Loaded_MaskOut, OldVal_MaskOut);
1002   Builder.CreateCondBr(ShouldContinue, LoopBB, EndBB);
1003 
1004   // Add the second value to the phi from above
1005   Loaded_MaskOut->addIncoming(OldVal_MaskOut, FailureBB);
1006 
1007   // partword.cmpxchg.end:
1008   Builder.SetInsertPoint(CI);
1009 
1010   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1011   Value *Res = UndefValue::get(CI->getType());
1012   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1013   Res = Builder.CreateInsertValue(Res, Success, 1);
1014 
1015   CI->replaceAllUsesWith(Res);
1016   CI->eraseFromParent();
1017   return true;
1018 }
1019 
1020 void AtomicExpand::expandAtomicOpToLLSC(
1021     Instruction *I, Type *ResultType, Value *Addr, Align AddrAlign,
1022     AtomicOrdering MemOpOrder,
1023     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1024   IRBuilder<> Builder(I);
1025   Value *Loaded = insertRMWLLSCLoop(Builder, ResultType, Addr, AddrAlign,
1026                                     MemOpOrder, PerformOp);
1027 
1028   I->replaceAllUsesWith(Loaded);
1029   I->eraseFromParent();
1030 }
1031 
1032 void AtomicExpand::expandAtomicRMWToMaskedIntrinsic(AtomicRMWInst *AI) {
1033   IRBuilder<> Builder(AI);
1034 
1035   PartwordMaskValues PMV =
1036       createMaskInstrs(Builder, AI, AI->getType(), AI->getPointerOperand(),
1037                        AI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1038 
1039   // The value operand must be sign-extended for signed min/max so that the
1040   // target's signed comparison instructions can be used. Otherwise, just
1041   // zero-ext.
1042   Instruction::CastOps CastOp = Instruction::ZExt;
1043   AtomicRMWInst::BinOp RMWOp = AI->getOperation();
1044   if (RMWOp == AtomicRMWInst::Max || RMWOp == AtomicRMWInst::Min)
1045     CastOp = Instruction::SExt;
1046 
1047   Value *ValOperand_Shifted = Builder.CreateShl(
1048       Builder.CreateCast(CastOp, AI->getValOperand(), PMV.WordType),
1049       PMV.ShiftAmt, "ValOperand_Shifted");
1050   Value *OldResult = TLI->emitMaskedAtomicRMWIntrinsic(
1051       Builder, AI, PMV.AlignedAddr, ValOperand_Shifted, PMV.Mask, PMV.ShiftAmt,
1052       AI->getOrdering());
1053   Value *FinalOldResult = extractMaskedValue(Builder, OldResult, PMV);
1054   AI->replaceAllUsesWith(FinalOldResult);
1055   AI->eraseFromParent();
1056 }
1057 
1058 void AtomicExpand::expandAtomicCmpXchgToMaskedIntrinsic(AtomicCmpXchgInst *CI) {
1059   IRBuilder<> Builder(CI);
1060 
1061   PartwordMaskValues PMV = createMaskInstrs(
1062       Builder, CI, CI->getCompareOperand()->getType(), CI->getPointerOperand(),
1063       CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1064 
1065   Value *CmpVal_Shifted = Builder.CreateShl(
1066       Builder.CreateZExt(CI->getCompareOperand(), PMV.WordType), PMV.ShiftAmt,
1067       "CmpVal_Shifted");
1068   Value *NewVal_Shifted = Builder.CreateShl(
1069       Builder.CreateZExt(CI->getNewValOperand(), PMV.WordType), PMV.ShiftAmt,
1070       "NewVal_Shifted");
1071   Value *OldVal = TLI->emitMaskedAtomicCmpXchgIntrinsic(
1072       Builder, CI, PMV.AlignedAddr, CmpVal_Shifted, NewVal_Shifted, PMV.Mask,
1073       CI->getMergedOrdering());
1074   Value *FinalOldVal = extractMaskedValue(Builder, OldVal, PMV);
1075   Value *Res = UndefValue::get(CI->getType());
1076   Res = Builder.CreateInsertValue(Res, FinalOldVal, 0);
1077   Value *Success = Builder.CreateICmpEQ(
1078       CmpVal_Shifted, Builder.CreateAnd(OldVal, PMV.Mask), "Success");
1079   Res = Builder.CreateInsertValue(Res, Success, 1);
1080 
1081   CI->replaceAllUsesWith(Res);
1082   CI->eraseFromParent();
1083 }
1084 
1085 Value *AtomicExpand::insertRMWLLSCLoop(
1086     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1087     AtomicOrdering MemOpOrder,
1088     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp) {
1089   LLVMContext &Ctx = Builder.getContext();
1090   BasicBlock *BB = Builder.GetInsertBlock();
1091   Function *F = BB->getParent();
1092 
1093   assert(AddrAlign >=
1094              F->getParent()->getDataLayout().getTypeStoreSize(ResultTy) &&
1095          "Expected at least natural alignment at this point.");
1096 
1097   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1098   //
1099   // The standard expansion we produce is:
1100   //     [...]
1101   // atomicrmw.start:
1102   //     %loaded = @load.linked(%addr)
1103   //     %new = some_op iN %loaded, %incr
1104   //     %stored = @store_conditional(%new, %addr)
1105   //     %try_again = icmp i32 ne %stored, 0
1106   //     br i1 %try_again, label %loop, label %atomicrmw.end
1107   // atomicrmw.end:
1108   //     [...]
1109   BasicBlock *ExitBB =
1110       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1111   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1112 
1113   // The split call above "helpfully" added a branch at the end of BB (to the
1114   // wrong place).
1115   std::prev(BB->end())->eraseFromParent();
1116   Builder.SetInsertPoint(BB);
1117   Builder.CreateBr(LoopBB);
1118 
1119   // Start the main loop block now that we've taken care of the preliminaries.
1120   Builder.SetInsertPoint(LoopBB);
1121   Value *Loaded = TLI->emitLoadLinked(Builder, ResultTy, Addr, MemOpOrder);
1122 
1123   Value *NewVal = PerformOp(Builder, Loaded);
1124 
1125   Value *StoreSuccess =
1126       TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
1127   Value *TryAgain = Builder.CreateICmpNE(
1128       StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1129   Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1130 
1131   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1132   return Loaded;
1133 }
1134 
1135 /// Convert an atomic cmpxchg of a non-integral type to an integer cmpxchg of
1136 /// the equivalent bitwidth.  We used to not support pointer cmpxchg in the
1137 /// IR.  As a migration step, we convert back to what use to be the standard
1138 /// way to represent a pointer cmpxchg so that we can update backends one by
1139 /// one.
1140 AtomicCmpXchgInst *
1141 AtomicExpand::convertCmpXchgToIntegerType(AtomicCmpXchgInst *CI) {
1142   auto *M = CI->getModule();
1143   Type *NewTy = getCorrespondingIntegerType(CI->getCompareOperand()->getType(),
1144                                             M->getDataLayout());
1145 
1146   IRBuilder<> Builder(CI);
1147 
1148   Value *Addr = CI->getPointerOperand();
1149   Type *PT = PointerType::get(NewTy, Addr->getType()->getPointerAddressSpace());
1150   Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1151 
1152   Value *NewCmp = Builder.CreatePtrToInt(CI->getCompareOperand(), NewTy);
1153   Value *NewNewVal = Builder.CreatePtrToInt(CI->getNewValOperand(), NewTy);
1154 
1155   auto *NewCI = Builder.CreateAtomicCmpXchg(
1156       NewAddr, NewCmp, NewNewVal, CI->getAlign(), CI->getSuccessOrdering(),
1157       CI->getFailureOrdering(), CI->getSyncScopeID());
1158   NewCI->setVolatile(CI->isVolatile());
1159   NewCI->setWeak(CI->isWeak());
1160   LLVM_DEBUG(dbgs() << "Replaced " << *CI << " with " << *NewCI << "\n");
1161 
1162   Value *OldVal = Builder.CreateExtractValue(NewCI, 0);
1163   Value *Succ = Builder.CreateExtractValue(NewCI, 1);
1164 
1165   OldVal = Builder.CreateIntToPtr(OldVal, CI->getCompareOperand()->getType());
1166 
1167   Value *Res = UndefValue::get(CI->getType());
1168   Res = Builder.CreateInsertValue(Res, OldVal, 0);
1169   Res = Builder.CreateInsertValue(Res, Succ, 1);
1170 
1171   CI->replaceAllUsesWith(Res);
1172   CI->eraseFromParent();
1173   return NewCI;
1174 }
1175 
1176 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1177   AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1178   AtomicOrdering FailureOrder = CI->getFailureOrdering();
1179   Value *Addr = CI->getPointerOperand();
1180   BasicBlock *BB = CI->getParent();
1181   Function *F = BB->getParent();
1182   LLVMContext &Ctx = F->getContext();
1183   // If shouldInsertFencesForAtomic() returns true, then the target does not
1184   // want to deal with memory orders, and emitLeading/TrailingFence should take
1185   // care of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1186   // should preserve the ordering.
1187   bool ShouldInsertFencesForAtomic = TLI->shouldInsertFencesForAtomic(CI);
1188   AtomicOrdering MemOpOrder = ShouldInsertFencesForAtomic
1189                                   ? AtomicOrdering::Monotonic
1190                                   : CI->getMergedOrdering();
1191 
1192   // In implementations which use a barrier to achieve release semantics, we can
1193   // delay emitting this barrier until we know a store is actually going to be
1194   // attempted. The cost of this delay is that we need 2 copies of the block
1195   // emitting the load-linked, affecting code size.
1196   //
1197   // Ideally, this logic would be unconditional except for the minsize check
1198   // since in other cases the extra blocks naturally collapse down to the
1199   // minimal loop. Unfortunately, this puts too much stress on later
1200   // optimisations so we avoid emitting the extra logic in those cases too.
1201   bool HasReleasedLoadBB = !CI->isWeak() && ShouldInsertFencesForAtomic &&
1202                            SuccessOrder != AtomicOrdering::Monotonic &&
1203                            SuccessOrder != AtomicOrdering::Acquire &&
1204                            !F->hasMinSize();
1205 
1206   // There's no overhead for sinking the release barrier in a weak cmpxchg, so
1207   // do it even on minsize.
1208   bool UseUnconditionalReleaseBarrier = F->hasMinSize() && !CI->isWeak();
1209 
1210   // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1211   //
1212   // The full expansion we produce is:
1213   //     [...]
1214   // %aligned.addr = ...
1215   // cmpxchg.start:
1216   //     %unreleasedload = @load.linked(%aligned.addr)
1217   //     %unreleasedload.extract = extract value from %unreleasedload
1218   //     %should_store = icmp eq %unreleasedload.extract, %desired
1219   //     br i1 %should_store, label %cmpxchg.releasingstore,
1220   //                          label %cmpxchg.nostore
1221   // cmpxchg.releasingstore:
1222   //     fence?
1223   //     br label cmpxchg.trystore
1224   // cmpxchg.trystore:
1225   //     %loaded.trystore = phi [%unreleasedload, %cmpxchg.releasingstore],
1226   //                            [%releasedload, %cmpxchg.releasedload]
1227   //     %updated.new = insert %new into %loaded.trystore
1228   //     %stored = @store_conditional(%updated.new, %aligned.addr)
1229   //     %success = icmp eq i32 %stored, 0
1230   //     br i1 %success, label %cmpxchg.success,
1231   //                     label %cmpxchg.releasedload/%cmpxchg.failure
1232   // cmpxchg.releasedload:
1233   //     %releasedload = @load.linked(%aligned.addr)
1234   //     %releasedload.extract = extract value from %releasedload
1235   //     %should_store = icmp eq %releasedload.extract, %desired
1236   //     br i1 %should_store, label %cmpxchg.trystore,
1237   //                          label %cmpxchg.failure
1238   // cmpxchg.success:
1239   //     fence?
1240   //     br label %cmpxchg.end
1241   // cmpxchg.nostore:
1242   //     %loaded.nostore = phi [%unreleasedload, %cmpxchg.start],
1243   //                           [%releasedload,
1244   //                               %cmpxchg.releasedload/%cmpxchg.trystore]
1245   //     @load_linked_fail_balance()?
1246   //     br label %cmpxchg.failure
1247   // cmpxchg.failure:
1248   //     fence?
1249   //     br label %cmpxchg.end
1250   // cmpxchg.end:
1251   //     %loaded.exit = phi [%loaded.nostore, %cmpxchg.failure],
1252   //                        [%loaded.trystore, %cmpxchg.trystore]
1253   //     %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1254   //     %loaded = extract value from %loaded.exit
1255   //     %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1256   //     %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1257   //     [...]
1258   BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1259   auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1260   auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1261   auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1262   auto ReleasedLoadBB =
1263       BasicBlock::Create(Ctx, "cmpxchg.releasedload", F, SuccessBB);
1264   auto TryStoreBB =
1265       BasicBlock::Create(Ctx, "cmpxchg.trystore", F, ReleasedLoadBB);
1266   auto ReleasingStoreBB =
1267       BasicBlock::Create(Ctx, "cmpxchg.fencedstore", F, TryStoreBB);
1268   auto StartBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, ReleasingStoreBB);
1269 
1270   // This grabs the DebugLoc from CI
1271   IRBuilder<> Builder(CI);
1272 
1273   // The split call above "helpfully" added a branch at the end of BB (to the
1274   // wrong place), but we might want a fence too. It's easiest to just remove
1275   // the branch entirely.
1276   std::prev(BB->end())->eraseFromParent();
1277   Builder.SetInsertPoint(BB);
1278   if (ShouldInsertFencesForAtomic && UseUnconditionalReleaseBarrier)
1279     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1280 
1281   PartwordMaskValues PMV =
1282       createMaskInstrs(Builder, CI, CI->getCompareOperand()->getType(), Addr,
1283                        CI->getAlign(), TLI->getMinCmpXchgSizeInBits() / 8);
1284   Builder.CreateBr(StartBB);
1285 
1286   // Start the main loop block now that we've taken care of the preliminaries.
1287   Builder.SetInsertPoint(StartBB);
1288   Value *UnreleasedLoad =
1289       TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
1290   Value *UnreleasedLoadExtract =
1291       extractMaskedValue(Builder, UnreleasedLoad, PMV);
1292   Value *ShouldStore = Builder.CreateICmpEQ(
1293       UnreleasedLoadExtract, CI->getCompareOperand(), "should_store");
1294 
1295   // If the cmpxchg doesn't actually need any ordering when it fails, we can
1296   // jump straight past that fence instruction (if it exists).
1297   Builder.CreateCondBr(ShouldStore, ReleasingStoreBB, NoStoreBB);
1298 
1299   Builder.SetInsertPoint(ReleasingStoreBB);
1300   if (ShouldInsertFencesForAtomic && !UseUnconditionalReleaseBarrier)
1301     TLI->emitLeadingFence(Builder, CI, SuccessOrder);
1302   Builder.CreateBr(TryStoreBB);
1303 
1304   Builder.SetInsertPoint(TryStoreBB);
1305   PHINode *LoadedTryStore =
1306       Builder.CreatePHI(PMV.WordType, 2, "loaded.trystore");
1307   LoadedTryStore->addIncoming(UnreleasedLoad, ReleasingStoreBB);
1308   Value *NewValueInsert =
1309       insertMaskedValue(Builder, LoadedTryStore, CI->getNewValOperand(), PMV);
1310   Value *StoreSuccess = TLI->emitStoreConditional(Builder, NewValueInsert,
1311                                                   PMV.AlignedAddr, MemOpOrder);
1312   StoreSuccess = Builder.CreateICmpEQ(
1313       StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1314   BasicBlock *RetryBB = HasReleasedLoadBB ? ReleasedLoadBB : StartBB;
1315   Builder.CreateCondBr(StoreSuccess, SuccessBB,
1316                        CI->isWeak() ? FailureBB : RetryBB);
1317 
1318   Builder.SetInsertPoint(ReleasedLoadBB);
1319   Value *SecondLoad;
1320   if (HasReleasedLoadBB) {
1321     SecondLoad =
1322         TLI->emitLoadLinked(Builder, PMV.WordType, PMV.AlignedAddr, MemOpOrder);
1323     Value *SecondLoadExtract = extractMaskedValue(Builder, SecondLoad, PMV);
1324     ShouldStore = Builder.CreateICmpEQ(SecondLoadExtract,
1325                                        CI->getCompareOperand(), "should_store");
1326 
1327     // If the cmpxchg doesn't actually need any ordering when it fails, we can
1328     // jump straight past that fence instruction (if it exists).
1329     Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1330     // Update PHI node in TryStoreBB.
1331     LoadedTryStore->addIncoming(SecondLoad, ReleasedLoadBB);
1332   } else
1333     Builder.CreateUnreachable();
1334 
1335   // Make sure later instructions don't get reordered with a fence if
1336   // necessary.
1337   Builder.SetInsertPoint(SuccessBB);
1338   if (ShouldInsertFencesForAtomic)
1339     TLI->emitTrailingFence(Builder, CI, SuccessOrder);
1340   Builder.CreateBr(ExitBB);
1341 
1342   Builder.SetInsertPoint(NoStoreBB);
1343   PHINode *LoadedNoStore =
1344       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.nostore");
1345   LoadedNoStore->addIncoming(UnreleasedLoad, StartBB);
1346   if (HasReleasedLoadBB)
1347     LoadedNoStore->addIncoming(SecondLoad, ReleasedLoadBB);
1348 
1349   // In the failing case, where we don't execute the store-conditional, the
1350   // target might want to balance out the load-linked with a dedicated
1351   // instruction (e.g., on ARM, clearing the exclusive monitor).
1352   TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1353   Builder.CreateBr(FailureBB);
1354 
1355   Builder.SetInsertPoint(FailureBB);
1356   PHINode *LoadedFailure =
1357       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.failure");
1358   LoadedFailure->addIncoming(LoadedNoStore, NoStoreBB);
1359   if (CI->isWeak())
1360     LoadedFailure->addIncoming(LoadedTryStore, TryStoreBB);
1361   if (ShouldInsertFencesForAtomic)
1362     TLI->emitTrailingFence(Builder, CI, FailureOrder);
1363   Builder.CreateBr(ExitBB);
1364 
1365   // Finally, we have control-flow based knowledge of whether the cmpxchg
1366   // succeeded or not. We expose this to later passes by converting any
1367   // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate
1368   // PHI.
1369   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1370   PHINode *LoadedExit =
1371       Builder.CreatePHI(UnreleasedLoad->getType(), 2, "loaded.exit");
1372   LoadedExit->addIncoming(LoadedTryStore, SuccessBB);
1373   LoadedExit->addIncoming(LoadedFailure, FailureBB);
1374   PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2, "success");
1375   Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1376   Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1377 
1378   // This is the "exit value" from the cmpxchg expansion. It may be of
1379   // a type wider than the one in the cmpxchg instruction.
1380   Value *LoadedFull = LoadedExit;
1381 
1382   Builder.SetInsertPoint(ExitBB, std::next(Success->getIterator()));
1383   Value *Loaded = extractMaskedValue(Builder, LoadedFull, PMV);
1384 
1385   // Look for any users of the cmpxchg that are just comparing the loaded value
1386   // against the desired one, and replace them with the CFG-derived version.
1387   SmallVector<ExtractValueInst *, 2> PrunedInsts;
1388   for (auto User : CI->users()) {
1389     ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1390     if (!EV)
1391       continue;
1392 
1393     assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1394            "weird extraction from { iN, i1 }");
1395 
1396     if (EV->getIndices()[0] == 0)
1397       EV->replaceAllUsesWith(Loaded);
1398     else
1399       EV->replaceAllUsesWith(Success);
1400 
1401     PrunedInsts.push_back(EV);
1402   }
1403 
1404   // We can remove the instructions now we're no longer iterating through them.
1405   for (auto EV : PrunedInsts)
1406     EV->eraseFromParent();
1407 
1408   if (!CI->use_empty()) {
1409     // Some use of the full struct return that we don't understand has happened,
1410     // so we've got to reconstruct it properly.
1411     Value *Res;
1412     Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1413     Res = Builder.CreateInsertValue(Res, Success, 1);
1414 
1415     CI->replaceAllUsesWith(Res);
1416   }
1417 
1418   CI->eraseFromParent();
1419   return true;
1420 }
1421 
1422 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst *RMWI) {
1423   auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1424   if (!C)
1425     return false;
1426 
1427   AtomicRMWInst::BinOp Op = RMWI->getOperation();
1428   switch (Op) {
1429   case AtomicRMWInst::Add:
1430   case AtomicRMWInst::Sub:
1431   case AtomicRMWInst::Or:
1432   case AtomicRMWInst::Xor:
1433     return C->isZero();
1434   case AtomicRMWInst::And:
1435     return C->isMinusOne();
1436   // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1437   default:
1438     return false;
1439   }
1440 }
1441 
1442 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst *RMWI) {
1443   if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1444     tryExpandAtomicLoad(ResultingLoad);
1445     return true;
1446   }
1447   return false;
1448 }
1449 
1450 Value *AtomicExpand::insertRMWCmpXchgLoop(
1451     IRBuilder<> &Builder, Type *ResultTy, Value *Addr, Align AddrAlign,
1452     AtomicOrdering MemOpOrder, SyncScope::ID SSID,
1453     function_ref<Value *(IRBuilder<> &, Value *)> PerformOp,
1454     CreateCmpXchgInstFun CreateCmpXchg) {
1455   LLVMContext &Ctx = Builder.getContext();
1456   BasicBlock *BB = Builder.GetInsertBlock();
1457   Function *F = BB->getParent();
1458 
1459   // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1460   //
1461   // The standard expansion we produce is:
1462   //     [...]
1463   //     %init_loaded = load atomic iN* %addr
1464   //     br label %loop
1465   // loop:
1466   //     %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1467   //     %new = some_op iN %loaded, %incr
1468   //     %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1469   //     %new_loaded = extractvalue { iN, i1 } %pair, 0
1470   //     %success = extractvalue { iN, i1 } %pair, 1
1471   //     br i1 %success, label %atomicrmw.end, label %loop
1472   // atomicrmw.end:
1473   //     [...]
1474   BasicBlock *ExitBB =
1475       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
1476   BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1477 
1478   // The split call above "helpfully" added a branch at the end of BB (to the
1479   // wrong place), but we want a load. It's easiest to just remove
1480   // the branch entirely.
1481   std::prev(BB->end())->eraseFromParent();
1482   Builder.SetInsertPoint(BB);
1483   LoadInst *InitLoaded = Builder.CreateAlignedLoad(ResultTy, Addr, AddrAlign);
1484   Builder.CreateBr(LoopBB);
1485 
1486   // Start the main loop block now that we've taken care of the preliminaries.
1487   Builder.SetInsertPoint(LoopBB);
1488   PHINode *Loaded = Builder.CreatePHI(ResultTy, 2, "loaded");
1489   Loaded->addIncoming(InitLoaded, BB);
1490 
1491   Value *NewVal = PerformOp(Builder, Loaded);
1492 
1493   Value *NewLoaded = nullptr;
1494   Value *Success = nullptr;
1495 
1496   CreateCmpXchg(Builder, Addr, Loaded, NewVal, AddrAlign,
1497                 MemOpOrder == AtomicOrdering::Unordered
1498                     ? AtomicOrdering::Monotonic
1499                     : MemOpOrder,
1500                 SSID, Success, NewLoaded);
1501   assert(Success && NewLoaded);
1502 
1503   Loaded->addIncoming(NewLoaded, LoopBB);
1504 
1505   Builder.CreateCondBr(Success, ExitBB, LoopBB);
1506 
1507   Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1508   return NewLoaded;
1509 }
1510 
1511 bool AtomicExpand::tryExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1512   unsigned MinCASSize = TLI->getMinCmpXchgSizeInBits() / 8;
1513   unsigned ValueSize = getAtomicOpSize(CI);
1514 
1515   switch (TLI->shouldExpandAtomicCmpXchgInIR(CI)) {
1516   default:
1517     llvm_unreachable("Unhandled case in tryExpandAtomicCmpXchg");
1518   case TargetLoweringBase::AtomicExpansionKind::None:
1519     if (ValueSize < MinCASSize)
1520       return expandPartwordCmpXchg(CI);
1521     return false;
1522   case TargetLoweringBase::AtomicExpansionKind::LLSC: {
1523     return expandAtomicCmpXchg(CI);
1524   }
1525   case TargetLoweringBase::AtomicExpansionKind::MaskedIntrinsic:
1526     expandAtomicCmpXchgToMaskedIntrinsic(CI);
1527     return true;
1528   }
1529 }
1530 
1531 // Note: This function is exposed externally by AtomicExpandUtils.h
1532 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1533                                     CreateCmpXchgInstFun CreateCmpXchg) {
1534   IRBuilder<> Builder(AI);
1535   Value *Loaded = AtomicExpand::insertRMWCmpXchgLoop(
1536       Builder, AI->getType(), AI->getPointerOperand(), AI->getAlign(),
1537       AI->getOrdering(), AI->getSyncScopeID(),
1538       [&](IRBuilder<> &Builder, Value *Loaded) {
1539         return performAtomicOp(AI->getOperation(), Builder, Loaded,
1540                                AI->getValOperand());
1541       },
1542       CreateCmpXchg);
1543 
1544   AI->replaceAllUsesWith(Loaded);
1545   AI->eraseFromParent();
1546   return true;
1547 }
1548 
1549 // In order to use one of the sized library calls such as
1550 // __atomic_fetch_add_4, the alignment must be sufficient, the size
1551 // must be one of the potentially-specialized sizes, and the value
1552 // type must actually exist in C on the target (otherwise, the
1553 // function wouldn't actually be defined.)
1554 static bool canUseSizedAtomicCall(unsigned Size, Align Alignment,
1555                                   const DataLayout &DL) {
1556   // TODO: "LargestSize" is an approximation for "largest type that
1557   // you can express in C". It seems to be the case that int128 is
1558   // supported on all 64-bit platforms, otherwise only up to 64-bit
1559   // integers are supported. If we get this wrong, then we'll try to
1560   // call a sized libcall that doesn't actually exist. There should
1561   // really be some more reliable way in LLVM of determining integer
1562   // sizes which are valid in the target's C ABI...
1563   unsigned LargestSize = DL.getLargestLegalIntTypeSizeInBits() >= 64 ? 16 : 8;
1564   return Alignment >= Size &&
1565          (Size == 1 || Size == 2 || Size == 4 || Size == 8 || Size == 16) &&
1566          Size <= LargestSize;
1567 }
1568 
1569 void AtomicExpand::expandAtomicLoadToLibcall(LoadInst *I) {
1570   static const RTLIB::Libcall Libcalls[6] = {
1571       RTLIB::ATOMIC_LOAD,   RTLIB::ATOMIC_LOAD_1, RTLIB::ATOMIC_LOAD_2,
1572       RTLIB::ATOMIC_LOAD_4, RTLIB::ATOMIC_LOAD_8, RTLIB::ATOMIC_LOAD_16};
1573   unsigned Size = getAtomicOpSize(I);
1574 
1575   bool expanded = expandAtomicOpToLibcall(
1576       I, Size, I->getAlign(), I->getPointerOperand(), nullptr, nullptr,
1577       I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1578   if (!expanded)
1579     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Load");
1580 }
1581 
1582 void AtomicExpand::expandAtomicStoreToLibcall(StoreInst *I) {
1583   static const RTLIB::Libcall Libcalls[6] = {
1584       RTLIB::ATOMIC_STORE,   RTLIB::ATOMIC_STORE_1, RTLIB::ATOMIC_STORE_2,
1585       RTLIB::ATOMIC_STORE_4, RTLIB::ATOMIC_STORE_8, RTLIB::ATOMIC_STORE_16};
1586   unsigned Size = getAtomicOpSize(I);
1587 
1588   bool expanded = expandAtomicOpToLibcall(
1589       I, Size, I->getAlign(), I->getPointerOperand(), I->getValueOperand(),
1590       nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1591   if (!expanded)
1592     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for Store");
1593 }
1594 
1595 void AtomicExpand::expandAtomicCASToLibcall(AtomicCmpXchgInst *I) {
1596   static const RTLIB::Libcall Libcalls[6] = {
1597       RTLIB::ATOMIC_COMPARE_EXCHANGE,   RTLIB::ATOMIC_COMPARE_EXCHANGE_1,
1598       RTLIB::ATOMIC_COMPARE_EXCHANGE_2, RTLIB::ATOMIC_COMPARE_EXCHANGE_4,
1599       RTLIB::ATOMIC_COMPARE_EXCHANGE_8, RTLIB::ATOMIC_COMPARE_EXCHANGE_16};
1600   unsigned Size = getAtomicOpSize(I);
1601 
1602   bool expanded = expandAtomicOpToLibcall(
1603       I, Size, I->getAlign(), I->getPointerOperand(), I->getNewValOperand(),
1604       I->getCompareOperand(), I->getSuccessOrdering(), I->getFailureOrdering(),
1605       Libcalls);
1606   if (!expanded)
1607     report_fatal_error("expandAtomicOpToLibcall shouldn't fail for CAS");
1608 }
1609 
1610 static ArrayRef<RTLIB::Libcall> GetRMWLibcall(AtomicRMWInst::BinOp Op) {
1611   static const RTLIB::Libcall LibcallsXchg[6] = {
1612       RTLIB::ATOMIC_EXCHANGE,   RTLIB::ATOMIC_EXCHANGE_1,
1613       RTLIB::ATOMIC_EXCHANGE_2, RTLIB::ATOMIC_EXCHANGE_4,
1614       RTLIB::ATOMIC_EXCHANGE_8, RTLIB::ATOMIC_EXCHANGE_16};
1615   static const RTLIB::Libcall LibcallsAdd[6] = {
1616       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_ADD_1,
1617       RTLIB::ATOMIC_FETCH_ADD_2, RTLIB::ATOMIC_FETCH_ADD_4,
1618       RTLIB::ATOMIC_FETCH_ADD_8, RTLIB::ATOMIC_FETCH_ADD_16};
1619   static const RTLIB::Libcall LibcallsSub[6] = {
1620       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_SUB_1,
1621       RTLIB::ATOMIC_FETCH_SUB_2, RTLIB::ATOMIC_FETCH_SUB_4,
1622       RTLIB::ATOMIC_FETCH_SUB_8, RTLIB::ATOMIC_FETCH_SUB_16};
1623   static const RTLIB::Libcall LibcallsAnd[6] = {
1624       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_AND_1,
1625       RTLIB::ATOMIC_FETCH_AND_2, RTLIB::ATOMIC_FETCH_AND_4,
1626       RTLIB::ATOMIC_FETCH_AND_8, RTLIB::ATOMIC_FETCH_AND_16};
1627   static const RTLIB::Libcall LibcallsOr[6] = {
1628       RTLIB::UNKNOWN_LIBCALL,   RTLIB::ATOMIC_FETCH_OR_1,
1629       RTLIB::ATOMIC_FETCH_OR_2, RTLIB::ATOMIC_FETCH_OR_4,
1630       RTLIB::ATOMIC_FETCH_OR_8, RTLIB::ATOMIC_FETCH_OR_16};
1631   static const RTLIB::Libcall LibcallsXor[6] = {
1632       RTLIB::UNKNOWN_LIBCALL,    RTLIB::ATOMIC_FETCH_XOR_1,
1633       RTLIB::ATOMIC_FETCH_XOR_2, RTLIB::ATOMIC_FETCH_XOR_4,
1634       RTLIB::ATOMIC_FETCH_XOR_8, RTLIB::ATOMIC_FETCH_XOR_16};
1635   static const RTLIB::Libcall LibcallsNand[6] = {
1636       RTLIB::UNKNOWN_LIBCALL,     RTLIB::ATOMIC_FETCH_NAND_1,
1637       RTLIB::ATOMIC_FETCH_NAND_2, RTLIB::ATOMIC_FETCH_NAND_4,
1638       RTLIB::ATOMIC_FETCH_NAND_8, RTLIB::ATOMIC_FETCH_NAND_16};
1639 
1640   switch (Op) {
1641   case AtomicRMWInst::BAD_BINOP:
1642     llvm_unreachable("Should not have BAD_BINOP.");
1643   case AtomicRMWInst::Xchg:
1644     return makeArrayRef(LibcallsXchg);
1645   case AtomicRMWInst::Add:
1646     return makeArrayRef(LibcallsAdd);
1647   case AtomicRMWInst::Sub:
1648     return makeArrayRef(LibcallsSub);
1649   case AtomicRMWInst::And:
1650     return makeArrayRef(LibcallsAnd);
1651   case AtomicRMWInst::Or:
1652     return makeArrayRef(LibcallsOr);
1653   case AtomicRMWInst::Xor:
1654     return makeArrayRef(LibcallsXor);
1655   case AtomicRMWInst::Nand:
1656     return makeArrayRef(LibcallsNand);
1657   case AtomicRMWInst::Max:
1658   case AtomicRMWInst::Min:
1659   case AtomicRMWInst::UMax:
1660   case AtomicRMWInst::UMin:
1661   case AtomicRMWInst::FAdd:
1662   case AtomicRMWInst::FSub:
1663     // No atomic libcalls are available for max/min/umax/umin.
1664     return {};
1665   }
1666   llvm_unreachable("Unexpected AtomicRMW operation.");
1667 }
1668 
1669 void AtomicExpand::expandAtomicRMWToLibcall(AtomicRMWInst *I) {
1670   ArrayRef<RTLIB::Libcall> Libcalls = GetRMWLibcall(I->getOperation());
1671 
1672   unsigned Size = getAtomicOpSize(I);
1673 
1674   bool Success = false;
1675   if (!Libcalls.empty())
1676     Success = expandAtomicOpToLibcall(
1677         I, Size, I->getAlign(), I->getPointerOperand(), I->getValOperand(),
1678         nullptr, I->getOrdering(), AtomicOrdering::NotAtomic, Libcalls);
1679 
1680   // The expansion failed: either there were no libcalls at all for
1681   // the operation (min/max), or there were only size-specialized
1682   // libcalls (add/sub/etc) and we needed a generic. So, expand to a
1683   // CAS libcall, via a CAS loop, instead.
1684   if (!Success) {
1685     expandAtomicRMWToCmpXchg(
1686         I, [this](IRBuilder<> &Builder, Value *Addr, Value *Loaded,
1687                   Value *NewVal, Align Alignment, AtomicOrdering MemOpOrder,
1688                   SyncScope::ID SSID, Value *&Success, Value *&NewLoaded) {
1689           // Create the CAS instruction normally...
1690           AtomicCmpXchgInst *Pair = Builder.CreateAtomicCmpXchg(
1691               Addr, Loaded, NewVal, Alignment, MemOpOrder,
1692               AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder), SSID);
1693           Success = Builder.CreateExtractValue(Pair, 1, "success");
1694           NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1695 
1696           // ...and then expand the CAS into a libcall.
1697           expandAtomicCASToLibcall(Pair);
1698         });
1699   }
1700 }
1701 
1702 // A helper routine for the above expandAtomic*ToLibcall functions.
1703 //
1704 // 'Libcalls' contains an array of enum values for the particular
1705 // ATOMIC libcalls to be emitted. All of the other arguments besides
1706 // 'I' are extracted from the Instruction subclass by the
1707 // caller. Depending on the particular call, some will be null.
1708 bool AtomicExpand::expandAtomicOpToLibcall(
1709     Instruction *I, unsigned Size, Align Alignment, Value *PointerOperand,
1710     Value *ValueOperand, Value *CASExpected, AtomicOrdering Ordering,
1711     AtomicOrdering Ordering2, ArrayRef<RTLIB::Libcall> Libcalls) {
1712   assert(Libcalls.size() == 6);
1713 
1714   LLVMContext &Ctx = I->getContext();
1715   Module *M = I->getModule();
1716   const DataLayout &DL = M->getDataLayout();
1717   IRBuilder<> Builder(I);
1718   IRBuilder<> AllocaBuilder(&I->getFunction()->getEntryBlock().front());
1719 
1720   bool UseSizedLibcall = canUseSizedAtomicCall(Size, Alignment, DL);
1721   Type *SizedIntTy = Type::getIntNTy(Ctx, Size * 8);
1722 
1723   const Align AllocaAlignment = DL.getPrefTypeAlign(SizedIntTy);
1724 
1725   // TODO: the "order" argument type is "int", not int32. So
1726   // getInt32Ty may be wrong if the arch uses e.g. 16-bit ints.
1727   ConstantInt *SizeVal64 = ConstantInt::get(Type::getInt64Ty(Ctx), Size);
1728   assert(Ordering != AtomicOrdering::NotAtomic && "expect atomic MO");
1729   Constant *OrderingVal =
1730       ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering));
1731   Constant *Ordering2Val = nullptr;
1732   if (CASExpected) {
1733     assert(Ordering2 != AtomicOrdering::NotAtomic && "expect atomic MO");
1734     Ordering2Val =
1735         ConstantInt::get(Type::getInt32Ty(Ctx), (int)toCABI(Ordering2));
1736   }
1737   bool HasResult = I->getType() != Type::getVoidTy(Ctx);
1738 
1739   RTLIB::Libcall RTLibType;
1740   if (UseSizedLibcall) {
1741     switch (Size) {
1742     case 1:
1743       RTLibType = Libcalls[1];
1744       break;
1745     case 2:
1746       RTLibType = Libcalls[2];
1747       break;
1748     case 4:
1749       RTLibType = Libcalls[3];
1750       break;
1751     case 8:
1752       RTLibType = Libcalls[4];
1753       break;
1754     case 16:
1755       RTLibType = Libcalls[5];
1756       break;
1757     }
1758   } else if (Libcalls[0] != RTLIB::UNKNOWN_LIBCALL) {
1759     RTLibType = Libcalls[0];
1760   } else {
1761     // Can't use sized function, and there's no generic for this
1762     // operation, so give up.
1763     return false;
1764   }
1765 
1766   if (!TLI->getLibcallName(RTLibType)) {
1767     // This target does not implement the requested atomic libcall so give up.
1768     return false;
1769   }
1770 
1771   // Build up the function call. There's two kinds. First, the sized
1772   // variants.  These calls are going to be one of the following (with
1773   // N=1,2,4,8,16):
1774   //  iN    __atomic_load_N(iN *ptr, int ordering)
1775   //  void  __atomic_store_N(iN *ptr, iN val, int ordering)
1776   //  iN    __atomic_{exchange|fetch_*}_N(iN *ptr, iN val, int ordering)
1777   //  bool  __atomic_compare_exchange_N(iN *ptr, iN *expected, iN desired,
1778   //                                    int success_order, int failure_order)
1779   //
1780   // Note that these functions can be used for non-integer atomic
1781   // operations, the values just need to be bitcast to integers on the
1782   // way in and out.
1783   //
1784   // And, then, the generic variants. They look like the following:
1785   //  void  __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1786   //  void  __atomic_store(size_t size, void *ptr, void *val, int ordering)
1787   //  void  __atomic_exchange(size_t size, void *ptr, void *val, void *ret,
1788   //                          int ordering)
1789   //  bool  __atomic_compare_exchange(size_t size, void *ptr, void *expected,
1790   //                                  void *desired, int success_order,
1791   //                                  int failure_order)
1792   //
1793   // The different signatures are built up depending on the
1794   // 'UseSizedLibcall', 'CASExpected', 'ValueOperand', and 'HasResult'
1795   // variables.
1796 
1797   AllocaInst *AllocaCASExpected = nullptr;
1798   Value *AllocaCASExpected_i8 = nullptr;
1799   AllocaInst *AllocaValue = nullptr;
1800   Value *AllocaValue_i8 = nullptr;
1801   AllocaInst *AllocaResult = nullptr;
1802   Value *AllocaResult_i8 = nullptr;
1803 
1804   Type *ResultTy;
1805   SmallVector<Value *, 6> Args;
1806   AttributeList Attr;
1807 
1808   // 'size' argument.
1809   if (!UseSizedLibcall) {
1810     // Note, getIntPtrType is assumed equivalent to size_t.
1811     Args.push_back(ConstantInt::get(DL.getIntPtrType(Ctx), Size));
1812   }
1813 
1814   // 'ptr' argument.
1815   // note: This assumes all address spaces share a common libfunc
1816   // implementation and that addresses are convertable.  For systems without
1817   // that property, we'd need to extend this mechanism to support AS-specific
1818   // families of atomic intrinsics.
1819   auto PtrTypeAS = PointerOperand->getType()->getPointerAddressSpace();
1820   Value *PtrVal =
1821       Builder.CreateBitCast(PointerOperand, Type::getInt8PtrTy(Ctx, PtrTypeAS));
1822   PtrVal = Builder.CreateAddrSpaceCast(PtrVal, Type::getInt8PtrTy(Ctx));
1823   Args.push_back(PtrVal);
1824 
1825   // 'expected' argument, if present.
1826   if (CASExpected) {
1827     AllocaCASExpected = AllocaBuilder.CreateAlloca(CASExpected->getType());
1828     AllocaCASExpected->setAlignment(AllocaAlignment);
1829     unsigned AllocaAS = AllocaCASExpected->getType()->getPointerAddressSpace();
1830 
1831     AllocaCASExpected_i8 = Builder.CreateBitCast(
1832         AllocaCASExpected, Type::getInt8PtrTy(Ctx, AllocaAS));
1833     Builder.CreateLifetimeStart(AllocaCASExpected_i8, SizeVal64);
1834     Builder.CreateAlignedStore(CASExpected, AllocaCASExpected, AllocaAlignment);
1835     Args.push_back(AllocaCASExpected_i8);
1836   }
1837 
1838   // 'val' argument ('desired' for cas), if present.
1839   if (ValueOperand) {
1840     if (UseSizedLibcall) {
1841       Value *IntValue =
1842           Builder.CreateBitOrPointerCast(ValueOperand, SizedIntTy);
1843       Args.push_back(IntValue);
1844     } else {
1845       AllocaValue = AllocaBuilder.CreateAlloca(ValueOperand->getType());
1846       AllocaValue->setAlignment(AllocaAlignment);
1847       AllocaValue_i8 =
1848           Builder.CreateBitCast(AllocaValue, Type::getInt8PtrTy(Ctx));
1849       Builder.CreateLifetimeStart(AllocaValue_i8, SizeVal64);
1850       Builder.CreateAlignedStore(ValueOperand, AllocaValue, AllocaAlignment);
1851       Args.push_back(AllocaValue_i8);
1852     }
1853   }
1854 
1855   // 'ret' argument.
1856   if (!CASExpected && HasResult && !UseSizedLibcall) {
1857     AllocaResult = AllocaBuilder.CreateAlloca(I->getType());
1858     AllocaResult->setAlignment(AllocaAlignment);
1859     unsigned AllocaAS = AllocaResult->getType()->getPointerAddressSpace();
1860     AllocaResult_i8 =
1861         Builder.CreateBitCast(AllocaResult, Type::getInt8PtrTy(Ctx, AllocaAS));
1862     Builder.CreateLifetimeStart(AllocaResult_i8, SizeVal64);
1863     Args.push_back(AllocaResult_i8);
1864   }
1865 
1866   // 'ordering' ('success_order' for cas) argument.
1867   Args.push_back(OrderingVal);
1868 
1869   // 'failure_order' argument, if present.
1870   if (Ordering2Val)
1871     Args.push_back(Ordering2Val);
1872 
1873   // Now, the return type.
1874   if (CASExpected) {
1875     ResultTy = Type::getInt1Ty(Ctx);
1876     Attr = Attr.addRetAttribute(Ctx, Attribute::ZExt);
1877   } else if (HasResult && UseSizedLibcall)
1878     ResultTy = SizedIntTy;
1879   else
1880     ResultTy = Type::getVoidTy(Ctx);
1881 
1882   // Done with setting up arguments and return types, create the call:
1883   SmallVector<Type *, 6> ArgTys;
1884   for (Value *Arg : Args)
1885     ArgTys.push_back(Arg->getType());
1886   FunctionType *FnType = FunctionType::get(ResultTy, ArgTys, false);
1887   FunctionCallee LibcallFn =
1888       M->getOrInsertFunction(TLI->getLibcallName(RTLibType), FnType, Attr);
1889   CallInst *Call = Builder.CreateCall(LibcallFn, Args);
1890   Call->setAttributes(Attr);
1891   Value *Result = Call;
1892 
1893   // And then, extract the results...
1894   if (ValueOperand && !UseSizedLibcall)
1895     Builder.CreateLifetimeEnd(AllocaValue_i8, SizeVal64);
1896 
1897   if (CASExpected) {
1898     // The final result from the CAS is {load of 'expected' alloca, bool result
1899     // from call}
1900     Type *FinalResultTy = I->getType();
1901     Value *V = UndefValue::get(FinalResultTy);
1902     Value *ExpectedOut = Builder.CreateAlignedLoad(
1903         CASExpected->getType(), AllocaCASExpected, AllocaAlignment);
1904     Builder.CreateLifetimeEnd(AllocaCASExpected_i8, SizeVal64);
1905     V = Builder.CreateInsertValue(V, ExpectedOut, 0);
1906     V = Builder.CreateInsertValue(V, Result, 1);
1907     I->replaceAllUsesWith(V);
1908   } else if (HasResult) {
1909     Value *V;
1910     if (UseSizedLibcall)
1911       V = Builder.CreateBitOrPointerCast(Result, I->getType());
1912     else {
1913       V = Builder.CreateAlignedLoad(I->getType(), AllocaResult,
1914                                     AllocaAlignment);
1915       Builder.CreateLifetimeEnd(AllocaResult_i8, SizeVal64);
1916     }
1917     I->replaceAllUsesWith(V);
1918   }
1919   I->eraseFromParent();
1920   return true;
1921 }
1922