1 //===-- AtomicExpandPass.cpp - Expand atomic instructions -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass (at IR level) to replace atomic instructions with
11 // target specific instruction which implement the same semantics in a way
12 // which better fits the target backend. This can include the use of either
13 // (intrinsic-based) load-linked/store-conditional loops, AtomicCmpXchg, or
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/MemoryLocation.h"
23 #include "llvm/CodeGen/AtomicExpandUtils.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstIterator.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/NoFolder.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "atomic-expand"
43 class AtomicExpand: public FunctionPass {
44 const TargetMachine *TM;
45 const TargetLowering *TLI;
47 static char ID; // Pass identification, replacement for typeid
48 explicit AtomicExpand(const TargetMachine *TM = nullptr)
49 : FunctionPass(ID), TM(TM), TLI(nullptr) {
50 initializeAtomicExpandPass(*PassRegistry::getPassRegistry());
53 bool runOnFunction(Function &F) override;
56 bool bracketInstWithFences(Instruction *I, AtomicOrdering Order,
57 bool IsStore, bool IsLoad);
58 IntegerType *getCorrespondingIntegerType(Type *T, const DataLayout &DL);
59 LoadInst *convertAtomicLoadToIntegerType(LoadInst *LI);
60 bool tryExpandAtomicLoad(LoadInst *LI);
61 bool expandAtomicLoadToLL(LoadInst *LI);
62 bool expandAtomicLoadToCmpXchg(LoadInst *LI);
63 StoreInst *convertAtomicStoreToIntegerType(StoreInst *SI);
64 bool expandAtomicStore(StoreInst *SI);
65 bool tryExpandAtomicRMW(AtomicRMWInst *AI);
66 bool expandAtomicOpToLLSC(
67 Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
68 std::function<Value *(IRBuilder<> &, Value *)> PerformOp);
69 bool expandAtomicCmpXchg(AtomicCmpXchgInst *CI);
70 bool isIdempotentRMW(AtomicRMWInst *AI);
71 bool simplifyIdempotentRMW(AtomicRMWInst *AI);
75 char AtomicExpand::ID = 0;
76 char &llvm::AtomicExpandID = AtomicExpand::ID;
77 INITIALIZE_TM_PASS(AtomicExpand, "atomic-expand",
78 "Expand Atomic calls in terms of either load-linked & store-conditional or cmpxchg",
81 FunctionPass *llvm::createAtomicExpandPass(const TargetMachine *TM) {
82 return new AtomicExpand(TM);
88 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal);
89 Value* GetUntaintedAddress(Value* CurrentAddress);
91 // The depth we trace down a variable to look for its dependence set.
92 const unsigned kDependenceDepth = 4;
94 // Recursively looks for variables that 'Val' depends on at the given depth
95 // 'Depth', and adds them in 'DepSet'. If 'InsertOnlyLeafNodes' is true, only
96 // inserts the leaf node values; otherwise, all visited nodes are included in
97 // 'DepSet'. Note that constants will be ignored.
98 template <typename SetType>
99 void recursivelyFindDependence(SetType* DepSet, Value* Val,
100 bool InsertOnlyLeafNodes = false,
101 unsigned Depth = kDependenceDepth) {
102 if (Val == nullptr) {
105 if (!InsertOnlyLeafNodes && !isa<Constant>(Val)) {
109 // Cannot go deeper. Insert the leaf nodes.
110 if (InsertOnlyLeafNodes && !isa<Constant>(Val)) {
116 // Go one step further to explore the dependence of the operands.
117 Instruction* I = nullptr;
118 if ((I = dyn_cast<Instruction>(Val))) {
119 if (isa<LoadInst>(I)) {
120 // A load is considerd the leaf load of the dependence tree. Done.
123 } else if (I->isBinaryOp()) {
124 BinaryOperator* I = dyn_cast<BinaryOperator>(Val);
125 Value *Op0 = I->getOperand(0), *Op1 = I->getOperand(1);
126 recursivelyFindDependence(DepSet, Op0, Depth - 1);
127 recursivelyFindDependence(DepSet, Op1, Depth - 1);
128 } else if (I->isCast()) {
129 Value* Op0 = I->getOperand(0);
130 recursivelyFindDependence(DepSet, Op0, Depth - 1);
131 } else if (I->getOpcode() == Instruction::Select) {
132 Value* Op0 = I->getOperand(0);
133 Value* Op1 = I->getOperand(1);
134 Value* Op2 = I->getOperand(2);
135 recursivelyFindDependence(DepSet, Op0, Depth - 1);
136 recursivelyFindDependence(DepSet, Op1, Depth - 1);
137 recursivelyFindDependence(DepSet, Op2, Depth - 1);
138 } else if (I->getOpcode() == Instruction::GetElementPtr) {
139 for (unsigned i = 0; i < I->getNumOperands(); i++) {
140 recursivelyFindDependence(DepSet, I->getOperand(i), Depth - 1);
142 } else if (I->getOpcode() == Instruction::Store) {
143 auto* SI = dyn_cast<StoreInst>(Val);
144 recursivelyFindDependence(DepSet, SI->getPointerOperand(), Depth - 1);
145 recursivelyFindDependence(DepSet, SI->getValueOperand(), Depth - 1);
147 Value* Op0 = nullptr;
148 Value* Op1 = nullptr;
149 switch (I->getOpcode()) {
150 case Instruction::ICmp:
151 case Instruction::FCmp: {
152 Op0 = I->getOperand(0);
153 Op1 = I->getOperand(1);
154 recursivelyFindDependence(DepSet, Op0, Depth - 1);
155 recursivelyFindDependence(DepSet, Op1, Depth - 1);
159 // Be conservative. Add it and be done with it.
165 } else if (isa<Constant>(Val)) {
166 // Not interested in constant values. Done.
169 // Be conservative. Add it and be done with it.
175 // Helper function to create a Cast instruction.
176 Value* createCast(IRBuilder<true, NoFolder>& Builder, Value* DepVal,
177 Type* TargetIntegerType) {
178 Instruction::CastOps CastOp = Instruction::BitCast;
179 switch (DepVal->getType()->getTypeID()) {
180 case Type::IntegerTyID: {
181 CastOp = Instruction::SExt;
184 case Type::FloatTyID:
185 case Type::DoubleTyID: {
186 CastOp = Instruction::FPToSI;
189 case Type::PointerTyID: {
190 CastOp = Instruction::PtrToInt;
196 return Builder.CreateCast(CastOp, DepVal, TargetIntegerType);
199 // Given a value, if it's a tainted address, this function returns the
200 // instruction that ORs the "dependence value" with the "original address".
201 // Otherwise, returns nullptr. This instruction is the first OR instruction
202 // where one of its operand is an AND instruction with an operand being 0.
204 // E.g., it returns '%4 = or i32 %3, %2' given 'CurrentAddress' is '%5'.
205 // %0 = load i32, i32* @y, align 4, !tbaa !1
206 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
207 // %1 = sext i1 %cmp to i32
208 // %2 = ptrtoint i32* @x to i32
209 // %3 = and i32 %1, 0
210 // %4 = or i32 %3, %2
211 // %5 = inttoptr i32 %4 to i32*
212 // store i32 1, i32* %5, align 4
213 Instruction* getOrAddress(Value* CurrentAddress) {
214 // Is it a cast from integer to pointer type.
215 Instruction* OrAddress = nullptr;
216 Instruction* AndDep = nullptr;
217 Instruction* CastToInt = nullptr;
218 Value* ActualAddress = nullptr;
219 Constant* ZeroConst = nullptr;
221 const Instruction* CastToPtr = dyn_cast<Instruction>(CurrentAddress);
222 if (CastToPtr && CastToPtr->getOpcode() == Instruction::IntToPtr) {
223 // Is it an OR instruction: %1 = or %and, %actualAddress.
224 if ((OrAddress = dyn_cast<Instruction>(CastToPtr->getOperand(0))) &&
225 OrAddress->getOpcode() == Instruction::Or) {
226 // The first operand should be and AND instruction.
227 AndDep = dyn_cast<Instruction>(OrAddress->getOperand(0));
228 if (AndDep && AndDep->getOpcode() == Instruction::And) {
229 // Also make sure its first operand of the "AND" is 0, or the "AND" is
230 // marked explicitly by "NoInstCombine".
231 if ((ZeroConst = dyn_cast<Constant>(AndDep->getOperand(1))) &&
232 ZeroConst->isNullValue()) {
238 // Looks like it's not been tainted.
242 // Given a value, if it's a tainted address, this function returns the
243 // instruction that taints the "dependence value". Otherwise, returns nullptr.
244 // This instruction is the last AND instruction where one of its operand is 0.
245 // E.g., it returns '%3' given 'CurrentAddress' is '%5'.
246 // %0 = load i32, i32* @y, align 4, !tbaa !1
247 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
248 // %1 = sext i1 %cmp to i32
249 // %2 = ptrtoint i32* @x to i32
250 // %3 = and i32 %1, 0
251 // %4 = or i32 %3, %2
252 // %5 = inttoptr i32 %4 to i32*
253 // store i32 1, i32* %5, align 4
254 Instruction* getAndDependence(Value* CurrentAddress) {
255 // If 'CurrentAddress' is tainted, get the OR instruction.
256 auto* OrAddress = getOrAddress(CurrentAddress);
257 if (OrAddress == nullptr) {
261 // No need to check the operands.
262 auto* AndDepInst = dyn_cast<Instruction>(OrAddress->getOperand(0));
267 // Given a value, if it's a tainted address, this function returns
268 // the "dependence value", which is the first operand in the AND instruction.
269 // E.g., it returns '%1' given 'CurrentAddress' is '%5'.
270 // %0 = load i32, i32* @y, align 4, !tbaa !1
271 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
272 // %1 = sext i1 %cmp to i32
273 // %2 = ptrtoint i32* @x to i32
274 // %3 = and i32 %1, 0
275 // %4 = or i32 %3, %2
276 // %5 = inttoptr i32 %4 to i32*
277 // store i32 1, i32* %5, align 4
278 Value* getDependence(Value* CurrentAddress) {
279 auto* AndInst = getAndDependence(CurrentAddress);
280 if (AndInst == nullptr) {
283 return AndInst->getOperand(0);
286 // Given an address that has been tainted, returns the only condition it depends
287 // on, if any; otherwise, returns nullptr.
288 Value* getConditionDependence(Value* Address) {
289 auto* Dep = getDependence(Address);
290 if (Dep == nullptr) {
291 // 'Address' has not been dependence-tainted.
295 Value* Operand = Dep;
297 auto* Inst = dyn_cast<Instruction>(Operand);
298 if (Inst == nullptr) {
299 // Non-instruction type does not have condition dependence.
302 if (Inst->getOpcode() == Instruction::ICmp) {
305 if (Inst->getNumOperands() != 1) {
308 Operand = Inst->getOperand(0);
314 // Conservatively decides whether the dependence set of 'Val1' includes the
315 // dependence set of 'Val2'. If 'ExpandSecondValue' is false, we do not expand
316 // 'Val2' and use that single value as its dependence set.
317 // If it returns true, it means the dependence set of 'Val1' includes that of
318 // 'Val2'; otherwise, it only means we cannot conclusively decide it.
319 bool dependenceSetInclusion(Value* Val1, Value* Val2,
320 int Val1ExpandLevel = 2 * kDependenceDepth,
321 int Val2ExpandLevel = kDependenceDepth) {
322 typedef SmallSet<Value*, 8> IncludingSet;
323 typedef SmallSet<Value*, 4> IncludedSet;
325 IncludingSet DepSet1;
327 // Look for more depths for the including set.
328 recursivelyFindDependence(&DepSet1, Val1, false /*Insert all visited nodes*/,
330 recursivelyFindDependence(&DepSet2, Val2, true /*Only insert leaf nodes*/,
333 auto set_inclusion = [](IncludingSet FullSet, IncludedSet Subset) {
334 for (auto* Dep : Subset) {
335 if (0 == FullSet.count(Dep)) {
341 bool inclusion = set_inclusion(DepSet1, DepSet2);
342 DEBUG(dbgs() << "[dependenceSetInclusion]: " << inclusion << "\n");
343 DEBUG(dbgs() << "Including set for: " << *Val1 << "\n");
344 DEBUG(for (const auto* Dep : DepSet1) { dbgs() << "\t\t" << *Dep << "\n"; });
345 DEBUG(dbgs() << "Included set for: " << *Val2 << "\n");
346 DEBUG(for (const auto* Dep : DepSet2) { dbgs() << "\t\t" << *Dep << "\n"; });
351 // Recursively iterates through the operands spawned from 'DepVal'. If there
352 // exists a single value that 'DepVal' only depends on, we call that value the
353 // root dependence of 'DepVal' and return it. Otherwise, return 'DepVal'.
354 Value* getRootDependence(Value* DepVal) {
355 SmallSet<Value*, 8> DepSet;
356 for (unsigned depth = kDependenceDepth; depth > 0; --depth) {
357 recursivelyFindDependence(&DepSet, DepVal, true /*Only insert leaf nodes*/,
359 if (DepSet.size() == 1) {
360 return *DepSet.begin();
367 // This function actually taints 'DepVal' to the address to 'SI'. If the
369 // of 'SI' already depends on whatever 'DepVal' depends on, this function
370 // doesn't do anything and returns false. Otherwise, returns true.
372 // This effect forces the store and any stores that comes later to depend on
373 // 'DepVal'. For example, we have a condition "cond", and a store instruction
374 // "s: STORE addr, val". If we want "s" (and any later store) to depend on
375 // "cond", we do the following:
376 // %conv = sext i1 %cond to i32
377 // %addrVal = ptrtoint i32* %addr to i32
378 // %andCond = and i32 conv, 0;
379 // %orAddr = or i32 %andCond, %addrVal;
380 // %NewAddr = inttoptr i32 %orAddr to i32*;
382 // This is a more concrete example:
384 // %0 = load i32, i32* @y, align 4, !tbaa !1
385 // %cmp = icmp ne i32 %0, 42 // <== this is like the condition
386 // %1 = sext i1 %cmp to i32
387 // %2 = ptrtoint i32* @x to i32
388 // %3 = and i32 %1, 0
389 // %4 = or i32 %3, %2
390 // %5 = inttoptr i32 %4 to i32*
391 // store i32 1, i32* %5, align 4
392 bool taintStoreAddress(StoreInst* SI, Value* DepVal,
393 const char* calling_func = __builtin_FUNCTION()) {
394 DEBUG(dbgs() << "Called from " << calling_func << '\n');
395 IRBuilder<true, NoFolder> Builder(SI);
396 BasicBlock* BB = SI->getParent();
397 Value* Address = SI->getPointerOperand();
398 Type* TargetIntegerType =
399 IntegerType::get(Address->getContext(),
400 BB->getModule()->getDataLayout().getPointerSizeInBits());
402 // Does SI's address already depends on whatever 'DepVal' depends on?
403 if (StoreAddressDependOnValue(SI, DepVal)) {
407 // Figure out if there's a root variable 'DepVal' depends on. For example, we
408 // can extract "getelementptr inbounds %struct, %struct* %0, i64 0, i32 123"
409 // to be "%struct* %0" since all other operands are constant.
410 DepVal = getRootDependence(DepVal);
412 // Is this already a dependence-tainted store?
413 Value* OldDep = getDependence(Address);
415 // The address of 'SI' has already been tainted. Just need to absorb the
416 // DepVal to the existing dependence in the address of SI.
417 Instruction* AndDep = getAndDependence(Address);
418 IRBuilder<true, NoFolder> Builder(AndDep);
419 Value* NewDep = nullptr;
420 if (DepVal->getType() == AndDep->getType()) {
421 NewDep = Builder.CreateAnd(OldDep, DepVal);
423 NewDep = Builder.CreateAnd(
424 OldDep, createCast(Builder, DepVal, TargetIntegerType));
427 auto* NewDepInst = dyn_cast<Instruction>(NewDep);
429 // Use the new AND instruction as the dependence
430 AndDep->setOperand(0, NewDep);
434 // SI's address has not been tainted. Now taint it with 'DepVal'.
435 Value* CastDepToInt = createCast(Builder, DepVal, TargetIntegerType);
436 Value* PtrToIntCast = Builder.CreatePtrToInt(Address, TargetIntegerType);
438 Builder.CreateAnd(CastDepToInt, ConstantInt::get(TargetIntegerType, 0));
439 auto AndInst = dyn_cast<Instruction>(AndDepVal);
440 // XXX-comment: The original IR InstCombiner would change our and instruction
441 // to a select and then the back end optimize the condition out. We attach a
442 // flag to instructions and set it here to inform the InstCombiner to not to
443 // touch this and instruction at all.
444 Value* OrAddr = Builder.CreateOr(AndDepVal, PtrToIntCast);
445 Value* NewAddr = Builder.CreateIntToPtr(OrAddr, Address->getType());
447 DEBUG(dbgs() << "[taintStoreAddress]\n"
448 << "Original store: " << *SI << '\n');
449 SI->setOperand(1, NewAddr);
452 DEBUG(dbgs() << "\tTargetIntegerType: " << *TargetIntegerType << '\n'
453 << "\tCast dependence value to integer: " << *CastDepToInt
455 << "\tCast address to integer: " << *PtrToIntCast << '\n'
456 << "\tAnd dependence value: " << *AndDepVal << '\n'
457 << "\tOr address: " << *OrAddr << '\n'
458 << "\tCast or instruction to address: " << *NewAddr << "\n\n");
463 // Looks for the previous store in the if block --- 'BrBB', which makes the
464 // speculative store 'StoreToHoist' safe.
465 Value* getSpeculativeStoreInPrevBB(StoreInst* StoreToHoist, BasicBlock* BrBB) {
466 assert(StoreToHoist && "StoreToHoist must be a real store");
468 Value* StorePtr = StoreToHoist->getPointerOperand();
470 // Look for a store to the same pointer in BrBB.
471 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(), RE = BrBB->rend();
473 Instruction* CurI = &*RI;
475 StoreInst* SI = dyn_cast<StoreInst>(CurI);
476 // Found the previous store make sure it stores to the same location.
477 // XXX-update: If the previous store's original untainted address are the
478 // same as 'StorePtr', we are also good to hoist the store.
479 if (SI && (SI->getPointerOperand() == StorePtr ||
480 GetUntaintedAddress(SI->getPointerOperand()) == StorePtr)) {
481 // Found the previous store, return its value operand.
487 "We should not reach here since this store is safe to speculate");
490 // XXX-comment: Returns true if it changes the code, false otherwise (the branch
491 // condition already depends on 'DepVal'.
492 bool taintConditionalBranch(BranchInst* BI, Value* DepVal) {
493 assert(BI->isConditional());
494 auto* Cond = BI->getOperand(0);
495 if (dependenceSetInclusion(Cond, DepVal)) {
496 // The dependence/ordering is self-evident.
500 IRBuilder<true, NoFolder> Builder(BI);
502 Builder.CreateAnd(DepVal, ConstantInt::get(DepVal->getType(), 0));
504 Builder.CreateTrunc(AndDep, IntegerType::get(DepVal->getContext(), 1));
505 auto* OrCond = Builder.CreateOr(TruncAndDep, Cond);
506 BI->setOperand(0, OrCond);
509 DEBUG(dbgs() << "\tTainted branch condition:\n" << *BI->getParent());
514 // XXX-update: For a relaxed load 'LI', find the first immediate atomic store or
515 // the first conditional branch. Returns nullptr if there's no such immediately
516 // following store/branch instructions, which we can only enforce the load with
518 Instruction* findFirstStoreCondBranchInst(LoadInst* LI) {
519 // In some situations, relaxed loads can be left as is:
520 // 1. The relaxed load is used to calculate the address of the immediate
522 // 2. The relaxed load is used as a condition in the immediate following
523 // condition, and there are no stores in between. This is actually quite
525 // int r1 = x.load(relaxed);
527 // y.store(1, relaxed);
529 // However, in this function, we don't deal with them directly. Instead, we
530 // just find the immediate following store/condition branch and return it.
532 auto* BB = LI->getParent();
534 auto BBI = BasicBlock::iterator(LI);
537 for (; BBI != BE; BBI++) {
538 auto* Inst = dyn_cast<Instruction>(&*BBI);
539 if (Inst == nullptr) {
542 if (Inst->getOpcode() == Instruction::Store) {
544 } else if (Inst->getOpcode() == Instruction::Br) {
545 auto* BrInst = dyn_cast<BranchInst>(Inst);
546 if (BrInst->isConditional()) {
549 // Reinitialize iterators with the destination of the unconditional
551 BB = BrInst->getSuccessor(0);
564 // XXX-comment: Returns whether the code has been changed.
565 bool taintMonotonicLoads(const SmallVector<LoadInst*, 1>& MonotonicLoadInsts) {
566 bool Changed = false;
567 for (auto* LI : MonotonicLoadInsts) {
568 auto* FirstInst = findFirstStoreCondBranchInst(LI);
569 if (FirstInst == nullptr) {
570 // We don't seem to be able to taint a following store/conditional branch
571 // instruction. Simply make it acquire.
572 DEBUG(dbgs() << "[RelaxedLoad]: Transformed to acquire load\n"
574 LI->setOrdering(Acquire);
578 // Taint 'FirstInst', which could be a store or a condition branch
580 if (FirstInst->getOpcode() == Instruction::Store) {
581 Changed |= taintStoreAddress(dyn_cast<StoreInst>(FirstInst), LI);
582 } else if (FirstInst->getOpcode() == Instruction::Br) {
583 Changed |= taintConditionalBranch(dyn_cast<BranchInst>(FirstInst), LI);
585 assert(false && "findFirstStoreCondBranchInst() should return a "
586 "store/condition branch instruction");
592 /**** Implementations of public methods for dependence tainting ****/
593 Value* GetUntaintedAddress(Value* CurrentAddress) {
594 auto* OrAddress = getOrAddress(CurrentAddress);
595 if (OrAddress == nullptr) {
596 // Is it tainted by a select instruction?
597 auto* Inst = dyn_cast<Instruction>(CurrentAddress);
598 if (nullptr != Inst && Inst->getOpcode() == Instruction::Select) {
599 // A selection instruction.
600 if (Inst->getOperand(1) == Inst->getOperand(2)) {
601 return Inst->getOperand(1);
605 return CurrentAddress;
607 Value* ActualAddress = nullptr;
609 auto* CastToInt = dyn_cast<Instruction>(OrAddress->getOperand(1));
610 if (CastToInt && CastToInt->getOpcode() == Instruction::PtrToInt) {
611 return CastToInt->getOperand(0);
613 // This should be a IntToPtr constant expression.
614 ConstantExpr* PtrToIntExpr =
615 dyn_cast<ConstantExpr>(OrAddress->getOperand(1));
616 if (PtrToIntExpr && PtrToIntExpr->getOpcode() == Instruction::PtrToInt) {
617 return PtrToIntExpr->getOperand(0);
621 // Looks like it's not been dependence-tainted. Returns itself.
622 return CurrentAddress;
625 MemoryLocation GetUntaintedMemoryLocation(StoreInst* SI) {
627 SI->getAAMetadata(AATags);
628 const auto& DL = SI->getModule()->getDataLayout();
629 const auto* OriginalAddr = GetUntaintedAddress(SI->getPointerOperand());
630 DEBUG(if (OriginalAddr != SI->getPointerOperand()) {
631 dbgs() << "[GetUntaintedMemoryLocation]\n"
632 << "Storing address: " << *SI->getPointerOperand()
633 << "\nUntainted address: " << *OriginalAddr << "\n";
635 return MemoryLocation(OriginalAddr,
636 DL.getTypeStoreSize(SI->getValueOperand()->getType()),
640 bool TaintDependenceToStore(StoreInst* SI, Value* DepVal) {
641 if (dependenceSetInclusion(SI, DepVal)) {
645 bool tainted = taintStoreAddress(SI, DepVal);
650 bool TaintDependenceToStoreAddress(StoreInst* SI, Value* DepVal) {
651 if (dependenceSetInclusion(SI->getPointerOperand(), DepVal)) {
655 bool tainted = taintStoreAddress(SI, DepVal);
660 bool CompressTaintedStore(BasicBlock* BB) {
661 // This function looks for windows of adajcent stores in 'BB' that satisfy the
662 // following condition (and then do optimization):
663 // *Addr(d1) = v1, d1 is a condition and is the only dependence the store's
664 // address depends on && Dep(v1) includes Dep(d1);
665 // *Addr(d2) = v2, d2 is a condition and is the only dependnece the store's
666 // address depends on && Dep(v2) includes Dep(d2) &&
667 // Dep(d2) includes Dep(d1);
669 // *Addr(dN) = vN, dN is a condition and is the only dependence the store's
670 // address depends on && Dep(dN) includes Dep(d"N-1").
672 // As a result, Dep(dN) includes [Dep(d1) V ... V Dep(d"N-1")], so we can
673 // safely transform the above to the following. In between these stores, we
674 // can omit untainted stores to the same address 'Addr' since they internally
675 // have dependence on the previous stores on the same address.
680 for (auto BI = BB->begin(), BE = BB->end(); BI != BE; BI++) {
681 // Look for the first store in such a window of adajacent stores.
682 auto* FirstSI = dyn_cast<StoreInst>(&*BI);
687 // The first store in the window must be tainted.
688 auto* UntaintedAddress = GetUntaintedAddress(FirstSI->getPointerOperand());
689 if (UntaintedAddress == FirstSI->getPointerOperand()) {
693 // The first store's address must directly depend on and only depend on a
695 auto* FirstSIDepCond = getConditionDependence(FirstSI->getPointerOperand());
696 if (nullptr == FirstSIDepCond) {
700 // Dep(first store's storing value) includes Dep(tainted dependence).
701 if (!dependenceSetInclusion(FirstSI->getValueOperand(), FirstSIDepCond)) {
705 // Look for subsequent stores to the same address that satisfy the condition
706 // of "compressing the dependence".
707 SmallVector<StoreInst*, 8> AdajacentStores;
708 AdajacentStores.push_back(FirstSI);
709 auto BII = BasicBlock::iterator(FirstSI);
710 for (BII++; BII != BE; BII++) {
711 auto* CurrSI = dyn_cast<StoreInst>(&*BII);
713 if (BII->mayHaveSideEffects()) {
714 // Be conservative. Instructions with side effects are similar to
721 auto* OrigAddress = GetUntaintedAddress(CurrSI->getPointerOperand());
722 auto* CurrSIDepCond = getConditionDependence(CurrSI->getPointerOperand());
723 // All other stores must satisfy either:
724 // A. 'CurrSI' is an untainted store to the same address, or
725 // B. the combination of the following 5 subconditions:
727 // 2. Untainted address is the same as the group's address;
728 // 3. The address is tainted with a sole value which is a condition;
729 // 4. The storing value depends on the condition in 3.
730 // 5. The condition in 3 depends on the previous stores dependence
733 // Condition A. Should ignore this store directly.
734 if (OrigAddress == CurrSI->getPointerOperand() &&
735 OrigAddress == UntaintedAddress) {
738 // Check condition B.
739 Value* Cond = nullptr;
740 if (OrigAddress == CurrSI->getPointerOperand() ||
741 OrigAddress != UntaintedAddress || CurrSIDepCond == nullptr ||
742 !dependenceSetInclusion(CurrSI->getValueOperand(), CurrSIDepCond)) {
743 // Check condition 1, 2, 3 & 4.
747 // Check condition 5.
748 StoreInst* PrevSI = AdajacentStores[AdajacentStores.size() - 1];
749 auto* PrevSIDepCond = getConditionDependence(PrevSI->getPointerOperand());
750 assert(PrevSIDepCond &&
751 "Store in the group must already depend on a condtion");
752 if (!dependenceSetInclusion(CurrSIDepCond, PrevSIDepCond)) {
756 AdajacentStores.push_back(CurrSI);
759 if (AdajacentStores.size() == 1) {
760 // The outer loop should keep looking from the next store.
764 // Now we have such a group of tainted stores to the same address.
765 DEBUG(dbgs() << "[CompressTaintedStore]\n");
766 DEBUG(dbgs() << "Original BB\n");
767 DEBUG(dbgs() << *BB << '\n');
768 auto* LastSI = AdajacentStores[AdajacentStores.size() - 1];
769 for (int i = 0; i < AdajacentStores.size() - 1; ++i) {
770 auto* SI = AdajacentStores[i];
772 // Use the original address for stores before the last one.
773 SI->setOperand(1, UntaintedAddress);
775 DEBUG(dbgs() << "Store address has been reversed: " << *SI << '\n';);
777 // XXX-comment: Try to make the last store use fewer registers.
778 // If LastSI's storing value is a select based on the condition with which
779 // its address is tainted, transform the tainted address to a select
780 // instruction, as follows:
781 // r1 = Select Cond ? A : B
786 // r1 = Select Cond ? A : B
787 // r2 = Select Cond ? Addr : Addr
789 // The idea is that both Select instructions depend on the same condition,
790 // so hopefully the backend can generate two cmov instructions for them (and
791 // this saves the number of registers needed).
792 auto* LastSIDep = getConditionDependence(LastSI->getPointerOperand());
793 auto* LastSIValue = dyn_cast<Instruction>(LastSI->getValueOperand());
794 if (LastSIValue && LastSIValue->getOpcode() == Instruction::Select &&
795 LastSIValue->getOperand(0) == LastSIDep) {
796 // XXX-comment: Maybe it's better for us to just leave it as an and/or
797 // dependence pattern.
799 IRBuilder<true, NoFolder> Builder(LastSI);
801 Builder.CreateSelect(LastSIDep, UntaintedAddress, UntaintedAddress);
802 LastSI->setOperand(1, Address);
803 DEBUG(dbgs() << "The last store becomes :" << *LastSI << "\n\n";);
811 bool PassDependenceToStore(Value* OldAddress, StoreInst* NewStore) {
812 Value* OldDep = getDependence(OldAddress);
813 // Return false when there's no dependence to pass from the OldAddress.
818 // No need to pass the dependence to NewStore's address if it already depends
819 // on whatever 'OldAddress' depends on.
820 if (StoreAddressDependOnValue(NewStore, OldDep)) {
823 return taintStoreAddress(NewStore, OldAddress);
826 SmallSet<Value*, 8> FindDependence(Value* Val) {
827 SmallSet<Value*, 8> DepSet;
828 recursivelyFindDependence(&DepSet, Val, true /*Only insert leaf nodes*/);
832 bool StoreAddressDependOnValue(StoreInst* SI, Value* DepVal) {
833 return dependenceSetInclusion(SI->getPointerOperand(), DepVal);
836 bool StoreDependOnValue(StoreInst* SI, Value* Dep) {
837 return dependenceSetInclusion(SI, Dep);
843 bool AtomicExpand::runOnFunction(Function &F) {
844 if (!TM || !TM->getSubtargetImpl(F)->enableAtomicExpand())
846 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
848 SmallVector<Instruction *, 1> AtomicInsts;
849 SmallVector<LoadInst*, 1> MonotonicLoadInsts;
851 // Changing control-flow while iterating through it is a bad idea, so gather a
852 // list of all atomic instructions before we start.
853 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
854 // XXX-update: For relaxed loads, change them to acquire. This includes
855 // relaxed loads, relaxed atomic RMW & relaxed atomic compare exchange.
857 switch (I->getOpcode()) {
858 case Instruction::AtomicCmpXchg: {
859 // XXX-comment: AtomicCmpXchg in AArch64 will be translated to a
860 // conditional branch that contains the value of the load anyway, so
861 // we don't need to do anything.
863 auto* CmpXchg = dyn_cast<AtomicCmpXchgInst>(&*I);
864 auto SuccOrdering = CmpXchg->getSuccessOrdering();
865 if (SuccOrdering == Monotonic) {
866 CmpXchg->setSuccessOrdering(Acquire);
867 } else if (SuccOrdering == Release) {
868 CmpXchg->setSuccessOrdering(AcquireRelease);
873 case Instruction::AtomicRMW: {
874 // XXX-comment: Similar to AtomicCmpXchg. These instructions in
875 // AArch64 will be translated to a loop whose condition depends on the
876 // store status, which further depends on the load value.
878 auto* RMW = dyn_cast<AtomicRMWInst>(&*I);
879 if (RMW->getOrdering() == Monotonic) {
880 RMW->setOrdering(Acquire);
885 case Instruction::Load: {
886 auto* LI = dyn_cast<LoadInst>(&*I);
887 if (LI->getOrdering() == Monotonic) {
889 DEBUG(dbgs() << "Transforming relaxed loads to acquire loads: "
891 LI->setOrdering(Acquire);
893 MonotonicLoadInsts.push_back(LI);
901 AtomicInsts.push_back(&*I);
905 bool MadeChange = false;
906 for (auto I : AtomicInsts) {
907 auto LI = dyn_cast<LoadInst>(I);
908 auto SI = dyn_cast<StoreInst>(I);
909 auto RMWI = dyn_cast<AtomicRMWInst>(I);
910 auto CASI = dyn_cast<AtomicCmpXchgInst>(I);
911 assert((LI || SI || RMWI || CASI || isa<FenceInst>(I)) &&
912 "Unknown atomic instruction");
914 auto FenceOrdering = Monotonic;
915 bool IsStore, IsLoad;
916 if (TLI->getInsertFencesForAtomic()) {
917 if (LI && isAtLeastAcquire(LI->getOrdering())) {
918 FenceOrdering = LI->getOrdering();
919 LI->setOrdering(Monotonic);
922 } else if (SI && isAtLeastRelease(SI->getOrdering())) {
923 FenceOrdering = SI->getOrdering();
924 SI->setOrdering(Monotonic);
927 } else if (RMWI && (isAtLeastRelease(RMWI->getOrdering()) ||
928 isAtLeastAcquire(RMWI->getOrdering()))) {
929 FenceOrdering = RMWI->getOrdering();
930 RMWI->setOrdering(Monotonic);
931 IsStore = IsLoad = true;
932 } else if (CASI && !TLI->shouldExpandAtomicCmpXchgInIR(CASI) &&
933 (isAtLeastRelease(CASI->getSuccessOrdering()) ||
934 isAtLeastAcquire(CASI->getSuccessOrdering()))) {
935 // If a compare and swap is lowered to LL/SC, we can do smarter fence
936 // insertion, with a stronger one on the success path than on the
937 // failure path. As a result, fence insertion is directly done by
938 // expandAtomicCmpXchg in that case.
939 FenceOrdering = CASI->getSuccessOrdering();
940 CASI->setSuccessOrdering(Monotonic);
941 CASI->setFailureOrdering(Monotonic);
942 IsStore = IsLoad = true;
945 if (FenceOrdering != Monotonic) {
946 MadeChange |= bracketInstWithFences(I, FenceOrdering, IsStore, IsLoad);
951 if (LI->getType()->isFloatingPointTy()) {
952 // TODO: add a TLI hook to control this so that each target can
953 // convert to lowering the original type one at a time.
954 LI = convertAtomicLoadToIntegerType(LI);
955 assert(LI->getType()->isIntegerTy() && "invariant broken");
959 MadeChange |= tryExpandAtomicLoad(LI);
961 if (SI->getValueOperand()->getType()->isFloatingPointTy()) {
962 // TODO: add a TLI hook to control this so that each target can
963 // convert to lowering the original type one at a time.
964 SI = convertAtomicStoreToIntegerType(SI);
965 assert(SI->getValueOperand()->getType()->isIntegerTy() &&
970 if (TLI->shouldExpandAtomicStoreInIR(SI))
971 MadeChange |= expandAtomicStore(SI);
973 // There are two different ways of expanding RMW instructions:
974 // - into a load if it is idempotent
975 // - into a Cmpxchg/LL-SC loop otherwise
976 // we try them in that order.
978 if (isIdempotentRMW(RMWI) && simplifyIdempotentRMW(RMWI)) {
981 MadeChange |= tryExpandAtomicRMW(RMWI);
983 } else if (CASI && TLI->shouldExpandAtomicCmpXchgInIR(CASI)) {
984 MadeChange |= expandAtomicCmpXchg(CASI);
988 MadeChange |= taintMonotonicLoads(MonotonicLoadInsts);
993 bool AtomicExpand::bracketInstWithFences(Instruction *I, AtomicOrdering Order,
994 bool IsStore, bool IsLoad) {
995 IRBuilder<> Builder(I);
997 auto LeadingFence = TLI->emitLeadingFence(Builder, Order, IsStore, IsLoad);
999 auto TrailingFence = TLI->emitTrailingFence(Builder, Order, IsStore, IsLoad);
1000 // The trailing fence is emitted before the instruction instead of after
1001 // because there is no easy way of setting Builder insertion point after
1002 // an instruction. So we must erase it from the BB, and insert it back
1003 // in the right place.
1004 // We have a guard here because not every atomic operation generates a
1006 if (TrailingFence) {
1007 TrailingFence->removeFromParent();
1008 TrailingFence->insertAfter(I);
1011 return (LeadingFence || TrailingFence);
1014 /// Get the iX type with the same bitwidth as T.
1015 IntegerType *AtomicExpand::getCorrespondingIntegerType(Type *T,
1016 const DataLayout &DL) {
1017 EVT VT = TLI->getValueType(DL, T);
1018 unsigned BitWidth = VT.getStoreSizeInBits();
1019 assert(BitWidth == VT.getSizeInBits() && "must be a power of two");
1020 return IntegerType::get(T->getContext(), BitWidth);
1023 /// Convert an atomic load of a non-integral type to an integer load of the
1024 /// equivelent bitwidth. See the function comment on
1025 /// convertAtomicStoreToIntegerType for background.
1026 LoadInst *AtomicExpand::convertAtomicLoadToIntegerType(LoadInst *LI) {
1027 auto *M = LI->getModule();
1028 Type *NewTy = getCorrespondingIntegerType(LI->getType(),
1029 M->getDataLayout());
1031 IRBuilder<> Builder(LI);
1033 Value *Addr = LI->getPointerOperand();
1034 Type *PT = PointerType::get(NewTy,
1035 Addr->getType()->getPointerAddressSpace());
1036 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1038 auto *NewLI = Builder.CreateLoad(NewAddr);
1039 NewLI->setAlignment(LI->getAlignment());
1040 NewLI->setVolatile(LI->isVolatile());
1041 NewLI->setAtomic(LI->getOrdering(), LI->getSynchScope());
1042 DEBUG(dbgs() << "Replaced " << *LI << " with " << *NewLI << "\n");
1044 Value *NewVal = Builder.CreateBitCast(NewLI, LI->getType());
1045 LI->replaceAllUsesWith(NewVal);
1046 LI->eraseFromParent();
1050 bool AtomicExpand::tryExpandAtomicLoad(LoadInst *LI) {
1051 switch (TLI->shouldExpandAtomicLoadInIR(LI)) {
1052 case TargetLoweringBase::AtomicExpansionKind::None:
1054 case TargetLoweringBase::AtomicExpansionKind::LLSC:
1055 return expandAtomicOpToLLSC(
1056 LI, LI->getPointerOperand(), LI->getOrdering(),
1057 [](IRBuilder<> &Builder, Value *Loaded) { return Loaded; });
1058 case TargetLoweringBase::AtomicExpansionKind::LLOnly:
1059 return expandAtomicLoadToLL(LI);
1060 case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
1061 return expandAtomicLoadToCmpXchg(LI);
1063 llvm_unreachable("Unhandled case in tryExpandAtomicLoad");
1066 bool AtomicExpand::expandAtomicLoadToLL(LoadInst *LI) {
1067 IRBuilder<> Builder(LI);
1069 // On some architectures, load-linked instructions are atomic for larger
1070 // sizes than normal loads. For example, the only 64-bit load guaranteed
1071 // to be single-copy atomic by ARM is an ldrexd (A3.5.3).
1073 TLI->emitLoadLinked(Builder, LI->getPointerOperand(), LI->getOrdering());
1074 TLI->emitAtomicCmpXchgNoStoreLLBalance(Builder);
1076 LI->replaceAllUsesWith(Val);
1077 LI->eraseFromParent();
1082 bool AtomicExpand::expandAtomicLoadToCmpXchg(LoadInst *LI) {
1083 IRBuilder<> Builder(LI);
1084 AtomicOrdering Order = LI->getOrdering();
1085 Value *Addr = LI->getPointerOperand();
1086 Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
1087 Constant *DummyVal = Constant::getNullValue(Ty);
1089 Value *Pair = Builder.CreateAtomicCmpXchg(
1090 Addr, DummyVal, DummyVal, Order,
1091 AtomicCmpXchgInst::getStrongestFailureOrdering(Order));
1092 Value *Loaded = Builder.CreateExtractValue(Pair, 0, "loaded");
1094 LI->replaceAllUsesWith(Loaded);
1095 LI->eraseFromParent();
1100 /// Convert an atomic store of a non-integral type to an integer store of the
1101 /// equivelent bitwidth. We used to not support floating point or vector
1102 /// atomics in the IR at all. The backends learned to deal with the bitcast
1103 /// idiom because that was the only way of expressing the notion of a atomic
1104 /// float or vector store. The long term plan is to teach each backend to
1105 /// instruction select from the original atomic store, but as a migration
1106 /// mechanism, we convert back to the old format which the backends understand.
1107 /// Each backend will need individual work to recognize the new format.
1108 StoreInst *AtomicExpand::convertAtomicStoreToIntegerType(StoreInst *SI) {
1109 IRBuilder<> Builder(SI);
1110 auto *M = SI->getModule();
1111 Type *NewTy = getCorrespondingIntegerType(SI->getValueOperand()->getType(),
1112 M->getDataLayout());
1113 Value *NewVal = Builder.CreateBitCast(SI->getValueOperand(), NewTy);
1115 Value *Addr = SI->getPointerOperand();
1116 Type *PT = PointerType::get(NewTy,
1117 Addr->getType()->getPointerAddressSpace());
1118 Value *NewAddr = Builder.CreateBitCast(Addr, PT);
1120 StoreInst *NewSI = Builder.CreateStore(NewVal, NewAddr);
1121 NewSI->setAlignment(SI->getAlignment());
1122 NewSI->setVolatile(SI->isVolatile());
1123 NewSI->setAtomic(SI->getOrdering(), SI->getSynchScope());
1124 DEBUG(dbgs() << "Replaced " << *SI << " with " << *NewSI << "\n");
1125 SI->eraseFromParent();
1129 bool AtomicExpand::expandAtomicStore(StoreInst *SI) {
1130 // This function is only called on atomic stores that are too large to be
1131 // atomic if implemented as a native store. So we replace them by an
1132 // atomic swap, that can be implemented for example as a ldrex/strex on ARM
1133 // or lock cmpxchg8/16b on X86, as these are atomic for larger sizes.
1134 // It is the responsibility of the target to only signal expansion via
1135 // shouldExpandAtomicRMW in cases where this is required and possible.
1136 IRBuilder<> Builder(SI);
1138 Builder.CreateAtomicRMW(AtomicRMWInst::Xchg, SI->getPointerOperand(),
1139 SI->getValueOperand(), SI->getOrdering());
1140 SI->eraseFromParent();
1142 // Now we have an appropriate swap instruction, lower it as usual.
1143 return tryExpandAtomicRMW(AI);
1146 static void createCmpXchgInstFun(IRBuilder<> &Builder, Value *Addr,
1147 Value *Loaded, Value *NewVal,
1148 AtomicOrdering MemOpOrder,
1149 Value *&Success, Value *&NewLoaded) {
1150 Value* Pair = Builder.CreateAtomicCmpXchg(
1151 Addr, Loaded, NewVal, MemOpOrder,
1152 AtomicCmpXchgInst::getStrongestFailureOrdering(MemOpOrder));
1153 Success = Builder.CreateExtractValue(Pair, 1, "success");
1154 NewLoaded = Builder.CreateExtractValue(Pair, 0, "newloaded");
1157 /// Emit IR to implement the given atomicrmw operation on values in registers,
1158 /// returning the new value.
1159 static Value *performAtomicOp(AtomicRMWInst::BinOp Op, IRBuilder<> &Builder,
1160 Value *Loaded, Value *Inc) {
1163 case AtomicRMWInst::Xchg:
1165 case AtomicRMWInst::Add:
1166 return Builder.CreateAdd(Loaded, Inc, "new");
1167 case AtomicRMWInst::Sub:
1168 return Builder.CreateSub(Loaded, Inc, "new");
1169 case AtomicRMWInst::And:
1170 return Builder.CreateAnd(Loaded, Inc, "new");
1171 case AtomicRMWInst::Nand:
1172 return Builder.CreateNot(Builder.CreateAnd(Loaded, Inc), "new");
1173 case AtomicRMWInst::Or:
1174 return Builder.CreateOr(Loaded, Inc, "new");
1175 case AtomicRMWInst::Xor:
1176 return Builder.CreateXor(Loaded, Inc, "new");
1177 case AtomicRMWInst::Max:
1178 NewVal = Builder.CreateICmpSGT(Loaded, Inc);
1179 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
1180 case AtomicRMWInst::Min:
1181 NewVal = Builder.CreateICmpSLE(Loaded, Inc);
1182 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
1183 case AtomicRMWInst::UMax:
1184 NewVal = Builder.CreateICmpUGT(Loaded, Inc);
1185 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
1186 case AtomicRMWInst::UMin:
1187 NewVal = Builder.CreateICmpULE(Loaded, Inc);
1188 return Builder.CreateSelect(NewVal, Loaded, Inc, "new");
1190 llvm_unreachable("Unknown atomic op");
1194 bool AtomicExpand::tryExpandAtomicRMW(AtomicRMWInst *AI) {
1195 switch (TLI->shouldExpandAtomicRMWInIR(AI)) {
1196 case TargetLoweringBase::AtomicExpansionKind::None:
1198 case TargetLoweringBase::AtomicExpansionKind::LLSC:
1199 return expandAtomicOpToLLSC(AI, AI->getPointerOperand(), AI->getOrdering(),
1200 [&](IRBuilder<> &Builder, Value *Loaded) {
1201 return performAtomicOp(AI->getOperation(),
1203 AI->getValOperand());
1205 case TargetLoweringBase::AtomicExpansionKind::CmpXChg:
1206 return expandAtomicRMWToCmpXchg(AI, createCmpXchgInstFun);
1208 llvm_unreachable("Unhandled case in tryExpandAtomicRMW");
1212 bool AtomicExpand::expandAtomicOpToLLSC(
1213 Instruction *I, Value *Addr, AtomicOrdering MemOpOrder,
1214 std::function<Value *(IRBuilder<> &, Value *)> PerformOp) {
1215 BasicBlock *BB = I->getParent();
1216 Function *F = BB->getParent();
1217 LLVMContext &Ctx = F->getContext();
1219 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1221 // The standard expansion we produce is:
1225 // %loaded = @load.linked(%addr)
1226 // %new = some_op iN %loaded, %incr
1227 // %stored = @store_conditional(%new, %addr)
1228 // %try_again = icmp i32 ne %stored, 0
1229 // br i1 %try_again, label %loop, label %atomicrmw.end
1233 BasicBlock *ExitBB = BB->splitBasicBlock(I->getIterator(), "atomicrmw.end");
1234 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1236 // This grabs the DebugLoc from I.
1237 IRBuilder<> Builder(I);
1239 // The split call above "helpfully" added a branch at the end of BB (to the
1240 // wrong place), but we might want a fence too. It's easiest to just remove
1241 // the branch entirely.
1242 std::prev(BB->end())->eraseFromParent();
1243 Builder.SetInsertPoint(BB);
1244 Builder.CreateBr(LoopBB);
1246 // Start the main loop block now that we've taken care of the preliminaries.
1247 Builder.SetInsertPoint(LoopBB);
1248 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1250 Value *NewVal = PerformOp(Builder, Loaded);
1252 Value *StoreSuccess =
1253 TLI->emitStoreConditional(Builder, NewVal, Addr, MemOpOrder);
1254 Value *TryAgain = Builder.CreateICmpNE(
1255 StoreSuccess, ConstantInt::get(IntegerType::get(Ctx, 32), 0), "tryagain");
1256 Builder.CreateCondBr(TryAgain, LoopBB, ExitBB);
1258 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1260 I->replaceAllUsesWith(Loaded);
1261 I->eraseFromParent();
1266 bool AtomicExpand::expandAtomicCmpXchg(AtomicCmpXchgInst *CI) {
1267 AtomicOrdering SuccessOrder = CI->getSuccessOrdering();
1268 AtomicOrdering FailureOrder = CI->getFailureOrdering();
1269 Value *Addr = CI->getPointerOperand();
1270 BasicBlock *BB = CI->getParent();
1271 Function *F = BB->getParent();
1272 LLVMContext &Ctx = F->getContext();
1273 // If getInsertFencesForAtomic() returns true, then the target does not want
1274 // to deal with memory orders, and emitLeading/TrailingFence should take care
1275 // of everything. Otherwise, emitLeading/TrailingFence are no-op and we
1276 // should preserve the ordering.
1277 AtomicOrdering MemOpOrder =
1278 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder;
1280 // Given: cmpxchg some_op iN* %addr, iN %desired, iN %new success_ord fail_ord
1282 // The full expansion we produce is:
1286 // %loaded = @load.linked(%addr)
1287 // %should_store = icmp eq %loaded, %desired
1288 // br i1 %should_store, label %cmpxchg.trystore,
1289 // label %cmpxchg.nostore
1290 // cmpxchg.trystore:
1291 // %stored = @store_conditional(%new, %addr)
1292 // %success = icmp eq i32 %stored, 0
1293 // br i1 %success, label %cmpxchg.success, label %loop/%cmpxchg.failure
1296 // br label %cmpxchg.end
1298 // @load_linked_fail_balance()?
1299 // br label %cmpxchg.failure
1302 // br label %cmpxchg.end
1304 // %success = phi i1 [true, %cmpxchg.success], [false, %cmpxchg.failure]
1305 // %restmp = insertvalue { iN, i1 } undef, iN %loaded, 0
1306 // %res = insertvalue { iN, i1 } %restmp, i1 %success, 1
1308 BasicBlock *ExitBB = BB->splitBasicBlock(CI->getIterator(), "cmpxchg.end");
1309 auto FailureBB = BasicBlock::Create(Ctx, "cmpxchg.failure", F, ExitBB);
1310 auto NoStoreBB = BasicBlock::Create(Ctx, "cmpxchg.nostore", F, FailureBB);
1311 auto SuccessBB = BasicBlock::Create(Ctx, "cmpxchg.success", F, NoStoreBB);
1312 auto TryStoreBB = BasicBlock::Create(Ctx, "cmpxchg.trystore", F, SuccessBB);
1313 auto LoopBB = BasicBlock::Create(Ctx, "cmpxchg.start", F, TryStoreBB);
1315 // This grabs the DebugLoc from CI
1316 IRBuilder<> Builder(CI);
1318 // The split call above "helpfully" added a branch at the end of BB (to the
1319 // wrong place), but we might want a fence too. It's easiest to just remove
1320 // the branch entirely.
1321 std::prev(BB->end())->eraseFromParent();
1322 Builder.SetInsertPoint(BB);
1323 TLI->emitLeadingFence(Builder, SuccessOrder, /*IsStore=*/true,
1325 Builder.CreateBr(LoopBB);
1327 // Start the main loop block now that we've taken care of the preliminaries.
1328 Builder.SetInsertPoint(LoopBB);
1329 Value *Loaded = TLI->emitLoadLinked(Builder, Addr, MemOpOrder);
1330 Value *ShouldStore =
1331 Builder.CreateICmpEQ(Loaded, CI->getCompareOperand(), "should_store");
1333 // If the cmpxchg doesn't actually need any ordering when it fails, we can
1334 // jump straight past that fence instruction (if it exists).
1335 Builder.CreateCondBr(ShouldStore, TryStoreBB, NoStoreBB);
1337 Builder.SetInsertPoint(TryStoreBB);
1338 Value *StoreSuccess = TLI->emitStoreConditional(
1339 Builder, CI->getNewValOperand(), Addr, MemOpOrder);
1340 StoreSuccess = Builder.CreateICmpEQ(
1341 StoreSuccess, ConstantInt::get(Type::getInt32Ty(Ctx), 0), "success");
1342 Builder.CreateCondBr(StoreSuccess, SuccessBB,
1343 CI->isWeak() ? FailureBB : LoopBB);
1345 // Make sure later instructions don't get reordered with a fence if necessary.
1346 Builder.SetInsertPoint(SuccessBB);
1347 TLI->emitTrailingFence(Builder, SuccessOrder, /*IsStore=*/true,
1349 Builder.CreateBr(ExitBB);
1351 Builder.SetInsertPoint(NoStoreBB);
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);
1358 Builder.SetInsertPoint(FailureBB);
1359 TLI->emitTrailingFence(Builder, FailureOrder, /*IsStore=*/true,
1361 Builder.CreateBr(ExitBB);
1363 // Finally, we have control-flow based knowledge of whether the cmpxchg
1364 // succeeded or not. We expose this to later passes by converting any
1365 // subsequent "icmp eq/ne %loaded, %oldval" into a use of an appropriate PHI.
1367 // Setup the builder so we can create any PHIs we need.
1368 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1369 PHINode *Success = Builder.CreatePHI(Type::getInt1Ty(Ctx), 2);
1370 Success->addIncoming(ConstantInt::getTrue(Ctx), SuccessBB);
1371 Success->addIncoming(ConstantInt::getFalse(Ctx), FailureBB);
1373 // Look for any users of the cmpxchg that are just comparing the loaded value
1374 // against the desired one, and replace them with the CFG-derived version.
1375 SmallVector<ExtractValueInst *, 2> PrunedInsts;
1376 for (auto User : CI->users()) {
1377 ExtractValueInst *EV = dyn_cast<ExtractValueInst>(User);
1381 assert(EV->getNumIndices() == 1 && EV->getIndices()[0] <= 1 &&
1382 "weird extraction from { iN, i1 }");
1384 if (EV->getIndices()[0] == 0)
1385 EV->replaceAllUsesWith(Loaded);
1387 EV->replaceAllUsesWith(Success);
1389 PrunedInsts.push_back(EV);
1392 // We can remove the instructions now we're no longer iterating through them.
1393 for (auto EV : PrunedInsts)
1394 EV->eraseFromParent();
1396 if (!CI->use_empty()) {
1397 // Some use of the full struct return that we don't understand has happened,
1398 // so we've got to reconstruct it properly.
1400 Res = Builder.CreateInsertValue(UndefValue::get(CI->getType()), Loaded, 0);
1401 Res = Builder.CreateInsertValue(Res, Success, 1);
1403 CI->replaceAllUsesWith(Res);
1406 CI->eraseFromParent();
1410 bool AtomicExpand::isIdempotentRMW(AtomicRMWInst* RMWI) {
1411 auto C = dyn_cast<ConstantInt>(RMWI->getValOperand());
1415 AtomicRMWInst::BinOp Op = RMWI->getOperation();
1417 case AtomicRMWInst::Add:
1418 case AtomicRMWInst::Sub:
1419 case AtomicRMWInst::Or:
1420 case AtomicRMWInst::Xor:
1422 case AtomicRMWInst::And:
1423 return C->isMinusOne();
1424 // FIXME: we could also treat Min/Max/UMin/UMax by the INT_MIN/INT_MAX/...
1430 bool AtomicExpand::simplifyIdempotentRMW(AtomicRMWInst* RMWI) {
1431 if (auto ResultingLoad = TLI->lowerIdempotentRMWIntoFencedLoad(RMWI)) {
1432 tryExpandAtomicLoad(ResultingLoad);
1438 bool llvm::expandAtomicRMWToCmpXchg(AtomicRMWInst *AI,
1439 CreateCmpXchgInstFun CreateCmpXchg) {
1442 AtomicOrdering MemOpOrder =
1443 AI->getOrdering() == Unordered ? Monotonic : AI->getOrdering();
1444 Value *Addr = AI->getPointerOperand();
1445 BasicBlock *BB = AI->getParent();
1446 Function *F = BB->getParent();
1447 LLVMContext &Ctx = F->getContext();
1449 // Given: atomicrmw some_op iN* %addr, iN %incr ordering
1451 // The standard expansion we produce is:
1453 // %init_loaded = load atomic iN* %addr
1456 // %loaded = phi iN [ %init_loaded, %entry ], [ %new_loaded, %loop ]
1457 // %new = some_op iN %loaded, %incr
1458 // %pair = cmpxchg iN* %addr, iN %loaded, iN %new
1459 // %new_loaded = extractvalue { iN, i1 } %pair, 0
1460 // %success = extractvalue { iN, i1 } %pair, 1
1461 // br i1 %success, label %atomicrmw.end, label %loop
1464 BasicBlock *ExitBB = BB->splitBasicBlock(AI->getIterator(), "atomicrmw.end");
1465 BasicBlock *LoopBB = BasicBlock::Create(Ctx, "atomicrmw.start", F, ExitBB);
1467 // This grabs the DebugLoc from AI.
1468 IRBuilder<> Builder(AI);
1470 // The split call above "helpfully" added a branch at the end of BB (to the
1471 // wrong place), but we want a load. It's easiest to just remove
1472 // the branch entirely.
1473 std::prev(BB->end())->eraseFromParent();
1474 Builder.SetInsertPoint(BB);
1475 LoadInst *InitLoaded = Builder.CreateLoad(Addr);
1476 // Atomics require at least natural alignment.
1477 InitLoaded->setAlignment(AI->getType()->getPrimitiveSizeInBits() / 8);
1478 Builder.CreateBr(LoopBB);
1480 // Start the main loop block now that we've taken care of the preliminaries.
1481 Builder.SetInsertPoint(LoopBB);
1482 PHINode *Loaded = Builder.CreatePHI(AI->getType(), 2, "loaded");
1483 Loaded->addIncoming(InitLoaded, BB);
1486 performAtomicOp(AI->getOperation(), Builder, Loaded, AI->getValOperand());
1488 Value *NewLoaded = nullptr;
1489 Value *Success = nullptr;
1491 CreateCmpXchg(Builder, Addr, Loaded, NewVal, MemOpOrder,
1492 Success, NewLoaded);
1493 assert(Success && NewLoaded);
1495 Loaded->addIncoming(NewLoaded, LoopBB);
1497 Builder.CreateCondBr(Success, ExitBB, LoopBB);
1499 Builder.SetInsertPoint(ExitBB, ExitBB->begin());
1501 AI->replaceAllUsesWith(NewLoaded);
1502 AI->eraseFromParent();