Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
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 contains code to emit Objective-C code as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGDebugInfo.h"
14
#include "CGObjCRuntime.h"
15
#include "CodeGenFunction.h"
16
#include "CodeGenModule.h"
17
#include "ConstantEmitter.h"
18
#include "TargetInfo.h"
19
#include "clang/AST/ASTContext.h"
20
#include "clang/AST/Attr.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/StmtObjC.h"
23
#include "clang/Basic/Diagnostic.h"
24
#include "clang/CodeGen/CGFunctionInfo.h"
25
#include "llvm/ADT/STLExtras.h"
26
#include "llvm/IR/DataLayout.h"
27
#include "llvm/IR/InlineAsm.h"
28
using namespace clang;
29
using namespace CodeGen;
30
31
typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32
static TryEmitResult
33
tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
34
static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35
                                   QualType ET,
36
                                   RValue Result);
37
38
/// Given the address of a variable of pointer type, find the correct
39
/// null to store into it.
40
917
static llvm::Constant *getNullForVariable(Address addr) {
41
917
  llvm::Type *type = addr.getElementType();
42
917
  return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43
917
}
44
45
/// Emits an instance of NSConstantString representing the object.
46
llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
47
4.93k
{
48
4.93k
  llvm::Constant *C =
49
4.93k
      CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
50
4.93k
  // FIXME: This bitcast should just be made an invariant on the Runtime.
51
4.93k
  return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
52
4.93k
}
53
54
/// EmitObjCBoxedExpr - This routine generates code to call
55
/// the appropriate expression boxing method. This will either be
56
/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57
/// or [NSValue valueWithBytes:objCType:].
58
///
59
llvm::Value *
60
508
CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
61
508
  // Generate the correct selector for this literal's concrete type.
62
508
  // Get the method.
63
508
  const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64
508
  const Expr *SubExpr = E->getSubExpr();
65
508
66
508
  if (E->isExpressibleAsConstantInitializer()) {
67
3
    ConstantEmitter ConstEmitter(CGM);
68
3
    return ConstEmitter.tryEmitAbstract(E, E->getType());
69
3
  }
70
505
71
505
  assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
72
505
  Selector Sel = BoxingMethod->getSelector();
73
505
74
505
  // Generate a reference to the class pointer, which will be the receiver.
75
505
  // Assumes that the method was introduced in the class that should be
76
505
  // messaged (avoids pulling it out of the result type).
77
505
  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
78
505
  const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
79
505
  llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
80
505
81
505
  CallArgList Args;
82
505
  const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
83
505
  QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
84
505
85
505
  // ObjCBoxedExpr supports boxing of structs and unions
86
505
  // via [NSValue valueWithBytes:objCType:]
87
505
  const QualType ValueType(SubExpr->getType().getCanonicalType());
88
505
  if (ValueType->isObjCBoxableRecordType()) {
89
26
    // Emit CodeGen for first parameter
90
26
    // and cast value to correct type
91
26
    Address Temporary = CreateMemTemp(SubExpr->getType());
92
26
    EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
93
26
    Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
94
26
    Args.add(RValue::get(BitCast.getPointer()), ArgQT);
95
26
96
26
    // Create char array to store type encoding
97
26
    std::string Str;
98
26
    getContext().getObjCEncodingForType(ValueType, Str);
99
26
    llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
100
26
101
26
    // Cast type encoding to correct type
102
26
    const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
103
26
    QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
104
26
    llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
105
26
106
26
    Args.add(RValue::get(Cast), EncodingQT);
107
479
  } else {
108
479
    Args.add(EmitAnyExpr(SubExpr), ArgQT);
109
479
  }
110
505
111
505
  RValue result = Runtime.GenerateMessageSend(
112
505
      *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
113
505
      Args, ClassDecl, BoxingMethod);
114
505
  return Builder.CreateBitCast(result.getScalarVal(),
115
505
                               ConvertType(E->getType()));
116
505
}
117
118
llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
119
229
                                    const ObjCMethodDecl *MethodWithObjects) {
120
229
  ASTContext &Context = CGM.getContext();
121
229
  const ObjCDictionaryLiteral *DLE = nullptr;
122
229
  const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
123
229
  if (!ALE)
124
110
    DLE = cast<ObjCDictionaryLiteral>(E);
125
229
126
229
  // Optimize empty collections by referencing constants, when available.
127
229
  uint64_t NumElements =
128
229
    ALE ? 
ALE->getNumElements()119
:
DLE->getNumElements()110
;
129
229
  if (NumElements == 0 && 
CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()16
) {
130
8
    StringRef ConstantName = ALE ? 
"__NSArray0__"4
:
"__NSDictionary0__"4
;
131
8
    QualType IdTy(CGM.getContext().getObjCIdType());
132
8
    llvm::Constant *Constant =
133
8
        CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
134
8
    LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
135
8
    llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
136
8
    cast<llvm::LoadInst>(Ptr)->setMetadata(
137
8
        CGM.getModule().getMDKindID("invariant.load"),
138
8
        llvm::MDNode::get(getLLVMContext(), None));
139
8
    return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
140
8
  }
141
221
142
221
  // Compute the type of the array we're initializing.
143
221
  llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
144
221
                            NumElements);
145
221
  QualType ElementType = Context.getObjCIdType().withConst();
146
221
  QualType ElementArrayType
147
221
    = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
148
221
                                   ArrayType::Normal, /*IndexTypeQuals=*/0);
149
221
150
221
  // Allocate the temporary array(s).
151
221
  Address Objects = CreateMemTemp(ElementArrayType, "objects");
152
221
  Address Keys = Address::invalid();
153
221
  if (DLE)
154
106
    Keys = CreateMemTemp(ElementArrayType, "keys");
155
221
156
221
  // In ARC, we may need to do extra work to keep all the keys and
157
221
  // values alive until after the call.
158
221
  SmallVector<llvm::Value *, 16> NeededObjects;
159
221
  bool TrackNeededObjects =
160
221
    (getLangOpts().ObjCAutoRefCount &&
161
221
    
CGM.getCodeGenOpts().OptimizationLevel != 013
);
162
221
163
221
  // Perform the actual initialialization of the array(s).
164
677
  for (uint64_t i = 0; i < NumElements; 
i++456
) {
165
456
    if (ALE) {
166
287
      // Emit the element and store it to the appropriate array slot.
167
287
      const Expr *Rhs = ALE->getElement(i);
168
287
      LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
169
287
                                 ElementType, AlignmentSource::Decl);
170
287
171
287
      llvm::Value *value = EmitScalarExpr(Rhs);
172
287
      EmitStoreThroughLValue(RValue::get(value), LV, true);
173
287
      if (TrackNeededObjects) {
174
7
        NeededObjects.push_back(value);
175
7
      }
176
287
    } else {
177
169
      // Emit the key and store it to the appropriate array slot.
178
169
      const Expr *Key = DLE->getKeyValueElement(i).Key;
179
169
      LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
180
169
                                    ElementType, AlignmentSource::Decl);
181
169
      llvm::Value *keyValue = EmitScalarExpr(Key);
182
169
      EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
183
169
184
169
      // Emit the value and store it to the appropriate array slot.
185
169
      const Expr *Value = DLE->getKeyValueElement(i).Value;
186
169
      LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
187
169
                                      ElementType, AlignmentSource::Decl);
188
169
      llvm::Value *valueValue = EmitScalarExpr(Value);
189
169
      EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
190
169
      if (TrackNeededObjects) {
191
2
        NeededObjects.push_back(keyValue);
192
2
        NeededObjects.push_back(valueValue);
193
2
      }
194
169
    }
195
456
  }
196
221
197
221
  // Generate the argument list.
198
221
  CallArgList Args;
199
221
  ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
200
221
  const ParmVarDecl *argDecl = *PI++;
201
221
  QualType ArgQT = argDecl->getType().getUnqualifiedType();
202
221
  Args.add(RValue::get(Objects.getPointer()), ArgQT);
203
221
  if (DLE) {
204
106
    argDecl = *PI++;
205
106
    ArgQT = argDecl->getType().getUnqualifiedType();
206
106
    Args.add(RValue::get(Keys.getPointer()), ArgQT);
207
106
  }
208
221
  argDecl = *PI;
209
221
  ArgQT = argDecl->getType().getUnqualifiedType();
210
221
  llvm::Value *Count =
211
221
    llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
212
221
  Args.add(RValue::get(Count), ArgQT);
213
221
214
221
  // Generate a reference to the class pointer, which will be the receiver.
215
221
  Selector Sel = MethodWithObjects->getSelector();
216
221
  QualType ResultType = E->getType();
217
221
  const ObjCObjectPointerType *InterfacePointerType
218
221
    = ResultType->getAsObjCInterfacePointerType();
219
221
  ObjCInterfaceDecl *Class
220
221
    = InterfacePointerType->getObjectType()->getInterface();
221
221
  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
222
221
  llvm::Value *Receiver = Runtime.GetClass(*this, Class);
223
221
224
221
  // Generate the message send.
225
221
  RValue result = Runtime.GenerateMessageSend(
226
221
      *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
227
221
      Receiver, Args, Class, MethodWithObjects);
228
221
229
221
  // The above message send needs these objects, but in ARC they are
230
221
  // passed in a buffer that is essentially __unsafe_unretained.
231
221
  // Therefore we must prevent the optimizer from releasing them until
232
221
  // after the call.
233
221
  if (TrackNeededObjects) {
234
5
    EmitARCIntrinsicUse(NeededObjects);
235
5
  }
236
221
237
221
  return Builder.CreateBitCast(result.getScalarVal(),
238
221
                               ConvertType(E->getType()));
239
221
}
240
241
119
llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
242
119
  return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
243
119
}
244
245
llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
246
110
                                            const ObjCDictionaryLiteral *E) {
247
110
  return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
248
110
}
249
250
/// Emit a selector.
251
100
llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
252
100
  // Untyped selector.
253
100
  // Note that this implementation allows for non-constant strings to be passed
254
100
  // as arguments to @selector().  Currently, the only thing preventing this
255
100
  // behaviour is the type checking in the front end.
256
100
  return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
257
100
}
258
259
17
llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
260
17
  // FIXME: This should pass the Decl not the name.
261
17
  return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
262
17
}
263
264
/// Adjust the type of an Objective-C object that doesn't match up due
265
/// to type erasure at various points, e.g., related result types or the use
266
/// of parameterized classes.
267
static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
268
12.9k
                                   RValue Result) {
269
12.9k
  if (!ExpT->isObjCRetainableType())
270
5.53k
    return Result;
271
7.44k
272
7.44k
  // If the converted types are the same, we're done.
273
7.44k
  llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
274
7.44k
  if (ExpLLVMTy == Result.getScalarVal()->getType())
275
2.32k
    return Result;
276
5.11k
277
5.11k
  // We have applied a substitution. Cast the rvalue appropriately.
278
5.11k
  return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
279
5.11k
                                               ExpLLVMTy));
280
5.11k
}
281
282
/// Decide whether to extend the lifetime of the receiver of a
283
/// returns-inner-pointer message.
284
static bool
285
10
shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
286
10
  switch (message->getReceiverKind()) {
287
0
288
0
  // For a normal instance message, we should extend unless the
289
0
  // receiver is loaded from a variable with precise lifetime.
290
10
  case ObjCMessageExpr::Instance: {
291
10
    const Expr *receiver = message->getInstanceReceiver();
292
10
293
10
    // Look through OVEs.
294
10
    if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
295
4
      if (opaque->getSourceExpr())
296
4
        receiver = opaque->getSourceExpr()->IgnoreParens();
297
4
    }
298
10
299
10
    const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
300
10
    if (!ice || ice->getCastKind() != CK_LValueToRValue) 
return true0
;
301
10
    receiver = ice->getSubExpr()->IgnoreParens();
302
10
303
10
    // Look through OVEs.
304
10
    if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
305
0
      if (opaque->getSourceExpr())
306
0
        receiver = opaque->getSourceExpr()->IgnoreParens();
307
0
    }
308
10
309
10
    // Only __strong variables.
310
10
    if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
311
0
      return true;
312
10
313
10
    // All ivars and fields have precise lifetime.
314
10
    if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
315
0
      return false;
316
10
317
10
    // Otherwise, check for variables.
318
10
    const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
319
10
    if (!declRef) 
return true3
;
320
7
    const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
321
7
    if (!var) 
return true0
;
322
7
323
7
    // All variables have precise lifetime except local variables with
324
7
    // automatic storage duration that aren't specially marked.
325
7
    return (var->hasLocalStorage() &&
326
7
            !var->hasAttr<ObjCPreciseLifetimeAttr>());
327
7
  }
328
7
329
7
  case ObjCMessageExpr::Class:
330
0
  case ObjCMessageExpr::SuperClass:
331
0
    // It's never necessary for class objects.
332
0
    return false;
333
0
334
0
  case ObjCMessageExpr::SuperInstance:
335
0
    // We generally assume that 'self' lives throughout a method call.
336
0
    return false;
337
0
  }
338
0
339
0
  llvm_unreachable("invalid receiver kind");
340
0
}
341
342
/// Given an expression of ObjC pointer type, check whether it was
343
/// immediately loaded from an ARC __weak l-value.
344
53
static const Expr *findWeakLValue(const Expr *E) {
345
53
  assert(E->getType()->isObjCRetainableType());
346
53
  E = E->IgnoreParens();
347
53
  if (auto CE = dyn_cast<CastExpr>(E)) {
348
50
    if (CE->getCastKind() == CK_LValueToRValue) {
349
50
      if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
350
8
        return CE->getSubExpr();
351
45
    }
352
50
  }
353
45
354
45
  return nullptr;
355
45
}
356
357
/// The ObjC runtime may provide entrypoints that are likely to be faster
358
/// than an ordinary message send of the appropriate selector.
359
///
360
/// The entrypoints are guaranteed to be equivalent to just sending the
361
/// corresponding message.  If the entrypoint is implemented naively as just a
362
/// message send, using it is a trade-off: it sacrifices a few cycles of
363
/// overhead to save a small amount of code.  However, it's possible for
364
/// runtimes to detect and special-case classes that use "standard"
365
/// behavior; if that's dynamically a large proportion of all objects, using
366
/// the entrypoint will also be faster than using a message send.
367
///
368
/// If the runtime does support a required entrypoint, then this method will
369
/// generate a call and return the resulting value.  Otherwise it will return
370
/// None and the caller can generate a msgSend instead.
371
static Optional<llvm::Value *>
372
tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
373
                                  llvm::Value *Receiver,
374
                                  const CallArgList& Args, Selector Sel,
375
                                  const ObjCMethodDecl *method,
376
12.4k
                                  bool isClassMessage) {
377
12.4k
  auto &CGM = CGF.CGM;
378
12.4k
  if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
379
30
    return None;
380
12.4k
381
12.4k
  auto &Runtime = CGM.getLangOpts().ObjCRuntime;
382
12.4k
  switch (Sel.getMethodFamily()) {
383
1.49k
  case OMF_alloc:
384
1.49k
    if (isClassMessage &&
385
1.49k
        
Runtime.shouldUseRuntimeFunctionsForAlloc()1.46k
&&
386
1.49k
        
ResultType->isObjCObjectPointerType()1.36k
) {
387
1.36k
        // [Foo alloc] -> objc_alloc(Foo) or
388
1.36k
        // [self alloc] -> objc_alloc(self)
389
1.36k
        if (Sel.isUnarySelector() && 
Sel.getNameForSlot(0) == "alloc"1.32k
)
390
1.32k
          return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
391
41
        // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
392
41
        // [self allocWithZone:nil] -> objc_allocWithZone(self)
393
41
        if (Sel.isKeywordSelector() && 
Sel.getNumArgs() == 137
&&
394
41
            
Args.size() == 137
&&
Args.front().getType()->isPointerType()37
&&
395
41
            
Sel.getNameForSlot(0) == "allocWithZone"33
) {
396
33
          const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
397
33
          if (isa<llvm::ConstantPointerNull>(arg))
398
25
            return CGF.EmitObjCAllocWithZone(Receiver,
399
25
                                             CGF.ConvertType(ResultType));
400
8
          return None;
401
8
        }
402
41
    }
403
138
    break;
404
138
405
138
  case OMF_autorelease:
406
56
    if (ResultType->isObjCObjectPointerType() &&
407
56
        CGM.getLangOpts().getGC() == LangOptions::NonGC &&
408
56
        Runtime.shouldUseARCFunctionsForRetainRelease())
409
46
      return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
410
10
    break;
411
10
412
40
  case OMF_retain:
413
40
    if (ResultType->isObjCObjectPointerType() &&
414
40
        
CGM.getLangOpts().getGC() == LangOptions::NonGC33
&&
415
40
        
Runtime.shouldUseARCFunctionsForRetainRelease()32
)
416
17
      return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
417
23
    break;
418
23
419
197
  case OMF_release:
420
197
    if (ResultType->isVoidType() &&
421
197
        
CGM.getLangOpts().getGC() == LangOptions::NonGC196
&&
422
197
        
Runtime.shouldUseARCFunctionsForRetainRelease()195
) {
423
187
      CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
424
187
      return nullptr;
425
187
    }
426
10
    break;
427
10
428
10.6k
  default:
429
10.6k
    break;
430
10.8k
  }
431
10.8k
  return None;
432
10.8k
}
433
434
CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
435
    CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
436
    Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
437
    const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
438
12.4k
    bool isClassMessage) {
439
12.4k
  if (Optional<llvm::Value *> SpecializedResult =
440
1.59k
          tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
441
1.59k
                                            Sel, Method, isClassMessage)) {
442
1.59k
    return RValue::get(SpecializedResult.getValue());
443
1.59k
  }
444
10.8k
  return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
445
10.8k
                             Method);
446
10.8k
}
447
448
/// Instead of '[[MyClass alloc] init]', try to generate
449
/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
450
/// caller side, as well as the optimized objc_alloc.
451
static Optional<llvm::Value *>
452
12.9k
tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
453
12.9k
  auto &Runtime = CGF.getLangOpts().ObjCRuntime;
454
12.9k
  if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
455
12.9k
    return None;
456
16
457
16
  // Match the exact pattern '[[MyClass alloc] init]'.
458
16
  Selector Sel = OME->getSelector();
459
16
  if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
460
16
      
!OME->getType()->isObjCObjectPointerType()14
||
!Sel.isUnarySelector()14
||
461
16
      
Sel.getNameForSlot(0) != "init"14
)
462
6
    return None;
463
10
464
10
  // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
465
10
  // with 'cls' a Class.
466
10
  auto *SubOME =
467
10
      dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
468
10
  if (!SubOME)
469
0
    return None;
470
10
  Selector SubSel = SubOME->getSelector();
471
10
472
10
  if (!SubOME->getType()->isObjCObjectPointerType() ||
473
10
      !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
474
0
    return None;
475
10
476
10
  llvm::Value *Receiver = nullptr;
477
10
  switch (SubOME->getReceiverKind()) {
478
6
  case ObjCMessageExpr::Instance:
479
6
    if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
480
2
      return None;
481
4
    Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
482
4
    break;
483
4
484
4
  case ObjCMessageExpr::Class: {
485
4
    QualType ReceiverType = SubOME->getClassReceiver();
486
4
    const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
487
4
    const ObjCInterfaceDecl *ID = ObjTy->getInterface();
488
4
    assert(ID && "null interface should be impossible here");
489
4
    Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
490
4
    break;
491
4
  }
492
4
  case ObjCMessageExpr::SuperInstance:
493
0
  case ObjCMessageExpr::SuperClass:
494
0
    return None;
495
8
  }
496
8
497
8
  return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
498
8
}
499
500
RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
501
12.9k
                                            ReturnValueSlot Return) {
502
12.9k
  // Only the lookup mechanism and first two arguments of the method
503
12.9k
  // implementation vary between runtimes.  We can get the receiver and
504
12.9k
  // arguments in generic code.
505
12.9k
506
12.9k
  bool isDelegateInit = E->isDelegateInitCall();
507
12.9k
508
12.9k
  const ObjCMethodDecl *method = E->getMethodDecl();
509
12.9k
510
12.9k
  // If the method is -retain, and the receiver's being loaded from
511
12.9k
  // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
512
12.9k
  if (method && 
E->getReceiverKind() == ObjCMessageExpr::Instance12.4k
&&
513
12.9k
      
method->getMethodFamily() == OMF_retain7.42k
) {
514
53
    if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
515
8
      LValue lvalue = EmitLValue(lvalueExpr);
516
8
      llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
517
8
      return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
518
8
    }
519
12.9k
  }
