1 //===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Objective-C code as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/InlineAsm.h"
28 using namespace clang;
29 using namespace CodeGen;
31 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
33 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
34 static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
38 /// Given the address of a variable of pointer type, find the correct
39 /// null to store into it.
40 static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45 /// Emits an instance of NSConstantString representing the object.
46 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
49 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
50 // FIXME: This bitcast should just be made an invariant on the Runtime.
51 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
54 /// EmitObjCBoxedExpr - This routine generates code to call
55 /// the appropriate expression boxing method. This will either be
56 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57 /// or [NSValue valueWithBytes:objCType:].
60 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
61 // Generate the correct selector for this literal's concrete type.
63 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 const Expr *SubExpr = E->getSubExpr();
65 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
69 // Generate a reference to the class pointer, which will be the receiver.
70 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
72 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
73 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
74 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
77 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
80 // ObjCBoxedExpr supports boxing of structs and unions
81 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
86 Address Temporary = CreateMemTemp(SubExpr->getType());
87 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
88 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
91 // Create char array to store type encoding
93 getContext().getObjCEncodingForType(ValueType, Str);
94 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
96 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
101 Args.add(RValue::get(Cast), EncodingQT);
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
109 return Builder.CreateBitCast(result.getScalarVal(),
110 ConvertType(E->getType()));
113 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
114 const ObjCMethodDecl *MethodWithObjects) {
115 ASTContext &Context = CGM.getContext();
116 const ObjCDictionaryLiteral *DLE = nullptr;
117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
119 DLE = cast<ObjCDictionaryLiteral>(E);
121 // Optimize empty collections by referencing constants, when available.
122 uint64_t NumElements =
123 ALE ? ALE->getNumElements() : DLE->getNumElements();
124 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
125 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
126 QualType IdTy(CGM.getContext().getObjCIdType());
127 llvm::Constant *Constant =
128 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
129 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
130 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
131 cast<llvm::LoadInst>(Ptr)->setMetadata(
132 CGM.getModule().getMDKindID("invariant.load"),
133 llvm::MDNode::get(getLLVMContext(), None));
134 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
137 // Compute the type of the array we're initializing.
138 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
140 QualType ElementType = Context.getObjCIdType().withConst();
141 QualType ElementArrayType
142 = Context.getConstantArrayType(ElementType, APNumElements,
143 ArrayType::Normal, /*IndexTypeQuals=*/0);
145 // Allocate the temporary array(s).
146 Address Objects = CreateMemTemp(ElementArrayType, "objects");
147 Address Keys = Address::invalid();
149 Keys = CreateMemTemp(ElementArrayType, "keys");
151 // In ARC, we may need to do extra work to keep all the keys and
152 // values alive until after the call.
153 SmallVector<llvm::Value *, 16> NeededObjects;
154 bool TrackNeededObjects =
155 (getLangOpts().ObjCAutoRefCount &&
156 CGM.getCodeGenOpts().OptimizationLevel != 0);
158 // Perform the actual initialialization of the array(s).
159 for (uint64_t i = 0; i < NumElements; i++) {
161 // Emit the element and store it to the appropriate array slot.
162 const Expr *Rhs = ALE->getElement(i);
163 LValue LV = MakeAddrLValue(
164 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
165 ElementType, AlignmentSource::Decl);
167 llvm::Value *value = EmitScalarExpr(Rhs);
168 EmitStoreThroughLValue(RValue::get(value), LV, true);
169 if (TrackNeededObjects) {
170 NeededObjects.push_back(value);
173 // Emit the key and store it to the appropriate array slot.
174 const Expr *Key = DLE->getKeyValueElement(i).Key;
175 LValue KeyLV = MakeAddrLValue(
176 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
177 ElementType, AlignmentSource::Decl);
178 llvm::Value *keyValue = EmitScalarExpr(Key);
179 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
181 // Emit the value and store it to the appropriate array slot.
182 const Expr *Value = DLE->getKeyValueElement(i).Value;
183 LValue ValueLV = MakeAddrLValue(
184 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
185 ElementType, AlignmentSource::Decl);
186 llvm::Value *valueValue = EmitScalarExpr(Value);
187 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
188 if (TrackNeededObjects) {
189 NeededObjects.push_back(keyValue);
190 NeededObjects.push_back(valueValue);
195 // Generate the argument list.
197 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
198 const ParmVarDecl *argDecl = *PI++;
199 QualType ArgQT = argDecl->getType().getUnqualifiedType();
200 Args.add(RValue::get(Objects.getPointer()), ArgQT);
203 ArgQT = argDecl->getType().getUnqualifiedType();
204 Args.add(RValue::get(Keys.getPointer()), ArgQT);
207 ArgQT = argDecl->getType().getUnqualifiedType();
209 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
210 Args.add(RValue::get(Count), ArgQT);
212 // Generate a reference to the class pointer, which will be the receiver.
213 Selector Sel = MethodWithObjects->getSelector();
214 QualType ResultType = E->getType();
215 const ObjCObjectPointerType *InterfacePointerType
216 = ResultType->getAsObjCInterfacePointerType();
217 ObjCInterfaceDecl *Class
218 = InterfacePointerType->getObjectType()->getInterface();
219 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
220 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
222 // Generate the message send.
223 RValue result = Runtime.GenerateMessageSend(
224 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
225 Receiver, Args, Class, MethodWithObjects);
227 // The above message send needs these objects, but in ARC they are
228 // passed in a buffer that is essentially __unsafe_unretained.
229 // Therefore we must prevent the optimizer from releasing them until
231 if (TrackNeededObjects) {
232 EmitARCIntrinsicUse(NeededObjects);
235 return Builder.CreateBitCast(result.getScalarVal(),
236 ConvertType(E->getType()));
239 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
240 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
243 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
244 const ObjCDictionaryLiteral *E) {
245 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
249 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
251 // Note that this implementation allows for non-constant strings to be passed
252 // as arguments to @selector(). Currently, the only thing preventing this
253 // behaviour is the type checking in the front end.
254 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
257 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
258 // FIXME: This should pass the Decl not the name.
259 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
262 /// Adjust the type of an Objective-C object that doesn't match up due
263 /// to type erasure at various points, e.g., related result types or the use
264 /// of parameterized classes.
265 static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
267 if (!ExpT->isObjCRetainableType())
270 // If the converted types are the same, we're done.
271 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
272 if (ExpLLVMTy == Result.getScalarVal()->getType())
275 // We have applied a substitution. Cast the rvalue appropriately.
276 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
280 /// Decide whether to extend the lifetime of the receiver of a
281 /// returns-inner-pointer message.
283 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
284 switch (message->getReceiverKind()) {
286 // For a normal instance message, we should extend unless the
287 // receiver is loaded from a variable with precise lifetime.
288 case ObjCMessageExpr::Instance: {
289 const Expr *receiver = message->getInstanceReceiver();
291 // Look through OVEs.
292 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
293 if (opaque->getSourceExpr())
294 receiver = opaque->getSourceExpr()->IgnoreParens();
297 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
298 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
299 receiver = ice->getSubExpr()->IgnoreParens();
301 // Look through OVEs.
302 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
303 if (opaque->getSourceExpr())
304 receiver = opaque->getSourceExpr()->IgnoreParens();
307 // Only __strong variables.
308 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
311 // All ivars and fields have precise lifetime.
312 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
315 // Otherwise, check for variables.
316 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
317 if (!declRef) return true;
318 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
319 if (!var) return true;
321 // All variables have precise lifetime except local variables with
322 // automatic storage duration that aren't specially marked.
323 return (var->hasLocalStorage() &&
324 !var->hasAttr<ObjCPreciseLifetimeAttr>());
327 case ObjCMessageExpr::Class:
328 case ObjCMessageExpr::SuperClass:
329 // It's never necessary for class objects.
332 case ObjCMessageExpr::SuperInstance:
333 // We generally assume that 'self' lives throughout a method call.
337 llvm_unreachable("invalid receiver kind");
340 /// Given an expression of ObjC pointer type, check whether it was
341 /// immediately loaded from an ARC __weak l-value.
342 static const Expr *findWeakLValue(const Expr *E) {
343 assert(E->getType()->isObjCRetainableType());
344 E = E->IgnoreParens();
345 if (auto CE = dyn_cast<CastExpr>(E)) {
346 if (CE->getCastKind() == CK_LValueToRValue) {
347 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
348 return CE->getSubExpr();
355 /// The ObjC runtime may provide entrypoints that are likely to be faster
356 /// than an ordinary message send of the appropriate selector.
358 /// The entrypoints are guaranteed to be equivalent to just sending the
359 /// corresponding message. If the entrypoint is implemented naively as just a
360 /// message send, using it is a trade-off: it sacrifices a few cycles of
361 /// overhead to save a small amount of code. However, it's possible for
362 /// runtimes to detect and special-case classes that use "standard"
363 /// behavior; if that's dynamically a large proportion of all objects, using
364 /// the entrypoint will also be faster than using a message send.
366 /// If the runtime does support a required entrypoint, then this method will
367 /// generate a call and return the resulting value. Otherwise it will return
368 /// None and the caller can generate a msgSend instead.
369 static Optional<llvm::Value *>
370 tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
371 llvm::Value *Receiver,
372 const CallArgList& Args, Selector Sel,
373 const ObjCMethodDecl *method,
374 bool isClassMessage) {
376 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
379 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
380 switch (Sel.getMethodFamily()) {
382 if (isClassMessage &&
383 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
384 ResultType->isObjCObjectPointerType()) {
385 // [Foo alloc] -> objc_alloc(Foo)
386 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
387 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
388 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
389 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
390 Args.size() == 1 && Args.front().getType()->isPointerType() &&
391 Sel.getNameForSlot(0) == "allocWithZone") {
392 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
393 if (isa<llvm::ConstantPointerNull>(arg))
394 return CGF.EmitObjCAllocWithZone(Receiver,
395 CGF.ConvertType(ResultType));
401 case OMF_autorelease:
402 if (ResultType->isObjCObjectPointerType() &&
403 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
404 Runtime.shouldUseARCFunctionsForRetainRelease())
405 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
409 if (ResultType->isObjCObjectPointerType() &&
410 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
411 Runtime.shouldUseARCFunctionsForRetainRelease())
412 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
416 if (ResultType->isVoidType() &&
417 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
418 Runtime.shouldUseARCFunctionsForRetainRelease()) {
419 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
430 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
431 ReturnValueSlot Return) {
432 // Only the lookup mechanism and first two arguments of the method
433 // implementation vary between runtimes. We can get the receiver and
434 // arguments in generic code.
436 bool isDelegateInit = E->isDelegateInitCall();
438 const ObjCMethodDecl *method = E->getMethodDecl();
440 // If the method is -retain, and the receiver's being loaded from
441 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
442 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
443 method->getMethodFamily() == OMF_retain) {
444 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
445 LValue lvalue = EmitLValue(lvalueExpr);
446 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
447 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
451 // We don't retain the receiver in delegate init calls, and this is
452 // safe because the receiver value is always loaded from 'self',
453 // which we zero out. We don't want to Block_copy block receivers,
457 CGM.getLangOpts().ObjCAutoRefCount &&
459 method->hasAttr<NSConsumesSelfAttr>());
461 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
462 bool isSuperMessage = false;
463 bool isClassMessage = false;
464 ObjCInterfaceDecl *OID = nullptr;
466 QualType ReceiverType;
467 llvm::Value *Receiver = nullptr;
468 switch (E->getReceiverKind()) {
469 case ObjCMessageExpr::Instance:
470 ReceiverType = E->getInstanceReceiver()->getType();
472 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
473 E->getInstanceReceiver());
474 Receiver = ter.getPointer();
475 if (ter.getInt()) retainSelf = false;
477 Receiver = EmitScalarExpr(E->getInstanceReceiver());
480 case ObjCMessageExpr::Class: {
481 ReceiverType = E->getClassReceiver();
482 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
483 assert(ObjTy && "Invalid Objective-C class message send");
484 OID = ObjTy->getInterface();
485 assert(OID && "Invalid Objective-C class message send");
486 Receiver = Runtime.GetClass(*this, OID);
487 isClassMessage = true;
491 case ObjCMessageExpr::SuperInstance:
492 ReceiverType = E->getSuperType();
493 Receiver = LoadObjCSelf();
494 isSuperMessage = true;
497 case ObjCMessageExpr::SuperClass:
498 ReceiverType = E->getSuperType();
499 Receiver = LoadObjCSelf();
500 isSuperMessage = true;
501 isClassMessage = true;
506 Receiver = EmitARCRetainNonBlock(Receiver);
508 // In ARC, we sometimes want to "extend the lifetime"
509 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
511 if (getLangOpts().ObjCAutoRefCount && method &&
512 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
513 shouldExtendReceiverForInnerPointerMessage(E))
514 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
516 QualType ResultType = method ? method->getReturnType() : E->getType();
519 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
521 // For delegate init calls in ARC, do an unsafe store of null into
522 // self. This represents the call taking direct ownership of that
523 // value. We have to do this after emitting the other call
524 // arguments because they might also reference self, but we don't
525 // have to worry about any of them modifying self because that would
526 // be an undefined read and write of an object in unordered
528 if (isDelegateInit) {
529 assert(getLangOpts().ObjCAutoRefCount &&
530 "delegate init calls should only be marked in ARC");
532 // Do an unsafe store of null into self.
534 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
535 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
539 if (isSuperMessage) {
540 // super is only valid in an Objective-C method
541 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
542 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
543 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
545 OMD->getClassInterface(),
552 // Call runtime methods directly if we can.
553 if (Optional<llvm::Value *> SpecializedResult =
554 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
555 E->getSelector(), method,
557 result = RValue::get(SpecializedResult.getValue());
559 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
560 E->getSelector(), Receiver, Args,
565 // For delegate init calls in ARC, implicitly store the result of
566 // the call back into self. This takes ownership of the value.
567 if (isDelegateInit) {
569 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
570 llvm::Value *newSelf = result.getScalarVal();
572 // The delegate return type isn't necessarily a matching type; in
573 // fact, it's quite likely to be 'id'.
574 llvm::Type *selfTy = selfAddr.getElementType();
575 newSelf = Builder.CreateBitCast(newSelf, selfTy);
577 Builder.CreateStore(newSelf, selfAddr);
580 return AdjustObjCObjectType(*this, E->getType(), result);
584 struct FinishARCDealloc final : EHScopeStack::Cleanup {
585 void Emit(CodeGenFunction &CGF, Flags flags) override {
586 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
588 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
589 const ObjCInterfaceDecl *iface = impl->getClassInterface();
590 if (!iface->getSuperClass()) return;
592 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
594 // Call [super dealloc] if we have a superclass.
595 llvm::Value *self = CGF.LoadObjCSelf();
598 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
599 CGF.getContext().VoidTy,
600 method->getSelector(),
604 /*is class msg*/ false,
611 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
612 /// the LLVM function and sets the other context used by
614 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
615 const ObjCContainerDecl *CD) {
616 SourceLocation StartLoc = OMD->getBeginLoc();
617 FunctionArgList args;
618 // Check if we should generate debug info for this method.
619 if (OMD->hasAttr<NoDebugAttr>())
620 DebugInfo = nullptr; // disable debug info indefinitely for this function
622 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
624 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
625 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
627 args.push_back(OMD->getSelfDecl());
628 args.push_back(OMD->getCmdDecl());
630 args.append(OMD->param_begin(), OMD->param_end());
633 CurEHLocation = OMD->getEndLoc();
635 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
636 OMD->getLocation(), StartLoc);
638 // In ARC, certain methods get an extra cleanup.
639 if (CGM.getLangOpts().ObjCAutoRefCount &&
640 OMD->isInstanceMethod() &&
641 OMD->getSelector().isUnarySelector()) {
642 const IdentifierInfo *ident =
643 OMD->getSelector().getIdentifierInfoForSlot(0);
644 if (ident->isStr("dealloc"))
645 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
649 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
650 LValue lvalue, QualType type);
652 /// Generate an Objective-C method. An Objective-C method is a C function with
653 /// its pointer, name, and types registered in the class structure.
654 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
655 StartObjCMethod(OMD, OMD->getClassInterface());
656 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
657 assert(isa<CompoundStmt>(OMD->getBody()));
658 incrementProfileCounter(OMD->getBody());
659 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
660 FinishFunction(OMD->getBodyRBrace());
663 /// emitStructGetterCall - Call the runtime function to load a property
664 /// into the return value slot.
665 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
666 bool isAtomic, bool hasStrong) {
667 ASTContext &Context = CGF.getContext();
670 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
673 // objc_copyStruct (ReturnValue, &structIvar,
674 // sizeof (Type of Ivar), isAtomic, false);
677 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
678 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
680 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
681 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
683 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
684 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
685 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
686 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
688 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
689 CGCallee callee = CGCallee::forDirect(fn);
690 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
691 callee, ReturnValueSlot(), args);
694 /// Determine whether the given architecture supports unaligned atomic
695 /// accesses. They don't have to be fast, just faster than a function
696 /// call and a mutex.
697 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
698 // FIXME: Allow unaligned atomic load/store on x86. (It is not
699 // currently supported by the backend.)
703 /// Return the maximum size that permits atomic accesses for the given
705 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
706 llvm::Triple::ArchType arch) {
707 // ARM has 8-byte atomic accesses, but it's not clear whether we
708 // want to rely on them here.
710 // In the default case, just assume that any size up to a pointer is
711 // fine given adequate alignment.
712 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
716 class PropertyImplStrategy {
719 /// The 'native' strategy is to use the architecture's provided
720 /// reads and writes.
723 /// Use objc_setProperty and objc_getProperty.
726 /// Use objc_setProperty for the setter, but use expression
727 /// evaluation for the getter.
728 SetPropertyAndExpressionGet,
730 /// Use objc_copyStruct.
733 /// The 'expression' strategy is to emit normal assignment or
734 /// lvalue-to-rvalue expressions.
738 StrategyKind getKind() const { return StrategyKind(Kind); }
740 bool hasStrongMember() const { return HasStrong; }
741 bool isAtomic() const { return IsAtomic; }
742 bool isCopy() const { return IsCopy; }
744 CharUnits getIvarSize() const { return IvarSize; }
745 CharUnits getIvarAlignment() const { return IvarAlignment; }
747 PropertyImplStrategy(CodeGenModule &CGM,
748 const ObjCPropertyImplDecl *propImpl);
752 unsigned IsAtomic : 1;
754 unsigned HasStrong : 1;
757 CharUnits IvarAlignment;
761 /// Pick an implementation strategy for the given property synthesis.
762 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
763 const ObjCPropertyImplDecl *propImpl) {
764 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
765 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
767 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
768 IsAtomic = prop->isAtomic();
769 HasStrong = false; // doesn't matter here.
771 // Evaluate the ivar's size and alignment.
772 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
773 QualType ivarType = ivar->getType();
774 std::tie(IvarSize, IvarAlignment) =
775 CGM.getContext().getTypeInfoInChars(ivarType);
777 // If we have a copy property, we always have to use getProperty/setProperty.
778 // TODO: we could actually use setProperty and an expression for non-atomics.
780 Kind = GetSetProperty;
785 if (setterKind == ObjCPropertyDecl::Retain) {
786 // In GC-only, there's nothing special that needs to be done.
787 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
790 // In ARC, if the property is non-atomic, use expression emission,
791 // which translates to objc_storeStrong. This isn't required, but
792 // it's slightly nicer.
793 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
794 // Using standard expression emission for the setter is only
795 // acceptable if the ivar is __strong, which won't be true if
796 // the property is annotated with __attribute__((NSObject)).
797 // TODO: falling all the way back to objc_setProperty here is
798 // just laziness, though; we could still use objc_storeStrong
799 // if we hacked it right.
800 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
803 Kind = SetPropertyAndExpressionGet;
806 // Otherwise, we need to at least use setProperty. However, if
807 // the property isn't atomic, we can use normal expression
808 // emission for the getter.
809 } else if (!IsAtomic) {
810 Kind = SetPropertyAndExpressionGet;
813 // Otherwise, we have to use both setProperty and getProperty.
815 Kind = GetSetProperty;
820 // If we're not atomic, just use expression accesses.
826 // Properties on bitfield ivars need to be emitted using expression
827 // accesses even if they're nominally atomic.
828 if (ivar->isBitField()) {
833 // GC-qualified or ARC-qualified ivars need to be emitted as
834 // expressions. This actually works out to being atomic anyway,
835 // except for ARC __strong, but that should trigger the above code.
836 if (ivarType.hasNonTrivialObjCLifetime() ||
837 (CGM.getLangOpts().getGC() &&
838 CGM.getContext().getObjCGCAttrKind(ivarType))) {
843 // Compute whether the ivar has strong members.
844 if (CGM.getLangOpts().getGC())
845 if (const RecordType *recordType = ivarType->getAs<RecordType>())
846 HasStrong = recordType->getDecl()->hasObjectMember();
848 // We can never access structs with object members with a native
849 // access, because we need to use write barriers. This is what
850 // objc_copyStruct is for.
856 // Otherwise, this is target-dependent and based on the size and
857 // alignment of the ivar.
859 // If the size of the ivar is not a power of two, give up. We don't
860 // want to get into the business of doing compare-and-swaps.
861 if (!IvarSize.isPowerOfTwo()) {
866 llvm::Triple::ArchType arch =
867 CGM.getTarget().getTriple().getArch();
869 // Most architectures require memory to fit within a single cache
870 // line, so the alignment has to be at least the size of the access.
871 // Otherwise we have to grab a lock.
872 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
877 // If the ivar's size exceeds the architecture's maximum atomic
878 // access size, we have to use CopyStruct.
879 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
884 // Otherwise, we can use native loads and stores.
888 /// Generate an Objective-C property getter function.
890 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
891 /// is illegal within a category.
892 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
893 const ObjCPropertyImplDecl *PID) {
894 llvm::Constant *AtomicHelperFn =
895 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
896 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
897 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
898 assert(OMD && "Invalid call to generate getter (empty method)");
899 StartObjCMethod(OMD, IMP->getClassInterface());
901 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
906 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
907 const Expr *getter = propImpl->getGetterCXXConstructor();
908 if (!getter) return true;
910 // Sema only makes only of these when the ivar has a C++ class type,
911 // so the form is pretty constrained.
913 // If the property has a reference type, we might just be binding a
914 // reference, in which case the result will be a gl-value. We should
915 // treat this as a non-trivial operation.
916 if (getter->isGLValue())
919 // If we selected a trivial copy-constructor, we're okay.
920 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
921 return (construct->getConstructor()->isTrivial());
923 // The constructor might require cleanups (in which case it's never
925 assert(isa<ExprWithCleanups>(getter));
929 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
930 /// copy the ivar into the resturn slot.
931 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
932 llvm::Value *returnAddr,
934 llvm::Constant *AtomicHelperFn) {
935 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
939 // The 1st argument is the return Slot.
940 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
942 // The 2nd argument is the address of the ivar.
943 llvm::Value *ivarAddr =
944 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
945 CGF.LoadObjCSelf(), ivar, 0).getPointer();
946 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
947 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
949 // Third argument is the helper function.
950 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
952 llvm::Constant *copyCppAtomicObjectFn =
953 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
954 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
956 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
957 callee, ReturnValueSlot(), args);
961 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
962 const ObjCPropertyImplDecl *propImpl,
963 const ObjCMethodDecl *GetterMethodDecl,
964 llvm::Constant *AtomicHelperFn) {
965 // If there's a non-trivial 'get' expression, we just have to emit that.
966 if (!hasTrivialGetExpr(propImpl)) {
967 if (!AtomicHelperFn) {
968 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
969 propImpl->getGetterCXXConstructor(),
970 /* NRVOCandidate=*/nullptr);
971 EmitReturnStmt(*ret);
974 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
975 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
976 ivar, AtomicHelperFn);
981 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
982 QualType propType = prop->getType();
983 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
985 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
987 // Pick an implementation strategy.
988 PropertyImplStrategy strategy(CGM, propImpl);
989 switch (strategy.getKind()) {
990 case PropertyImplStrategy::Native: {
991 // We don't need to do anything for a zero-size struct.
992 if (strategy.getIvarSize().isZero())
995 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
997 // Currently, all atomic accesses have to be through integer
998 // types, so there's no point in trying to pick a prettier type.
999 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1000 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1001 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1003 // Perform an atomic load. This does not impose ordering constraints.
1004 Address ivarAddr = LV.getAddress();
1005 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1006 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1007 load->setAtomic(llvm::AtomicOrdering::Unordered);
1009 // Store that value into the return address. Doing this with a
1010 // bitcast is likely to produce some pretty ugly IR, but it's not
1011 // the *most* terrible thing in the world.
1012 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1013 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1014 llvm::Value *ivarVal = load;
1015 if (ivarSize > retTySize) {
1016 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1017 ivarVal = Builder.CreateTrunc(load, newTy);
1018 bitcastType = newTy->getPointerTo();
1020 Builder.CreateStore(ivarVal,
1021 Builder.CreateBitCast(ReturnValue, bitcastType));
1023 // Make sure we don't do an autorelease.
1024 AutoreleaseResult = false;
1028 case PropertyImplStrategy::GetSetProperty: {
1029 llvm::Constant *getPropertyFn =
1030 CGM.getObjCRuntime().GetPropertyGetFunction();
1031 if (!getPropertyFn) {
1032 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1035 CGCallee callee = CGCallee::forDirect(getPropertyFn);
1037 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1038 // FIXME: Can't this be simpler? This might even be worse than the
1039 // corresponding gcc code.
1041 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1042 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1043 llvm::Value *ivarOffset =
1044 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1047 args.add(RValue::get(self), getContext().getObjCIdType());
1048 args.add(RValue::get(cmd), getContext().getObjCSelType());
1049 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1050 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1051 getContext().BoolTy);
1053 // FIXME: We shouldn't need to get the function info here, the
1054 // runtime already should have computed it to build the function.
1055 llvm::Instruction *CallInstruction;
1056 RValue RV = EmitCall(
1057 getTypes().arrangeBuiltinFunctionCall(propType, args),
1058 callee, ReturnValueSlot(), args, &CallInstruction);
1059 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1060 call->setTailCall();
1062 // We need to fix the type here. Ivars with copy & retain are
1063 // always objects so we don't need to worry about complex or
1065 RV = RValue::get(Builder.CreateBitCast(
1067 getTypes().ConvertType(getterMethod->getReturnType())));
1069 EmitReturnOfRValue(RV, propType);
1071 // objc_getProperty does an autorelease, so we should suppress ours.
1072 AutoreleaseResult = false;
1077 case PropertyImplStrategy::CopyStruct:
1078 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1079 strategy.hasStrongMember());
1082 case PropertyImplStrategy::Expression:
1083 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1084 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1086 QualType ivarType = ivar->getType();
1087 switch (getEvaluationKind(ivarType)) {
1089 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1090 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1094 case TEK_Aggregate: {
1095 // The return value slot is guaranteed to not be aliased, but
1096 // that's not necessarily the same as "on the stack", so
1097 // we still potentially need objc_memmove_collectable.
1098 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1099 /* Src= */ LV, ivarType, overlapForReturnValue());
1104 if (propType->isReferenceType()) {
1105 value = LV.getAddress().getPointer();
1107 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1108 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1109 if (getLangOpts().ObjCAutoRefCount) {
1110 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1112 value = EmitARCLoadWeak(LV.getAddress());
1115 // Otherwise we want to do a simple load, suppressing the
1116 // final autorelease.
1118 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1119 AutoreleaseResult = false;
1122 value = Builder.CreateBitCast(
1123 value, ConvertType(GetterMethodDecl->getReturnType()));
1126 EmitReturnOfRValue(RValue::get(value), propType);
1130 llvm_unreachable("bad evaluation kind");
1134 llvm_unreachable("bad @property implementation strategy!");
1137 /// emitStructSetterCall - Call the runtime function to store the value
1138 /// from the first formal parameter into the given ivar.
1139 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1140 ObjCIvarDecl *ivar) {
1141 // objc_copyStruct (&structIvar, &Arg,
1142 // sizeof (struct something), true, false);
1145 // The first argument is the address of the ivar.
1146 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1147 CGF.LoadObjCSelf(), ivar, 0)
1149 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1150 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1152 // The second argument is the address of the parameter variable.
1153 ParmVarDecl *argVar = *OMD->param_begin();
1154 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1155 argVar->getType().getNonReferenceType(), VK_LValue,
1157 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1158 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1159 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1161 // The third argument is the sizeof the type.
1163 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1164 args.add(RValue::get(size), CGF.getContext().getSizeType());
1166 // The fourth argument is the 'isAtomic' flag.
1167 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1169 // The fifth argument is the 'hasStrong' flag.
1170 // FIXME: should this really always be false?
1171 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1173 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1174 CGCallee callee = CGCallee::forDirect(fn);
1176 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1177 callee, ReturnValueSlot(), args);
1180 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1181 /// the value from the first formal parameter into the given ivar, using
1182 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1183 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1184 ObjCMethodDecl *OMD,
1186 llvm::Constant *AtomicHelperFn) {
1187 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1191 // The first argument is the address of the ivar.
1192 llvm::Value *ivarAddr =
1193 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1194 CGF.LoadObjCSelf(), ivar, 0).getPointer();
1195 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1196 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1198 // The second argument is the address of the parameter variable.
1199 ParmVarDecl *argVar = *OMD->param_begin();
1200 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1201 argVar->getType().getNonReferenceType(), VK_LValue,
1203 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
1204 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1205 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1207 // Third argument is the helper function.
1208 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1210 llvm::Constant *fn =
1211 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1212 CGCallee callee = CGCallee::forDirect(fn);
1214 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1215 callee, ReturnValueSlot(), args);
1219 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1220 Expr *setter = PID->getSetterCXXAssignment();
1221 if (!setter) return true;
1223 // Sema only makes only of these when the ivar has a C++ class type,
1224 // so the form is pretty constrained.
1226 // An operator call is trivial if the function it calls is trivial.
1227 // This also implies that there's nothing non-trivial going on with
1228 // the arguments, because operator= can only be trivial if it's a
1229 // synthesized assignment operator and therefore both parameters are
1231 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1232 if (const FunctionDecl *callee
1233 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1234 if (callee->isTrivial())
1239 assert(isa<ExprWithCleanups>(setter));
1243 static bool UseOptimizedSetter(CodeGenModule &CGM) {
1244 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1246 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1250 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1251 const ObjCPropertyImplDecl *propImpl,
1252 llvm::Constant *AtomicHelperFn) {
1253 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1254 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1255 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
1257 // Just use the setter expression if Sema gave us one and it's
1259 if (!hasTrivialSetExpr(propImpl)) {
1260 if (!AtomicHelperFn)
1261 // If non-atomic, assignment is called directly.
1262 EmitStmt(propImpl->getSetterCXXAssignment());
1264 // If atomic, assignment is called via a locking api.
1265 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1270 PropertyImplStrategy strategy(CGM, propImpl);
1271 switch (strategy.getKind()) {
1272 case PropertyImplStrategy::Native: {
1273 // We don't need to do anything for a zero-size struct.
1274 if (strategy.getIvarSize().isZero())
1277 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1280 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1281 Address ivarAddr = ivarLValue.getAddress();
1283 // Currently, all atomic accesses have to be through integer
1284 // types, so there's no point in trying to pick a prettier type.
1285 llvm::Type *bitcastType =
1286 llvm::Type::getIntNTy(getLLVMContext(),
1287 getContext().toBits(strategy.getIvarSize()));
1289 // Cast both arguments to the chosen operation type.
1290 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1291 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1293 // This bitcast load is likely to cause some nasty IR.
1294 llvm::Value *load = Builder.CreateLoad(argAddr);
1296 // Perform an atomic store. There are no memory ordering requirements.
1297 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1298 store->setAtomic(llvm::AtomicOrdering::Unordered);
1302 case PropertyImplStrategy::GetSetProperty:
1303 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1305 llvm::Constant *setOptimizedPropertyFn = nullptr;
1306 llvm::Constant *setPropertyFn = nullptr;
1307 if (UseOptimizedSetter(CGM)) {
1308 // 10.8 and iOS 6.0 code and GC is off
1309 setOptimizedPropertyFn =
1310 CGM.getObjCRuntime()
1311 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1313 if (!setOptimizedPropertyFn) {
1314 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1319 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1320 if (!setPropertyFn) {
1321 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1326 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1327 // <is-atomic>, <is-copy>).
1329 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1331 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1332 llvm::Value *ivarOffset =
1333 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1334 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1335 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1336 arg = Builder.CreateBitCast(arg, VoidPtrTy);
1339 args.add(RValue::get(self), getContext().getObjCIdType());
1340 args.add(RValue::get(cmd), getContext().getObjCSelType());
1341 if (setOptimizedPropertyFn) {
1342 args.add(RValue::get(arg), getContext().getObjCIdType());
1343 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1344 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1345 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1346 callee, ReturnValueSlot(), args);
1348 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1349 args.add(RValue::get(arg), getContext().getObjCIdType());
1350 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1351 getContext().BoolTy);
1352 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1353 getContext().BoolTy);
1354 // FIXME: We shouldn't need to get the function info here, the runtime
1355 // already should have computed it to build the function.
1356 CGCallee callee = CGCallee::forDirect(setPropertyFn);
1357 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1358 callee, ReturnValueSlot(), args);
1364 case PropertyImplStrategy::CopyStruct:
1365 emitStructSetterCall(*this, setterMethod, ivar);
1368 case PropertyImplStrategy::Expression:
1372 // Otherwise, fake up some ASTs and emit a normal assignment.
1373 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1374 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1375 VK_LValue, SourceLocation());
1376 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1377 selfDecl->getType(), CK_LValueToRValue, &self,
1379 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1380 SourceLocation(), SourceLocation(),
1381 &selfLoad, true, true);
1383 ParmVarDecl *argDecl = *setterMethod->param_begin();
1384 QualType argType = argDecl->getType().getNonReferenceType();
1385 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1387 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1388 argType.getUnqualifiedType(), CK_LValueToRValue,
1391 // The property type can differ from the ivar type in some situations with
1392 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1393 // The following absurdity is just to ensure well-formed IR.
1394 CastKind argCK = CK_NoOp;
1395 if (ivarRef.getType()->isObjCObjectPointerType()) {
1396 if (argLoad.getType()->isObjCObjectPointerType())
1398 else if (argLoad.getType()->isBlockPointerType())
1399 argCK = CK_BlockPointerToObjCPointerCast;
1401 argCK = CK_CPointerToObjCPointerCast;
1402 } else if (ivarRef.getType()->isBlockPointerType()) {
1403 if (argLoad.getType()->isBlockPointerType())
1406 argCK = CK_AnyPointerToBlockPointerCast;
1407 } else if (ivarRef.getType()->isPointerType()) {
1410 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1411 ivarRef.getType(), argCK, &argLoad,
1413 Expr *finalArg = &argLoad;
1414 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1416 finalArg = &argCast;
1419 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1420 ivarRef.getType(), VK_RValue, OK_Ordinary,
1421 SourceLocation(), FPOptions());
1425 /// Generate an Objective-C property setter function.
1427 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1428 /// is illegal within a category.
1429 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1430 const ObjCPropertyImplDecl *PID) {
1431 llvm::Constant *AtomicHelperFn =
1432 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1433 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1434 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1435 assert(OMD && "Invalid call to generate setter (empty method)");
1436 StartObjCMethod(OMD, IMP->getClassInterface());
1438 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1444 struct DestroyIvar final : EHScopeStack::Cleanup {
1447 const ObjCIvarDecl *ivar;
1448 CodeGenFunction::Destroyer *destroyer;
1449 bool useEHCleanupForArray;
1451 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1452 CodeGenFunction::Destroyer *destroyer,
1453 bool useEHCleanupForArray)
1454 : addr(addr), ivar(ivar), destroyer(destroyer),
1455 useEHCleanupForArray(useEHCleanupForArray) {}
1457 void Emit(CodeGenFunction &CGF, Flags flags) override {
1459 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1460 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1461 flags.isForNormalCleanup() && useEHCleanupForArray);
1466 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1467 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1470 llvm::Value *null = getNullForVariable(addr);
1471 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1474 static void emitCXXDestructMethod(CodeGenFunction &CGF,
1475 ObjCImplementationDecl *impl) {
1476 CodeGenFunction::RunCleanupsScope scope(CGF);
1478 llvm::Value *self = CGF.LoadObjCSelf();
1480 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1481 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1482 ivar; ivar = ivar->getNextIvar()) {
1483 QualType type = ivar->getType();
1485 // Check whether the ivar is a destructible type.
1486 QualType::DestructionKind dtorKind = type.isDestructedType();
1487 if (!dtorKind) continue;
1489 CodeGenFunction::Destroyer *destroyer = nullptr;
1491 // Use a call to objc_storeStrong to destroy strong ivars, for the
1492 // general benefit of the tools.
1493 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1494 destroyer = destroyARCStrongWithStore;
1496 // Otherwise use the default for the destruction kind.
1498 destroyer = CGF.getDestroyer(dtorKind);
1501 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1503 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1504 cleanupKind & EHCleanup);
1507 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1510 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1513 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1514 StartObjCMethod(MD, IMP->getClassInterface());
1516 // Emit .cxx_construct.
1518 // Suppress the final autorelease in ARC.
1519 AutoreleaseResult = false;
1521 for (const auto *IvarInit : IMP->inits()) {
1522 FieldDecl *Field = IvarInit->getAnyMember();
1523 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1524 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1525 LoadObjCSelf(), Ivar, 0);
1526 EmitAggExpr(IvarInit->getInit(),
1527 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1528 AggValueSlot::DoesNotNeedGCBarriers,
1529 AggValueSlot::IsNotAliased,
1530 AggValueSlot::DoesNotOverlap));
1532 // constructor returns 'self'.
1533 CodeGenTypes &Types = CGM.getTypes();
1534 QualType IdTy(CGM.getContext().getObjCIdType());
1535 llvm::Value *SelfAsId =
1536 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1537 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1539 // Emit .cxx_destruct.
1541 emitCXXDestructMethod(*this, IMP);
1546 llvm::Value *CodeGenFunction::LoadObjCSelf() {
1547 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1548 DeclRefExpr DRE(getContext(), Self,
1549 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1550 Self->getType(), VK_LValue, SourceLocation());
1551 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1554 QualType CodeGenFunction::TypeOfSelfObject() {
1555 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1556 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1557 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1558 getContext().getCanonicalType(selfDecl->getType()));
1559 return PTy->getPointeeType();
1562 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1563 llvm::Constant *EnumerationMutationFnPtr =
1564 CGM.getObjCRuntime().EnumerationMutationFunction();
1565 if (!EnumerationMutationFnPtr) {
1566 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1569 CGCallee EnumerationMutationFn =
1570 CGCallee::forDirect(EnumerationMutationFnPtr);
1572 CGDebugInfo *DI = getDebugInfo();
1574 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1576 RunCleanupsScope ForScope(*this);
1578 // The local variable comes into scope immediately.
1579 AutoVarEmission variable = AutoVarEmission::invalid();
1580 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1581 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1583 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1585 // Fast enumeration state.
1586 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1587 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1588 EmitNullInitialization(StatePtr, StateTy);
1590 // Number of elements in the items array.
1591 static const unsigned NumItems = 16;
1593 // Fetch the countByEnumeratingWithState:objects:count: selector.
1594 IdentifierInfo *II[] = {
1595 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1596 &CGM.getContext().Idents.get("objects"),
1597 &CGM.getContext().Idents.get("count")
1599 Selector FastEnumSel =
1600 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1603 getContext().getConstantArrayType(getContext().getObjCIdType(),
1604 llvm::APInt(32, NumItems),
1605 ArrayType::Normal, 0);
1606 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1608 // Emit the collection pointer. In ARC, we do a retain.
1609 llvm::Value *Collection;
1610 if (getLangOpts().ObjCAutoRefCount) {
1611 Collection = EmitARCRetainScalarExpr(S.getCollection());
1613 // Enter a cleanup to do the release.
1614 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1616 Collection = EmitScalarExpr(S.getCollection());
1619 // The 'continue' label needs to appear within the cleanup for the
1620 // collection object.
1621 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1623 // Send it our message:
1626 // The first argument is a temporary of the enumeration-state type.
1627 Args.add(RValue::get(StatePtr.getPointer()),
1628 getContext().getPointerType(StateTy));
1630 // The second argument is a temporary array with space for NumItems
1631 // pointers. We'll actually be loading elements from the array
1632 // pointer written into the control state; this buffer is so that
1633 // collections that *aren't* backed by arrays can still queue up
1634 // batches of elements.
1635 Args.add(RValue::get(ItemsPtr.getPointer()),
1636 getContext().getPointerType(ItemsTy));
1638 // The third argument is the capacity of that temporary array.
1639 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1640 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1641 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1643 // Start the enumeration.
1645 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1646 getContext().getNSUIntegerType(),
1647 FastEnumSel, Collection, Args);
1649 // The initial number of objects that were returned in the buffer.
1650 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1652 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1653 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1655 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1657 // If the limit pointer was zero to begin with, the collection is
1658 // empty; skip all this. Set the branch weight assuming this has the same
1659 // probability of exiting the loop as any other loop exit.
1660 uint64_t EntryCount = getCurrentProfileCount();
1661 Builder.CreateCondBr(
1662 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1664 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1666 // Otherwise, initialize the loop.
1667 EmitBlock(LoopInitBB);
1669 // Save the initial mutations value. This is the value at an
1670 // address that was written into the state object by
1671 // countByEnumeratingWithState:objects:count:.
1672 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1673 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1674 llvm::Value *StateMutationsPtr
1675 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1677 llvm::Value *initialMutations =
1678 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1679 "forcoll.initial-mutations");
1681 // Start looping. This is the point we return to whenever we have a
1682 // fresh, non-empty batch of objects.
1683 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1684 EmitBlock(LoopBodyBB);
1686 // The current index into the buffer.
1687 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1688 index->addIncoming(zero, LoopInitBB);
1690 // The current buffer size.
1691 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1692 count->addIncoming(initialBufferLimit, LoopInitBB);
1694 incrementProfileCounter(&S);
1696 // Check whether the mutations value has changed from where it was
1697 // at start. StateMutationsPtr should actually be invariant between
1699 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1700 llvm::Value *currentMutations
1701 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1704 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1705 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1707 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1708 WasNotMutatedBB, WasMutatedBB);
1710 // If so, call the enumeration-mutation function.
1711 EmitBlock(WasMutatedBB);
1713 Builder.CreateBitCast(Collection,
1714 ConvertType(getContext().getObjCIdType()));
1716 Args2.add(RValue::get(V), getContext().getObjCIdType());
1717 // FIXME: We shouldn't need to get the function info here, the runtime already
1718 // should have computed it to build the function.
1720 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1721 EnumerationMutationFn, ReturnValueSlot(), Args2);
1723 // Otherwise, or if the mutation function returns, just continue.
1724 EmitBlock(WasNotMutatedBB);
1726 // Initialize the element variable.
1727 RunCleanupsScope elementVariableScope(*this);
1728 bool elementIsVariable;
1729 LValue elementLValue;
1730 QualType elementType;
1731 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1732 // Initialize the variable, in case it's a __block variable or something.
1733 EmitAutoVarInit(variable);
1735 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1736 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1737 D->getType(), VK_LValue, SourceLocation());
1738 elementLValue = EmitLValue(&tempDRE);
1739 elementType = D->getType();
1740 elementIsVariable = true;
1742 if (D->isARCPseudoStrong())
1743 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1745 elementLValue = LValue(); // suppress warning
1746 elementType = cast<Expr>(S.getElement())->getType();
1747 elementIsVariable = false;
1749 llvm::Type *convertedElementType = ConvertType(elementType);
1751 // Fetch the buffer out of the enumeration state.
1752 // TODO: this pointer should actually be invariant between
1753 // refreshes, which would help us do certain loop optimizations.
1754 Address StateItemsPtr = Builder.CreateStructGEP(
1755 StatePtr, 1, getPointerSize(), "stateitems.ptr");
1756 llvm::Value *EnumStateItems =
1757 Builder.CreateLoad(StateItemsPtr, "stateitems");
1759 // Fetch the value at the current index from the buffer.
1760 llvm::Value *CurrentItemPtr =
1761 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1762 llvm::Value *CurrentItem =
1763 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
1765 // Cast that value to the right type.
1766 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1769 // Make sure we have an l-value. Yes, this gets evaluated every
1770 // time through the loop.
1771 if (!elementIsVariable) {
1772 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1773 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1775 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1779 // If we do have an element variable, this assignment is the end of
1780 // its initialization.
1781 if (elementIsVariable)
1782 EmitAutoVarCleanups(variable);
1784 // Perform the loop body, setting up break and continue labels.
1785 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1787 RunCleanupsScope Scope(*this);
1788 EmitStmt(S.getBody());
1790 BreakContinueStack.pop_back();
1792 // Destroy the element variable now.
1793 elementVariableScope.ForceCleanup();
1795 // Check whether there are more elements.
1796 EmitBlock(AfterBody.getBlock());
1798 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1800 // First we check in the local buffer.
1801 llvm::Value *indexPlusOne =
1802 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1804 // If we haven't overrun the buffer yet, we can continue.
1805 // Set the branch weights based on the simplifying assumption that this is
1806 // like a while-loop, i.e., ignoring that the false branch fetches more
1807 // elements and then returns to the loop.
1808 Builder.CreateCondBr(
1809 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1810 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1812 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1813 count->addIncoming(count, AfterBody.getBlock());
1815 // Otherwise, we have to fetch more elements.
1816 EmitBlock(FetchMoreBB);
1819 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1820 getContext().getNSUIntegerType(),
1821 FastEnumSel, Collection, Args);
1823 // If we got a zero count, we're done.
1824 llvm::Value *refetchCount = CountRV.getScalarVal();
1826 // (note that the message send might split FetchMoreBB)
1827 index->addIncoming(zero, Builder.GetInsertBlock());
1828 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1830 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1831 EmptyBB, LoopBodyBB);
1833 // No more elements.
1836 if (!elementIsVariable) {
1837 // If the element was not a declaration, set it to be null.
1839 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1840 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1841 EmitStoreThroughLValue(RValue::get(null), elementLValue);
1845 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1847 ForScope.ForceCleanup();
1848 EmitBlock(LoopEnd.getBlock());
1851 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1852 CGM.getObjCRuntime().EmitTryStmt(*this, S);
1855 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1856 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1859 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1860 const ObjCAtSynchronizedStmt &S) {
1861 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1865 struct CallObjCRelease final : EHScopeStack::Cleanup {
1866 CallObjCRelease(llvm::Value *object) : object(object) {}
1867 llvm::Value *object;
1869 void Emit(CodeGenFunction &CGF, Flags flags) override {
1870 // Releases at the end of the full-expression are imprecise.
1871 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1876 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
1877 /// release at the end of the full-expression.
1878 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1879 llvm::Value *object) {
1880 // If we're in a conditional branch, we need to make the cleanup
1882 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1886 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1887 llvm::Value *value) {
1888 return EmitARCRetainAutorelease(type, value);
1891 /// Given a number of pointers, inform the optimizer that they're
1892 /// being intrinsically used up until this point in the program.
1893 void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1894 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
1896 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
1898 // This isn't really a "runtime" function, but as an intrinsic it
1899 // doesn't really matter as long as we align things up.
1900 EmitNounwindRuntimeCall(fn, values);
1903 static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1904 llvm::Constant *RTF) {
1905 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
1906 // If the target runtime doesn't naturally support ARC, emit weak
1907 // references to the runtime support library. We don't really
1908 // permit this to fail, but we need a particular relocation style.
1909 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1910 !CGM.getTriple().isOSBinFormatCOFF()) {
1911 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1916 /// Perform an operation having the signature
1918 /// where a null input causes a no-op and returns null.
1919 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1921 llvm::Type *returnType,
1922 llvm::Constant *&fn,
1923 llvm::Intrinsic::ID IntID,
1924 bool isTailCall = false) {
1925 if (isa<llvm::ConstantPointerNull>(value))
1929 fn = CGF.CGM.getIntrinsic(IntID);
1930 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
1933 // Cast the argument to 'id'.
1934 llvm::Type *origType = returnType ? returnType : value->getType();
1935 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1937 // Call the function.
1938 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1940 call->setTailCall();
1942 // Cast the result back to the original type.
1943 return CGF.Builder.CreateBitCast(call, origType);
1946 /// Perform an operation having the following signature:
1948 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1950 llvm::Constant *&fn,
1951 llvm::Intrinsic::ID IntID) {
1953 fn = CGF.CGM.getIntrinsic(IntID);
1954 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
1957 // Cast the argument to 'id*'.
1958 llvm::Type *origType = addr.getElementType();
1959 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1961 // Call the function.
1962 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
1964 // Cast the result back to a dereference of the original type.
1965 if (origType != CGF.Int8PtrTy)
1966 result = CGF.Builder.CreateBitCast(result, origType);
1971 /// Perform an operation having the following signature:
1973 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1976 llvm::Constant *&fn,
1977 llvm::Intrinsic::ID IntID,
1979 assert(addr.getElementType() == value->getType());
1982 fn = CGF.CGM.getIntrinsic(IntID);
1983 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
1986 llvm::Type *origType = value->getType();
1988 llvm::Value *args[] = {
1989 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
1990 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1992 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
1994 if (ignored) return nullptr;
1996 return CGF.Builder.CreateBitCast(result, origType);
1999 /// Perform an operation having the following signature:
2000 /// void (i8**, i8**)
2001 static void emitARCCopyOperation(CodeGenFunction &CGF,
2004 llvm::Constant *&fn,
2005 llvm::Intrinsic::ID IntID) {
2006 assert(dst.getType() == src.getType());
2009 fn = CGF.CGM.getIntrinsic(IntID);
2010 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
2013 llvm::Value *args[] = {
2014 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2015 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
2017 CGF.EmitNounwindRuntimeCall(fn, args);
2020 /// Perform an operation having the signature
2022 /// where a null input causes a no-op and returns null.
2023 static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2025 llvm::Type *returnType,
2026 llvm::Constant *&fn,
2028 if (isa<llvm::ConstantPointerNull>(value))
2032 llvm::FunctionType *fnType =
2033 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2034 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2036 // We have Native ARC, so set nonlazybind attribute for performance
2037 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2038 if (fnName == "objc_retain")
2039 f->addFnAttr(llvm::Attribute::NonLazyBind);
2042 // Cast the argument to 'id'.
2043 llvm::Type *origType = returnType ? returnType : value->getType();
2044 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2046 // Call the function.
2047 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2049 // Cast the result back to the original type.
2050 return CGF.Builder.CreateBitCast(call, origType);
2053 /// Produce the code to do a retain. Based on the type, calls one of:
2054 /// call i8* \@objc_retain(i8* %value)
2055 /// call i8* \@objc_retainBlock(i8* %value)
2056 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2057 if (type->isBlockPointerType())
2058 return EmitARCRetainBlock(value, /*mandatory*/ false);
2060 return EmitARCRetainNonBlock(value);
2063 /// Retain the given object, with normal retain semantics.
2064 /// call i8* \@objc_retain(i8* %value)
2065 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
2066 return emitARCValueOperation(*this, value, nullptr,
2067 CGM.getObjCEntrypoints().objc_retain,
2068 llvm::Intrinsic::objc_retain);
2071 /// Retain the given block, with _Block_copy semantics.
2072 /// call i8* \@objc_retainBlock(i8* %value)
2074 /// \param mandatory - If false, emit the call with metadata
2075 /// indicating that it's okay for the optimizer to eliminate this call
2076 /// if it can prove that the block never escapes except down the stack.
2077 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2080 = emitARCValueOperation(*this, value, nullptr,
2081 CGM.getObjCEntrypoints().objc_retainBlock,
2082 llvm::Intrinsic::objc_retainBlock);
2084 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2085 // tell the optimizer that it doesn't need to do this copy if the
2086 // block doesn't escape, where being passed as an argument doesn't
2087 // count as escaping.
2088 if (!mandatory && isa<llvm::Instruction>(result)) {
2089 llvm::CallInst *call
2090 = cast<llvm::CallInst>(result->stripPointerCasts());
2091 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
2093 call->setMetadata("clang.arc.copy_on_escape",
2094 llvm::MDNode::get(Builder.getContext(), None));
2100 static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
2101 // Fetch the void(void) inline asm which marks that we're going to
2102 // do something with the autoreleased return value.
2103 llvm::InlineAsm *&marker
2104 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
2107 = CGF.CGM.getTargetCodeGenInfo()
2108 .getARCRetainAutoreleasedReturnValueMarker();
2110 // If we have an empty assembly string, there's nothing to do.
2111 if (assembly.empty()) {
2113 // Otherwise, at -O0, build an inline asm that we're going to call
2115 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2116 llvm::FunctionType *type =
2117 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
2119 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2121 // If we're at -O1 and above, we don't want to litter the code
2122 // with this marker yet, so leave a breadcrumb for the ARC
2123 // optimizer to pick up.
2125 llvm::NamedMDNode *metadata =
2126 CGF.CGM.getModule().getOrInsertNamedMetadata(
2127 "clang.arc.retainAutoreleasedReturnValueMarker");
2128 assert(metadata->getNumOperands() <= 1);
2129 if (metadata->getNumOperands() == 0) {
2130 auto &ctx = CGF.getLLVMContext();
2131 metadata->addOperand(llvm::MDNode::get(ctx,
2132 llvm::MDString::get(ctx, assembly)));
2137 // Call the marker asm if we made one, which we do only at -O0.
2139 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
2142 /// Retain the given object which is the result of a function call.
2143 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2145 /// Yes, this function name is one character away from a different
2146 /// call with completely different semantics.
2148 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2149 emitAutoreleasedReturnValueMarker(*this);
2150 return emitARCValueOperation(*this, value, nullptr,
2151 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2152 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
2155 /// Claim a possibly-autoreleased return value at +0. This is only
2156 /// valid to do in contexts which do not rely on the retain to keep
2157 /// the object valid for all of its uses; for example, when
2158 /// the value is ignored, or when it is being assigned to an
2159 /// __unsafe_unretained variable.
2161 /// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2163 CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2164 emitAutoreleasedReturnValueMarker(*this);
2165 return emitARCValueOperation(*this, value, nullptr,
2166 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2167 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
2170 /// Release the given object.
2171 /// call void \@objc_release(i8* %value)
2172 void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2173 ARCPreciseLifetime_t precise) {
2174 if (isa<llvm::ConstantPointerNull>(value)) return;
2176 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
2178 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2179 setARCRuntimeFunctionLinkage(CGM, fn);
2182 // Cast the argument to 'id'.
2183 value = Builder.CreateBitCast(value, Int8PtrTy);
2185 // Call objc_release.
2186 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2188 if (precise == ARCImpreciseLifetime) {
2189 call->setMetadata("clang.imprecise_release",
2190 llvm::MDNode::get(Builder.getContext(), None));
2194 /// Destroy a __strong variable.
2196 /// At -O0, emit a call to store 'null' into the address;
2197 /// instrumenting tools prefer this because the address is exposed,
2198 /// but it's relatively cumbersome to optimize.
2200 /// At -O1 and above, just load and call objc_release.
2202 /// call void \@objc_storeStrong(i8** %addr, i8* null)
2203 void CodeGenFunction::EmitARCDestroyStrong(Address addr,
2204 ARCPreciseLifetime_t precise) {
2205 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2206 llvm::Value *null = getNullForVariable(addr);
2207 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2211 llvm::Value *value = Builder.CreateLoad(addr);
2212 EmitARCRelease(value, precise);
2215 /// Store into a strong object. Always calls this:
2216 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2217 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
2220 assert(addr.getElementType() == value->getType());
2222 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
2224 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2225 setARCRuntimeFunctionLinkage(CGM, fn);
2228 llvm::Value *args[] = {
2229 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
2230 Builder.CreateBitCast(value, Int8PtrTy)
2232 EmitNounwindRuntimeCall(fn, args);
2234 if (ignored) return nullptr;
2238 /// Store into a strong object. Sometimes calls this:
2239 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2240 /// Other times, breaks it down into components.
2241 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2242 llvm::Value *newValue,
2244 QualType type = dst.getType();
2245 bool isBlock = type->isBlockPointerType();
2247 // Use a store barrier at -O0 unless this is a block type or the
2248 // lvalue is inadequately aligned.
2249 if (shouldUseFusedARCCalls() &&
2251 (dst.getAlignment().isZero() ||
2252 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2253 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2256 // Otherwise, split it out.
2258 // Retain the new value.
2259 newValue = EmitARCRetain(type, newValue);
2261 // Read the old value.
2262 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
2264 // Store. We do this before the release so that any deallocs won't
2265 // see the old value.
2266 EmitStoreOfScalar(newValue, dst);
2268 // Finally, release the old value.
2269 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2274 /// Autorelease the given object.
2275 /// call i8* \@objc_autorelease(i8* %value)
2276 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2277 return emitARCValueOperation(*this, value, nullptr,
2278 CGM.getObjCEntrypoints().objc_autorelease,
2279 llvm::Intrinsic::objc_autorelease);
2282 /// Autorelease the given object.
2283 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2285 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2286 return emitARCValueOperation(*this, value, nullptr,
2287 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
2288 llvm::Intrinsic::objc_autoreleaseReturnValue,
2289 /*isTailCall*/ true);
2292 /// Do a fused retain/autorelease of the given object.
2293 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2295 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2296 return emitARCValueOperation(*this, value, nullptr,
2297 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
2298 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
2299 /*isTailCall*/ true);
2302 /// Do a fused retain/autorelease of the given object.
2303 /// call i8* \@objc_retainAutorelease(i8* %value)
2305 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2306 /// call i8* \@objc_autorelease(i8* %retain)
2307 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2308 llvm::Value *value) {
2309 if (!type->isBlockPointerType())
2310 return EmitARCRetainAutoreleaseNonBlock(value);
2312 if (isa<llvm::ConstantPointerNull>(value)) return value;
2314 llvm::Type *origType = value->getType();
2315 value = Builder.CreateBitCast(value, Int8PtrTy);
2316 value = EmitARCRetainBlock(value, /*mandatory*/ true);
2317 value = EmitARCAutorelease(value);
2318 return Builder.CreateBitCast(value, origType);
2321 /// Do a fused retain/autorelease of the given object.
2322 /// call i8* \@objc_retainAutorelease(i8* %value)
2324 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2325 return emitARCValueOperation(*this, value, nullptr,
2326 CGM.getObjCEntrypoints().objc_retainAutorelease,
2327 llvm::Intrinsic::objc_retainAutorelease);
2330 /// i8* \@objc_loadWeak(i8** %addr)
2331 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2332 llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2333 return emitARCLoadOperation(*this, addr,
2334 CGM.getObjCEntrypoints().objc_loadWeak,
2335 llvm::Intrinsic::objc_loadWeak);
2338 /// i8* \@objc_loadWeakRetained(i8** %addr)
2339 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
2340 return emitARCLoadOperation(*this, addr,
2341 CGM.getObjCEntrypoints().objc_loadWeakRetained,
2342 llvm::Intrinsic::objc_loadWeakRetained);
2345 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2347 llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
2350 return emitARCStoreOperation(*this, addr, value,
2351 CGM.getObjCEntrypoints().objc_storeWeak,
2352 llvm::Intrinsic::objc_storeWeak, ignored);
2355 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2356 /// Returns %value. %addr is known to not have a current weak entry.
2357 /// Essentially equivalent to:
2358 /// *addr = nil; objc_storeWeak(addr, value);
2359 void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
2360 // If we're initializing to null, just write null to memory; no need
2361 // to get the runtime involved. But don't do this if optimization
2362 // is enabled, because accounting for this would make the optimizer
2363 // much more complicated.
2364 if (isa<llvm::ConstantPointerNull>(value) &&
2365 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2366 Builder.CreateStore(value, addr);
2370 emitARCStoreOperation(*this, addr, value,
2371 CGM.getObjCEntrypoints().objc_initWeak,
2372 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
2375 /// void \@objc_destroyWeak(i8** %addr)
2376 /// Essentially objc_storeWeak(addr, nil).
2377 void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
2378 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
2380 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2381 setARCRuntimeFunctionLinkage(CGM, fn);
2384 // Cast the argument to 'id*'.
2385 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2387 EmitNounwindRuntimeCall(fn, addr.getPointer());
2390 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2391 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2392 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2393 void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
2394 emitARCCopyOperation(*this, dst, src,
2395 CGM.getObjCEntrypoints().objc_moveWeak,
2396 llvm::Intrinsic::objc_moveWeak);
2399 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2400 /// Disregards the current value in %dest. Essentially
2401 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2402 void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
2403 emitARCCopyOperation(*this, dst, src,
2404 CGM.getObjCEntrypoints().objc_copyWeak,
2405 llvm::Intrinsic::objc_copyWeak);
2408 void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2410 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2411 Object = EmitObjCConsumeObject(Ty, Object);
2412 EmitARCStoreWeak(DstAddr, Object, false);
2415 void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2417 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2418 Object = EmitObjCConsumeObject(Ty, Object);
2419 EmitARCStoreWeak(DstAddr, Object, false);
2420 EmitARCDestroyWeak(SrcAddr);
2423 /// Produce the code to do a objc_autoreleasepool_push.
2424 /// call i8* \@objc_autoreleasePoolPush(void)
2425 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2426 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
2428 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2429 setARCRuntimeFunctionLinkage(CGM, fn);
2432 return EmitNounwindRuntimeCall(fn);
2435 /// Produce the code to do a primitive release.
2436 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
2437 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2438 assert(value->getType() == Int8PtrTy);
2440 if (getInvokeDest()) {
2441 // Call the runtime method not the intrinsic if we are handling exceptions
2442 llvm::Constant *&fn =
2443 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2445 llvm::FunctionType *fnType =
2446 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2447 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2448 setARCRuntimeFunctionLinkage(CGM, fn);
2451 // objc_autoreleasePoolPop can throw.
2452 EmitRuntimeCallOrInvoke(fn, value);
2454 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2456 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2457 setARCRuntimeFunctionLinkage(CGM, fn);
2460 EmitRuntimeCall(fn, value);
2464 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2465 /// Which is: [[NSAutoreleasePool alloc] init];
2466 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2467 /// init is declared as: - (id) init; in its NSObject super class.
2469 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2470 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2471 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2472 // [NSAutoreleasePool alloc]
2473 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2474 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2477 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2478 getContext().getObjCIdType(),
2479 AllocSel, Receiver, Args);
2482 Receiver = AllocRV.getScalarVal();
2483 II = &CGM.getContext().Idents.get("init");
2484 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2486 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2487 getContext().getObjCIdType(),
2488 InitSel, Receiver, Args);
2489 return InitRV.getScalarVal();
2492 /// Allocate the given objc object.
2493 /// call i8* \@objc_alloc(i8* %value)
2494 llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2495 llvm::Type *resultType) {
2496 return emitObjCValueOperation(*this, value, resultType,
2497 CGM.getObjCEntrypoints().objc_alloc,
2501 /// Allocate the given objc object.
2502 /// call i8* \@objc_allocWithZone(i8* %value)
2503 llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2504 llvm::Type *resultType) {
2505 return emitObjCValueOperation(*this, value, resultType,
2506 CGM.getObjCEntrypoints().objc_allocWithZone,
2507 "objc_allocWithZone");
2510 /// Produce the code to do a primitive release.
2512 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2513 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2514 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2516 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2517 getContext().VoidTy, DrainSel, Arg, Args);
2520 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2523 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2526 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2529 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2532 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2535 CGF.EmitARCDestroyWeak(addr);
2538 void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2540 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2541 CGF.EmitARCIntrinsicUse(value);
2544 /// Autorelease the given object.
2545 /// call i8* \@objc_autorelease(i8* %value)
2546 llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2547 llvm::Type *returnType) {
2548 return emitObjCValueOperation(*this, value, returnType,
2549 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2550 "objc_autorelease");
2553 /// Retain the given object, with normal retain semantics.
2554 /// call i8* \@objc_retain(i8* %value)
2555 llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2556 llvm::Type *returnType) {
2557 return emitObjCValueOperation(*this, value, returnType,
2558 CGM.getObjCEntrypoints().objc_retainRuntimeFunction,
2562 /// Release the given object.
2563 /// call void \@objc_release(i8* %value)
2564 void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2565 ARCPreciseLifetime_t precise) {
2566 if (isa<llvm::ConstantPointerNull>(value)) return;
2568 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
2571 llvm::FunctionType *fnType =
2572 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2573 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2574 setARCRuntimeFunctionLinkage(CGM, fn);
2575 // We have Native ARC, so set nonlazybind attribute for performance
2576 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2577 f->addFnAttr(llvm::Attribute::NonLazyBind);
2581 // Cast the argument to 'id'.
2582 value = Builder.CreateBitCast(value, Int8PtrTy);
2584 // Call objc_release.
2585 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2587 if (precise == ARCImpreciseLifetime) {
2588 call->setMetadata("clang.imprecise_release",
2589 llvm::MDNode::get(Builder.getContext(), None));
2594 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
2597 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2599 void Emit(CodeGenFunction &CGF, Flags flags) override {
2600 CGF.EmitObjCAutoreleasePoolPop(Token);
2603 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
2606 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2608 void Emit(CodeGenFunction &CGF, Flags flags) override {
2609 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2614 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2615 if (CGM.getLangOpts().ObjCAutoRefCount)
2616 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2618 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2621 static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2623 case Qualifiers::OCL_None:
2624 case Qualifiers::OCL_ExplicitNone:
2625 case Qualifiers::OCL_Strong:
2626 case Qualifiers::OCL_Autoreleasing:
2629 case Qualifiers::OCL_Weak:
2633 llvm_unreachable("impossible lifetime!");
2636 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2639 llvm::Value *result;
2640 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2642 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2644 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2645 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2647 return TryEmitResult(result, !shouldRetain);
2650 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2652 e = e->IgnoreParens();
2653 QualType type = e->getType();
2655 // If we're loading retained from a __strong xvalue, we can avoid
2656 // an extra retain/release pair by zeroing out the source of this
2657 // "move" operation.
2658 if (e->isXValue() &&
2659 !type.isConstQualified() &&
2660 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2662 LValue lv = CGF.EmitLValue(e);
2664 // Load the object pointer.
2665 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2666 SourceLocation()).getScalarVal();
2668 // Set the source pointer to NULL.
2669 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2671 return TryEmitResult(result, true);
2674 // As a very special optimization, in ARC++, if the l-value is the
2675 // result of a non-volatile assignment, do a simple retain of the
2676 // result of the call to objc_storeWeak instead of reloading.
2677 if (CGF.getLangOpts().CPlusPlus &&
2678 !type.isVolatileQualified() &&
2679 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2680 isa<BinaryOperator>(e) &&
2681 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2682 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2684 // Try to emit code for scalar constant instead of emitting LValue and
2685 // loading it because we are not guaranteed to have an l-value. One of such
2686 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2687 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2688 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2689 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2690 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2691 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2694 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2697 typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2698 llvm::Value *value)>
2701 /// Insert code immediately after a call.
2702 static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2704 ValueTransform doAfterCall,
2705 ValueTransform doFallback) {
2706 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2707 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2709 // Place the retain immediately following the call.
2710 CGF.Builder.SetInsertPoint(call->getParent(),
2711 ++llvm::BasicBlock::iterator(call));
2712 value = doAfterCall(CGF, value);
2714 CGF.Builder.restoreIP(ip);
2716 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2717 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2719 // Place the retain at the beginning of the normal destination block.
2720 llvm::BasicBlock *BB = invoke->getNormalDest();
2721 CGF.Builder.SetInsertPoint(BB, BB->begin());
2722 value = doAfterCall(CGF, value);
2724 CGF.Builder.restoreIP(ip);
2727 // Bitcasts can arise because of related-result returns. Rewrite
2729 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2730 llvm::Value *operand = bitcast->getOperand(0);
2731 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
2732 bitcast->setOperand(0, operand);
2735 // Generic fall-back case.
2737 // Retain using the non-block variant: we never need to do a copy
2738 // of a block that's been returned to us.
2739 return doFallback(CGF, value);
2743 /// Given that the given expression is some sort of call (which does
2744 /// not return retained), emit a retain following it.
2745 static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2747 llvm::Value *value = CGF.EmitScalarExpr(e);
2748 return emitARCOperationAfterCall(CGF, value,
2749 [](CodeGenFunction &CGF, llvm::Value *value) {
2750 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2752 [](CodeGenFunction &CGF, llvm::Value *value) {
2753 return CGF.EmitARCRetainNonBlock(value);
2757 /// Given that the given expression is some sort of call (which does
2758 /// not return retained), perform an unsafeClaim following it.
2759 static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2761 llvm::Value *value = CGF.EmitScalarExpr(e);
2762 return emitARCOperationAfterCall(CGF, value,
2763 [](CodeGenFunction &CGF, llvm::Value *value) {
2764 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2766 [](CodeGenFunction &CGF, llvm::Value *value) {
2771 llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2772 bool allowUnsafeClaim) {
2773 if (allowUnsafeClaim &&
2774 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2775 return emitARCUnsafeClaimCallResult(*this, E);
2777 llvm::Value *value = emitARCRetainCallResult(*this, E);
2778 return EmitObjCConsumeObject(E->getType(), value);
2782 /// Determine whether it might be important to emit a separate
2783 /// objc_retain_block on the result of the given expression, or
2784 /// whether it's okay to just emit it in a +1 context.
2785 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2786 assert(e->getType()->isBlockPointerType());
2787 e = e->IgnoreParens();
2789 // For future goodness, emit block expressions directly in +1
2790 // contexts if we can.
2791 if (isa<BlockExpr>(e))
2794 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2795 switch (cast->getCastKind()) {
2796 // Emitting these operations in +1 contexts is goodness.
2797 case CK_LValueToRValue:
2798 case CK_ARCReclaimReturnedObject:
2799 case CK_ARCConsumeObject:
2800 case CK_ARCProduceObject:
2803 // These operations preserve a block type.
2806 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2808 // These operations are known to be bad (or haven't been considered).
2809 case CK_AnyPointerToBlockPointerCast:
2819 /// A CRTP base class for emitting expressions of retainable object
2820 /// pointer type in ARC.
2821 template <typename Impl, typename Result> class ARCExprEmitter {
2823 CodeGenFunction &CGF;
2824 Impl &asImpl() { return *static_cast<Impl*>(this); }
2826 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2829 Result visit(const Expr *e);
2830 Result visitCastExpr(const CastExpr *e);
2831 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2832 Result visitBinaryOperator(const BinaryOperator *e);
2833 Result visitBinAssign(const BinaryOperator *e);
2834 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2835 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2836 Result visitBinAssignWeak(const BinaryOperator *e);
2837 Result visitBinAssignStrong(const BinaryOperator *e);
2839 // Minimal implementation:
2840 // Result visitLValueToRValue(const Expr *e)
2841 // Result visitConsumeObject(const Expr *e)
2842 // Result visitExtendBlockObject(const Expr *e)
2843 // Result visitReclaimReturnedObject(const Expr *e)
2844 // Result visitCall(const Expr *e)
2845 // Result visitExpr(const Expr *e)
2847 // Result emitBitCast(Result result, llvm::Type *resultType)
2848 // llvm::Value *getValueOfResult(Result result)
2852 /// Try to emit a PseudoObjectExpr under special ARC rules.
2854 /// This massively duplicates emitPseudoObjectRValue.
2855 template <typename Impl, typename Result>
2857 ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
2858 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2860 // Find the result expression.
2861 const Expr *resultExpr = E->getResultExpr();
2865 for (PseudoObjectExpr::const_semantics_iterator
2866 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2867 const Expr *semantic = *i;
2869 // If this semantic expression is an opaque value, bind it
2870 // to the result of its source expression.
2871 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2872 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2875 // If this semantic is the result of the pseudo-object
2876 // expression, try to evaluate the source as +1.
2877 if (ov == resultExpr) {
2878 assert(!OVMA::shouldBindAsLValue(ov));
2879 result = asImpl().visit(ov->getSourceExpr());
2880 opaqueData = OVMA::bind(CGF, ov,
2881 RValue::get(asImpl().getValueOfResult(result)));
2883 // Otherwise, just bind it.
2885 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2887 opaques.push_back(opaqueData);
2889 // Otherwise, if the expression is the result, evaluate it
2890 // and remember the result.
2891 } else if (semantic == resultExpr) {
2892 result = asImpl().visit(semantic);
2894 // Otherwise, evaluate the expression in an ignored context.
2896 CGF.EmitIgnoredExpr(semantic);
2900 // Unbind all the opaques now.
2901 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2902 opaques[i].unbind(CGF);
2907 template <typename Impl, typename Result>
2908 Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2909 switch (e->getCastKind()) {
2911 // No-op casts don't change the type, so we just ignore them.
2913 return asImpl().visit(e->getSubExpr());
2915 // These casts can change the type.
2916 case CK_CPointerToObjCPointerCast:
2917 case CK_BlockPointerToObjCPointerCast:
2918 case CK_AnyPointerToBlockPointerCast:
2920 llvm::Type *resultType = CGF.ConvertType(e->getType());
2921 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2922 Result result = asImpl().visit(e->getSubExpr());
2923 return asImpl().emitBitCast(result, resultType);
2926 // Handle some casts specially.
2927 case CK_LValueToRValue:
2928 return asImpl().visitLValueToRValue(e->getSubExpr());
2929 case CK_ARCConsumeObject:
2930 return asImpl().visitConsumeObject(e->getSubExpr());
2931 case CK_ARCExtendBlockObject:
2932 return asImpl().visitExtendBlockObject(e->getSubExpr());
2933 case CK_ARCReclaimReturnedObject:
2934 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2936 // Otherwise, use the default logic.
2938 return asImpl().visitExpr(e);
2942 template <typename Impl, typename Result>
2944 ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2945 switch (e->getOpcode()) {
2947 CGF.EmitIgnoredExpr(e->getLHS());
2948 CGF.EnsureInsertPoint();
2949 return asImpl().visit(e->getRHS());
2952 return asImpl().visitBinAssign(e);
2955 return asImpl().visitExpr(e);
2959 template <typename Impl, typename Result>
2960 Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2961 switch (e->getLHS()->getType().getObjCLifetime()) {
2962 case Qualifiers::OCL_ExplicitNone:
2963 return asImpl().visitBinAssignUnsafeUnretained(e);
2965 case Qualifiers::OCL_Weak:
2966 return asImpl().visitBinAssignWeak(e);
2968 case Qualifiers::OCL_Autoreleasing:
2969 return asImpl().visitBinAssignAutoreleasing(e);
2971 case Qualifiers::OCL_Strong:
2972 return asImpl().visitBinAssignStrong(e);
2974 case Qualifiers::OCL_None:
2975 return asImpl().visitExpr(e);
2977 llvm_unreachable("bad ObjC ownership qualifier");
2980 /// The default rule for __unsafe_unretained emits the RHS recursively,
2981 /// stores into the unsafe variable, and propagates the result outward.
2982 template <typename Impl, typename Result>
2983 Result ARCExprEmitter<Impl,Result>::
2984 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2985 // Recursively emit the RHS.
2986 // For __block safety, do this before emitting the LHS.
2987 Result result = asImpl().visit(e->getRHS());
2989 // Perform the store.
2991 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2992 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2998 template <typename Impl, typename Result>
3000 ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3001 return asImpl().visitExpr(e);
3004 template <typename Impl, typename Result>
3006 ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3007 return asImpl().visitExpr(e);
3010 template <typename Impl, typename Result>
3012 ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3013 return asImpl().visitExpr(e);
3016 /// The general expression-emission logic.
3017 template <typename Impl, typename Result>
3018 Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3019 // We should *never* see a nested full-expression here, because if
3020 // we fail to emit at +1, our caller must not retain after we close
3021 // out the full-expression. This isn't as important in the unsafe
3023 assert(!isa<ExprWithCleanups>(e));
3025 // Look through parens, __extension__, generic selection, etc.
3026 e = e->IgnoreParens();
3028 // Handle certain kinds of casts.
3029 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3030 return asImpl().visitCastExpr(ce);
3032 // Handle the comma operator.
3033 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3034 return asImpl().visitBinaryOperator(op);
3036 // TODO: handle conditional operators here
3038 // For calls and message sends, use the retained-call logic.
3039 // Delegate inits are a special case in that they're the only
3040 // returns-retained expression that *isn't* surrounded by
3042 } else if (isa<CallExpr>(e) ||
3043 (isa<ObjCMessageExpr>(e) &&
3044 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3045 return asImpl().visitCall(e);
3047 // Look through pseudo-object expressions.
3048 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3049 return asImpl().visitPseudoObjectExpr(pseudo);
3052 return asImpl().visitExpr(e);
3057 /// An emitter for +1 results.
3058 struct ARCRetainExprEmitter :
3059 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3061 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3063 llvm::Value *getValueOfResult(TryEmitResult result) {
3064 return result.getPointer();
3067 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3068 llvm::Value *value = result.getPointer();
3069 value = CGF.Builder.CreateBitCast(value, resultType);
3070 result.setPointer(value);
3074 TryEmitResult visitLValueToRValue(const Expr *e) {
3075 return tryEmitARCRetainLoadOfScalar(CGF, e);
3078 /// For consumptions, just emit the subexpression and thus elide
3079 /// the retain/release pair.
3080 TryEmitResult visitConsumeObject(const Expr *e) {
3081 llvm::Value *result = CGF.EmitScalarExpr(e);
3082 return TryEmitResult(result, true);
3085 /// Block extends are net +0. Naively, we could just recurse on
3086 /// the subexpression, but actually we need to ensure that the
3087 /// value is copied as a block, so there's a little filter here.
3088 TryEmitResult visitExtendBlockObject(const Expr *e) {
3089 llvm::Value *result; // will be a +0 value
3091 // If we can't safely assume the sub-expression will produce a
3092 // block-copied value, emit the sub-expression at +0.
3093 if (shouldEmitSeparateBlockRetain(e)) {
3094 result = CGF.EmitScalarExpr(e);
3096 // Otherwise, try to emit the sub-expression at +1 recursively.
3098 TryEmitResult subresult = asImpl().visit(e);
3100 // If that produced a retained value, just use that.
3101 if (subresult.getInt()) {
3105 // Otherwise it's +0.
3106 result = subresult.getPointer();
3109 // Retain the object as a block.
3110 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3111 return TryEmitResult(result, true);
3114 /// For reclaims, emit the subexpression as a retained call and
3115 /// skip the consumption.
3116 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3117 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3118 return TryEmitResult(result, true);
3121 /// When we have an undecorated call, retroactively do a claim.
3122 TryEmitResult visitCall(const Expr *e) {
3123 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3124 return TryEmitResult(result, true);
3127 // TODO: maybe special-case visitBinAssignWeak?
3129 TryEmitResult visitExpr(const Expr *e) {
3130 // We didn't find an obvious production, so emit what we've got and
3131 // tell the caller that we didn't manage to retain.
3132 llvm::Value *result = CGF.EmitScalarExpr(e);
3133 return TryEmitResult(result, false);
3138 static TryEmitResult
3139 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3140 return ARCRetainExprEmitter(CGF).visit(e);
3143 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3146 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3147 llvm::Value *value = result.getPointer();
3148 if (!result.getInt())
3149 value = CGF.EmitARCRetain(type, value);
3153 /// EmitARCRetainScalarExpr - Semantically equivalent to
3154 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3155 /// best-effort attempt to peephole expressions that naturally produce
3156 /// retained objects.
3157 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
3158 // The retain needs to happen within the full-expression.
3159 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3160 enterFullExpression(cleanups);
3161 RunCleanupsScope scope(*this);
3162 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3165 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3166 llvm::Value *value = result.getPointer();
3167 if (!result.getInt())
3168 value = EmitARCRetain(e->getType(), value);
3173 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
3174 // The retain needs to happen within the full-expression.
3175 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3176 enterFullExpression(cleanups);
3177 RunCleanupsScope scope(*this);
3178 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3181 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3182 llvm::Value *value = result.getPointer();
3183 if (result.getInt())
3184 value = EmitARCAutorelease(value);
3186 value = EmitARCRetainAutorelease(e->getType(), value);
3190 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3191 llvm::Value *result;
3194 if (shouldEmitSeparateBlockRetain(e)) {
3195 result = EmitScalarExpr(e);
3198 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3199 result = subresult.getPointer();
3200 doRetain = !subresult.getInt();
3204 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3205 return EmitObjCConsumeObject(e->getType(), result);
3208 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3209 // In ARC, retain and autorelease the expression.
3210 if (getLangOpts().ObjCAutoRefCount) {
3211 // Do so before running any cleanups for the full-expression.
3212 // EmitARCRetainAutoreleaseScalarExpr does this for us.
3213 return EmitARCRetainAutoreleaseScalarExpr(expr);
3216 // Otherwise, use the normal scalar-expression emission. The
3217 // exception machinery doesn't do anything special with the
3218 // exception like retaining it, so there's no safety associated with
3219 // only running cleanups after the throw has started, and when it
3220 // matters it tends to be substantially inferior code.
3221 return EmitScalarExpr(expr);
3226 /// An emitter for assigning into an __unsafe_unretained context.
3227 struct ARCUnsafeUnretainedExprEmitter :
3228 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3230 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3232 llvm::Value *getValueOfResult(llvm::Value *value) {
3236 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3237 return CGF.Builder.CreateBitCast(value, resultType);
3240 llvm::Value *visitLValueToRValue(const Expr *e) {
3241 return CGF.EmitScalarExpr(e);
3244 /// For consumptions, just emit the subexpression and perform the
3245 /// consumption like normal.
3246 llvm::Value *visitConsumeObject(const Expr *e) {
3247 llvm::Value *value = CGF.EmitScalarExpr(e);
3248 return CGF.EmitObjCConsumeObject(e->getType(), value);
3251 /// No special logic for block extensions. (This probably can't
3252 /// actually happen in this emitter, though.)
3253 llvm::Value *visitExtendBlockObject(const Expr *e) {
3254 return CGF.EmitARCExtendBlockObject(e);
3257 /// For reclaims, perform an unsafeClaim if that's enabled.
3258 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3259 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3262 /// When we have an undecorated call, just emit it without adding
3263 /// the unsafeClaim.
3264 llvm::Value *visitCall(const Expr *e) {
3265 return CGF.EmitScalarExpr(e);
3268 /// Just do normal scalar emission in the default case.
3269 llvm::Value *visitExpr(const Expr *e) {
3270 return CGF.EmitScalarExpr(e);
3275 static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3277 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3280 /// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3281 /// immediately releasing the resut of EmitARCRetainScalarExpr, but
3282 /// avoiding any spurious retains, including by performing reclaims
3283 /// with objc_unsafeClaimAutoreleasedReturnValue.
3284 llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3285 // Look through full-expressions.
3286 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3287 enterFullExpression(cleanups);
3288 RunCleanupsScope scope(*this);
3289 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3292 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3295 std::pair<LValue,llvm::Value*>
3296 CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3298 // Evaluate the RHS first. If we're ignoring the result, assume
3299 // that we can emit at an unsafe +0.
3302 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3304 value = EmitScalarExpr(e->getRHS());
3307 // Emit the LHS and perform the store.
3308 LValue lvalue = EmitLValue(e->getLHS());
3309 EmitStoreOfScalar(value, lvalue);
3311 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3314 std::pair<LValue,llvm::Value*>
3315 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3317 // Evaluate the RHS first.
3318 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3319 llvm::Value *value = result.getPointer();
3321 bool hasImmediateRetain = result.getInt();
3323 // If we didn't emit a retained object, and the l-value is of block
3324 // type, then we need to emit the block-retain immediately in case
3325 // it invalidates the l-value.
3326 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
3327 value = EmitARCRetainBlock(value, /*mandatory*/ false);
3328 hasImmediateRetain = true;
3331 LValue lvalue = EmitLValue(e->getLHS());
3333 // If the RHS was emitted retained, expand this.
3334 if (hasImmediateRetain) {
3335 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
3336 EmitStoreOfScalar(value, lvalue);
3337 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
3339 value = EmitARCStoreStrong(lvalue, value, ignored);
3342 return std::pair<LValue,llvm::Value*>(lvalue, value);
3345 std::pair<LValue,llvm::Value*>
3346 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3347 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3348 LValue lvalue = EmitLValue(e->getLHS());
3350 EmitStoreOfScalar(value, lvalue);
3352 return std::pair<LValue,llvm::Value*>(lvalue, value);
3355 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
3356 const ObjCAutoreleasePoolStmt &ARPS) {
3357 const Stmt *subStmt = ARPS.getSubStmt();
3358 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3360 CGDebugInfo *DI = getDebugInfo();
3362 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
3364 // Keep track of the current cleanup stack depth.
3365 RunCleanupsScope Scope(*this);
3366 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
3367 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3368 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3370 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3371 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3374 for (const auto *I : S.body())
3378 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
3381 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3382 /// make sure it survives garbage collection until this point.
3383 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3384 // We just use an inline assembly.
3385 llvm::FunctionType *extenderType
3386 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
3387 llvm::Value *extender
3388 = llvm::InlineAsm::get(extenderType,
3390 /* constraints */ "r",
3391 /* side effects */ true);
3393 object = Builder.CreateBitCast(object, VoidPtrTy);
3394 EmitNounwindRuntimeCall(extender, object);
3397 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
3398 /// non-trivial copy assignment function, produce following helper function.
3399 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3402 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3403 const ObjCPropertyImplDecl *PID) {
3404 if (!getLangOpts().CPlusPlus ||
3405 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3407 QualType Ty = PID->getPropertyIvarDecl()->getType();
3408 if (!Ty->isRecordType())
3410 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3411 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3413 llvm::Constant *HelperFn = nullptr;
3414 if (hasTrivialSetExpr(PID))
3416 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3417 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3420 ASTContext &C = getContext();
3422 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
3424 QualType ReturnTy = C.VoidTy;
3425 QualType DestTy = C.getPointerType(Ty);
3426 QualType SrcTy = Ty;
3428 SrcTy = C.getPointerType(SrcTy);
3430 SmallVector<QualType, 2> ArgTys;
3431 ArgTys.push_back(DestTy);
3432 ArgTys.push_back(SrcTy);
3433 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3435 FunctionDecl *FD = FunctionDecl::Create(
3436 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3437 FunctionTy, nullptr, SC_Static, false, false);
3439 FunctionArgList args;
3440 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3441 ImplicitParamDecl::Other);
3442 args.push_back(&DstDecl);
3443 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3444 ImplicitParamDecl::Other);
3445 args.push_back(&SrcDecl);
3447 const CGFunctionInfo &FI =
3448 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3450 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3452 llvm::Function *Fn =
3453 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3454 "__assign_helper_atomic_property_",
3457 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3459 StartFunction(FD, ReturnTy, Fn, FI, args);
3461 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3463 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3464 VK_LValue, OK_Ordinary, SourceLocation(), false);
3466 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3468 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3469 VK_LValue, OK_Ordinary, SourceLocation(), false);
3471 Expr *Args[2] = { &DST, &SRC };
3472 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
3473 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3474 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3475 VK_LValue, SourceLocation(), FPOptions());
3480 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3481 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
3486 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3487 const ObjCPropertyImplDecl *PID) {
3488 if (!getLangOpts().CPlusPlus ||
3489 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
3491 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3492 QualType Ty = PD->getType();
3493 if (!Ty->isRecordType())
3495 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
3497 llvm::Constant *HelperFn = nullptr;
3498 if (hasTrivialGetExpr(PID))
3500 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3501 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3504 ASTContext &C = getContext();
3505 IdentifierInfo *II =
3506 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3508 QualType ReturnTy = C.VoidTy;
3509 QualType DestTy = C.getPointerType(Ty);
3510 QualType SrcTy = Ty;
3512 SrcTy = C.getPointerType(SrcTy);
3514 SmallVector<QualType, 2> ArgTys;
3515 ArgTys.push_back(DestTy);
3516 ArgTys.push_back(SrcTy);
3517 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3519 FunctionDecl *FD = FunctionDecl::Create(
3520 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3521 FunctionTy, nullptr, SC_Static, false, false);
3523 FunctionArgList args;
3524 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3525 ImplicitParamDecl::Other);
3526 args.push_back(&DstDecl);
3527 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3528 ImplicitParamDecl::Other);
3529 args.push_back(&SrcDecl);
3531 const CGFunctionInfo &FI =
3532 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
3534 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
3536 llvm::Function *Fn = llvm::Function::Create(
3537 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3540 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
3542 StartFunction(FD, ReturnTy, Fn, FI, args);
3544 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3547 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3548 VK_LValue, OK_Ordinary, SourceLocation(), false);
3550 CXXConstructExpr *CXXConstExpr =
3551 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3553 SmallVector<Expr*, 4> ConstructorArgs;
3554 ConstructorArgs.push_back(&SRC);
3555 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3556 CXXConstExpr->arg_end());
3558 CXXConstructExpr *TheCXXConstructExpr =
3559 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3560 CXXConstExpr->getConstructor(),
3561 CXXConstExpr->isElidable(),
3563 CXXConstExpr->hadMultipleCandidates(),
3564 CXXConstExpr->isListInitialization(),
3565 CXXConstExpr->isStdInitListInitialization(),
3566 CXXConstExpr->requiresZeroInitialization(),
3567 CXXConstExpr->getConstructionKind(),
3570 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3573 RValue DV = EmitAnyExpr(&DstExpr);
3575 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
3576 EmitAggExpr(TheCXXConstructExpr,
3577 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3579 AggValueSlot::IsDestructed,
3580 AggValueSlot::DoesNotNeedGCBarriers,
3581 AggValueSlot::IsNotAliased,
3582 AggValueSlot::DoesNotOverlap));
3585 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3586 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3591 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3592 // Get selectors for retain/autorelease.
3593 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3594 Selector CopySelector =
3595 getContext().Selectors.getNullarySelector(CopyID);
3596 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3597 Selector AutoreleaseSelector =
3598 getContext().Selectors.getNullarySelector(AutoreleaseID);
3600 // Emit calls to retain/autorelease.
3601 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3602 llvm::Value *Val = Block;
3604 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3606 Val, CallArgList(), nullptr, nullptr);
3607 Val = Result.getScalarVal();
3608 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3609 Ty, AutoreleaseSelector,
3610 Val, CallArgList(), nullptr, nullptr);
3611 Val = Result.getScalarVal();
3616 CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3617 assert(Args.size() == 3 && "Expected 3 argument here!");
3619 if (!CGM.IsOSVersionAtLeastFn) {
3620 llvm::FunctionType *FTy =
3621 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3622 CGM.IsOSVersionAtLeastFn =
3623 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3626 llvm::Value *CallRes =
3627 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3629 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3632 void CodeGenModule::emitAtAvailableLinkGuard() {
3633 if (!IsOSVersionAtLeastFn)
3635 // @available requires CoreFoundation only on Darwin.
3636 if (!Target.getTriple().isOSDarwin())
3638 // Add -framework CoreFoundation to the linker commands. We still want to
3639 // emit the core foundation reference down below because otherwise if
3640 // CoreFoundation is not used in the code, the linker won't link the
3642 auto &Context = getLLVMContext();
3643 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3644 llvm::MDString::get(Context, "CoreFoundation")};
3645 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3646 // Emit a reference to a symbol from CoreFoundation to ensure that
3647 // CoreFoundation is linked into the final binary.
3648 llvm::FunctionType *FTy =
3649 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3650 llvm::Constant *CFFunc =
3651 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3653 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3654 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3655 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3656 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3657 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3658 CodeGenFunction CGF(*this);
3659 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3660 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3661 CGF.Builder.CreateUnreachable();
3662 addCompilerUsedGlobal(CFLinkCheckFunc);
3665 CGObjCRuntime::~CGObjCRuntime() {}