Newer
Older
case IC_StoreWeak:
case IC_LoadWeak:
case IC_LoadWeakRetained:
case IC_InitWeak:
case IC_DestroyWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (isNullOrUndef(CI->getArgOperand(0))) {
Type *Ty = CI->getArgOperand(0)->getType();
new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
Constant::getNullValue(Ty),
CI);
CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
CI->eraseFromParent();
continue;
}
break;
}
case IC_CopyWeak:
case IC_MoveWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (isNullOrUndef(CI->getArgOperand(0)) ||
isNullOrUndef(CI->getArgOperand(1))) {
Type *Ty = CI->getArgOperand(0)->getType();
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
Constant::getNullValue(Ty),
CI);
CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
CI->eraseFromParent();
continue;
}
break;
}
case IC_Retain:
OptimizeRetainCall(F, Inst);
break;
case IC_RetainRV:
if (OptimizeRetainRVCall(F, Inst))
continue;
break;
case IC_AutoreleaseRV:
OptimizeAutoreleaseRVCall(F, Inst);
break;
}
// objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
if (IsAutorelease(Class) && Inst->use_empty()) {
CallInst *Call = cast<CallInst>(Inst);
const Value *Arg = Call->getArgOperand(0);
Arg = FindSingleUseIdentifiedObject(Arg);
if (Arg) {
Changed = true;
++NumAutoreleases;
// Create the declaration lazily.
LLVMContext &C = Inst->getContext();
CallInst *NewCall =
CallInst::Create(getReleaseCallee(F.getParent()),
Call->getArgOperand(0), "", Call);
NewCall->setMetadata(ImpreciseReleaseMDKind,
MDNode::get(C, ArrayRef<Value *>()));
EraseInstruction(Call);
Inst = NewCall;
Class = IC_Release;
}
}
// For functions which can never be passed stack arguments, add
// a tail keyword.
if (IsAlwaysTail(Class)) {
Changed = true;
cast<CallInst>(Inst)->setTailCall();
}
// Set nounwind as needed.
if (IsNoThrow(Class)) {
Changed = true;
cast<CallInst>(Inst)->setDoesNotThrow();
}
if (!IsNoopOnNull(Class)) {
UsedInThisFunction |= 1 << Class;
continue;
}
const Value *Arg = GetObjCArg(Inst);
// ARC calls with null are no-ops. Delete them.
if (isNullOrUndef(Arg)) {
Changed = true;
++NumNoops;
EraseInstruction(Inst);
continue;
}
// Keep track of which of retain, release, autorelease, and retain_block
// are actually present in this function.
UsedInThisFunction |= 1 << Class;
// If Arg is a PHI, and one or more incoming values to the
// PHI are null, and the call is control-equivalent to the PHI, and there
// are no relevant side effects between the PHI and the call, the call
// could be pushed up to just those paths with non-null incoming values.
// For now, don't bother splitting critical edges for this.
SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
Worklist.push_back(std::make_pair(Inst, Arg));
do {
std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
Inst = Pair.first;
Arg = Pair.second;
const PHINode *PN = dyn_cast<PHINode>(Arg);
if (!PN) continue;
// Determine if the PHI has any null operands, or any incoming
// critical edges.
bool HasNull = false;
bool HasCriticalEdges = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming =
StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
if (isNullOrUndef(Incoming))
HasNull = true;
else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
.getNumSuccessors() != 1) {
HasCriticalEdges = true;
break;
}
}
// If we have null operands and no critical edges, optimize.
if (!HasCriticalEdges && HasNull) {
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
// Check that there is nothing that cares about the reference
// count between the call and the phi.
FindDependencies(NeedsPositiveRetainCount, Arg,
Inst->getParent(), Inst,
DependingInstructions, Visited, PA);
if (DependingInstructions.size() == 1 &&
*DependingInstructions.begin() == PN) {
Changed = true;
++NumPartialNoops;
// Clone the call into each predecessor that has a non-null value.
CallInst *CInst = cast<CallInst>(Inst);
Type *ParamTy = CInst->getArgOperand(0)->getType();
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming =
StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
if (!isNullOrUndef(Incoming)) {
CallInst *Clone = cast<CallInst>(CInst->clone());
Value *Op = PN->getIncomingValue(i);
Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
if (Op->getType() != ParamTy)
Op = new BitCastInst(Op, ParamTy, "", InsertPos);
Clone->setArgOperand(0, Op);
Clone->insertBefore(InsertPos);
Worklist.push_back(std::make_pair(Clone, Incoming));
}
}
// Erase the original call.
EraseInstruction(CInst);
continue;
}
}
} while (!Worklist.empty());
}
}
/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
/// control flow, or other CFG structures where moving code across the edge
/// would result in it being executed more.
void
ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const {
// If any top-down local-use or possible-dec has a succ which is earlier in
// the sequence, forget it.
for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
E = MyStates.top_down_ptr_end(); I != E; ++I)
switch (I->second.GetSeq()) {
default: break;
case S_Use: {
const Value *Arg = I->first;
const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
bool SomeSuccHasSame = false;
bool AllSuccsHaveSame = true;
PtrState &S = MyStates.getPtrTopDownState(Arg);
for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
switch (SuccS.GetSeq()) {
case S_CanRelease: {
if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
S.ClearSequenceProgress();
continue;
}
case S_Use:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
AllSuccsHaveSame = false;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
// If the state at the other end of any of the successor edges
// matches the current state, require all edges to match. This
// guards against loops in the middle of a sequence.
if (SomeSuccHasSame && !AllSuccsHaveSame)
S.ClearSequenceProgress();
}
case S_CanRelease: {
const Value *Arg = I->first;
const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
bool SomeSuccHasSame = false;
bool AllSuccsHaveSame = true;
PtrState &S = MyStates.getPtrTopDownState(Arg);
for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
switch (SuccS.GetSeq()) {
case S_None: {
if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
S.ClearSequenceProgress();
continue;
}
case S_CanRelease:
SomeSuccHasSame = true;
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
case S_Use:
if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
AllSuccsHaveSame = false;
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
// If the state at the other end of any of the successor edges
// matches the current state, require all edges to match. This
// guards against loops in the middle of a sequence.
if (SomeSuccHasSame && !AllSuccsHaveSame)
S.ClearSequenceProgress();
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
}
}
}
bool
ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
MapVector<Value *, RRInfo> &Retains) {
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
// Merge the states from each successor to compute the initial state
// for the current block.
const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
succ_const_iterator SI(TI), SE(TI, false);
if (SI == SE)
MyStates.SetAsExit();
else
do {
const BasicBlock *Succ = *SI++;
if (Succ == BB)
continue;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
// If we haven't seen this node yet, then we've found a CFG cycle.
// Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
if (I == BBStates.end())
continue;
MyStates.InitFromSucc(I->second);
while (SI != SE) {
Succ = *SI++;
if (Succ != BB) {
I = BBStates.find(Succ);
if (I != BBStates.end())
MyStates.MergeSucc(I->second);
}
}
break;
} while (SI != SE);
// Visit all the instructions, bottom-up.
for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
Instruction *Inst = llvm::prior(I);
InstructionClass Class = GetInstructionClass(Inst);
const Value *Arg = 0;
switch (Class) {
case IC_Release: {
Arg = GetObjCArg(Inst);
PtrState &S = MyStates.getPtrBottomUpState(Arg);
// If we see two releases in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second release, which may allow us to
// eliminate the first release too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
NestingDetected = true;
S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
S.RRI.clear();
S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
S.RRI.Calls.insert(Inst);
S.IncrementRefCount();
S.IncrementNestCount();
break;
}
case IC_RetainBlock:
case IC_Retain:
case IC_RetainRV: {
Arg = GetObjCArg(Inst);
PtrState &S = MyStates.getPtrBottomUpState(Arg);
S.DecrementRefCount();
S.SetAtLeastOneRefCount();
S.DecrementNestCount();
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
switch (S.GetSeq()) {
case S_Stop:
case S_Release:
case S_MovableRelease:
case S_Use:
S.RRI.ReverseInsertPts.clear();
// FALL THROUGH
case S_CanRelease:
// Don't do retain+release tracking for IC_RetainRV, because it's
// better to let it remain as the first instruction after a call.
if (Class != IC_RetainRV) {
S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Retains[Inst] = S.RRI;
}
S.ClearSequenceProgress();
break;
case S_None:
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
}
case IC_AutoreleasepoolPop:
// Conservatively, clear MyStates for all known pointers.
MyStates.clearBottomUpPointers();
continue;
case IC_AutoreleasepoolPush:
case IC_None:
// These are irrelevant.
continue;
default:
break;
}
// Consider any other possible effects of this instruction on each
// pointer being tracked.
for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; // Handled above.
PtrState &S = MI->second;
Sequence Seq = S.GetSeq();
// Check for possible releases.
if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
S.DecrementRefCount();
switch (Seq) {
case S_Use:
S.SetSeq(S_CanRelease);
continue;
case S_CanRelease:
case S_Release:
case S_MovableRelease:
case S_Stop:
case S_None:
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
// Check for possible direct uses.
switch (Seq) {
case S_Release:
case S_MovableRelease:
if (CanUse(Inst, Ptr, PA, Class)) {
S.RRI.ReverseInsertPts.clear();
S.RRI.ReverseInsertPts.insert(Inst);
S.SetSeq(S_Use);
} else if (Seq == S_Release &&
(Class == IC_User || Class == IC_CallOrUser)) {
// Non-movable releases depend on any possible objc pointer use.
S.SetSeq(S_Stop);
S.RRI.ReverseInsertPts.clear();
S.RRI.ReverseInsertPts.insert(Inst);
}
break;
case S_Stop:
if (CanUse(Inst, Ptr, PA, Class))
S.SetSeq(S_Use);
break;
case S_CanRelease:
case S_Use:
case S_None:
break;
case S_Retain:
llvm_unreachable("bottom-up pointer in retain state!");
}
}
}
return NestingDetected;
}
bool
ObjCARCOpt::VisitTopDown(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases) {
bool NestingDetected = false;
BBState &MyStates = BBStates[BB];
// Merge the states from each predecessor to compute the initial state
// for the current block.
const_pred_iterator PI(BB), PE(BB, false);
if (PI == PE)
MyStates.SetAsEntry();
else
do {
const BasicBlock *Pred = *PI++;
if (Pred == BB)
continue;
DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
assert(I != BBStates.end());
// If we haven't seen this node yet, then we've found a CFG cycle.
// Be optimistic here; it's CheckForCFGHazards' job detect trouble.
if (!I->second.isVisitedTopDown())
continue;
MyStates.InitFromPred(I->second);
while (PI != PE) {
Pred = *PI++;
if (Pred != BB) {
I = BBStates.find(Pred);
assert(I != BBStates.end());
if (I->second.isVisitedTopDown())
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
MyStates.MergePred(I->second);
}
}
break;
} while (PI != PE);
// Visit all the instructions, top-down.
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Instruction *Inst = I;
InstructionClass Class = GetInstructionClass(Inst);
const Value *Arg = 0;
switch (Class) {
case IC_RetainBlock:
case IC_Retain:
case IC_RetainRV: {
Arg = GetObjCArg(Inst);
PtrState &S = MyStates.getPtrTopDownState(Arg);
// Don't do retain+release tracking for IC_RetainRV, because it's
// better to let it remain as the first instruction after a call.
if (Class != IC_RetainRV) {
// If we see two retains in a row on the same pointer. If so, make
// a note, and we'll cicle back to revisit it after we've
// hopefully eliminated the second retain, which may allow us to
// eliminate the first retain too.
// Theoretically we could implement removal of nested retain+release
// pairs by making PtrState hold a stack of states, but this is
// simple and avoids adding overhead for the non-nested case.
if (S.GetSeq() == S_Retain)
NestingDetected = true;
S.SetSeq(S_Retain);
S.RRI.clear();
S.RRI.IsRetainBlock = Class == IC_RetainBlock;
// Don't check S.IsKnownIncremented() here because it's not
// sufficient.
S.RRI.KnownSafe = S.IsKnownNested();
S.RRI.Calls.insert(Inst);
}
S.SetAtLeastOneRefCount();
S.IncrementRefCount();
S.IncrementNestCount();
continue;
}
case IC_Release: {
Arg = GetObjCArg(Inst);
PtrState &S = MyStates.getPtrTopDownState(Arg);
S.DecrementRefCount();
S.DecrementNestCount();
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
switch (S.GetSeq()) {
case S_Retain:
case S_CanRelease:
S.RRI.ReverseInsertPts.clear();
// FALL THROUGH
case S_Use:
S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
Releases[Inst] = S.RRI;
S.ClearSequenceProgress();
break;
case S_None:
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
break;
}
case IC_AutoreleasepoolPop:
// Conservatively, clear MyStates for all known pointers.
MyStates.clearTopDownPointers();
continue;
case IC_AutoreleasepoolPush:
case IC_None:
// These are irrelevant.
continue;
default:
break;
}
// Consider any other possible effects of this instruction on each
// pointer being tracked.
for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
const Value *Ptr = MI->first;
if (Ptr == Arg)
continue; // Handled above.
PtrState &S = MI->second;
Sequence Seq = S.GetSeq();
// Check for possible releases.
if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
S.DecrementRefCount();
switch (Seq) {
case S_Retain:
S.SetSeq(S_CanRelease);
S.RRI.ReverseInsertPts.clear();
S.RRI.ReverseInsertPts.insert(Inst);
// One call can't cause a transition from S_Retain to S_CanRelease
// and S_CanRelease to S_Use. If we've made the first transition,
// we're done.
continue;
case S_Use:
case S_CanRelease:
case S_None:
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
// Check for possible direct uses.
switch (Seq) {
case S_CanRelease:
if (CanUse(Inst, Ptr, PA, Class))
S.SetSeq(S_Use);
break;
case S_Use:
case S_Retain:
case S_None:
break;
case S_Stop:
case S_Release:
case S_MovableRelease:
llvm_unreachable("top-down pointer in release state!");
}
}
}
CheckForCFGHazards(BB, BBStates, MyStates);
return NestingDetected;
}
// Visit - Visit the function both top-down and bottom-up.
bool
ObjCARCOpt::Visit(Function &F,
DenseMap<const BasicBlock *, BBState> &BBStates,
MapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases) {
// Use reverse-postorder on the reverse CFG for bottom-up, because we
// magically know that loops will be well behaved, i.e. they won't repeatedly
// call retain on a single pointer without doing a release. We can't use
// ReversePostOrderTraversal here because we want to walk up from each
// function exit point.
SmallPtrSet<BasicBlock *, 16> Visited;
SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
SmallVector<BasicBlock *, 16> Order;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
BasicBlock *BB = I;
if (BB->getTerminator()->getNumSuccessors() == 0)
Stack.push_back(std::make_pair(BB, pred_begin(BB)));
}
while (!Stack.empty()) {
pred_iterator End = pred_end(Stack.back().first);
while (Stack.back().second != End) {
BasicBlock *BB = *Stack.back().second++;
if (Visited.insert(BB))
Stack.push_back(std::make_pair(BB, pred_begin(BB)));
}
Order.push_back(Stack.pop_back_val().first);
}
bool BottomUpNestingDetected = false;
for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Order.rbegin(), E = Order.rend(); I != E; ++I) {
BasicBlock *BB = *I;
BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
}
// Use regular reverse-postorder for top-down.
bool TopDownNestingDetected = false;
typedef ReversePostOrderTraversal<Function *> RPOTType;
RPOTType RPOT(&F);
for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
BasicBlock *BB = *I;
TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
}
return TopDownNestingDetected && BottomUpNestingDetected;
}
/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
void ObjCARCOpt::MoveCalls(Value *Arg,
RRInfo &RetainsToMove,
RRInfo &ReleasesToMove,
MapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts,
Module *M) {
Type *ArgTy = Arg->getType();
Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
// Insert the new retain and release calls.
for (SmallPtrSet<Instruction *, 2>::const_iterator
PI = ReleasesToMove.ReverseInsertPts.begin(),
PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Instruction *InsertPt = *PI;
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
CallInst *Call =
CallInst::Create(RetainsToMove.IsRetainBlock ?
getRetainBlockCallee(M) : getRetainCallee(M),
MyArg, "", InsertPt);
Call->setDoesNotThrow();
if (!RetainsToMove.IsRetainBlock)
Call->setTailCall();
}
for (SmallPtrSet<Instruction *, 2>::const_iterator
PI = RetainsToMove.ReverseInsertPts.begin(),
PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Instruction *LastUse = *PI;
Instruction *InsertPts[] = { 0, 0, 0 };
if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
// We can't insert code immediately after an invoke instruction, so
// insert code at the beginning of both successor blocks instead.
// The invoke's return value isn't available in the unwind block,
// but our releases will never depend on it, because they must be
// paired with retains from before the invoke.
InsertPts[0] = II->getNormalDest()->getFirstNonPHI();
InsertPts[1] = II->getUnwindDest()->getFirstNonPHI();
} else {
// Insert code immediately after the last use.
InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
}
for (Instruction **I = InsertPts; *I; ++I) {
Instruction *InsertPt = *I;
Value *MyArg = ArgTy == ParamTy ? Arg :
new BitCastInst(Arg, ParamTy, "", InsertPt);
CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
"", InsertPt);
// Attach a clang.imprecise_release metadata tag, if appropriate.
if (MDNode *M = ReleasesToMove.ReleaseMetadata)
Call->setMetadata(ImpreciseReleaseMDKind, M);
Call->setDoesNotThrow();
if (ReleasesToMove.IsTailCallRelease)
Call->setTailCall();
}
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
}
// Delete the original retain and release calls.
for (SmallPtrSet<Instruction *, 2>::const_iterator
AI = RetainsToMove.Calls.begin(),
AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
Instruction *OrigRetain = *AI;
Retains.blot(OrigRetain);
DeadInsts.push_back(OrigRetain);
}
for (SmallPtrSet<Instruction *, 2>::const_iterator
AI = ReleasesToMove.Calls.begin(),
AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
Instruction *OrigRelease = *AI;
Releases.erase(OrigRelease);
DeadInsts.push_back(OrigRelease);
}
}
bool
ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
&BBStates,
MapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
Module *M) {
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
bool AnyPairsCompletelyEliminated = false;
RRInfo RetainsToMove;
RRInfo ReleasesToMove;
SmallVector<Instruction *, 4> NewRetains;
SmallVector<Instruction *, 4> NewReleases;
SmallVector<Instruction *, 8> DeadInsts;
for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
E = Retains.end(); I != E; ) {
Value *V = (I++)->first;
if (!V) continue; // blotted
Instruction *Retain = cast<Instruction>(V);
Value *Arg = GetObjCArg(Retain);
// If the object being released is in static or stack storage, we know it's
// not being managed by ObjC reference counting, so we can delete pairs
// regardless of what possible decrements or uses lie between them.
bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
// If a pair happens in a region where it is known that the reference count
// is already incremented, we can similarly ignore possible decrements.
bool KnownSafeTD = true, KnownSafeBU = true;
// Connect the dots between the top-down-collected RetainsToMove and
// bottom-up-collected ReleasesToMove to form sets of related calls.
// This is an iterative process so that we connect multiple releases
// to multiple retains if needed.
unsigned OldDelta = 0;
unsigned NewDelta = 0;
unsigned OldCount = 0;
unsigned NewCount = 0;
bool FirstRelease = true;
bool FirstRetain = true;
NewRetains.push_back(Retain);
for (;;) {
for (SmallVectorImpl<Instruction *>::const_iterator
NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
Instruction *NewRetain = *NI;
MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
assert(It != Retains.end());
const RRInfo &NewRetainRRI = It->second;
KnownSafeTD &= NewRetainRRI.KnownSafe;
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
for (SmallPtrSet<Instruction *, 2>::const_iterator
LI = NewRetainRRI.Calls.begin(),
LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
Instruction *NewRetainRelease = *LI;
DenseMap<Value *, RRInfo>::const_iterator Jt =
Releases.find(NewRetainRelease);
if (Jt == Releases.end())
goto next_retain;
const RRInfo &NewRetainReleaseRRI = Jt->second;
assert(NewRetainReleaseRRI.Calls.count(NewRetain));
if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
OldDelta -=
BBStates[NewRetainRelease->getParent()].GetAllPathCount();
// Merge the ReleaseMetadata and IsTailCallRelease values.
if (FirstRelease) {
ReleasesToMove.ReleaseMetadata =
NewRetainReleaseRRI.ReleaseMetadata;
ReleasesToMove.IsTailCallRelease =
NewRetainReleaseRRI.IsTailCallRelease;
FirstRelease = false;
} else {
if (ReleasesToMove.ReleaseMetadata !=
NewRetainReleaseRRI.ReleaseMetadata)
ReleasesToMove.ReleaseMetadata = 0;
if (ReleasesToMove.IsTailCallRelease !=
NewRetainReleaseRRI.IsTailCallRelease)
ReleasesToMove.IsTailCallRelease = false;
}
// Collect the optimal insertion points.
if (!KnownSafe)
for (SmallPtrSet<Instruction *, 2>::const_iterator
RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
RE = NewRetainReleaseRRI.ReverseInsertPts.end();
RI != RE; ++RI) {
Instruction *RIP = *RI;
if (ReleasesToMove.ReverseInsertPts.insert(RIP))
NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
}
NewReleases.push_back(NewRetainRelease);
}
}
}
NewRetains.clear();
if (NewReleases.empty()) break;
// Back the other way.
for (SmallVectorImpl<Instruction *>::const_iterator
NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
Instruction *NewRelease = *NI;
DenseMap<Value *, RRInfo>::const_iterator It =
Releases.find(NewRelease);
assert(It != Releases.end());
const RRInfo &NewReleaseRRI = It->second;
KnownSafeBU &= NewReleaseRRI.KnownSafe;
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
for (SmallPtrSet<Instruction *, 2>::const_iterator
LI = NewReleaseRRI.Calls.begin(),
LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
Instruction *NewReleaseRetain = *LI;
MapVector<Value *, RRInfo>::const_iterator Jt =
Retains.find(NewReleaseRetain);
if (Jt == Retains.end())
goto next_retain;
const RRInfo &NewReleaseRetainRRI = Jt->second;
assert(NewReleaseRetainRRI.Calls.count(NewRelease));
if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
unsigned PathCount =
BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
OldDelta += PathCount;
OldCount += PathCount;
// Merge the IsRetainBlock values.
if (FirstRetain) {
RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
FirstRetain = false;
} else if (ReleasesToMove.IsRetainBlock !=
NewReleaseRetainRRI.IsRetainBlock)
// It's not possible to merge the sequences if one uses
// objc_retain and the other uses objc_retainBlock.
goto next_retain;
// Collect the optimal insertion points.
if (!KnownSafe)
for (SmallPtrSet<Instruction *, 2>::const_iterator
RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
RE = NewReleaseRetainRRI.ReverseInsertPts.end();
RI != RE; ++RI) {
Instruction *RIP = *RI;
if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
PathCount = BBStates[RIP->getParent()].GetAllPathCount();
NewDelta += PathCount;
NewCount += PathCount;
}
}
NewRetains.push_back(NewReleaseRetain);
}
}
}
NewReleases.clear();
if (NewRetains.empty()) break;
}
// If the pointer is known incremented or nested, we can safely delete the
// pair regardless of what's between them.
if (KnownSafeTD || KnownSafeBU) {
RetainsToMove.ReverseInsertPts.clear();
ReleasesToMove.ReverseInsertPts.clear();
NewCount = 0;
} else {
// Determine whether the new insertion points we computed preserve the
// balance of retain and release calls through the program.
// TODO: If the fully aggressive solution isn't valid, try to find a
// less aggressive solution which is.
if (NewDelta != 0)
goto next_retain;
}
// Determine whether the original call points are balanced in the retain and
// release calls through the program. If not, conservatively don't touch
// them.
// TODO: It's theoretically possible to do code motion in this case, as
// long as the existing imbalances are maintained.
if (OldDelta != 0)
goto next_retain;
// Ok, everything checks out and we're all set. Let's move some code!
Changed = true;
AnyPairsCompletelyEliminated = NewCount == 0;
NumRRs += OldCount - NewCount;
MoveCalls(Arg, RetainsToMove, ReleasesToMove,
Retains, Releases, DeadInsts, M);
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
next_retain:
NewReleases.clear();
NewRetains.clear();
RetainsToMove.clear();
ReleasesToMove.clear();
}
// Now that we're done moving everything, we can delete the newly dead
// instructions, as we no longer need them as insert points.
while (!DeadInsts.empty())
EraseInstruction(DeadInsts.pop_back_val());
return AnyPairsCompletelyEliminated;
}
/// OptimizeWeakCalls - Weak pointer optimizations.
void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
// First, do memdep-style RLE and S2L optimizations. We can't use memdep
// itself because it uses AliasAnalysis and we need to do provenance
// queries instead.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
InstructionClass Class = GetBasicInstructionClass(Inst);
if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
continue;
// Delete objc_loadWeak calls with no users.
if (Class == IC_LoadWeak && Inst->use_empty()) {
Inst->eraseFromParent();
continue;
}
// TODO: For now, just look for an earlier available version of this value
// within the same block. Theoretically, we could do memdep-style non-local
// analysis too, but that would want caching. A better approach would be to
// use the technique that EarlyCSE uses.
inst_iterator Current = llvm::prior(I);
BasicBlock *CurrentBB = Current.getBasicBlockIterator();
for (BasicBlock::iterator B = CurrentBB->begin(),
J = Current.getInstructionIterator();
J != B; --J) {
Instruction *EarlierInst = &*llvm::prior(J);
InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
switch (EarlierClass) {
case IC_LoadWeak:
case IC_LoadWeakRetained: {
// If this is loading from the same pointer, replace this load's value
// with that one.
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case AliasAnalysis::MustAlias:
Changed = true;
// If the load has a builtin retain, insert a plain retain for it.
if (Class == IC_LoadWeakRetained) {
CallInst *CI =
CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
"", Call);
CI->setTailCall();
}
// Zap the fully redundant load.
Call->replaceAllUsesWith(EarlierCall);
Call->eraseFromParent();
goto clobbered;
case AliasAnalysis::MayAlias:
case AliasAnalysis::PartialAlias:
goto clobbered;
case AliasAnalysis::NoAlias:
break;
}
break;
}
case IC_StoreWeak:
case IC_InitWeak: {
// If this is storing to the same pointer and has the same size etc.
// replace this load's value with the stored value.
CallInst *Call = cast<CallInst>(Inst);
CallInst *EarlierCall = cast<CallInst>(EarlierInst);
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case AliasAnalysis::MustAlias:
Changed = true;
// If the load has a builtin retain, insert a plain retain for it.
if (Class == IC_LoadWeakRetained) {
CallInst *CI =
CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
"", Call);
CI->setTailCall();
}
// Zap the fully redundant load.
Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
Call->eraseFromParent();
goto clobbered;
case AliasAnalysis::MayAlias:
case AliasAnalysis::PartialAlias: