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