520
12.9k
521
12.9k
  if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
522
8
    return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
523
12.9k
524
12.9k
  // We don't retain the receiver in delegate init calls, and this is
525
12.9k
  // safe because the receiver value is always loaded from 'self',
526
12.9k
  // which we zero out.  We don't want to Block_copy block receivers,
527
12.9k
  // though.
528
12.9k
  bool retainSelf =
529
12.9k
    (!isDelegateInit &&
530
12.9k
     
CGM.getLangOpts().ObjCAutoRefCount12.9k
&&
531
12.9k
     
method190
&&
532
12.9k
     
method->hasAttr<NSConsumesSelfAttr>()190
);
533
12.9k
534
12.9k
  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
535
12.9k
  bool isSuperMessage = false;
536
12.9k
  bool isClassMessage = false;
537
12.9k
  ObjCInterfaceDecl *OID = nullptr;
538
12.9k
  // Find the receiver
539
12.9k
  QualType ReceiverType;
540
12.9k
  llvm::Value *Receiver = nullptr;
541
12.9k
  switch (E->getReceiverKind()) {
542
7.93k
  case ObjCMessageExpr::Instance:
543
7.93k
    ReceiverType = E->getInstanceReceiver()->getType();
544
7.93k
    isClassMessage = ReceiverType->isObjCClassType();
545
7.93k
    if (retainSelf) {
546
11
      TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
547
11
                                                   E->getInstanceReceiver());
548
11
      Receiver = ter.getPointer();
549
11
      if (ter.getInt()) retainSelf = false;
550
11
    } else
551
7.92k
      Receiver = EmitScalarExpr(E->getInstanceReceiver());
552
7.93k
    break;
553
0
554
4.53k
  case ObjCMessageExpr::Class: {
555
4.53k
    ReceiverType = E->getClassReceiver();
556
4.53k
    OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
557
4.53k
    assert(OID && "Invalid Objective-C class message send");
558
4.53k
    Receiver = Runtime.GetClass(*this, OID);
559
4.53k
    isClassMessage = true;
560
4.53k
    break;
561
0
  }
562
0
563
447
  case ObjCMessageExpr::SuperInstance:
564
447
    ReceiverType = E->getSuperType();
565
447
    Receiver = LoadObjCSelf();
566
447
    isSuperMessage = true;
567
447
    break;
568
0
569
42
  case ObjCMessageExpr::SuperClass:
570
42
    ReceiverType = E->getSuperType();
571
42
    Receiver = LoadObjCSelf();
572
42
    isSuperMessage = true;
573
42
    isClassMessage = true;
574
42
    break;
575
12.9k
  }
576
12.9k
577
12.9k
  if (retainSelf)
578
0
    Receiver = EmitARCRetainNonBlock(Receiver);
579
12.9k
580
12.9k
  // In ARC, we sometimes want to "extend the lifetime"
581
12.9k
  // (i.e. retain+autorelease) of receivers of returns-inner-pointer
582
12.9k
  // messages.
583
12.9k
  if (getLangOpts().ObjCAutoRefCount && 
method199
&&
584
12.9k
      
method->hasAttr<ObjCReturnsInnerPointerAttr>()199
&&
585
12.9k
      
shouldExtendReceiverForInnerPointerMessage(E)10
)
586
6
    Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
587
12.9k
588
12.9k
  QualType ResultType = method ? 
method->getReturnType()12.4k
:
E->getType()544
;
589
12.9k
590
12.9k
  CallArgList Args;
591
12.9k
  EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
592
12.9k
593
12.9k
  // For delegate init calls in ARC, do an unsafe store of null into
594
12.9k
  // self.  This represents the call taking direct ownership of that
595
12.9k
  // value.  We have to do this after emitting the other call
596
12.9k
  // arguments because they might also reference self, but we don't
597
12.9k
  // have to worry about any of them modifying self because that would
598
12.9k
  // be an undefined read and write of an object in unordered
599
12.9k
  // expressions.
600
12.9k
  if (isDelegateInit) {
601
9
    assert(getLangOpts().ObjCAutoRefCount &&
602
9
           "delegate init calls should only be marked in ARC");
603
9
604
9
    // Do an unsafe store of null into self.
605
9
    Address selfAddr =
606
9
      GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
607
9
    Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
608
9
  }
609
12.9k
610
12.9k
  RValue result;
611
12.9k
  if (isSuperMessage) {
612
489
    // super is only valid in an Objective-C method
613
489
    const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
614
489
    bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
615
489
    result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
616
489
                                              E->getSelector(),
617
489
                                              OMD->getClassInterface(),
618
489
                                              isCategoryImpl,
619
489
                                              Receiver,
620
489
                                              isClassMessage,
621
489
                                              Args,
622
489
                                              method);
623
12.4k
  } else {
624
12.4k
    // Call runtime methods directly if we can.
625
12.4k
    result = Runtime.GeneratePossiblySpecializedMessageSend(
626
12.4k
        *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
627
12.4k
        method, isClassMessage);
628
12.4k
  }
629
12.9k
630
12.9k
  // For delegate init calls in ARC, implicitly store the result of
631
12.9k
  // the call back into self.  This takes ownership of the value.
632
12.9k
  if (isDelegateInit) {
633
9
    Address selfAddr =
634
9
      GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
635
9
    llvm::Value *newSelf = result.getScalarVal();
636
9
637
9
    // The delegate return type isn't necessarily a matching type; in
638
9
    // fact, it's quite likely to be 'id'.
639
9
    llvm::Type *selfTy = selfAddr.getElementType();
640
9
    newSelf = Builder.CreateBitCast(newSelf, selfTy);
641
9
642
9
    Builder.CreateStore(newSelf, selfAddr);
643
9
  }
644
12.9k
645
12.9k
  return AdjustObjCObjectType(*this, E->getType(), result);
646
12.9k
}
647
648
namespace {
649
struct FinishARCDealloc final : EHScopeStack::Cleanup {
650
8
  void Emit(CodeGenFunction &CGF, Flags flags) override {
651
8
    const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
652
8
653
8
    const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
654
8
    const ObjCInterfaceDecl *iface = impl->getClassInterface();
655
8
    if (!iface->getSuperClass()) 
return0
;
656
8
657
8
    bool isCategory = isa<ObjCCategoryImplDecl>(impl);
658
8
659
8
    // Call [super dealloc] if we have a superclass.
660
8
    llvm::Value *self = CGF.LoadObjCSelf();
661
8
662
8
    CallArgList args;
663
8
    CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
664
8
                                                      CGF.getContext().VoidTy,
665
8
                                                      method->getSelector(),
666
8
                                                      iface,
667
8
                                                      isCategory,
668
8
                                                      self,
669
8
                                                      /*is class msg*/ false,
670
8
                                                      args,
671
8
                                                      method);
672
8
  }
673
};
674
}
675
676
/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
677
/// the LLVM function and sets the other context used by
678
/// CodeGenFunction.
679
void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
680
2.52k
                                      const ObjCContainerDecl *CD) {
681
2.52k
  SourceLocation StartLoc = OMD->getBeginLoc();
682
2.52k
  FunctionArgList args;
683
2.52k
  // Check if we should generate debug info for this method.
684
2.52k
  if (OMD->hasAttr<NoDebugAttr>())
685
0
    DebugInfo = nullptr; // disable debug info indefinitely for this function
686
2.52k
687
2.52k
  llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
688
2.52k
689
2.52k
  const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
690
2.52k
  if (OMD->isDirectMethod()) {
691
39
    Fn->setVisibility(llvm::Function::HiddenVisibility);
692
39
    CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
693
39
    CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
694
2.49k
  } else {
695
2.49k
    CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
696
2.49k
  }
697
2.52k
698
2.52k
  args.push_back(OMD->getSelfDecl());
699
2.52k
  args.push_back(OMD->getCmdDecl());
700
2.52k
701
2.52k
  args.append(OMD->param_begin(), OMD->param_end());
702
2.52k
703
2.52k
  CurGD = OMD;
704
2.52k
  CurEHLocation = OMD->getEndLoc();
705
2.52k
706
2.52k
  StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
707
2.52k
                OMD->getLocation(), StartLoc);
708
2.52k
709
2.52k
  if (OMD->isDirectMethod()) {
710
39
    // This function is a direct call, it has to implement a nil check
711
39
    // on entry.
712
39
    //
713
39
    // TODO: possibly have several entry points to elide the check
714
39
    CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
715
39
  }
716
2.52k
717
2.52k
  // In ARC, certain methods get an extra cleanup.
718
2.52k
  if (CGM.getLangOpts().ObjCAutoRefCount &&
719
2.52k
      
OMD->isInstanceMethod()282
&&
720
2.52k
      
OMD->getSelector().isUnarySelector()264
) {
721
186
    const IdentifierInfo *ident =
722
186
      OMD->getSelector().getIdentifierInfoForSlot(0);
723
186
    if (ident->isStr("dealloc"))
724
8
      EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
725
186
  }
726
2.52k
}
727
728
static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
729
                                              LValue lvalue, QualType type);
730
731
/// Generate an Objective-C method.  An Objective-C method is a C function with
732
/// its pointer, name, and types registered in the class structure.
733
1.56k
void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
734
1.56k
  StartObjCMethod(OMD, OMD->getClassInterface());
735
1.56k
  PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
736
1.56k
  assert(isa<CompoundStmt>(OMD->getBody()));
737
1.56k
  incrementProfileCounter(OMD->getBody());
738
1.56k
  EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
739
1.56k
  FinishFunction(OMD->getBodyRBrace());
740
1.56k
}
741
742
/// emitStructGetterCall - Call the runtime function to load a property
743
/// into the return value slot.
744
static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
745
24
                                 bool isAtomic, bool hasStrong) {
746
24
  ASTContext &Context = CGF.getContext();
747
24
748
24
  Address src =
749
24
      CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
750
24
          .getAddress(CGF);
751
24
752
24
  // objc_copyStruct (ReturnValue, &structIvar,
753
24
  //                  sizeof (Type of Ivar), isAtomic, false);
754
24
  CallArgList args;
755
24
756
24
  Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
757
24
  args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
758
24
759
24
  src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
760
24
  args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
761
24
762
24
  CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
763
24
  args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
764
24
  args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
765
24
  args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
766
24
767
24
  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
768
24
  CGCallee callee = CGCallee::forDirect(fn);
769
24
  CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
770
24
               callee, ReturnValueSlot(), args);
771
24
}
772
773
/// Determine whether the given architecture supports unaligned atomic
774
/// accesses.  They don't have to be fast, just faster than a function
775
/// call and a mutex.
776
31
static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
777
31
  // FIXME: Allow unaligned atomic load/store on x86.  (It is not
778
31
  // currently supported by the backend.)
779
31
  return 0;
780
31
}
781
782
/// Return the maximum size that permits atomic accesses for the given
783
/// architecture.
784
static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
785
401
                                        llvm::Triple::ArchType arch) {
786
401
  // ARM has 8-byte atomic accesses, but it's not clear whether we
787
401
  // want to rely on them here.
788
401
789
401
  // In the default case, just assume that any size up to a pointer is
790
401
  // fine given adequate alignment.
791
401
  return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
792
401
}
793
794
namespace {
795
  class PropertyImplStrategy {
796
  public:
797
    enum StrategyKind {
798
      /// The 'native' strategy is to use the architecture's provided
799
      /// reads and writes.
800
      Native,
801
802
      /// Use objc_setProperty and objc_getProperty.
803
      GetSetProperty,
804
805
      /// Use objc_setProperty for the setter, but use expression
806
      /// evaluation for the getter.
807
      SetPropertyAndExpressionGet,
808
809
      /// Use objc_copyStruct.
810
      CopyStruct,
811
812
      /// The 'expression' strategy is to emit normal assignment or
813
      /// lvalue-to-rvalue expressions.
814
      Expression
815
    };
816
817
849
    StrategyKind getKind() const { return StrategyKind(Kind); }
818
819
24
    bool hasStrongMember() const { return HasStrong; }
820
283
    bool isAtomic() const { return IsAtomic; }
821
153
    bool isCopy() const { return IsCopy; }
822
823
788
    CharUnits getIvarSize() const { return IvarSize; }
824
0
    CharUnits getIvarAlignment() const { return IvarAlignment; }
825
826
    PropertyImplStrategy(CodeGenModule &CGM,
827
                         const ObjCPropertyImplDecl *propImpl);
828
829
  private:
830
    unsigned Kind : 8;
831
    unsigned IsAtomic : 1;
832
    unsigned IsCopy : 1;
833
    unsigned HasStrong : 1;
834
835
    CharUnits IvarSize;
836
    CharUnits IvarAlignment;
837
  };
838
}
839
840
/// Pick an implementation strategy for the given property synthesis.
841
PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
842
849
                                     const ObjCPropertyImplDecl *propImpl) {
843
849
  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
844
849
  ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
845
849
846
849
  IsCopy = (setterKind == ObjCPropertyDecl::Copy);
847
849
  IsAtomic = prop->isAtomic();
848
849
  HasStrong = false; // doesn't matter here.
849
849
850
849
  // Evaluate the ivar's size and alignment.
851
849
  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
852
849
  QualType ivarType = ivar->getType();
853
849
  std::tie(IvarSize, IvarAlignment) =
854
849
      CGM.getContext().getTypeInfoInChars(ivarType);
855
849
856
849
  // If we have a copy property, we always have to use getProperty/setProperty.
857
849
  // TODO: we could actually use setProperty and an expression for non-atomics.
858
849
  if (IsCopy) {
859
76
    Kind = GetSetProperty;
860
76
    return;
861
76
  }
862
773
863
773
  // Handle retain.
864
773
  if (setterKind == ObjCPropertyDecl::Retain) {
865
242
    // In GC-only, there's nothing special that needs to be done.
866
242
    if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
867
4
      // fallthrough
868
4
869
4
    // In ARC, if the property is non-atomic, use expression emission,
870
4
    // which translates to objc_storeStrong.  This isn't required, but
871
4
    // it's slightly nicer.
872
238
    } else if (CGM.getLangOpts().ObjCAutoRefCount && 
!IsAtomic36
) {
873
10
      // Using standard expression emission for the setter is only
874
10
      // acceptable if the ivar is __strong, which won't be true if
875
10
      // the property is annotated with __attribute__((NSObject)).
876
10
      // TODO: falling all the way back to objc_setProperty here is
877
10
      // just laziness, though;  we could still use objc_storeStrong
878
10
      // if we hacked it right.
879
10
      if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
880
8
        Kind = Expression;
881
2
      else
882
2
        Kind = SetPropertyAndExpressionGet;
883
10
      return;
884
10
885
10
    // Otherwise, we need to at least use setProperty.  However, if
886
10
    // the property isn't atomic, we can use normal expression
887
10
    // emission for the getter.
888
228
    } else if (!IsAtomic) {
889
92
      Kind = SetPropertyAndExpressionGet;
890
92
      return;
891
92
892
92
    // Otherwise, we have to use both setProperty and getProperty.
893
136
    } else {
894
136
      Kind = GetSetProperty;
895
136
      return;
896
136
    }
897
535
  }
898
535
899
535
  // If we're not atomic, just use expression accesses.
900
535
  if (!IsAtomic) {
901
57
    Kind = Expression;
902
57
    return;
903
57
  }
904
478
905
478
  // Properties on bitfield ivars need to be emitted using expression
906
478
  // accesses even if they're nominally atomic.
907
478
  if (ivar->isBitField()) {
908
2
    Kind = Expression;
909
2
    return;
910
2
  }
911
476
912
476
  // GC-qualified or ARC-qualified ivars need to be emitted as
913
476
  // expressions.  This actually works out to being atomic anyway,
914
476
  // except for ARC __strong, but that should trigger the above code.
915
476
  if (ivarType.hasNonTrivialObjCLifetime() ||
916
476
      
(474
CGM.getLangOpts().getGC()474
&&
917
474
       
CGM.getContext().getObjCGCAttrKind(ivarType)60
)) {
918
32
    Kind = Expression;
919
32
    return;
920
32
  }
921
444
922
444
  // Compute whether the ivar has strong members.
923
444
  if (CGM.getLangOpts().getGC())
924
30
    if (const RecordType *recordType = ivarType->getAs<RecordType>())
925
14
      HasStrong = recordType->getDecl()->hasObjectMember();
926
444
927
444
  // We can never access structs with object members with a native
928
444
  // access, because we need to use write barriers.  This is what
929
444
  // objc_copyStruct is for.
930
444
  if (HasStrong) {
931
6
    Kind = CopyStruct;
932
6
    return;
933
6
  }
934
438
935
438
  // Otherwise, this is target-dependent and based on the size and
936
438
  // alignment of the ivar.
937
438
938
438
  // If the size of the ivar is not a power of two, give up.  We don't
939
438
  // want to get into the business of doing compare-and-swaps.
940
438
  if (!IvarSize.isPowerOfTwo()) {
941
6
    Kind = CopyStruct;
942
6
    return;
943
6
  }
944
432
945
432
  llvm::Triple::ArchType arch =
946
432
    CGM.getTarget().getTriple().getArch();
947
432
948
432
  // Most architectures require memory to fit within a single cache
949
432
  // line, so the alignment has to be at least the size of the access.
950
432
  // Otherwise we have to grab a lock.
951
432
  if (IvarAlignment < IvarSize && 
!hasUnalignedAtomics(arch)31
) {
952
31
    Kind = CopyStruct;
953
31
    return;
954
31
  }
955
401
956
401
  // If the ivar's size exceeds the architecture's maximum atomic
957
401
  // access size, we have to use CopyStruct.
958
401
  if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
959
6
    Kind = CopyStruct;
960
6
    return;
961
6
  }
962
395
963
395
  // Otherwise, we can use native loads and stores.
964
395
  Kind = Native;
965
395
}
966
967
/// Generate an Objective-C property getter function.
968
///
969
/// The given Decl must be an ObjCImplementationDecl. \@synthesize
970
/// is illegal within a category.
971
void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
972
441
                                         const ObjCPropertyImplDecl *PID) {
973
441
  llvm::Constant *AtomicHelperFn =
974
441
      CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
975
441
  ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
976
441
  assert(OMD && "Invalid call to generate getter (empty method)");
977
441
  StartObjCMethod(OMD, IMP->getClassInterface());
978
441
979
441
  generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
980
441
981
441
  FinishFunction(OMD->getEndLoc());
982
441
}
983
984
453
static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
985
453
  const Expr *getter = propImpl->getGetterCXXConstructor();
986
453
  if (!getter) 
return true422
;
987
31
988
31
  // Sema only makes only of these when the ivar has a C++ class type,
989
31
  // so the form is pretty constrained.
990
31
991
31
  // If the property has a reference type, we might just be binding a
992
31
  // reference, in which case the result will be a gl-value.  We should
993
31
  // treat this as a non-trivial operation.
994
31
  if (getter->isGLValue())
995
2
    return false;
996
29
997
29
  // If we selected a trivial copy-constructor, we're okay.
998
29
  if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
999
29
    return (construct->getConstructor()->isTrivial());
1000
0
1001
0
  // The constructor might require cleanups (in which case it's never
1002
0
  // trivial).
1003
0
  assert(isa<ExprWithCleanups>(getter));
1004
0
  return false;
1005
0
}
1006
1007
/// emitCPPObjectAtomicGetterCall - Call the runtime function to
1008
/// copy the ivar into the resturn slot.
1009
static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
1010
                                          llvm::Value *returnAddr,
1011
                                          ObjCIvarDecl *ivar,
