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