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