1012
6
                                          llvm::Constant *AtomicHelperFn) {
1013
6
  // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1014
6
  //                           AtomicHelperFn);
1015
6
  CallArgList args;
1016
6
1017
6
  // The 1st argument is the return Slot.
1018
6
  args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1019
6
1020
6
  // The 2nd argument is the address of the ivar.
1021
6
  llvm::Value *ivarAddr =
1022
6
      CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1023
6
          .getPointer(CGF);
1024
6
  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1025
6
  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1026
6
1027
6
  // Third argument is the helper function.
1028
6
  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1029
6
1030
6
  llvm::FunctionCallee copyCppAtomicObjectFn =
1031
6
      CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1032
6
  CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1033
6
  CGF.EmitCall(
1034
6
      CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1035
6
               callee, ReturnValueSlot(), args);
1036
6
}
1037
1038
void
1039
CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1040
                                        const ObjCPropertyImplDecl *propImpl,
1041
                                        const ObjCMethodDecl *GetterMethodDecl,
1042
441
                                        llvm::Constant *AtomicHelperFn) {
1043
441
  // If there's a non-trivial 'get' expression, we just have to emit that.
1044
441
  if (!hasTrivialGetExpr(propImpl)) {
1045
11
    if (!AtomicHelperFn) {
1046
5
      auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1047
5
                                     propImpl->getGetterCXXConstructor(),
1048
5
                                     /* NRVOCandidate=*/nullptr);
1049
5
      EmitReturnStmt(*ret);
1050
5
    }
1051
6
    else {
1052
6
      ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1053
6
      emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
1054
6
                                    ivar, AtomicHelperFn);
1055
6
    }
1056
11
    return;
1057
11
  }
1058
430
1059
430
  const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1060
430
  QualType propType = prop->getType();
1061
430
  ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1062
430
1063
430
  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1064
430
1065
430
  // Pick an implementation strategy.
1066
430
  PropertyImplStrategy strategy(CGM, propImpl);
1067
430
  switch (strategy.getKind()) {
1068
203
  case PropertyImplStrategy::Native: {
1069
203
    // We don't need to do anything for a zero-size struct.
1070
203
    if (strategy.getIvarSize().isZero())
1071
1
      return;
1072
202
1073
202
    LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1074
202
1075
202
    // Currently, all atomic accesses have to be through integer
1076
202
    // types, so there's no point in trying to pick a prettier type.
1077
202
    uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1078
202
    llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1079
202
    bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1080
202
1081
202
    // Perform an atomic load.  This does not impose ordering constraints.
1082
202
    Address ivarAddr = LV.getAddress(*this);
1083
202
    ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1084
202
    llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1085
202
    load->setAtomic(llvm::AtomicOrdering::Unordered);
1086
202
1087
202
    // Store that value into the return address.  Doing this with a
1088
202
    // bitcast is likely to produce some pretty ugly IR, but it's not
1089
202
    // the *most* terrible thing in the world.
1090
202
    llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1091
202
    uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1092
202
    llvm::Value *ivarVal = load;
1093
202
    if (ivarSize > retTySize) {
1094
1
      llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1095
1
      ivarVal = Builder.CreateTrunc(load, newTy);
1096
1
      bitcastType = newTy->getPointerTo();
1097
1
    }
1098
202
    Builder.CreateStore(ivarVal,
1099
202
                        Builder.CreateBitCast(ReturnValue, bitcastType));
1100
202
1101
202
    // Make sure we don't do an autorelease.
1102
202
    AutoreleaseResult = false;
1103
202
    return;
1104
202
  }
1105
202
1106
202
  case PropertyImplStrategy::GetSetProperty: {
1107
106
    llvm::FunctionCallee getPropertyFn =
1108
106
        CGM.getObjCRuntime().GetPropertyGetFunction();
1109
106
    if (!getPropertyFn) {
1110
0
      CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1111
0
      return;
1112
0
    }
1113
106
    CGCallee callee = CGCallee::forDirect(getPropertyFn);
1114
106
1115
106
    // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1116
106
    // FIXME: Can't this be simpler? This might even be worse than the
1117
106
    // corresponding gcc code.
1118
106
    llvm::Value *cmd =
1119
106
      Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1120
106
    llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1121
106
    llvm::Value *ivarOffset =
1122
106
      EmitIvarOffset(classImpl->getClassInterface(), ivar);
1123
106
1124
106
    CallArgList args;
1125
106
    args.add(RValue::get(self), getContext().getObjCIdType());
1126
106
    args.add(RValue::get(cmd), getContext().getObjCSelType());
1127
106
    args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1128
106
    args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1129
106
             getContext().BoolTy);
1130
106
1131
106
    // FIXME: We shouldn't need to get the function info here, the
1132
106
    // runtime already should have computed it to build the function.
1133
106
    llvm::CallBase *CallInstruction;
1134
106
    RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1135
106
                             getContext().getObjCIdType(), args),
1136
106
                         callee, ReturnValueSlot(), args, &CallInstruction);
1137
106
    if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1138
106
      call->setTailCall();
1139
106
1140
106
    // We need to fix the type here. Ivars with copy & retain are
1141
106
    // always objects so we don't need to worry about complex or
1142
106
    // aggregates.
1143
106
    RV = RValue::get(Builder.CreateBitCast(
1144
106
        RV.getScalarVal(),
1145
106
        getTypes().ConvertType(getterMethod->getReturnType())));
1146
106
1147
106
    EmitReturnOfRValue(RV, propType);
1148
106
1149
106
    // objc_getProperty does an autorelease, so we should suppress ours.
1150
106
    AutoreleaseResult = false;
1151
106
1152
106
    return;
1153
106
  }
1154
106
1155
106
  case PropertyImplStrategy::CopyStruct:
1156
24
    emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1157
24
                         strategy.hasStrongMember());
1158
24
    return;
1159
106
1160
106
  case PropertyImplStrategy::Expression:
1161
97
  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1162
97
    LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1163
97
1164
97
    QualType ivarType = ivar->getType();
1165
97
    switch (getEvaluationKind(ivarType)) {
1166
0
    case TEK_Complex: {
1167
0
      ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1168
0
      EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1169
0
                         /*init*/ true);
1170
0
      return;
1171
0
    }
1172
4
    case TEK_Aggregate: {
1173
4
      // The return value slot is guaranteed to not be aliased, but
1174
4
      // that's not necessarily the same as "on the stack", so
1175
4
      // we still potentially need objc_memmove_collectable.
1176
4
      EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1177
4
                        /* Src= */ LV, ivarType, getOverlapForReturnValue());
1178
4
      return;
1179
0
    }
1180
93
    case TEK_Scalar: {
1181
93
      llvm::Value *value;
1182
93
      if (propType->isReferenceType()) {
1183
0
        value = LV.getAddress(*this).getPointer();
1184
93
      } else {
1185
93
        // We want to load and autoreleaseReturnValue ARC __weak ivars.
1186
93
        if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1187
7
          if (getLangOpts().ObjCAutoRefCount) {
1188
6
            value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1189
6
          } else {
1190
1
            value = EmitARCLoadWeak(LV.getAddress(*this));
1191
1
          }
1192
7
1193
7
        // Otherwise we want to do a simple load, suppressing the
1194
7
        // final autorelease.
1195
86
        } else {
1196
86
          value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1197
86
          AutoreleaseResult = false;
1198
86
        }
1199
93
1200
93
        value = Builder.CreateBitCast(
1201
93
            value, ConvertType(GetterMethodDecl->getReturnType()));
1202
93
      }
1203
93
1204
93
      EmitReturnOfRValue(RValue::get(value), propType);
1205
93
      return;
1206
0
    }
1207
0
    }
1208
0
    llvm_unreachable("bad evaluation kind");
1209
0
  }
1210
0
1211
0
  }
1212
0
  llvm_unreachable("bad @property implementation strategy!");
1213
0
}
1214
1215
/// emitStructSetterCall - Call the runtime function to store the value
1216
/// from the first formal parameter into the given ivar.
1217
static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1218
25
                                 ObjCIvarDecl *ivar) {
1219
25
  // objc_copyStruct (&structIvar, &Arg,
1220
25
  //                  sizeof (struct something), true, false);
1221
25
  CallArgList args;
1222
25
1223
25
  // The first argument is the address of the ivar.
1224
25
  llvm::Value *ivarAddr =
1225
25
      CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1226
25
          .getPointer(CGF);
1227
25
  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1228
25
  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1229
25
1230
25
  // The second argument is the address of the parameter variable.
1231
25
  ParmVarDecl *argVar = *OMD->param_begin();
1232
25
  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1233
25
                     argVar->getType().getNonReferenceType(), VK_LValue,
1234
25
                     SourceLocation());
1235
25
  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1236
25
  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1237
25
  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1238
25
1239
25
  // The third argument is the sizeof the type.
1240
25
  llvm::Value *size =
1241
25
    CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1242
25
  args.add(RValue::get(size), CGF.getContext().getSizeType());
1243
25
1244
25
  // The fourth argument is the 'isAtomic' flag.
1245
25
  args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1246
25
1247
25
  // The fifth argument is the 'hasStrong' flag.
1248
25
  // FIXME: should this really always be false?
1249
25
  args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1250
25
1251
25
  llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1252
25
  CGCallee callee = CGCallee::forDirect(fn);
1253
25
  CGF.EmitCall(
1254
25
      CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1255
25
               callee, ReturnValueSlot(), args);
1256
25
}
1257
1258
/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1259
/// the value from the first formal parameter into the given ivar, using
1260
/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1261
static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1262
                                          ObjCMethodDecl *OMD,
1263
                                          ObjCIvarDecl *ivar,
1264
7
                                          llvm::Constant *AtomicHelperFn) {
1265
7
  // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1266
7
  //                           AtomicHelperFn);
1267
7
  CallArgList args;
1268
7
1269
7
  // The first argument is the address of the ivar.
1270
7
  llvm::Value *ivarAddr =
1271
7
      CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1272
7
          .getPointer(CGF);
1273
7
  ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1274
7
  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1275
7
1276
7
  // The second argument is the address of the parameter variable.
1277
7
  ParmVarDecl *argVar = *OMD->param_begin();
1278
7
  DeclRefExpr argRef(CGF.getContext(), argVar, false,
1279
7
                     argVar->getType().getNonReferenceType(), VK_LValue,
1280
7
                     SourceLocation());
1281
7
  llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1282
7
  argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1283
7
  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1284
7
1285
7
  // Third argument is the helper function.
1286
7
  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1287
7
1288
7
  llvm::FunctionCallee fn =
1289
7
      CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1290
7
  CGCallee callee = CGCallee::forDirect(fn);
1291
7
  CGF.EmitCall(
1292
7
      CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1293
7
               callee, ReturnValueSlot(), args);
1294
7
}
1295
1296
1297
444
static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1298
444
  Expr *setter = PID->getSetterCXXAssignment();
1299
444
  if (!setter) 
return true411
;
1300
33
1301
33
  // Sema only makes only of these when the ivar has a C++ class type,
1302
33
  // so the form is pretty constrained.
1303
33
1304
33
  // An operator call is trivial if the function it calls is trivial.
1305
33
  // This also implies that there's nothing non-trivial going on with
1306
33
  // the arguments, because operator= can only be trivial if it's a
1307
33
  // synthesized assignment operator and therefore both parameters are
1308
33
  // references.
1309
33
  if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1310
33
    if (const FunctionDecl *callee
1311
33
          = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1312
33
      if (callee->isTrivial())
1313
14
        return true;
1314
19
    return false;
1315
19
  }
1316
0
1317
0
  assert(isa<ExprWithCleanups>(setter));
1318
0
  return false;
1319
0
}
1320
1321
153
static bool UseOptimizedSetter(CodeGenModule &CGM) {
1322
153
  if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1323
0
    return false;
1324
153
  return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1325
153
}
1326
1327
void
1328
CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1329
                                        const ObjCPropertyImplDecl *propImpl,
1330
431
                                        llvm::Constant *AtomicHelperFn) {
1331
431
  ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1332
431
  ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1333
431
1334
431
  // Just use the setter expression if Sema gave us one and it's
1335
431
  // non-trivial.
1336
431
  if (!hasTrivialSetExpr(propImpl)) {
1337
12
    if (!AtomicHelperFn)
1338
5
      // If non-atomic, assignment is called directly.
1339
5
      EmitStmt(propImpl->getSetterCXXAssignment());
1340
7
    else
1341
7
      // If atomic, assignment is called via a locking api.
1342
7
      emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1343
7
                                    AtomicHelperFn);
1344
12
    return;
1345
12
  }
1346
419
1347
419
  PropertyImplStrategy strategy(CGM, propImpl);
1348
419
  switch (strategy.getKind()) {
1349
192
  case PropertyImplStrategy::Native: {
1350
192
    // We don't need to do anything for a zero-size struct.
1351
192
    if (strategy.getIvarSize().isZero())
1352
1
      return;
1353
191
1354
191
    Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1355
191
1356
191
    LValue ivarLValue =
1357
191
      EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1358
191
    Address ivarAddr = ivarLValue.getAddress(*this);
1359
191
1360
191
    // Currently, all atomic accesses have to be through integer
1361
191
    // types, so there's no point in trying to pick a prettier type.
1362
191
    llvm::Type *bitcastType =
1363
191
      llvm::Type::getIntNTy(getLLVMContext(),
1364
191
                            getContext().toBits(strategy.getIvarSize()));
1365
191
1366
191
    // Cast both arguments to the chosen operation type.
1367
191
    argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1368
191
    ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1369
191
1370
191
    // This bitcast load is likely to cause some nasty IR.
1371
191
    llvm::Value *load = Builder.CreateLoad(argAddr);
1372
191
1373
191
    // Perform an atomic store.  There are no memory ordering requirements.
1374
191
    llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1375
191
    store->setAtomic(llvm::AtomicOrdering::Unordered);
1376
191
    return;
1377
191
  }
1378
191
1379
191
  case PropertyImplStrategy::GetSetProperty:
1380
153
  case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1381
153
1382
153
    llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1383
153
    llvm::FunctionCallee setPropertyFn = nullptr;
1384
153
    if (UseOptimizedSetter(CGM)) {
1385
90
      // 10.8 and iOS 6.0 code and GC is off
1386
90
      setOptimizedPropertyFn =
1387
90
          CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1388
90
              strategy.isAtomic(), strategy.isCopy());
1389
90
      if (!setOptimizedPropertyFn) {
1390
0
        CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1391
0
        return;
1392
0
      }
1393
63
    }
1394
63
    else {
1395
63
      setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1396
63
      if (!setPropertyFn) {
1397
0
        CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1398
0
        return;
1399
0
      }
1400
153
    }
1401
153
1402
153
    // Emit objc_setProperty((id) self, _cmd, offset, arg,
1403
153
    //                       <is-atomic>, <is-copy>).
1404
153
    llvm::Value *cmd =
1405
153
      Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1406
153
    llvm::Value *self =
1407
153
      Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1408
153
    llvm::Value *ivarOffset =
1409
153
      EmitIvarOffset(classImpl->getClassInterface(), ivar);
1410
153
    Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1411
153
    llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1412
153
    arg = Builder.CreateBitCast(arg, VoidPtrTy);
1413
153
1414
153
    CallArgList args;
1415
153
    args.add(RValue::get(self), getContext().getObjCIdType());
1416
153
    args.add(RValue::get(cmd), getContext().getObjCSelType());
1417
153
    if (setOptimizedPropertyFn) {
1418
90
      args.add(RValue::get(arg), getContext().getObjCIdType());
1419
90
      args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1420
90
      CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1421
90
      EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1422
90
               callee, ReturnValueSlot(), args);
1423
90
    } else {
1424
63
      args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1425
63
      args.add(RValue::get(arg), getContext().getObjCIdType());
1426
63
      args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1427
63
               getContext().BoolTy);
1428
63
      args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1429
63
               getContext().BoolTy);
1430
63
      // FIXME: We shouldn't need to get the function info here, the runtime
1431
63
      // already should have computed it to build the function.
1432
63
      CGCallee callee = CGCallee::forDirect(setPropertyFn);
1433
63
      EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1434
63
               callee, ReturnValueSlot(), args);
1435
63
    }
1436
153
1437
153
    return;
1438
153
  }
1439
153
1440
153
  case PropertyImplStrategy::CopyStruct:
1441
25
    emitStructSetterCall(*this, setterMethod, ivar);
1442
25
    return;
1443
153
1444
153
  case PropertyImplStrategy::Expression:
1445
49
    break;
1446
49
  }
1447
49
1448
49
  // Otherwise, fake up some ASTs and emit a normal assignment.
1449
49
  ValueDecl *selfDecl = setterMethod->getSelfDecl();
1450
49
  DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1451
49
                   VK_LValue, SourceLocation());
1452
49
  ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1453
49
                            selfDecl->getType(), CK_LValueToRValue, &self,
1454
49
                            VK_RValue);
1455
49
  ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1456
49
                          SourceLocation(), SourceLocation(),
1457
49
                          &selfLoad, true, true);
1458
49
1459
49
  ParmVarDecl *argDecl = *setterMethod->param_begin();
1460
49
  QualType argType = argDecl->getType().getNonReferenceType();
1461
49
  DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1462
49
                  SourceLocation());
1463
49
  ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1464
49
                           argType.getUnqualifiedType(), CK_LValueToRValue,
1465
49
                           &arg, VK_RValue);
1466
49
1467
49
  // The property type can differ from the ivar type in some situations with
1468
49
  // Objective-C pointer types, we can always bit cast the RHS in these cases.
1469
49
  // The following absurdity is just to ensure well-formed IR.
1470
49
  CastKind argCK = CK_NoOp;
1471
49
  if (ivarRef.getType()->isObjCObjectPointerType()) {
1472
34
    if (argLoad.getType()->isObjCObjectPointerType())
1473
34
      argCK = CK_BitCast;
1474
0
    else if (argLoad.getType()->isBlockPointerType())
1475
0
      argCK = CK_BlockPointerToObjCPointerCast;
1476
0
    else
1477
0
      argCK = CK_CPointerToObjCPointerCast;
1478
34
  } else 
if (15
ivarRef.getType()->isBlockPointerType()15
) {
1479
0
     if (argLoad.getType()->isBlockPointerType())
1480
0
      argCK = CK_BitCast;
1481
0
    else
1482
0
      argCK = CK_AnyPointerToBlockPointerCast;
1483
15
  } else if (ivarRef.getType()->isPointerType()) {
1484
0
    argCK = CK_BitCast;
1485
0
  }
1486
49
  ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1487
49
                           ivarRef.getType(), argCK, &argLoad,
1488
49
                           VK_RValue);
1489
49
  Expr *finalArg = &argLoad;
1490
49
  if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1491
49
                                           argLoad.getType()))
1492
3
    finalArg = &argCast;
1493
49
1494
49
1495
49
  BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1496
49
                        ivarRef.getType(), VK_RValue, OK_Ordinary,
1497
49
                        SourceLocation(), FPOptions());
1498
49
  EmitStmt(&assign);
1499
49
}
1500
1501
/// Generate an Objective-C property setter function.
1502
///
1503
/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1504
/// is illegal within a category.
1505
void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1506
431
                                         const ObjCPropertyImplDecl *PID) {
1507
431
  llvm::Constant *AtomicHelperFn =
1508
431
      CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1509
431
  ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1510
431
  assert(OMD && "Invalid call to generate setter (empty method)");
1511
431
  StartObjCMethod(OMD, IMP->getClassInterface());
1512
431
1513
431
  generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1514
431
1515
431
  FinishFunction(OMD->getEndLoc());
1516
431
}
1517
1518
namespace {
1519
  struct DestroyIvar final : EHScopeStack::Cleanup {
1520
  private:
1521
    llvm::Value *addr;
1522
    const ObjCIvarDecl *ivar;
1523
    CodeGenFunction::Destroyer *destroyer;
1524
    bool useEHCleanupForArray;
1525
  public:
1526
    DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1527
                CodeGenFunction::Destroyer *destroyer,
1528
                bool useEHCleanupForArray)
1529
      : addr(addr), ivar(ivar), destroyer(destroyer),
1530
107
        useEHCleanupForArray(useEHCleanupForArray) {}
1531
1532
107
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1533
107
      LValue lvalue
1534
107
        = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1535
107
      CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1536
107
                      flags.isForNormalCleanup() && useEHCleanupForArray);
