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