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