1537
107
    }
1538
  };
1539
}
1540
1541
/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1542
static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1543
                                      Address addr,
1544
62
                                      QualType type) {
1545
62
  llvm::Value *null = getNullForVariable(addr);
1546
62
  CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1547
62
}
1548
1549
static void emitCXXDestructMethod(CodeGenFunction &CGF,
1550
72
                                  ObjCImplementationDecl *impl) {
1551
72
  CodeGenFunction::RunCleanupsScope scope(CGF);
1552
72
1553
72
  llvm::Value *self = CGF.LoadObjCSelf();
1554
72
1555
72
  const ObjCInterfaceDecl *iface = impl->getClassInterface();
1556
72
  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1557
200
       ivar; 
ivar = ivar->getNextIvar()128
) {
1558
128
    QualType type = ivar->getType();
1559
128
1560
128
    // Check whether the ivar is a destructible type.
1561
128
    QualType::DestructionKind dtorKind = type.isDestructedType();
1562
128
    if (!dtorKind) 
continue21
;
1563
107
1564
107
    CodeGenFunction::Destroyer *destroyer = nullptr;
1565
107
1566
107
    // Use a call to objc_storeStrong to destroy strong ivars, for the
1567
107
    // general benefit of the tools.
1568
107
    if (dtorKind == QualType::DK_objc_strong_lifetime) {
1569
62
      destroyer = destroyARCStrongWithStore;
1570
62
1571
62
    // Otherwise use the default for the destruction kind.
1572
62
    } else {
1573
45
      destroyer = CGF.getDestroyer(dtorKind);
1574
45
    }
1575
107
1576
107
    CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1577
107
1578
107
    CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1579
107
                                         cleanupKind & EHCleanup);
1580
107
  }
1581
72
1582
72
  assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1583
72
}
1584
1585
void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1586
                                                 ObjCMethodDecl *MD,
1587
90
                                                 bool ctor) {
1588
90
  MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1589
90
  StartObjCMethod(MD, IMP->getClassInterface());
1590
90
1591
90
  // Emit .cxx_construct.
1592
90
  if (ctor) {
1593
18
    // Suppress the final autorelease in ARC.
1594
18
    AutoreleaseResult = false;
1595
18
1596
27
    for (const auto *IvarInit : IMP->inits()) {
1597
27
      FieldDecl *Field = IvarInit->getAnyMember();
1598
27
      ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1599
27
      LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1600
27
                                    LoadObjCSelf(), Ivar, 0);
1601
27
      EmitAggExpr(IvarInit->getInit(),
1602
27
                  AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
1603
27
                                          AggValueSlot::DoesNotNeedGCBarriers,
1604
27
                                          AggValueSlot::IsNotAliased,
1605
27
                                          AggValueSlot::DoesNotOverlap));
1606
27
    }
1607
18
    // constructor returns 'self'.
1608
18
    CodeGenTypes &Types = CGM.getTypes();
1609
18
    QualType IdTy(CGM.getContext().getObjCIdType());
1610
18
    llvm::Value *SelfAsId =
1611
18
      Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1612
18
    EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1613
18
1614
18
  // Emit .cxx_destruct.
1615
72
  } else {
1616
72
    emitCXXDestructMethod(*this, IMP);
1617
72
  }
1618
90
  FinishFunction();
1619
90
}
1620
1621
1.42k
llvm::Value *CodeGenFunction::LoadObjCSelf() {
1622
1.42k
  VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1623
1.42k
  DeclRefExpr DRE(getContext(), Self,
1624
1.42k
                  /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1625
1.42k
                  Self->getType(), VK_LValue, SourceLocation());
1626
1.42k
  return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1627
1.42k
}
1628
1629
686
QualType CodeGenFunction::TypeOfSelfObject() {
1630
686
  const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1631
686
  ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1632
686
  const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1633
686
    getContext().getCanonicalType(selfDecl->getType()));
1634
686
  return PTy->getPointeeType();
1635
686
}
1636
1637
73
void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1638
73
  llvm::FunctionCallee EnumerationMutationFnPtr =
1639
73
      CGM.getObjCRuntime().EnumerationMutationFunction();
1640
73
  if (!EnumerationMutationFnPtr) {
1641
0
    CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1642
0
    return;
1643
0
  }
1644
73
  CGCallee EnumerationMutationFn =
1645
73
    CGCallee::forDirect(EnumerationMutationFnPtr);
1646
73
1647
73
  CGDebugInfo *DI = getDebugInfo();
1648
73
  if (DI)
1649
36
    DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1650
73
1651
73
  RunCleanupsScope ForScope(*this);
1652
73
1653
73
  // The local variable comes into scope immediately.
1654
73
  AutoVarEmission variable = AutoVarEmission::invalid();
1655
73
  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1656
73
    variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1657
73
1658
73
  JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1659
73
1660
73
  // Fast enumeration state.
1661
73
  QualType StateTy = CGM.getObjCFastEnumerationStateType();
1662
73
  Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1663
73
  EmitNullInitialization(StatePtr, StateTy);
1664
73
1665
73
  // Number of elements in the items array.
1666
73
  static const unsigned NumItems = 16;
1667
73
1668
73
  // Fetch the countByEnumeratingWithState:objects:count: selector.
1669
73
  IdentifierInfo *II[] = {
1670
73
    &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1671
73
    &CGM.getContext().Idents.get("objects"),
1672
73
    &CGM.getContext().Idents.get("count")
1673
73
  };
1674
73
  Selector FastEnumSel =
1675
73
    CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1676
73
1677
73
  QualType ItemsTy =
1678
73
    getContext().getConstantArrayType(getContext().getObjCIdType(),
1679
73
                                      llvm::APInt(32, NumItems), nullptr,
1680
73
                                      ArrayType::Normal, 0);
1681
73
  Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1682
73
1683
73
  // Emit the collection pointer.  In ARC, we do a retain.
1684
73
  llvm::Value *Collection;
1685
73
  if (getLangOpts().ObjCAutoRefCount) {
1686
12
    Collection = EmitARCRetainScalarExpr(S.getCollection());
1687
12
1688
12
    // Enter a cleanup to do the release.
1689
12
    EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1690
61
  } else {
1691
61
    Collection = EmitScalarExpr(S.getCollection());
1692
61
  }
1693
73
1694
73
  // The 'continue' label needs to appear within the cleanup for the
1695
73
  // collection object.
1696
73
  JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1697
73
1698
73
  // Send it our message:
1699
73
  CallArgList Args;
1700
73
1701
73
  // The first argument is a temporary of the enumeration-state type.
1702
73
  Args.add(RValue::get(StatePtr.getPointer()),
1703
73
           getContext().getPointerType(StateTy));
1704
73
1705
73
  // The second argument is a temporary array with space for NumItems
1706
73
  // pointers.  We'll actually be loading elements from the array
1707
73
  // pointer written into the control state; this buffer is so that
1708
73
  // collections that *aren't* backed by arrays can still queue up
1709
73
  // batches of elements.
1710
73
  Args.add(RValue::get(ItemsPtr.getPointer()),
1711
73
           getContext().getPointerType(ItemsTy));
1712
73
1713
73
  // The third argument is the capacity of that temporary array.
1714
73
  llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1715
73
  llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1716
73
  Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1717
73
1718
73
  // Start the enumeration.
1719
73
  RValue CountRV =
1720
73
      CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1721
73
                                               getContext().getNSUIntegerType(),
1722
73
                                               FastEnumSel, Collection, Args);
1723
73
1724
73
  // The initial number of objects that were returned in the buffer.
1725
73
  llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1726
73
1727
73
  llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1728
73
  llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1729
73
1730
73
  llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1731
73
1732
73
  // If the limit pointer was zero to begin with, the collection is
1733
73
  // empty; skip all this. Set the branch weight assuming this has the same
1734
73
  // probability of exiting the loop as any other loop exit.
1735
73
  uint64_t EntryCount = getCurrentProfileCount();
1736
73
  Builder.CreateCondBr(
1737
73
      Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1738
73
      LoopInitBB,
1739
73
      createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1740
73
1741
73
  // Otherwise, initialize the loop.
1742
73
  EmitBlock(LoopInitBB);
1743
73
1744
73
  // Save the initial mutations value.  This is the value at an
1745
73
  // address that was written into the state object by
1746
73
  // countByEnumeratingWithState:objects:count:.
1747
73
  Address StateMutationsPtrPtr =
1748
73
      Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1749
73
  llvm::Value *StateMutationsPtr
1750
73
    = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1751
73
1752
73
  llvm::Value *initialMutations =
1753
73
    Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1754
73
                              "forcoll.initial-mutations");
1755
73
1756
73
  // Start looping.  This is the point we return to whenever we have a
1757
73
  // fresh, non-empty batch of objects.
1758
73
  llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1759
73
  EmitBlock(LoopBodyBB);
1760
73
1761
73
  // The current index into the buffer.
1762
73
  llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1763
73
  index->addIncoming(zero, LoopInitBB);
1764
73
1765
73
  // The current buffer size.
1766
73
  llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1767
73
  count->addIncoming(initialBufferLimit, LoopInitBB);
1768
73
1769
73
  incrementProfileCounter(&S);
1770
73
1771
73
  // Check whether the mutations value has changed from where it was
1772
73
  // at start.  StateMutationsPtr should actually be invariant between
1773
73
  // refreshes.
1774
73
  StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1775
73
  llvm::Value *currentMutations
1776
73
    = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1777
73
                                "statemutations");
1778
73
1779
73
  llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1780
73
  llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1781
73
1782
73
  Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1783
73
                       WasNotMutatedBB, WasMutatedBB);
1784
73
1785
73
  // If so, call the enumeration-mutation function.
1786
73
  EmitBlock(WasMutatedBB);
1787
73
  llvm::Value *V =
1788
73
    Builder.CreateBitCast(Collection,
1789
73
                          ConvertType(getContext().getObjCIdType()));
1790
73
  CallArgList Args2;
1791
73
  Args2.add(RValue::get(V), getContext().getObjCIdType());
1792
73
  // FIXME: We shouldn't need to get the function info here, the runtime already
1793
73
  // should have computed it to build the function.
1794
73
  EmitCall(
1795
73
          CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1796
73
           EnumerationMutationFn, ReturnValueSlot(), Args2);
1797
73
1798
73
  // Otherwise, or if the mutation function returns, just continue.
1799
73
  EmitBlock(WasNotMutatedBB);
1800
73
1801
73
  // Initialize the element variable.
1802
73
  RunCleanupsScope elementVariableScope(*this);
1803
73
  bool elementIsVariable;
1804
73
  LValue elementLValue;
1805
73
  QualType elementType;
1806
73
  if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1807
73
    // Initialize the variable, in case it's a __block variable or something.
1808
73
    EmitAutoVarInit(variable);
1809
73
1810
73
    const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1811
73
    DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1812
73
                        D->getType(), VK_LValue, SourceLocation());
1813
73
    elementLValue = EmitLValue(&tempDRE);
1814
73
    elementType = D->getType();
1815
73
    elementIsVariable = true;
1816
73
1817
73
    if (D->isARCPseudoStrong())
1818
9
      elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1819
73
  } else {
1820
0
    elementLValue = LValue(); // suppress warning
1821
0
    elementType = cast<Expr>(S.getElement())->getType();
1822
0
    elementIsVariable = false;
1823
0
  }
1824
73
  llvm::Type *convertedElementType = ConvertType(elementType);
1825
73
1826
73
  // Fetch the buffer out of the enumeration state.
1827
73
  // TODO: this pointer should actually be invariant between
1828
73
  // refreshes, which would help us do certain loop optimizations.
1829
73
  Address StateItemsPtr =
1830
73
      Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1831
73
  llvm::Value *EnumStateItems =
1832
73
    Builder.CreateLoad(StateItemsPtr, "stateitems");
1833
73
1834
73
  // Fetch the value at the current index from the buffer.
1835
73
  llvm::Value *CurrentItemPtr =
1836
73
    Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1837
73
  llvm::Value *CurrentItem =
1838
73
    Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
1839
73
1840
73
  // Cast that value to the right type.
1841
73
  CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1842
73
                                      "currentitem");
1843
73
1844
73
  // Make sure we have an l-value.  Yes, this gets evaluated every
1845
73
  // time through the loop.
1846
73
  if (!elementIsVariable) {
1847
0
    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1848
0
    EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1849
73
  } else {
1850
73
    EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1851
73
                           /*isInit*/ true);
1852
73
  }
1853
73
1854
73
  // If we do have an element variable, this assignment is the end of
1855
73
  // its initialization.
1856
73
  if (elementIsVariable)
1857
73
    EmitAutoVarCleanups(variable);
1858
73
1859
73
  // Perform the loop body, setting up break and continue labels.
1860
73
  BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1861
73
  {
1862
73
    RunCleanupsScope Scope(*this);
1863
73
    EmitStmt(S.getBody());
1864
73
  }
1865
73
  BreakContinueStack.pop_back();
1866
73
1867
73
  // Destroy the element variable now.
1868
73
  elementVariableScope.ForceCleanup();
1869
73
1870
73
  // Check whether there are more elements.
1871
73
  EmitBlock(AfterBody.getBlock());
1872
73
1873
73
  llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1874
73
1875
73
  // First we check in the local buffer.
1876
73
  llvm::Value *indexPlusOne =
1877
73
      Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1878
73
1879
73
  // If we haven't overrun the buffer yet, we can continue.
1880
73
  // Set the branch weights based on the simplifying assumption that this is
1881
73
  // like a while-loop, i.e., ignoring that the false branch fetches more
1882
73
  // elements and then returns to the loop.
1883
73
  Builder.CreateCondBr(
1884
73
      Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1885
73
      createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1886
73
1887
73
  index->addIncoming(indexPlusOne, AfterBody.getBlock());
1888
73
  count->addIncoming(count, AfterBody.getBlock());
1889
73
1890
73
  // Otherwise, we have to fetch more elements.
1891
73
  EmitBlock(FetchMoreBB);
1892
73
1893
73
  CountRV =
1894
73
      CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1895
73
                                               getContext().getNSUIntegerType(),
1896
73
                                               FastEnumSel, Collection, Args);
1897
73
1898
73
  // If we got a zero count, we're done.
1899
73
  llvm::Value *refetchCount = CountRV.getScalarVal();
1900
73
1901
73
  // (note that the message send might split FetchMoreBB)
1902
73
  index->addIncoming(zero, Builder.GetInsertBlock());
1903
73
  count->addIncoming(refetchCount, Builder.GetInsertBlock());
1904
73
1905
73
  Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1906
73
                       EmptyBB, LoopBodyBB);
1907
73
1908
73
  // No more elements.
1909
73
  EmitBlock(EmptyBB);
1910
73
1911
73
  if (!elementIsVariable) {
1912
0
    // If the element was not a declaration, set it to be null.
1913
0
1914
0
    llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1915
0
    elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1916
0
    EmitStoreThroughLValue(RValue::get(null), elementLValue);
1917
0
  }
1918
73
1919
73
  if (DI)
1920
36
    DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1921
73
1922
73
  ForScope.ForceCleanup();
1923
73
  EmitBlock(LoopEnd.getBlock());
1924
73
}
1925
1926
218
void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1927
218
  CGM.getObjCRuntime().EmitTryStmt(*this, S);
1928
218
}
1929
1930
50
void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1931
50
  CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1932
50
}
1933
1934
void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1935
13
                                              const ObjCAtSynchronizedStmt &S) {
1936
13
  CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1937
13
}
1938
1939
namespace {
1940
  struct CallObjCRelease final : EHScopeStack::Cleanup {
1941
270
    CallObjCRelease(llvm::Value *object) : object(object) {}
1942
    llvm::Value *object;
1943
1944
274
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1945
274
      // Releases at the end of the full-expression are imprecise.
1946
274
      CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1947
274
    }
1948
  };
1949
}
1950
1951
/// Produce the code for a CK_ARCConsumeObject.  Does a primitive
1952
/// release at the end of the full-expression.
1953
llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1954
270
                                                    llvm::Value *object) {
1955
270
  // If we're in a conditional branch, we need to make the cleanup
1956
270
  // conditional.
1957
270
  pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1958
270
  return object;
1959
270
}
1960
1961
llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1962
0
                                                           llvm::Value *value) {
1963
0
  return EmitARCRetainAutorelease(type, value);
1964
0
}
1965
1966
/// Given a number of pointers, inform the optimizer that they're
1967
/// being intrinsically used up until this point in the program.
1968
18
void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1969
18
  llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
1970
18
  if (!fn)
1971
9
    fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
1972
18
1973
18
  // This isn't really a "runtime" function, but as an intrinsic it
1974
18
  // doesn't really matter as long as we align things up.
1975
18
  EmitNounwindRuntimeCall(fn, values);
1976
18
}
1977
1978
863
static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
1979
863
  if (auto *F = dyn_cast<llvm::Function>(RTF)) {
1980
863
    // If the target runtime doesn't naturally support ARC, emit weak
1981
863
    // references to the runtime support library.  We don't really
1982
863
    // permit this to fail, but we need a particular relocation style.
1983
863
    if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1984
863
        
!CGM.getTriple().isOSBinFormatCOFF()423
) {
1985
418
      F->setLinkage(llvm::Function::ExternalWeakLinkage);
1986
418
    }
1987
863
  }
1988
863
}
1989
1990
static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1991
196
                                         llvm::FunctionCallee RTF) {
1992
196
  setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1993
196
}
1994
1995
/// Perform an operation having the signature
1996
///   i8* (i8*)
1997
/// where a null input causes a no-op and returns null.
1998
static llvm::Value *emitARCValueOperation(
1999
    CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2000
    llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2001
1.10k
    llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
2002
1.10k
  if (isa<llvm::ConstantPointerNull>(value))
2003
169
    return value;
2004
936
2005
936
  if (!fn) {
2006
205
    fn = CGF.CGM.getIntrinsic(IntID);
2007
205
    setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2008
205
  }
2009
936
2010
936
  // Cast the argument to 'id'.
2011
936
  llvm::Type *origType = returnType ? 
returnType0
: value->getType();
2012
936
  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2013
936
2014
936
  // Call the function.
2015
936
  llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2016
936
  call->setTailCallKind(tailKind);
2017
936
2018
936
  // Cast the result back to the original type.
2019
936
  return CGF.Builder.CreateBitCast(call, origType);
2020
936
}
2021
2022
/// Perform an operation having the following signature:
2023
///   i8* (i8**)
2024
static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2025
                                         llvm::Function *&fn,
2026
190
                                         llvm::Intrinsic::ID IntID) {
2027
190
  if (!fn) {
2028
36
    fn = CGF.CGM.getIntrinsic(IntID);
2029
36
    setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2030
36
  }
2031
190
2032
190
  // Cast the argument to 'id*'.
2033
190
  llvm::Type *origType = addr.getElementType();
2034
190
  addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2035
190
2036
190
  // Call the function.
2037
190
  llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
2038
190
2039
190
  // Cast the result back to a dereference of the original type.
2040
190
  if (origType != CGF.Int8PtrTy)
2041
19
    result = CGF.Builder.CreateBitCast(result, origType);
2042
190
2043
190
  return result;
2044
190
}
2045
2046
/// Perform an operation having the following signature:
2047
///   i8* (i8**, i8*)
2048
static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
2049
                                          llvm::Value *value,
2050
                                          llvm::Function *&fn,
2051
                                          llvm::Intrinsic::ID IntID,
