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