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