2052
97
                                          bool ignored) {
2053
97
  assert(addr.getElementType() == value->getType());
2054
97
2055
97
  if (!fn) {
2056
52
    fn = CGF.CGM.getIntrinsic(IntID);
2057
52
    setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2058
52
  }
2059
97
2060
97
  llvm::Type *origType = value->getType();
2061
97
2062
97
  llvm::Value *args[] = {
2063
97
    CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
2064
97
    CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2065
97
  };
2066
97
  llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
2067
97
2068
97
  if (ignored) 
return nullptr76
;
2069
21
2070
21
  return CGF.Builder.CreateBitCast(result, origType);
2071
21
}
2072
2073
/// Perform an operation having the following signature:
2074
///   void (i8**, i8**)
2075
static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2076
                                 llvm::Function *&fn,
2077
319
                                 llvm::Intrinsic::ID IntID) {
2078
319
  assert(dst.getType() == src.getType());
2079
319
2080
319
  if (!fn) {
2081
45
    fn = CGF.CGM.getIntrinsic(IntID);
2082
45
    setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2083
45
  }
2084
319
2085
319
  llvm::Value *args[] = {
2086
319
    CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2087
319
    CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2088
319
  };
2089
319
  CGF.EmitNounwindRuntimeCall(fn, args);
2090
319
}
2091
2092
/// Perform an operation having the signature
2093
///   i8* (i8*)
2094
/// where a null input causes a no-op and returns null.
2095
static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2096
                                           llvm::Value *value,
2097
                                           llvm::Type *returnType,
2098
                                           llvm::FunctionCallee &fn,
2099
1.42k
                                           StringRef fnName) {
2100
1.42k
  if (isa<llvm::ConstantPointerNull>(value))
2101
0
    return value;
2102
1.42k
2103
1.42k
  if (!fn) {
2104
300
    llvm::FunctionType *fnType =
2105
300
      llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2106
300
    fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2107
300
2108
300
    // We have Native ARC, so set nonlazybind attribute for performance
2109
300
    if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2110
300
      if (fnName == "objc_retain")
2111
5
        f->addFnAttr(llvm::Attribute::NonLazyBind);
2112
300
  }
2113
1.42k
2114
1.42k
  // Cast the argument to 'id'.
2115
1.42k
  llvm::Type *origType = returnType ? returnType : 
value->getType()0
;
2116
1.42k
  value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2117
1.42k
2118
1.42k
  // Call the function.
2119
1.42k
  llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
2120
1.42k
2121
1.42k
  // Cast the result back to the original type.
2122
1.42k
  return CGF.Builder.CreateBitCast(Inst, origType);
2123
1.42k
}
2124
2125
/// Produce the code to do a retain.  Based on the type, calls one of:
2126
///   call i8* \@objc_retain(i8* %value)
2127
///   call i8* \@objc_retainBlock(i8* %value)
2128
580
llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2129
580
  if (type->isBlockPointerType())
2130
108
    return EmitARCRetainBlock(value, /*mandatory*/ false);
2131
472
  else
2132
472
    return EmitARCRetainNonBlock(value);
2133
580
}
2134
2135
/// Retain the given object, with normal retain semantics.
2136
///   call i8* \@objc_retain(i8* %value)
2137
548
llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2138
548
  return emitARCValueOperation(*this, value, nullptr,
2139
548
                               CGM.getObjCEntrypoints().objc_retain,
2140
548
                               llvm::Intrinsic::objc_retain);
2141
548
}
2142
2143
/// Retain the given block, with _Block_copy semantics.
2144
///   call i8* \@objc_retainBlock(i8* %value)
2145
///
2146
/// \param mandatory - If false, emit the call with metadata
2147
/// indicating that it's okay for the optimizer to eliminate this call
2148
/// if it can prove that the block never escapes except down the stack.
2149
llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2150
137
                                                 bool mandatory) {
2151
137
  llvm::Value *result
2152
137
    = emitARCValueOperation(*this, value, nullptr,
2153
137
                            CGM.getObjCEntrypoints().objc_retainBlock,
2154
137
                            llvm::Intrinsic::objc_retainBlock);
2155
137
2156
137
  // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2157
137
  // tell the optimizer that it doesn't need to do this copy if the
2158
137
  // block doesn't escape, where being passed as an argument doesn't
2159
137
  // count as escaping.
2160
137
  if (!mandatory && 
isa<llvm::Instruction>(result)120
) {
2161
105
    llvm::CallInst *call
2162
105
      = cast<llvm::CallInst>(result->stripPointerCasts());
2163
105
    assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
2164
105
2165
105
    call->setMetadata("clang.arc.copy_on_escape",
2166
105
                      llvm::MDNode::get(Builder.getContext(), None));
2167
105
  }
2168
137
2169
137
  return result;
2170
137
}
2171
2172
329
static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2173
329
  // Fetch the void(void) inline asm which marks that we're going to
2174
329
  // do something with the autoreleased return value.
2175
329
  llvm::InlineAsm *&marker
2176
329
    = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2177
329
  if (!marker) {
2178
275
    StringRef assembly
2179
275
      = CGF.CGM.getTargetCodeGenInfo()
2180
275
           .getARCRetainAutoreleasedReturnValueMarker();
2181
275
2182
275
    // If we have an empty assembly string, there's nothing to do.
2183
275
    if (assembly.empty()) {
2184
233
2185
233
    // Otherwise, at -O0, build an inline asm that we're going to call
2186
233
    // in a moment.
2187
233
    } else 
if (42
CGF.CGM.getCodeGenOpts().OptimizationLevel == 042
) {
2188
16
      llvm::FunctionType *type =
2189
16
        llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2190
16
2191
16
      marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2192
16
2193
16
    // If we're at -O1 and above, we don't want to litter the code
2194
16
    // with this marker yet, so leave a breadcrumb for the ARC
2195
16
    // optimizer to pick up.
2196
26
    } else {
2197
26
      const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2198
26
      if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2199
3
        auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2200
3
        CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
2201
3
      }
2202
26
    }
2203
275
  }
2204
329
2205
329
  // Call the marker asm if we made one, which we do only at -O0.
2206
329
  if (marker)
2207
70
    CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2208
329
}
2209
2210
/// Retain the given object which is the result of a function call.
2211
///   call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2212
///
2213
/// Yes, this function name is one character away from a different
2214
/// call with completely different semantics.
2215
llvm::Value *
2216
293
CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2217
293
  emitAutoreleasedReturnValueMarker(*this);
2218
293
  llvm::CallInst::TailCallKind tailKind =
2219
293
      CGM.getTargetCodeGenInfo()
2220
293
              .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2221
293
          ? 
llvm::CallInst::TCK_NoTail227
2222
293
          : 
llvm::CallInst::TCK_None66
;
2223
293
  return emitARCValueOperation(
2224
293
      *this, value, nullptr,
2225
293
      CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2226
293
      llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
2227
293
}
2228
2229
/// Claim a possibly-autoreleased return value at +0.  This is only
2230
/// valid to do in contexts which do not rely on the retain to keep
2231
/// the object valid for all of its uses; for example, when
2232
/// the value is ignored, or when it is being assigned to an
2233
/// __unsafe_unretained variable.
2234
///
2235
///   call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2236
llvm::Value *
2237
36
CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2238
36
  emitAutoreleasedReturnValueMarker(*this);
2239
36
  return emitARCValueOperation(*this, value, nullptr,
2240
36
              CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2241
36
                     llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
2242
36
}
2243
2244
/// Release the given object.
2245
///   call void \@objc_release(i8* %value)
2246
void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2247
627
                                     ARCPreciseLifetime_t precise) {
2248
627
  if (isa<llvm::ConstantPointerNull>(value)) 
return0
;
2249
627
2250
627
  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
2251
627
  if (!fn) {
2252
69
    fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2253
69
    setARCRuntimeFunctionLinkage(CGM, fn);
2254
69
  }
2255
627
2256
627
  // Cast the argument to 'id'.
2257
627
  value = Builder.CreateBitCast(value, Int8PtrTy);
2258
627
2259
627
  // Call objc_release.
2260
627
  llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2261
627
2262
627
  if (precise == ARCImpreciseLifetime) {
2263
595
    call->setMetadata("clang.imprecise_release",
2264
595
                      llvm::MDNode::get(Builder.getContext(), None));
2265
595
  }
2266
627
}
2267
2268
/// Destroy a __strong variable.
2269
///
2270
/// At -O0, emit a call to store 'null' into the address;
2271
/// instrumenting tools prefer this because the address is exposed,
2272
/// but it's relatively cumbersome to optimize.
2273
///
2274
/// At -O1 and above, just load and call objc_release.
2275
///
2276
///   call void \@objc_storeStrong(i8** %addr, i8* null)
2277
void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2278
1.08k
                                           ARCPreciseLifetime_t precise) {
2279
1.08k
  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2280
843
    llvm::Value *null = getNullForVariable(addr);
2281
843
    EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2282
843
    return;
2283
843
  }
2284
244
2285
244
  llvm::Value *value = Builder.CreateLoad(addr);
2286
244
  EmitARCRelease(value, precise);
2287
244
}
2288
2289
/// Store into a strong object.  Always calls this:
2290
///   call void \@objc_storeStrong(i8** %addr, i8* %value)
2291
llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2292
                                                     llvm::Value *value,
2293
1.23k
                                                     bool ignored) {
2294
1.23k
  assert(addr.getElementType() == value->getType());
2295
1.23k
2296
1.23k
  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2297
1.23k
  if (!fn) {
2298
106
    fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2299
106
    setARCRuntimeFunctionLinkage(CGM, fn);
2300
106
  }
2301
1.23k
2302
1.23k
  llvm::Value *args[] = {
2303
1.23k
    Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2304
1.23k
    Builder.CreateBitCast(value, Int8PtrTy)
2305
1.23k
  };
2306
1.23k
  EmitNounwindRuntimeCall(fn, args);
2307
1.23k
2308
1.23k
  if (ignored) 
return nullptr1.22k
;
2309
13
  return value;
2310
13
}
2311
2312
/// Store into a strong object.  Sometimes calls this:
2313
///   call void \@objc_storeStrong(i8** %addr, i8* %value)
2314
/// Other times, breaks it down into components.
2315
llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2316
                                                 llvm::Value *newValue,
2317
95
                                                 bool ignored) {
2318
95
  QualType type = dst.getType();
2319
95
  bool isBlock = type->isBlockPointerType();
2320
95
2321
95
  // Use a store barrier at -O0 unless this is a block type or the
2322
95
  // lvalue is inadequately aligned.
2323
95
  if (shouldUseFusedARCCalls() &&
2324
95
      
!isBlock86
&&
2325
95
      
(84
dst.getAlignment().isZero()84
||
2326
84
       dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2327
84
    return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
2328
84
  }
2329
11
2330
11
  // Otherwise, split it out.
2331
11
2332
11
  // Retain the new value.
2333
11
  newValue = EmitARCRetain(type, newValue);
2334
11
2335
11
  // Read the old value.
2336
11
  llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2337
11
2338
11
  // Store.  We do this before the release so that any deallocs won't
2339
11
  // see the old value.
2340
11
  EmitStoreOfScalar(newValue, dst);
2341
11
2342
11
  // Finally, release the old value.
2343
11
  EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2344
11
2345
11
  return newValue;
2346
11
}
2347
2348
/// Autorelease the given object.
2349
///   call i8* \@objc_autorelease(i8* %value)
2350
6
llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2351
6
  return emitARCValueOperation(*this, value, nullptr,
2352
6
                               CGM.getObjCEntrypoints().objc_autorelease,
2353
6
                               llvm::Intrinsic::objc_autorelease);
2354
6
}
2355
2356
/// Autorelease the given object.
2357
///   call i8* \@objc_autoreleaseReturnValue(i8* %value)
2358
llvm::Value *
2359
68
CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2360
68
  return emitARCValueOperation(*this, value, nullptr,
2361
68
                            CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2362
68
                               llvm::Intrinsic::objc_autoreleaseReturnValue,
2363
68
                               llvm::CallInst::TCK_Tail);
2364
68
}
2365
2366
/// Do a fused retain/autorelease of the given object.
2367
///   call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2368
llvm::Value *
2369
7
CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2370
7
  return emitARCValueOperation(*this, value, nullptr,
2371
7
                     CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2372
7
                             llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2373
7
                               llvm::CallInst::TCK_Tail);
2374
7
}
2375
2376
/// Do a fused retain/autorelease of the given object.
2377
///   call i8* \@objc_retainAutorelease(i8* %value)
2378
/// or
2379
///   %retain = call i8* \@objc_retainBlock(i8* %value)
2380
///   call i8* \@objc_autorelease(i8* %retain)
2381
llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2382
10
                                                       llvm::Value *value) {
2383
10
  if (!type->isBlockPointerType())
2384
10
    return EmitARCRetainAutoreleaseNonBlock(value);
2385
0
2386
0
  if (isa<llvm::ConstantPointerNull>(value)) return value;
2387
0
2388
0
  llvm::Type *origType = value->getType();
2389
0
  value = Builder.CreateBitCast(value, Int8PtrTy);
2390
0
  value = EmitARCRetainBlock(value, /*mandatory*/ true);
2391
0
  value = EmitARCAutorelease(value);
2392
0
  return Builder.CreateBitCast(value, origType);
2393
0
}
2394
2395
/// Do a fused retain/autorelease of the given object.
2396
///   call i8* \@objc_retainAutorelease(i8* %value)
2397
llvm::Value *
2398
10
CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2399
10
  return emitARCValueOperation(*this, value, nullptr,
2400
10
                               CGM.getObjCEntrypoints().objc_retainAutorelease,
2401
10
                               llvm::Intrinsic::objc_retainAutorelease);
2402
10
}
2403
2404
/// i8* \@objc_loadWeak(i8** %addr)
2405
/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2406
16
llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2407
16
  return emitARCLoadOperation(*this, addr,
2408
16
                              CGM.getObjCEntrypoints().objc_loadWeak,
2409
16
                              llvm::Intrinsic::objc_loadWeak);
2410
16
}
2411
2412
/// i8* \@objc_loadWeakRetained(i8** %addr)
2413
174
llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2414
174
  return emitARCLoadOperation(*this, addr,
2415
174
                              CGM.getObjCEntrypoints().objc_loadWeakRetained,
2416
174
                              llvm::Intrinsic::objc_loadWeakRetained);
2417
174
}
2418
2419
/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2420
/// Returns %value.
2421
llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2422
                                               llvm::Value *value,
2423
50
                                               bool ignored) {
2424
50
  return emitARCStoreOperation(*this, addr, value,
2425
50
                               CGM.getObjCEntrypoints().objc_storeWeak,
2426
50
                               llvm::Intrinsic::objc_storeWeak, ignored);
2427
50
}
2428
2429
/// i8* \@objc_initWeak(i8** %addr, i8* %value)
2430
/// Returns %value.  %addr is known to not have a current weak entry.
2431
/// Essentially equivalent to:
2432
///   *addr = nil; objc_storeWeak(addr, value);
2433
179
void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2434
179
  // If we're initializing to null, just write null to memory; no need
2435
179
  // to get the runtime involved.  But don't do this if optimization
2436
179
  // is enabled, because accounting for this would make the optimizer
2437
179
  // much more complicated.
2438
179
  if (isa<llvm::ConstantPointerNull>(value) &&
2439
179
      
CGM.getCodeGenOpts().OptimizationLevel == 0138
) {
2440
132
    Builder.CreateStore(value, addr);
2441
132
    return;
2442
132
  }
2443
47
2444
47
  emitARCStoreOperation(*this, addr, value,
2445
47
                        CGM.getObjCEntrypoints().objc_initWeak,
2446
47
                        llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2447
47
}
2448
2449
/// void \@objc_destroyWeak(i8** %addr)
2450
/// Essentially objc_storeWeak(addr, nil).
2451
532
void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2452
532
  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2453
532
  if (!fn) {
2454
56
    fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2455
56
    setARCRuntimeFunctionLinkage(CGM, fn);
2456
56
  }
2457
532
2458
532
  // Cast the argument to 'id*'.
2459
532
  addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2460
532
2461
532
  EmitNounwindRuntimeCall(fn, addr.getPointer());
2462
532
}
2463
2464
/// void \@objc_moveWeak(i8** %dest, i8** %src)
2465
/// Disregards the current value in %dest.  Leaves %src pointing to nothing.
2466
/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2467
14
void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2468
14
  emitARCCopyOperation(*this, dst, src,
2469
14
                       CGM.getObjCEntrypoints().objc_moveWeak,
2470
14
                       llvm::Intrinsic::objc_moveWeak);
2471
14
}
2472
2473
/// void \@objc_copyWeak(i8** %dest, i8** %src)
2474
/// Disregards the current value in %dest.  Essentially
2475
///   objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2476
305
void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2477
305
  emitARCCopyOperation(*this, dst, src,
2478
305
                       CGM.getObjCEntrypoints().objc_copyWeak,
2479
305
                       llvm::Intrinsic::objc_copyWeak);
2480
305
}
2481
2482
void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2483
4
                                            Address SrcAddr) {
2484
4
  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2485
4
  Object = EmitObjCConsumeObject(Ty, Object);
2486
4
  EmitARCStoreWeak(DstAddr, Object, false);
2487
4
}
2488
2489
void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2490
4
                                            Address SrcAddr) {
2491
4
  llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2492
4
  Object = EmitObjCConsumeObject(Ty, Object);
2493
4
  EmitARCStoreWeak(DstAddr, Object, false);
2494
4
  EmitARCDestroyWeak(SrcAddr);
2495
4
}
2496
2497
/// Produce the code to do a objc_autoreleasepool_push.
2498
///   call i8* \@objc_autoreleasePoolPush(void)
2499
100
llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2500
100
  llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2501
100
  if (!fn) {
2502
98
    fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2503
98
    setARCRuntimeFunctionLinkage(CGM, fn);
2504
98
  }
2505
100
2506
100
  return EmitNounwindRuntimeCall(fn);
2507
100
}
2508
2509
/// Produce the code to do a primitive release.
2510
///   call void \@objc_autoreleasePoolPop(i8* %ptr)
2511
100
void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2512
100
  assert(value->getType() == Int8PtrTy);
2513
100
2514
100
  if (getInvokeDest()) {
2515
2
    // Call the runtime method not the intrinsic if we are handling exceptions
2516
2
    llvm::FunctionCallee &fn =
2517
2
        CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2518
2
    if (!fn) {
2519
2
      llvm::FunctionType *fnType =
2520
2
        llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2521
2
      fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2522
2
      setARCRuntimeFunctionLinkage(CGM, fn);
2523
2
    }
2524
2
2525
2
    // objc_autoreleasePoolPop can throw.
2526
2
    EmitRuntimeCallOrInvoke(fn, value);
2527
98
  } else {
2528
98
    llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2529
98
    if (!fn) {
2530
98
      fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2531
98
      setARCRuntimeFunctionLinkage(CGM, fn);
2532
98
    }
2533
98
2534
98
    EmitRuntimeCall(fn, value);
2535
98
  }
2536
100
}
2537
2538
/// Produce the code to do an MRR version objc_autoreleasepool_push.
2539
/// Which is: [[NSAutoreleasePool alloc] init];
2540
/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2541
/// init is declared as: - (id) init; in its NSObject super class.
2542
///
2543
17
llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2544
17
  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2545
17
  llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2546
17
  // [NSAutoreleasePool alloc]
2547
17
  IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2548
17
  Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2549
17
  CallArgList Args;
2550
17
  RValue AllocRV =
2551
17
    Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2552
17
                                getContext().getObjCIdType(),
2553
17
                                AllocSel, Receiver, Args);
2554
17
2555
17
  // [Receiver init]
2556
17
  Receiver = AllocRV.getScalarVal();
2557
17
  II = &CGM.getContext().Idents.get("init");
2558
17
  Selector InitSel = getContext().Selectors.getSelector(0, &II);
2559
17
  RValue InitRV =
2560
17
    Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2561
17
                                getContext().getObjCIdType(),
2562
17
                                InitSel, Receiver, Args);
2563
17
  return InitRV.getScalarVal();
2564
17
}
2565
2566
/// Allocate the given objc object.
2567
///   call i8* \@objc_alloc(i8* %value)
2568
llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2569
1.32k
                                            llvm::Type *resultType) {
2570
1.32k
  return emitObjCValueOperation(*this, value, resultType,
2571
1.32k
                                CGM.getObjCEntrypoints().objc_alloc,
2572
1.32k
                                "objc_alloc");
2573
1.32k
}
2574
2575
/// Allocate the given objc object.
2576
///   call i8* \@objc_allocWithZone(i8* %value)
2577
llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2578
25
                                                    llvm::Type *resultType) {
2579
25
  return emitObjCValueOperation(*this, value, resultType,
2580
25
                                CGM.getObjCEntrypoints().objc_allocWithZone,
2581
25
                                "objc_allocWithZone");
2582
25
}
2583
2584
llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2585
8
                                                llvm::Type *resultType) {
2586
8
  return emitObjCValueOperation(*this, value, resultType,
2587
8
                                CGM.getObjCEntrypoints().objc_alloc_init,
2588
8
                                "objc_alloc_init");
2589
8
}
2590
2591
/// Produce the code to do a primitive release.
2592
/// [tmp drain];
2593
17
void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2594
17
  IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2595
17
  Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2596
17
  CallArgList Args;
2597
17
  CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2598
17
                              getContext().VoidTy, DrainSel, Arg, Args);
2599
17
}
2600
2601
void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2602
                                              Address addr,
2603
42
                                              QualType type) {
2604
42
  CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2605
42
}
2606
2607
void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2608
                                                Address addr,
2609
1.02k
                                                QualType type) {
2610
1.02k
  CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2611
1.02k
}
2612
2613
void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2614
                                     Address addr,
2615
517
                                     QualType type) {
2616
517
  CGF.EmitARCDestroyWeak(addr);
2617
517
}
2618
2619
void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2620
4
                                          QualType type) {
2621
4
  llvm::Value *value = CGF.Builder.CreateLoad(addr);
2622
4
  CGF.EmitARCIntrinsicUse(value);
2623
4
}
2624
2625
/// Autorelease the given object.
2626
///   call i8* \@objc_autorelease(i8* %value)
2627
llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2628
46
                                                  llvm::Type *returnType) {
2629
46
  return emitObjCValueOperation(
2630
46
      *this, value, returnType,
2631
46
      CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2632
46
      "objc_autorelease");
2633
46
}
2634
2635
/// Retain the given object, with normal retain semantics.
2636
///   call i8* \@objc_retain(i8* %value)
2637
llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2638
17
                                                     llvm::Type *returnType) {
2639
17
  return emitObjCValueOperation(
2640
17
      *this, value, returnType,
2641
17
      CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
2642
17
}
2643
2644
/// Release the given object.
2645
///   call void \@objc_release(i8* %value)
2646
void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2647
187
                                      ARCPreciseLifetime_t precise) {
2648
187
  if (isa<llvm::ConstantPointerNull>(value)) 
return0
;
2649
187
2650
187
  llvm::FunctionCallee &fn =
2651
187
      CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
2652
187
  if (!fn) {
2653
96
    llvm::FunctionType *fnType =
2654
96
        llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2655
96
    fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2656
96
    setARCRuntimeFunctionLinkage(CGM, fn);
2657
96
    // We have Native ARC, so set nonlazybind attribute for performance
2658
96
    if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2659
96
      f->addFnAttr(llvm::Attribute::NonLazyBind);
2660
96
  }
2661
187
2662
187
  // Cast the argument to 'id'.
2663
187
  value = Builder.CreateBitCast(value, Int8PtrTy);
2664
187
2665
187
  // Call objc_release.
2666
187
  llvm::CallBase *call = EmitCallOrInvoke(fn, value);
2667
187
2668
187
  if (precise == ARCImpreciseLifetime) {
2669
0
    call->setMetadata("clang.imprecise_release",
2670
0
                      llvm::MDNode::get(Builder.getContext(), None));
2671
0
  }
2672
187
}
2673
2674
namespace {
2675
  struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2676
    llvm::Value *Token;
2677
2678
100
    CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2679
2680
100
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2681
100
      CGF.EmitObjCAutoreleasePoolPop(Token);
2682
100
    }
2683
  };
2684
  struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2685
    llvm::Value *Token;
2686
2687
17
    CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2688
2689
17
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2690
17
      CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2691
17
    }
2692
  };
2693
}
2694
2695
4
void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2696
4
  if (CGM.getLangOpts().ObjCAutoRefCount)
2697
4
    EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2698
0
  else
2699
0
    EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2700
4
}
2701
2702
309
static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2703
309
  switch (lifetime) {
2704
284
  case Qualifiers::OCL_None:
2705
284
  case Qualifiers::OCL_ExplicitNone:
2706
284
  case Qualifiers::OCL_Strong:
2707
284
  case Qualifiers::OCL_Autoreleasing:
2708
284
    return true;
2709
284
2710
284
  case Qualifiers::OCL_Weak:
2711
25
    return false;
2712
0
  }
2713
0
2714
0
  llvm_unreachable("impossible lifetime!");
2715
0
}
2716
2717
static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2718
                                                  LValue lvalue,
2719
307
                                                  QualType type) {
2720
307
  llvm::Value *result;
2721
307
  bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2722
307
  if (shouldRetain) {
2723
283
    result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2724
283
  } else {
2725
24
    assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2726
24
    result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
2727
24
  }
2728
307
  return TryEmitResult(result, !shouldRetain);
2729
307
}
2730
2731
static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2732
307
                                                  const Expr *e) {
2733
307
  e = e->IgnoreParens();
2734
307
  QualType type = e->getType();
2735
307
2736
307
  // If we're loading retained from a __strong xvalue, we can avoid
2737
307
  // an extra retain/release pair by zeroing out the source of this
2738
307
  // "move" operation.
2739
307
  if (e->isXValue() &&
2740
307
      
!type.isConstQualified()4
&&
2741
307
      
type.getObjCLifetime() == Qualifiers::OCL_Strong3
) {
2742
3
    // Emit the lvalue.
2743
3
    LValue lv = CGF.EmitLValue(e);
2744
3
2745
3
    // Load the object pointer.
2746
3
    llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2747
3
                                               SourceLocation()).getScalarVal();
2748
3
2749
3
    // Set the source pointer to NULL.
2750
3
    CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
2751
3
2752
3
    return TryEmitResult(result, true);
2753
3
  }
2754
304
2755
304
  // As a very special optimization, in ARC++, if the l-value is the
2756
304
  // result of a non-volatile assignment, do a simple retain of the
2757
304
  // result of the call to objc_storeWeak instead of reloading.
2758
304
  if (CGF.getLangOpts().CPlusPlus &&
2759
304
      
!type.isVolatileQualified()101
&&
2760
304
      
type.getObjCLifetime() == Qualifiers::OCL_Weak100
&&
2761
304
      
isa<BinaryOperator>(e)2
&&
2762
304
      
cast<BinaryOperator>(e)->getOpcode() == BO_Assign1
)
2763
1
    return TryEmitResult(CGF.EmitScalarExpr(e), false);
2764
303
2765
303
  // Try to emit code for scalar constant instead of emitting LValue and
2766
303
  // loading it because we are not guaranteed to have an l-value. One of such
2767
303
  // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2768
303
  if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2769
268
    auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2770
268
    if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2771
2
      return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2772
2
                           !shouldRetainObjCLifetime(type.getObjCLifetime()));
2773
301
  }
2774
301
2775
301
  return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2776
301
}
2777
2778
typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2779
                                         llvm::Value *value)>
2780
  ValueTransform;
2781
2782
/// Insert code immediately after a call.
2783
static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2784
                                              llvm::Value *value,
2785
                                              ValueTransform doAfterCall,
2786
344
                                              ValueTransform doFallback) {
2787
344
  if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2788
316
    CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2789
316
2790
316
    // Place the retain immediately following the call.
2791
316
    CGF.Builder.SetInsertPoint(call->getParent(),
2792
316
                               ++llvm::BasicBlock::iterator(call));
2793
316
    value = doAfterCall(CGF, value);
2794
316
2795
316
    CGF.Builder.restoreIP(ip);
2796
316
    return value;
2797
316
  } else 
if (llvm::InvokeInst *28
invoke28
= dyn_cast<llvm::InvokeInst>(value)) {
2798
11
    CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2799
11
2800
11
    // Place the retain at the beginning of the normal destination block.
2801
11
    llvm::BasicBlock *BB = invoke->getNormalDest();
2802
11
    CGF.Builder.SetInsertPoint(BB, BB->begin());
2803
11
    value = doAfterCall(CGF, value);
2804
11
2805
11
    CGF.Builder.restoreIP(ip);
2806
11
    return value;
2807
11
2808
11
  // Bitcasts can arise because of related-result returns.  Rewrite
2809
11
  // the operand.
2810
17
  } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2811
16
    llvm::Value *operand = bitcast->getOperand(0);
2812
16
    operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2813
16
    bitcast->setOperand(0, operand);
2814
16
    return bitcast;
2815
16
2816
16
  // Generic fall-back case.
2817
16
  } else {
2818
1
    // Retain using the non-block variant: we never need to do a copy
2819
1
    // of a block that's been returned to us.
2820
1
    return doFallback(CGF, value);
2821
1
  }
2822
344
}
2823
2824
/// Given that the given expression is some sort of call (which does
2825
/// not return retained), emit a retain following it.
2826
static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2827
292
                                            const Expr *e) {
2828
292
  llvm::Value *value = CGF.EmitScalarExpr(e);
2829
292
  return emitARCOperationAfterCall(CGF, value,
2830
292
           [](CodeGenFunction &CGF, llvm::Value *value) {
2831
291
             return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2832
291
           },
2833
292
           [](CodeGenFunction &CGF, llvm::Value *value) {
2834
1
             return CGF.EmitARCRetainNonBlock(value);
2835
1
           });
2836
292
}
2837
2838
/// Given that the given expression is some sort of call (which does
2839
/// not return retained), perform an unsafeClaim following it.
2840
static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2841
36
                                                 const Expr *e) {
2842
36
  llvm::Value *value = CGF.EmitScalarExpr(e);
2843
36
  return emitARCOperationAfterCall(CGF, value,
2844
36
           [](CodeGenFunction &CGF, llvm::Value *value) {
2845
36
             return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2846
36
           },
2847
36
           [](CodeGenFunction &CGF, llvm::Value *value) {
2848
0
             return value;
2849
0
           });
2850
36
}
2851
2852
llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2853
123
                                                      bool allowUnsafeClaim) {
2854
123
  if (allowUnsafeClaim &&
2855
123
      
CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()59
) {
2856
36
    return emitARCUnsafeClaimCallResult(*this, E);
2857
87
  } else {
2858
87
    llvm::Value *value = emitARCRetainCallResult(*this, E);
2859
87
    return EmitObjCConsumeObject(E->getType(), value);
2860
87
  }
2861
123
}
2862
2863
/// Determine whether it might be important to emit a separate
2864
/// objc_retain_block on the result of the given expression, or
2865
/// whether it's okay to just emit it in a +1 context.
2866
15
static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2867
15
  assert(e->getType()->isBlockPointerType());
2868
15
  e = e->IgnoreParens();
2869
15
2870
15
  // For future goodness, emit block expressions directly in +1
2871
15
  // contexts if we can.
2872
15
  if (isa<BlockExpr>(e))
2873
11
    return false;
2874
4
2875
4
  if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2876
3
    switch (cast->getCastKind()) {
2877
0
    // Emitting these operations in +1 contexts is goodness.
2878
3
    case CK_LValueToRValue:
2879
3
    case CK_ARCReclaimReturnedObject:
2880
3
    case CK_ARCConsumeObject:
2881
3
    case CK_ARCProduceObject:
2882
3
      return false;
2883
3
2884
3
    // These operations preserve a block type.
2885
3
    case CK_NoOp:
2886
0
    case CK_BitCast:
2887
0
      return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2888
0
2889
0
    // These operations are known to be bad (or haven't been considered).
2890
0
    case CK_AnyPointerToBlockPointerCast:
2891
0
    default:
2892
0
      return true;
2893
1
    }
2894
1
  }
2895
1
2896
1
  return true;
2897
1
}
2898
2899
namespace {
2900
/// A CRTP base class for emitting expressions of retainable object
2901
/// pointer type in ARC.
2902
template <typename Impl, typename Result> class ARCExprEmitter {
2903
protected:
2904
  CodeGenFunction &CGF;
2905
2.77k
  Impl &asImpl() { return *static_cast<Impl*>(this); }
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::asImpl()
Line
Count
Source
2905
2.36k
  Impl &asImpl() { return *static_cast<Impl*>(this); }
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::asImpl()
Line
Count
Source
2905
410
  Impl &asImpl() { return *static_cast<Impl*>(this); }
2906
2907
1.12k
  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::ARCExprEmitter(clang::CodeGen::CodeGenFunction&)
Line
Count
Source
2907
998
  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::ARCExprEmitter(clang::CodeGen::CodeGenFunction&)
Line
Count
Source
2907
130
  ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2908
2909
public:
2910
  Result visit(const Expr *e);
2911
  Result visitCastExpr(const CastExpr *e);
2912
  Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2913
  Result visitBlockExpr(const BlockExpr *e);
2914
  Result visitBinaryOperator(const BinaryOperator *e);
2915
  Result visitBinAssign(const BinaryOperator *e);
2916
  Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2917
  Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2918
  Result visitBinAssignWeak(const BinaryOperator *e);
2919
  Result visitBinAssignStrong(const BinaryOperator *e);
2920
2921
  // Minimal implementation:
2922
  //   Result visitLValueToRValue(const Expr *e)
2923
  //   Result visitConsumeObject(const Expr *e)
2924
  //   Result visitExtendBlockObject(const Expr *e)
2925
  //   Result visitReclaimReturnedObject(const Expr *e)
2926
  //   Result visitCall(const Expr *e)
2927
  //   Result visitExpr(const Expr *e)
2928
  //
2929
  //   Result emitBitCast(Result result, llvm::Type *resultType)
2930
  //   llvm::Value *getValueOfResult(Result result)
2931
};
2932
}
2933
2934
/// Try to emit a PseudoObjectExpr under special ARC rules.
2935
///
2936
/// This massively duplicates emitPseudoObjectRValue.
2937
template <typename Impl, typename Result>
2938
Result
2939
10
ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
2940
10
  SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2941
10
2942
10
  // Find the result expression.
2943
10
  const Expr *resultExpr = E->getResultExpr();
2944
10
  assert(resultExpr);
2945
10
  Result result;
2946
10
2947
10
  for (PseudoObjectExpr::const_semantics_iterator
2948
31
         i = E->semantics_begin(), e = E->semantics_end(); i != e; 
++i21
) {
2949
21
    const Expr *semantic = *i;
2950
21
2951
21
    // If this semantic expression is an opaque value, bind it
2952
21
    // to the result of its source expression.
2953
21
    if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2954
11
      typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2955
11
      OVMA opaqueData;
2956
11
2957
11
      // If this semantic is the result of the pseudo-object
2958
11
      // expression, try to evaluate the source as +1.
2959
11
      if (ov == resultExpr) {
2960
0
        assert(!OVMA::shouldBindAsLValue(ov));
2961
0
        result = asImpl().visit(ov->getSourceExpr());
2962
0
        opaqueData = OVMA::bind(CGF, ov,
2963
0
                            RValue::get(asImpl().getValueOfResult(result)));
2964
0
2965
0
      // Otherwise, just bind it.
2966
11
      } else {
2967
11
        opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2968
11
      }
2969
11
      opaques.push_back(opaqueData);
2970
11
2971
11
    // Otherwise, if the expression is the result, evaluate it
2972
11
    // and remember the result.
2973
11
    } else 
if (10
semantic == resultExpr10
) {
2974
10
      result = asImpl().visit(semantic);
2975
10
2976
10
    // Otherwise, evaluate the expression in an ignored context.
2977
10
    } else {
2978
0
      CGF.EmitIgnoredExpr(semantic);
2979
0
    }
2980
21
  }
2981
10
2982
10
  // Unbind all the opaques now.
2983
21
  for (unsigned i = 0, e = opaques.size(); i != e; 
++i11
)
2984
11
    opaques[i].unbind(CGF);
2985
10
2986
10
  return result;
2987
10
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Line
Count
Source
2939
10
ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
2940
10
  SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2941
10
2942
10
  // Find the result expression.
2943
10
  const Expr *resultExpr = E->getResultExpr();
2944
10
  assert(resultExpr);
2945
10
  Result result;
2946
10
2947
10
  for (PseudoObjectExpr::const_semantics_iterator
2948
31
         i = E->semantics_begin(), e = E->semantics_end(); i != e; 
++i21
) {
2949
21
    const Expr *semantic = *i;
2950
21
2951
21
    // If this semantic expression is an opaque value, bind it
2952
21
    // to the result of its source expression.
2953
21
    if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2954
11
      typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2955
11
      OVMA opaqueData;
2956
11
2957
11
      // If this semantic is the result of the pseudo-object
2958
11
      // expression, try to evaluate the source as +1.
2959
11
      if (ov == resultExpr) {
2960
0
        assert(!OVMA::shouldBindAsLValue(ov));
2961
0
        result = asImpl().visit(ov->getSourceExpr());
2962
0
        opaqueData = OVMA::bind(CGF, ov,
2963
0
                            RValue::get(asImpl().getValueOfResult(result)));
2964
0
2965
0
      // Otherwise, just bind it.
2966
11
      } else {
2967
11
        opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2968
11
      }
2969
11
      opaques.push_back(opaqueData);
2970
11
2971
11
    // Otherwise, if the expression is the result, evaluate it
2972
11
    // and remember the result.
2973
11
    } else 
if (10
semantic == resultExpr10
) {
2974
10
      result = asImpl().visit(semantic);
2975
10
2976
10
    // Otherwise, evaluate the expression in an ignored context.
2977
10
    } else {
2978
0
      CGF.EmitIgnoredExpr(semantic);
2979
0
    }
2980
21
  }
2981
10
2982
10
  // Unbind all the opaques now.
2983
21
  for (unsigned i = 0, e = opaques.size(); i != e; 
++i11
)
2984
11
    opaques[i].unbind(CGF);
2985
10
2986
10
  return result;
2987
10
}
Unexecuted instantiation: CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitPseudoObjectExpr(clang::PseudoObjectExpr const*)
2988
2989
template <typename Impl, typename Result>
2990
0
Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2991
0
  // The default implementation just forwards the expression to visitExpr.
2992
0
  return asImpl().visitExpr(e);
2993
0
}
2994
2995
template <typename Impl, typename Result>
2996
940
Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2997
940
  switch (e->getCastKind()) {
2998
0
2999
0
  // No-op casts don't change the type, so we just ignore them.
3000
13
  case CK_NoOp:
3001
13
    return asImpl().visit(e->getSubExpr());
3002
0
3003
0
  // These casts can change the type.
3004
198
  case CK_CPointerToObjCPointerCast:
3005
198
  case CK_BlockPointerToObjCPointerCast:
3006
198
  case CK_AnyPointerToBlockPointerCast:
3007
198
  case CK_BitCast: {
3008
198
    llvm::Type *resultType = CGF.ConvertType(e->getType());
3009
198
    assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3010
198
    Result result = asImpl().visit(e->getSubExpr());
3011
198
    return asImpl().emitBitCast(result, resultType);
3012
198
  }
3013
198
3014
198
  // Handle some casts specially.
3015
320
  case CK_LValueToRValue:
3016
320
    return asImpl().visitLValueToRValue(e->getSubExpr());
3017
198
  case CK_ARCConsumeObject:
3018
84
    return asImpl().visitConsumeObject(e->getSubExpr());
3019
198
  case CK_ARCExtendBlockObject:
3020
9
    return asImpl().visitExtendBlockObject(e->getSubExpr());
3021
229
  case CK_ARCReclaimReturnedObject:
3022
229
    return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3023
198
3024
198
  // Otherwise, use the default logic.
3025
198
  default:
3026
87
    return asImpl().visitExpr(e);
3027
940
  }
3028
940
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitCastExpr(clang::CastExpr const*)
Line
Count
Source
2996
854
Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2997
854
  switch (e->getCastKind()) {
2998
0
2999
0
  // No-op casts don't change the type, so we just ignore them.
3000
13
  case CK_NoOp:
3001
13
    return asImpl().visit(e->getSubExpr());
3002
0
3003
0
  // These casts can change the type.
3004
165
  case CK_CPointerToObjCPointerCast:
3005
165
  case CK_BlockPointerToObjCPointerCast:
3006
165
  case CK_AnyPointerToBlockPointerCast:
3007
165
  case CK_BitCast: {
3008
165
    llvm::Type *resultType = CGF.ConvertType(e->getType());
3009
165
    assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3010
165
    Result result = asImpl().visit(e->getSubExpr());
3011
165
    return asImpl().emitBitCast(result, resultType);
3012
165
  }
3013
165
3014
165
  // Handle some casts specially.
3015
307
  case CK_LValueToRValue:
3016
307
    return asImpl().visitLValueToRValue(e->getSubExpr());
3017
165
  case CK_ARCConsumeObject:
3018
80
    return asImpl().visitConsumeObject(e->getSubExpr());
3019
165
  case CK_ARCExtendBlockObject:
3020
9
    return asImpl().visitExtendBlockObject(e->getSubExpr());
3021
195
  case CK_ARCReclaimReturnedObject:
3022
195
    return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3023
165
3024
165
  // Otherwise, use the default logic.
3025
165
  default:
3026
85
    return asImpl().visitExpr(e);
3027
854
  }
3028
854
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitCastExpr(clang::CastExpr const*)
Line
Count
Source
2996
86
Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2997
86
  switch (e->getCastKind()) {
2998
0
2999
0
  // No-op casts don't change the type, so we just ignore them.
3000
0
  case CK_NoOp:
3001
0
    return asImpl().visit(e->getSubExpr());
3002
0
3003
0
  // These casts can change the type.
3004
33
  case CK_CPointerToObjCPointerCast:
3005
33
  case CK_BlockPointerToObjCPointerCast:
3006
33
  case CK_AnyPointerToBlockPointerCast:
3007
33
  case CK_BitCast: {
3008
33
    llvm::Type *resultType = CGF.ConvertType(e->getType());
3009
33
    assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3010
33
    Result result = asImpl().visit(e->getSubExpr());
3011
33
    return asImpl().emitBitCast(result, resultType);
3012
33
  }
3013
33
3014
33
  // Handle some casts specially.
3015
33
  case CK_LValueToRValue:
3016
13
    return asImpl().visitLValueToRValue(e->getSubExpr());
3017
33
  case CK_ARCConsumeObject:
3018
4
    return asImpl().visitConsumeObject(e->getSubExpr());
3019
33
  case CK_ARCExtendBlockObject:
3020
0
    return asImpl().visitExtendBlockObject(e->getSubExpr());
3021
34
  case CK_ARCReclaimReturnedObject:
3022
34
    return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3023
33
3024
33
  // Otherwise, use the default logic.
3025
33
  default:
3026
2
    return asImpl().visitExpr(e);
3027
86
  }
3028
86
}
3029
3030
template <typename Impl, typename Result>
3031
Result
3032
64
ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3033
64
  switch (e->getOpcode()) {
3034
0
  case BO_Comma:
3035
0
    CGF.EmitIgnoredExpr(e->getLHS());
3036
0
    CGF.EnsureInsertPoint();
3037
0
    return asImpl().visit(e->getRHS());
3038
0
3039
64
  case BO_Assign:
3040
64
    return asImpl().visitBinAssign(e);
3041
0
3042
0
  default:
3043
0
    return asImpl().visitExpr(e);
3044
64
  }
3045
64
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
3032
32
ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3033
32
  switch (e->getOpcode()) {
3034
0
  case BO_Comma:
3035
0
    CGF.EmitIgnoredExpr(e->getLHS());
3036
0
    CGF.EnsureInsertPoint();
3037
0
    return asImpl().visit(e->getRHS());
3038
0
3039
32
  case BO_Assign:
3040
32
    return asImpl().visitBinAssign(e);
3041
0
3042
0
  default:
3043
0
    return asImpl().visitExpr(e);
3044
32
  }
3045
32
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinaryOperator(clang::BinaryOperator const*)
Line
Count
Source
3032
32
ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3033
32
  switch (e->getOpcode()) {
3034
0
  case BO_Comma:
3035
0
    CGF.EmitIgnoredExpr(e->getLHS());
3036
0
    CGF.EnsureInsertPoint();
3037
0
    return asImpl().visit(e->getRHS());
3038
0
3039
32
  case BO_Assign:
3040
32
    return asImpl().visitBinAssign(e);
3041
0
3042
0
  default:
3043
0
    return asImpl().visitExpr(e);
3044
32
  }
3045
32
}
3046
3047
template <typename Impl, typename Result>
3048
64
Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3049
64
  switch (e->getLHS()->getType().getObjCLifetime()) {
3050
32
  case Qualifiers::OCL_ExplicitNone:
3051
32
    return asImpl().visitBinAssignUnsafeUnretained(e);
3052
0
3053
8
  case Qualifiers::OCL_Weak:
3054
8
    return asImpl().visitBinAssignWeak(e);
3055
0
3056
4
  case Qualifiers::OCL_Autoreleasing:
3057
4
    return asImpl().visitBinAssignAutoreleasing(e);
3058
0
3059
20
  case Qualifiers::OCL_Strong:
3060
20
    return asImpl().visitBinAssignStrong(e);
3061
0
3062
0
  case Qualifiers::OCL_None:
3063
0
    return asImpl().visitExpr(e);
3064
0
  }
3065
0
  llvm_unreachable("bad ObjC ownership qualifier");
3066
0
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinAssign(clang::BinaryOperator const*)
Line
Count
Source
3048
32
Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3049
32
  switch (e->getLHS()->getType().getObjCLifetime()) {
3050
16
  case Qualifiers::OCL_ExplicitNone:
3051
16
    return asImpl().visitBinAssignUnsafeUnretained(e);
3052
0
3053
8
  case Qualifiers::OCL_Weak:
3054
8
    return asImpl().visitBinAssignWeak(e);
3055
0
3056
4
  case Qualifiers::OCL_Autoreleasing:
3057
4
    return asImpl().visitBinAssignAutoreleasing(e);
3058
0
3059
4
  case Qualifiers::OCL_Strong:
3060
4
    return asImpl().visitBinAssignStrong(e);
3061
0
3062
0
  case Qualifiers::OCL_None:
3063
0
    return asImpl().visitExpr(e);
3064
0
  }
3065
0
  llvm_unreachable("bad ObjC ownership qualifier");
3066
0
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinAssign(clang::BinaryOperator const*)
Line
Count
Source
3048
32
Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3049
32
  switch (e->getLHS()->getType().getObjCLifetime()) {
3050
16
  case Qualifiers::OCL_ExplicitNone:
3051
16
    return asImpl().visitBinAssignUnsafeUnretained(e);
3052
0
3053
0
  case Qualifiers::OCL_Weak:
3054
0
    return asImpl().visitBinAssignWeak(e);
3055
0
3056
0
  case Qualifiers::OCL_Autoreleasing:
3057
0
    return asImpl().visitBinAssignAutoreleasing(e);
3058
0
3059
16
  case Qualifiers::OCL_Strong:
3060
16
    return asImpl().visitBinAssignStrong(e);
3061
0
3062
0
  case Qualifiers::OCL_None:
3063
0
    return asImpl().visitExpr(e);
3064
0
  }
3065
0
  llvm_unreachable("bad ObjC ownership qualifier");
3066
0
}
3067
3068
/// The default rule for __unsafe_unretained emits the RHS recursively,
3069
/// stores into the unsafe variable, and propagates the result outward.
3070
template <typename Impl, typename Result>
3071
Result ARCExprEmitter<Impl,Result>::
3072
32
                    visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3073
32
  // Recursively emit the RHS.
3074
32
  // For __block safety, do this before emitting the LHS.
3075
32
  Result result = asImpl().visit(e->getRHS());
3076
32
3077
32
  // Perform the store.
3078
32
  LValue lvalue =
3079
32
    CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3080
32
  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3081
32
                             lvalue);
3082
32
3083
32
  return result;
3084
32
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinAssignUnsafeUnretained(clang::BinaryOperator const*)
Line
Count
Source
3072
16
                    visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3073
16
  // Recursively emit the RHS.
3074
16
  // For __block safety, do this before emitting the LHS.
3075
16
  Result result = asImpl().visit(e->getRHS());
3076
16
3077
16
  // Perform the store.
3078
16
  LValue lvalue =
3079
16
    CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3080
16
  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3081
16
                             lvalue);
3082
16
3083
16
  return result;
3084
16
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinAssignUnsafeUnretained(clang::BinaryOperator const*)
Line
Count
Source
3072
16
                    visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3073
16
  // Recursively emit the RHS.
3074
16
  // For __block safety, do this before emitting the LHS.
3075
16
  Result result = asImpl().visit(e->getRHS());
3076
16
3077
16
  // Perform the store.
3078
16
  LValue lvalue =
3079
16
    CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3080
16
  CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3081
16
                             lvalue);
3082
16
3083
16
  return result;
3084
16
}
3085
3086
template <typename Impl, typename Result>
3087
Result
3088
4
ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3089
4
  return asImpl().visitExpr(e);
3090
4
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinAssignAutoreleasing(clang::BinaryOperator const*)
Line
Count
Source
3088
4
ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3089
4
  return asImpl().visitExpr(e);
3090
4
}
Unexecuted instantiation: CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinAssignAutoreleasing(clang::BinaryOperator const*)
3091
3092
template <typename Impl, typename Result>
3093
Result
3094
8
ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3095
8
  return asImpl().visitExpr(e);
3096
8
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinAssignWeak(clang::BinaryOperator const*)
Line
Count
Source
3094
8
ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3095
8
  return asImpl().visitExpr(e);
3096
8
}
Unexecuted instantiation: CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinAssignWeak(clang::BinaryOperator const*)
3097
3098
template <typename Impl, typename Result>
3099
Result
3100
20
ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3101
20
  return asImpl().visitExpr(e);
3102
20
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visitBinAssignStrong(clang::BinaryOperator const*)
Line
Count
Source
3100
4
ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3101
4
  return asImpl().visitExpr(e);
3102
4
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visitBinAssignStrong(clang::BinaryOperator const*)
Line
Count
Source
3100
16
ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3101
16
  return asImpl().visitExpr(e);
3102
16
}
3103
3104
/// The general expression-emission logic.
3105
template <typename Impl, typename Result>
3106
1.39k
Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3107
1.39k
  // We should *never* see a nested full-expression here, because if
3108
1.39k
  // we fail to emit at +1, our caller must not retain after we close
3109
1.39k
  // out the full-expression.  This isn't as important in the unsafe
3110
1.39k
  // emitter.
3111
1.39k
  assert(!isa<ExprWithCleanups>(e));
3112
1.39k
3113
1.39k
  // Look through parens, __extension__, generic selection, etc.
3114
1.39k
  e = e->IgnoreParens();
3115
1.39k
3116
1.39k
  // Handle certain kinds of casts.
3117
1.39k
  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3118
940
    return asImpl().visitCastExpr(ce);
3119
940
3120
940
  // Handle the comma operator.
3121
940
  } else 
if (auto 450
op450
= dyn_cast<BinaryOperator>(e)) {
3122
64
    return asImpl().visitBinaryOperator(op);
3123
64
3124
64
  // TODO: handle conditional operators here
3125
64
3126
64
  // For calls and message sends, use the retained-call logic.
3127
64
  // Delegate inits are a special case in that they're the only
3128
64
  // returns-retained expression that *isn't* surrounded by
3129
64
  // a consume.
3130
386
  } else if (isa<CallExpr>(e) ||
3131
386
             
(376
isa<ObjCMessageExpr>(e)376
&&
3132
376
              
!cast<ObjCMessageExpr>(e)->isDelegateInitCall()13
)) {
3133
14
    return asImpl().visitCall(e);
3134
14
3135
14
  // Look through pseudo-object expressions.
3136
372
  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3137
10
    return asImpl().visitPseudoObjectExpr(pseudo);
3138
362
  } else if (auto *be = dyn_cast<BlockExpr>(e))
3139
149
    return asImpl().visitBlockExpr(be);
3140
213
3141
213
  return asImpl().visitExpr(e);
3142
213
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCRetainExprEmitter, llvm::PointerIntPair<llvm::Value*, 1u, bool, llvm::PointerLikeTypeTraits<llvm::Value*>, llvm::PointerIntPairInfo<llvm::Value*, 1u, llvm::PointerLikeTypeTraits<llvm::Value*> > > >::visit(clang::Expr const*)
Line
Count
Source
3106
1.21k
Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3107
1.21k
  // We should *never* see a nested full-expression here, because if
3108
1.21k
  // we fail to emit at +1, our caller must not retain after we close
3109
1.21k
  // out the full-expression.  This isn't as important in the unsafe
3110
1.21k
  // emitter.
3111
1.21k
  assert(!isa<ExprWithCleanups>(e));
3112
1.21k
3113
1.21k
  // Look through parens, __extension__, generic selection, etc.
3114
1.21k
  e = e->IgnoreParens();
3115
1.21k
3116
1.21k
  // Handle certain kinds of casts.
3117
1.21k
  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3118
854
    return asImpl().visitCastExpr(ce);
3119
854
3120
854
  // Handle the comma operator.
3121
854
  } else 
if (auto 357
op357
= dyn_cast<BinaryOperator>(e)) {
3122
32
    return asImpl().visitBinaryOperator(op);
3123
32
3124
32
  // TODO: handle conditional operators here
3125
32
3126
32
  // For calls and message sends, use the retained-call logic.
3127
32
  // Delegate inits are a special case in that they're the only
3128
32
  // returns-retained expression that *isn't* surrounded by
3129
32
  // a consume.
3130
325
  } else if (isa<CallExpr>(e) ||
3131
325
             
(319
isa<ObjCMessageExpr>(e)319
&&
3132
319
              
!cast<ObjCMessageExpr>(e)->isDelegateInitCall()13
)) {
3133
10
    return asImpl().visitCall(e);
3134
10
3135
10
  // Look through pseudo-object expressions.
3136
315
  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3137
10
    return asImpl().visitPseudoObjectExpr(pseudo);
3138
305
  } else if (auto *be = dyn_cast<BlockExpr>(e))
3139
149
    return asImpl().visitBlockExpr(be);
3140
156
3141
156
  return asImpl().visitExpr(e);
3142
156
}
CGObjC.cpp:(anonymous namespace)::ARCExprEmitter<(anonymous namespace)::ARCUnsafeUnretainedExprEmitter, llvm::Value*>::visit(clang::Expr const*)
Line
Count
Source
3106
179
Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3107
179
  // We should *never* see a nested full-expression here, because if
3108
179
  // we fail to emit at +1, our caller must not retain after we close
3109
179
  // out the full-expression.  This isn't as important in the unsafe
3110
179
  // emitter.
3111
179
  assert(!isa<ExprWithCleanups>(e));
3112
179
3113
179
  // Look through parens, __extension__, generic selection, etc.
3114
179
  e = e->IgnoreParens();
3115
179
3116
179
  // Handle certain kinds of casts.
3117
179
  if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3118
86
    return asImpl().visitCastExpr(ce);
3119
86
3120
86
  // Handle the comma operator.
3121
93
  } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3122
32
    return asImpl().visitBinaryOperator(op);
3123
32
3124
32
  // TODO: handle conditional operators here
3125
32
3126
32
  // For calls and message sends, use the retained-call logic.
3127
32
  // Delegate inits are a special case in that they're the only
3128
32
  // returns-retained expression that *isn't* surrounded by
3129
32
  // a consume.
3130
61
  } else if (isa<CallExpr>(e) ||
3131
61
             
(57
isa<ObjCMessageExpr>(e)57
&&
3132
57
              
!cast<ObjCMessageExpr>(e)->isDelegateInitCall()0
)) {
3133
4
    return asImpl().visitCall(e);
3134
4
3135
4
  // Look through pseudo-object expressions.
3136
57
  } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3137
0
    return asImpl().visitPseudoObjectExpr(pseudo);
3138
57
  } else if (auto *be = dyn_cast<BlockExpr>(e))
3139
0
    return asImpl().visitBlockExpr(be);
3140
57
3141
57
  return asImpl().visitExpr(e);
3142
57
}
3143
3144
namespace {
3145
3146
/// An emitter for +1 results.
3147
struct ARCRetainExprEmitter :
3148
  public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3149
3150
998
  ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3151
3152
16
  llvm::Value *getValueOfResult(TryEmitResult result) {
3153
16
    return result.getPointer();
3154
16
  }
3155
3156
165
  TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3157
165
    llvm::Value *value = result.getPointer();
3158
165
    value = CGF.Builder.CreateBitCast(value, resultType);
3159
165
    result.setPointer(value);
3160
165
    return result;
3161
165
  }
3162
3163
307
  TryEmitResult visitLValueToRValue(const Expr *e) {
3164
307
    return tryEmitARCRetainLoadOfScalar(CGF, e);
3165
307
  }
3166
3167
  /// For consumptions, just emit the subexpression and thus elide
3168
  /// the retain/release pair.
3169
80
  TryEmitResult visitConsumeObject(const Expr *e) {
3170
80
    llvm::Value *result = CGF.EmitScalarExpr(e);
3171
80
    return TryEmitResult(result, true);
3172
80
  }
3173
3174
149
  TryEmitResult visitBlockExpr(const BlockExpr *e) {
3175
149
    TryEmitResult result = visitExpr(e);
3176
149
    // Avoid the block-retain if this is a block literal that doesn't need to be
3177
149
    // copied to the heap.
3178
149
    if (e->getBlockDecl()->canAvoidCopyToHeap())
3179
49
      result.setInt(true);
3180
149
    return result;
3181
149
  }
3182
3183
  /// Block extends are net +0.  Naively, we could just recurse on
3184
  /// the subexpression, but actually we need to ensure that the
3185
  /// value is copied as a block, so there's a little filter here.
3186
9
  TryEmitResult visitExtendBlockObject(const Expr *e) {
3187
9
    llvm::Value *result; // will be a +0 value
3188
9
3189
9
    // If we can't safely assume the sub-expression will produce a
3190
9
    // block-copied value, emit the sub-expression at +0.
3191
9
    if (shouldEmitSeparateBlockRetain(e)) {
3192
0
      result = CGF.EmitScalarExpr(e);
3193
0
3194
0
    // Otherwise, try to emit the sub-expression at +1 recursively.
3195
9
    } else {
3196
9
      TryEmitResult subresult = asImpl().visit(e);
3197
9
3198
9
      // If that produced a retained value, just use that.
3199
9
      if (subresult.getInt()) {
3200
0
        return subresult;
3201
0
      }
3202
9
3203
9
      // Otherwise it's +0.
3204
9
      result = subresult.getPointer();
3205
9
    }
3206
9
3207
9
    // Retain the object as a block.
3208
9
    result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3209
9
    return TryEmitResult(result, true);
3210
9
  }
3211
3212
  /// For reclaims, emit the subexpression as a retained call and
3213
  /// skip the consumption.
3214
195
  TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3215
195
    llvm::Value *result = emitARCRetainCallResult(CGF, e);
3216
195
    return TryEmitResult(result, true);
3217
195
  }
3218
3219
  /// When we have an undecorated call, retroactively do a claim.
3220
10
  TryEmitResult visitCall(const Expr *e) {
3221
10
    llvm::Value *result = emitARCRetainCallResult(CGF, e);
3222
10
    return TryEmitResult(result, true);
3223
10
  }
3224
3225
  // TODO: maybe special-case visitBinAssignWeak?
3226
3227
406
  TryEmitResult visitExpr(const Expr *e) {
3228
406
    // We didn't find an obvious production, so emit what we've got and
3229
406
    // tell the caller that we didn't manage to retain.
3230
406
    llvm::Value *result = CGF.EmitScalarExpr(e);
3231
406
    return TryEmitResult(result, false);
3232
406
  }
3233
};
3234
}
3235
3236
static TryEmitResult
3237
998
tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3238
998
  return ARCRetainExprEmitter(CGF).visit(e);
3239
998
}
3240
3241
static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3242
                                                LValue lvalue,
3243
6
                                                QualType type) {
3244
6
  TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3245
6
  llvm::Value *value = result.getPointer();
3246
6
  if (!result.getInt())
3247
0
    value = CGF.EmitARCRetain(type, value);
3248
6
  return value;
3249
6
}
3250
3251
/// EmitARCRetainScalarExpr - Semantically equivalent to
3252
/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3253
/// best-effort attempt to peephole expressions that naturally produce
3254
/// retained objects.
3255
847
llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3256
847
  // The retain needs to happen within the full-expression.
3257
847
  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3258
10
    enterFullExpression(cleanups);
3259
10
    RunCleanupsScope scope(*this);
3260
10
    return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3261
10
  }
3262
837
3263
837
  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3264
837
  llvm::Value *value = result.getPointer();
3265
837
  if (!result.getInt())
3266
541
    value = EmitARCRetain(e->getType(), value);
3267
837
  return value;
3268
837
}
3269
3270
llvm::Value *
3271
11
CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3272
11
  // The retain needs to happen within the full-expression.
3273
11
  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3274
1
    enterFullExpression(cleanups);
3275
1
    RunCleanupsScope scope(*this);
3276
1
    return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3277
1
  }
3278
10
3279
10
  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3280
10
  llvm::Value *value = result.getPointer();
3281
10
  if (result.getInt())
3282
6
    value = EmitARCAutorelease(value);
3283
4
  else
3284
4
    value = EmitARCRetainAutorelease(e->getType(), value);
3285
10
  return value;
3286
10
}
3287
3288
6
llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3289
6
  llvm::Value *result;
3290
6
  bool doRetain;
3291
6
3292
6
  if (shouldEmitSeparateBlockRetain(e)) {
3293
1
    result = EmitScalarExpr(e);
3294
1
    doRetain = true;
3295
5
  } else {
3296
5
    TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3297
5
    result = subresult.getPointer();
3298
5
    doRetain = !subresult.getInt();
3299
5
  }
3300
6
3301
6
  if (doRetain)
3302
6
    result = EmitARCRetainBlock(result, /*mandatory*/ true);
3303
6
  return EmitObjCConsumeObject(e->getType(), result);
3304
6
}
3305
3306
36
llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3307
36
  // In ARC, retain and autorelease the expression.
3308
36
  if (getLangOpts().ObjCAutoRefCount) {
3309
1
    // Do so before running any cleanups for the full-expression.
3310
1
    // EmitARCRetainAutoreleaseScalarExpr does this for us.
3311
1
    return EmitARCRetainAutoreleaseScalarExpr(expr);
3312
1
  }
3313
35
3314
35
  // Otherwise, use the normal scalar-expression emission.  The
3315
35
  // exception machinery doesn't do anything special with the
3316
35
  // exception like retaining it, so there's no safety associated with
3317
35
  // only running cleanups after the throw has started, and when it
3318
35
  // matters it tends to be substantially inferior code.
3319
35
  return EmitScalarExpr(expr);
3320
35
}
3321
3322
namespace {
3323
3324
/// An emitter for assigning into an __unsafe_unretained context.
3325
struct ARCUnsafeUnretainedExprEmitter :
3326
  public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3327
3328
130
  ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3329
3330
16
  llvm::Value *getValueOfResult(llvm::Value *value) {
3331
16
    return value;
3332
16
  }
3333
3334
33
  llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3335
33
    return CGF.Builder.CreateBitCast(value, resultType);
3336
33
  }
3337
3338
13
  llvm::Value *visitLValueToRValue(const Expr *e) {
3339
13
    return CGF.EmitScalarExpr(e);
3340
13
  }
3341
3342
  /// For consumptions, just emit the subexpression and perform the
3343
  /// consumption like normal.
3344
4
  llvm::Value *visitConsumeObject(const Expr *e) {
3345
4
    llvm::Value *value = CGF.EmitScalarExpr(e);
3346
4
    return CGF.EmitObjCConsumeObject(e->getType(), value);
3347
4
  }
3348
3349
  /// No special logic for block extensions.  (This probably can't
3350
  /// actually happen in this emitter, though.)
3351
0
  llvm::Value *visitExtendBlockObject(const Expr *e) {
3352
0
    return CGF.EmitARCExtendBlockObject(e);
3353
0
  }
3354
3355
  /// For reclaims, perform an unsafeClaim if that's enabled.
3356
34
  llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3357
34
    return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3358
34
  }
3359
3360
  /// When we have an undecorated call, just emit it without adding
3361
  /// the unsafeClaim.
3362
4
  llvm::Value *visitCall(const Expr *e) {
3363
4
    return CGF.EmitScalarExpr(e);
3364
4
  }
3365
3366
  /// Just do normal scalar emission in the default case.
3367
75
  llvm::Value *visitExpr(const Expr *e) {
3368
75
    return CGF.EmitScalarExpr(e);
3369
75
  }
3370
};
3371
}
3372
3373
static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3374
130
                                                      const Expr *e) {
3375
130
  return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3376
130
}
3377
3378
/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3379
/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3380
/// avoiding any spurious retains, including by performing reclaims
3381
/// with objc_unsafeClaimAutoreleasedReturnValue.
3382
130
llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3383
130
  // Look through full-expressions.
3384
130
  if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3385
0
    enterFullExpression(cleanups);
3386
0
    RunCleanupsScope scope(*this);
3387
0
    return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3388
0
  }
3389
130
3390
130
  return emitARCUnsafeUnretainedScalarExpr(*this, e);
3391
130
}
3392
3393
std::pair<LValue,llvm::Value*>
3394
CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3395
29
                                              bool ignored) {
3396
29
  // Evaluate the RHS first.  If we're ignoring the result, assume
3397
29
  // that we can emit at an unsafe +0.
3398
29
  llvm::Value *value;
3399
29
  if (ignored) {
3400
29
    value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3401
29
  } else {
3402
0
    value = EmitScalarExpr(e->getRHS());
3403
0
  }
3404
29
3405
29
  // Emit the LHS and perform the store.
3406
29
  LValue lvalue = EmitLValue(e->getLHS());
3407
29
  EmitStoreOfScalar(value, lvalue);
3408
29
3409
29
  return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3410
29
}
3411
3412
std::pair<LValue,llvm::Value*>
3413
CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3414
135
                                    bool ignored) {
3415
135
  // Evaluate the RHS first.
3416
135
  TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3417
135
  llvm::Value *value = result.getPointer();
3418
135
3419
135
  bool hasImmediateRetain = result.getInt();
3420
135
3421
135
  // If we didn't emit a retained object, and the l-value is of block
3422
135
  // type, then we need to emit the block-retain immediately in case
3423
135
  // it invalidates the l-value.
3424
135
  if (!hasImmediateRetain && 
e->getType()->isBlockPointerType()83
) {
3425
12
    value = EmitARCRetainBlock(value, /*mandatory*/ false);
3426
12
    hasImmediateRetain = true;
3427
12
  }
3428
135
3429
135
  LValue lvalue = EmitLValue(e->getLHS());
3430
135
3431
135
  // If the RHS was emitted retained, expand this.
3432
135
  if (hasImmediateRetain) {
3433
64
    llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3434
64
    EmitStoreOfScalar(value, lvalue);
3435
64
    EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3436
71
  } else {
3437
71
    value = EmitARCStoreStrong(lvalue, value, ignored);
3438
71
  }
3439
135
3440
135
  return std::pair<LValue,llvm::Value*>(lvalue, value);
3441
135
}
3442
3443
std::pair<LValue,llvm::Value*>
3444
4
CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3445
4
  llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3446
4
  LValue lvalue = EmitLValue(e->getLHS());
3447
4
3448
4
  EmitStoreOfScalar(value, lvalue);
3449
4
3450
4
  return std::pair<LValue,llvm::Value*>(lvalue, value);
3451
4
}
3452
3453
void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3454
113
                                          const ObjCAutoreleasePoolStmt &ARPS) {
3455
113
  const Stmt *subStmt = ARPS.getSubStmt();
3456
113
  const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3457
113
3458
113
  CGDebugInfo *DI = getDebugInfo();
3459
113
  if (DI)
3460
94
    DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3461
113
3462
113
  // Keep track of the current cleanup stack depth.
3463
113
  RunCleanupsScope Scope(*this);
3464
113
  if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3465
96
    llvm::Value *token = EmitObjCAutoreleasePoolPush();
3466
96
    EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3467
96
  } else {
3468
17
    llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3469
17
    EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3470
17
  }
3471
113
3472
113
  for (const auto *I : S.body())
3473
530
    EmitStmt(I);
3474
113
3475
113
  if (DI)
3476
94
    DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3477
113
}
3478
3479
/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3480
/// make sure it survives garbage collection until this point.
3481
1
void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3482
1
  // We just use an inline assembly.
3483
1
  llvm::FunctionType *extenderType
3484
1
    = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3485
1
  llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3486
1
                                                   /* assembly */ "",
3487
1
                                                   /* constraints */ "r",
3488
1
                                                   /* side effects */ true);
3489
1
3490
1
  object = Builder.CreateBitCast(object, VoidPtrTy);
3491
1
  EmitNounwindRuntimeCall(extender, object);
3492
1
}
3493
3494
/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3495
/// non-trivial copy assignment function, produce following helper function.
3496
/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3497
///
3498
llvm::Constant *
3499
CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3500
431
                                        const ObjCPropertyImplDecl *PID) {
3501
431
  if (!getLangOpts().CPlusPlus ||
3502
431
      
!getLangOpts().ObjCRuntime.hasAtomicCopyHelper()30
)
3503
401
    return nullptr;
3504
30
  QualType Ty = PID->getPropertyIvarDecl()->getType();
3505
30
  if (!Ty->isRecordType())
3506
10
    return nullptr;
3507
20
  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3508
20
  if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3509
7
    return nullptr;
3510
13
  llvm::Constant *HelperFn = nullptr;
3511
13
  if (hasTrivialSetExpr(PID))
3512
6
    return nullptr;
3513
7
  assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3514
7
  if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3515
2
    return HelperFn;
3516
5
3517
5
  ASTContext &C = getContext();
3518
5
  IdentifierInfo *II
3519
5
    = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3520
5
3521
5
  QualType ReturnTy = C.VoidTy;
3522
5
  QualType DestTy = C.getPointerType(Ty);
3523
5
  QualType SrcTy = Ty;
3524
5
  SrcTy.addConst();
3525
5
  SrcTy = C.getPointerType(SrcTy);
3526
5
3527
5
  SmallVector<QualType, 2> ArgTys;
3528
5
  ArgTys.push_back(DestTy);
3529
5
  ArgTys.push_back(SrcTy);
3530
5
  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3531
5
3532
5
  FunctionDecl *FD = FunctionDecl::Create(
3533
5
      C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3534
5
      FunctionTy, nullptr, SC_Static, false, false);
3535
5
3536
5
  FunctionArgList args;
3537
5
  ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3538
5
                            ImplicitParamDecl::Other);
3539
5
  args.push_back(&DstDecl);
3540
5
  ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3541
5
                            ImplicitParamDecl::Other);
3542
5
  args.push_back(&SrcDecl);
3543
5
3544
5
  const CGFunctionInfo &FI =
3545
5
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3546
5
3547
5
  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3548
5
3549
5
  llvm::Function *Fn =
3550
5
    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3551
5
                           "__assign_helper_atomic_property_",
3552
5
                           &CGM.getModule());
3553
5
3554
5
  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3555
5
3556
5
  StartFunction(FD, ReturnTy, Fn, FI, args);
3557
5
3558
5
  DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3559
5
                      SourceLocation());
3560
5
  UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3561
5
                    VK_LValue, OK_Ordinary, SourceLocation(), false);
3562
5
3563
5
  DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3564
5
                      SourceLocation());
3565
5
  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3566
5
                    VK_LValue, OK_Ordinary, SourceLocation(), false);
3567
5
3568
5
  Expr *Args[2] = { &DST, &SRC };
3569
5
  CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3570
5
  CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3571
5
      C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3572
5
      VK_LValue, SourceLocation(), FPOptions());
3573
5
3574
5
  EmitStmt(TheCall);
3575
5
3576
5
  FinishFunction();
3577
5
  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3578
5
  CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3579
5
  return HelperFn;
3580
5
}
3581
3582
llvm::Constant *
3583
CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3584
441
                                            const ObjCPropertyImplDecl *PID) {
3585
441
  if (!getLangOpts().CPlusPlus ||
3586
441
      
!getLangOpts().ObjCRuntime.hasAtomicCopyHelper()29
)
3587
412
    return nullptr;
3588
29
  const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3589
29
  QualType Ty = PD->getType();
3590
29
  if (!Ty->isRecordType())
3591
12
    return nullptr;
3592
17
  if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3593
5
    return nullptr;
3594
12
  llvm::Constant *HelperFn = nullptr;
3595
12
  if (hasTrivialGetExpr(PID))
3596
6
    return nullptr;
3597
6
  assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3598
6
  if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3599
2
    return HelperFn;
3600
4
3601
4
  ASTContext &C = getContext();
3602
4
  IdentifierInfo *II =
3603
4
      &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3604
4
3605
4
  QualType ReturnTy = C.VoidTy;
3606
4
  QualType DestTy = C.getPointerType(Ty);
3607
4
  QualType SrcTy = Ty;
3608
4
  SrcTy.addConst();
3609
4
  SrcTy = C.getPointerType(SrcTy);
3610
4
3611
4
  SmallVector<QualType, 2> ArgTys;
3612
4
  ArgTys.push_back(DestTy);
3613
4
  ArgTys.push_back(SrcTy);
3614
4
  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3615
4
3616
4
  FunctionDecl *FD = FunctionDecl::Create(
3617
4
      C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3618
4
      FunctionTy, nullptr, SC_Static, false, false);
3619
4
3620
4
  FunctionArgList args;
3621
4
  ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3622
4
                            ImplicitParamDecl::Other);
3623
4
  args.push_back(&DstDecl);
3624
4
  ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3625
4
                            ImplicitParamDecl::Other);
3626
4
  args.push_back(&SrcDecl);
3627
4
3628
4
  const CGFunctionInfo &FI =
3629
4
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3630
4
3631
4
  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3632
4
3633
4
  llvm::Function *Fn = llvm::Function::Create(
3634
4
      LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3635
4
      &CGM.getModule());
3636
4
3637
4
  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3638
4
3639
4
  StartFunction(FD, ReturnTy, Fn, FI, args);
3640
4
3641
4
  DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3642
4
                      SourceLocation());
3643
4
3644
4
  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3645
4
                    VK_LValue, OK_Ordinary, SourceLocation(), false);
3646
4
3647
4
  CXXConstructExpr *CXXConstExpr =
3648
4
    cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3649
4
3650
4
  SmallVector<Expr*, 4> ConstructorArgs;
3651
4
  ConstructorArgs.push_back(&SRC);
3652
4
  ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3653
4
                         CXXConstExpr->arg_end());
3654
4
3655
4
  CXXConstructExpr *TheCXXConstructExpr =
3656
4
    CXXConstructExpr::Create(C, Ty, SourceLocation(),
3657
4
                             CXXConstExpr->getConstructor(),
3658
4
                             CXXConstExpr->isElidable(),
3659
4
                             ConstructorArgs,
3660
4
                             CXXConstExpr->hadMultipleCandidates(),
3661
4
                             CXXConstExpr->isListInitialization(),
3662
4
                             CXXConstExpr->isStdInitListInitialization(),
3663
4
                             CXXConstExpr->requiresZeroInitialization(),
3664
4
                             CXXConstExpr->getConstructionKind(),
3665
4
                             SourceRange());
3666
4
3667
4
  DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3668
4
                      SourceLocation());
3669
4
3670
4
  RValue DV = EmitAnyExpr(&DstExpr);
3671
4
  CharUnits Alignment
3672
4
    = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3673
4
  EmitAggExpr(TheCXXConstructExpr,
3674
4
              AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3675
4
                                    Qualifiers(),
3676
4
                                    AggValueSlot::IsDestructed,
3677
4
                                    AggValueSlot::DoesNotNeedGCBarriers,
3678
4
                                    AggValueSlot::IsNotAliased,
3679
4
                                    AggValueSlot::DoesNotOverlap));
3680
4
3681
4
  FinishFunction();
3682
4
  HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3683
4
  CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3684
4
  return HelperFn;
3685
4
}
3686
3687
llvm::Value *
3688
5
CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3689
5
  // Get selectors for retain/autorelease.
3690
5
  IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3691
5
  Selector CopySelector =
3692
5
      getContext().Selectors.getNullarySelector(CopyID);
3693
5
  IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3694
5
  Selector AutoreleaseSelector =
3695
5
      getContext().Selectors.getNullarySelector(AutoreleaseID);
3696
5
3697
5
  // Emit calls to retain/autorelease.
3698
5
  CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3699
5
  llvm::Value *Val = Block;
3700
5
  RValue Result;
3701
5
  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3702
5
                                       Ty, CopySelector,
3703
5
                                       Val, CallArgList(), nullptr, nullptr);
3704
5
  Val = Result.getScalarVal();
3705
5
  Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3706
5
                                       Ty, AutoreleaseSelector,
3707
5
                                       Val, CallArgList(), nullptr, nullptr);
3708
5
  Val = Result.getScalarVal();
3709
5
  return Val;
3710
5
}
3711
3712
llvm::Value *
3713
6
CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3714
6
  assert(Args.size() == 3 && "Expected 3 argument here!");
3715
6
3716
6
  if (!CGM.IsOSVersionAtLeastFn) {
3717
4
    llvm::FunctionType *FTy =
3718
4
        llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3719
4
    CGM.IsOSVersionAtLeastFn =
3720
4
        CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3721
4
  }
3722
6
3723
6
  llvm::Value *CallRes =
3724
6
      EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3725
6
3726
6
  return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3727
6
}
3728
3729
24.9k
void CodeGenModule::emitAtAvailableLinkGuard() {
3730
24.9k
  if (!IsOSVersionAtLeastFn)
3731
24.9k
    return;
3732
4
  // @available requires CoreFoundation only on Darwin.
3733
4
  if (!Target.getTriple().isOSDarwin())
3734
0
    return;
3735
4
  // Add -framework CoreFoundation to the linker commands. We still want to
3736
4
  // emit the core foundation reference down below because otherwise if
3737
4
  // CoreFoundation is not used in the code, the linker won't link the
3738
4
  // framework.
3739
4
  auto &Context = getLLVMContext();
3740
4
  llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3741
4
                             llvm::MDString::get(Context, "CoreFoundation")};
3742
4
  LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3743
4
  // Emit a reference to a symbol from CoreFoundation to ensure that
3744
4
  // CoreFoundation is linked into the final binary.
3745
4
  llvm::FunctionType *FTy =
3746
4
      llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3747
4
  llvm::FunctionCallee CFFunc =
3748
4
      CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3749
4
3750
4
  llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3751
4
  llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3752
4
      CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3753
4
      llvm::AttributeList(), /*Local=*/true);
3754
4
  llvm::Function *CFLinkCheckFunc =
3755
4
      cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3756
4
  if (CFLinkCheckFunc->empty()) {
3757
4
    CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3758
4
    CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3759
4
    CodeGenFunction CGF(*this);
3760
4
    CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3761
4
    CGF.EmitNounwindRuntimeCall(CFFunc,
3762
4
                                llvm::Constant::getNullValue(VoidPtrTy));
3763
4
    CGF.Builder.CreateUnreachable();
3764
4
    addCompilerUsedGlobal(CFLinkCheckFunc);
3765
4
  }
3766
4
}
3767
3768
11.7k
CGObjCRuntime::~CGObjCRuntime() {}