1//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGObjCRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "ConstantEmitter.h"
18#include "TargetInfo.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/StmtObjC.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/CodeGen/CGFunctionInfo.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Analysis/ObjCARCUtil.h"
27#include "llvm/BinaryFormat/MachO.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InlineAsm.h"
30using namespace clang;
31using namespace CodeGen;
32
33typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
34static TryEmitResult
35tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
36static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
37 QualType ET,
38 RValue Result);
39
40/// Given the address of a variable of pointer type, find the correct
41/// null to store into it.
42static llvm::Constant *getNullForVariable(Address addr) {
43 llvm::Type *type = addr.getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
47/// Emits an instance of NSConstantString representing the object.
48llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
49{
50 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
52 // FIXME: This bitcast should just be made an invariant on the Runtime.
53 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
54}
55
56/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
59/// or [NSValue valueWithBytes:objCType:].
60///
61llvm::Value *
62CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
63 // Generate the correct selector for this literal's concrete type.
64 // Get the method.
65 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
66 const Expr *SubExpr = E->getSubExpr();
67
68 if (E->isExpressibleAsConstantInitializer()) {
69 ConstantEmitter ConstEmitter(CGM);
70 return ConstEmitter.tryEmitAbstract(E, E->getType());
71 }
72
73 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
74 Selector Sel = BoxingMethod->getSelector();
75
76 // Generate a reference to the class pointer, which will be the receiver.
77 // Assumes that the method was introduced in the class that should be
78 // messaged (avoids pulling it out of the result type).
79 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
80 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
81 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
82
83 CallArgList Args;
84 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
85 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
86
87 // ObjCBoxedExpr supports boxing of structs and unions
88 // via [NSValue valueWithBytes:objCType:]
89 const QualType ValueType(SubExpr->getType().getCanonicalType());
90 if (ValueType->isObjCBoxableRecordType()) {
91 // Emit CodeGen for first parameter
92 // and cast value to correct type
93 Address Temporary = CreateMemTemp(SubExpr->getType());
94 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
95 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
96 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
97
98 // Create char array to store type encoding
99 std::string Str;
100 getContext().getObjCEncodingForType(ValueType, Str);
101 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
102
103 // Cast type encoding to correct type
104 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
105 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
106 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
107
108 Args.add(RValue::get(Cast), EncodingQT);
109 } else {
110 Args.add(EmitAnyExpr(SubExpr), ArgQT);
111 }
112
113 RValue result = Runtime.GenerateMessageSend(
114 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
115 Args, ClassDecl, BoxingMethod);
116 return Builder.CreateBitCast(result.getScalarVal(),
117 ConvertType(E->getType()));
118}
119
120llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
121 const ObjCMethodDecl *MethodWithObjects) {
122 ASTContext &Context = CGM.getContext();
123 const ObjCDictionaryLiteral *DLE = nullptr;
124 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
125 if (!ALE)
126 DLE = cast<ObjCDictionaryLiteral>(E);
127
128 // Optimize empty collections by referencing constants, when available.
129 uint64_t NumElements =
130 ALE ? ALE->getNumElements() : DLE->getNumElements();
131 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
132 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
133 QualType IdTy(CGM.getContext().getObjCIdType());
134 llvm::Constant *Constant =
135 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
136 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
137 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
138 cast<llvm::LoadInst>(Ptr)->setMetadata(
139 CGM.getModule().getMDKindID("invariant.load"),
140 llvm::MDNode::get(getLLVMContext(), None));
141 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
142 }
143
144 // Compute the type of the array we're initializing.
145 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
146 NumElements);
147 QualType ElementType = Context.getObjCIdType().withConst();
148 QualType ElementArrayType
149 = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
150 ArrayType::Normal, /*IndexTypeQuals=*/0);
151
152 // Allocate the temporary array(s).
153 Address Objects = CreateMemTemp(ElementArrayType, "objects");
154 Address Keys = Address::invalid();
155 if (DLE)
156 Keys = CreateMemTemp(ElementArrayType, "keys");
157
158 // In ARC, we may need to do extra work to keep all the keys and
159 // values alive until after the call.
160 SmallVector<llvm::Value *, 16> NeededObjects;
161 bool TrackNeededObjects =
162 (getLangOpts().ObjCAutoRefCount &&
163 CGM.getCodeGenOpts().OptimizationLevel != 0);
164
165 // Perform the actual initialialization of the array(s).
166 for (uint64_t i = 0; i < NumElements; i++) {
167 if (ALE) {
168 // Emit the element and store it to the appropriate array slot.
169 const Expr *Rhs = ALE->getElement(i);
170 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
171 ElementType, AlignmentSource::Decl);
172
173 llvm::Value *value = EmitScalarExpr(Rhs);
174 EmitStoreThroughLValue(RValue::get(value), LV, true);
175 if (TrackNeededObjects) {
176 NeededObjects.push_back(value);
177 }
178 } else {
179 // Emit the key and store it to the appropriate array slot.
180 const Expr *Key = DLE->getKeyValueElement(i).Key;
181 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
182 ElementType, AlignmentSource::Decl);
183 llvm::Value *keyValue = EmitScalarExpr(Key);
184 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
185
186 // Emit the value and store it to the appropriate array slot.
187 const Expr *Value = DLE->getKeyValueElement(i).Value;
188 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
189 ElementType, AlignmentSource::Decl);
190 llvm::Value *valueValue = EmitScalarExpr(Value);
191 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
192 if (TrackNeededObjects) {
193 NeededObjects.push_back(keyValue);
194 NeededObjects.push_back(valueValue);
195 }
196 }
197 }
198
199 // Generate the argument list.
200 CallArgList Args;
201 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
202 const ParmVarDecl *argDecl = *PI++;
203 QualType ArgQT = argDecl->getType().getUnqualifiedType();
204 Args.add(RValue::get(Objects.getPointer()), ArgQT);
205 if (DLE) {
206 argDecl = *PI++;
207 ArgQT = argDecl->getType().getUnqualifiedType();
208 Args.add(RValue::get(Keys.getPointer()), ArgQT);
209 }
210 argDecl = *PI;
211 ArgQT = argDecl->getType().getUnqualifiedType();
212 llvm::Value *Count =
213 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
214 Args.add(RValue::get(Count), ArgQT);
215
216 // Generate a reference to the class pointer, which will be the receiver.
217 Selector Sel = MethodWithObjects->getSelector();
218 QualType ResultType = E->getType();
219 const ObjCObjectPointerType *InterfacePointerType
220 = ResultType->getAsObjCInterfacePointerType();
221 ObjCInterfaceDecl *Class
222 = InterfacePointerType->getObjectType()->getInterface();
223 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
224 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
225
226 // Generate the message send.
227 RValue result = Runtime.GenerateMessageSend(
228 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
229 Receiver, Args, Class, MethodWithObjects);
230
231 // The above message send needs these objects, but in ARC they are
232 // passed in a buffer that is essentially __unsafe_unretained.
233 // Therefore we must prevent the optimizer from releasing them until
234 // after the call.
235 if (TrackNeededObjects) {
236 EmitARCIntrinsicUse(NeededObjects);
237 }
238
239 return Builder.CreateBitCast(result.getScalarVal(),
240 ConvertType(E->getType()));
241}
242
243llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
244 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
245}
246
247llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
248 const ObjCDictionaryLiteral *E) {
249 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
250}
251
252/// Emit a selector.
253llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
254 // Untyped selector.
255 // Note that this implementation allows for non-constant strings to be passed
256 // as arguments to @selector(). Currently, the only thing preventing this
257 // behaviour is the type checking in the front end.
258 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
259}
260
261llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
262 // FIXME: This should pass the Decl not the name.
263 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
264}
265
266/// Adjust the type of an Objective-C object that doesn't match up due
267/// to type erasure at various points, e.g., related result types or the use
268/// of parameterized classes.
269static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
270 RValue Result) {
271 if (!ExpT->isObjCRetainableType())
272 return Result;
273
274 // If the converted types are the same, we're done.
275 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
276 if (ExpLLVMTy == Result.getScalarVal()->getType())
277 return Result;
278
279 // We have applied a substitution. Cast the rvalue appropriately.
280 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
281 ExpLLVMTy));
282}
283
284/// Decide whether to extend the lifetime of the receiver of a
285/// returns-inner-pointer message.
286static bool
287shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
288 switch (message->getReceiverKind()) {
289
290 // For a normal instance message, we should extend unless the
291 // receiver is loaded from a variable with precise lifetime.
292 case ObjCMessageExpr::Instance: {
293 const Expr *receiver = message->getInstanceReceiver();
294
295 // Look through OVEs.
296 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
297 if (opaque->getSourceExpr())
298 receiver = opaque->getSourceExpr()->IgnoreParens();
299 }
300
301 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
302 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
303 receiver = ice->getSubExpr()->IgnoreParens();
304
305 // Look through OVEs.
306 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
307 if (opaque->getSourceExpr())
308 receiver = opaque->getSourceExpr()->IgnoreParens();
309 }
310
311 // Only __strong variables.
312 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
313 return true;
314
315 // All ivars and fields have precise lifetime.
316 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
317 return false;
318
319 // Otherwise, check for variables.
320 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
321 if (!declRef) return true;
322 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
323 if (!var) return true;
324
325 // All variables have precise lifetime except local variables with
326 // automatic storage duration that aren't specially marked.
327 return (var->hasLocalStorage() &&
328 !var->hasAttr<ObjCPreciseLifetimeAttr>());
329 }
330
331 case ObjCMessageExpr::Class:
332 case ObjCMessageExpr::SuperClass:
333 // It's never necessary for class objects.
334 return false;
335
336 case ObjCMessageExpr::SuperInstance:
337 // We generally assume that 'self' lives throughout a method call.
338 return false;
339 }
340
341 llvm_unreachable("invalid receiver kind");
342}
343
344/// Given an expression of ObjC pointer type, check whether it was
345/// immediately loaded from an ARC __weak l-value.
346static const Expr *findWeakLValue(const Expr *E) {
347 assert(E->getType()->isObjCRetainableType());
348 E = E->IgnoreParens();
349 if (auto CE = dyn_cast<CastExpr>(E)) {
350 if (CE->getCastKind() == CK_LValueToRValue) {
351 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
352 return CE->getSubExpr();
353 }
354 }
355
356 return nullptr;
357}
358
359/// The ObjC runtime may provide entrypoints that are likely to be faster
360/// than an ordinary message send of the appropriate selector.
361///
362/// The entrypoints are guaranteed to be equivalent to just sending the
363/// corresponding message. If the entrypoint is implemented naively as just a
364/// message send, using it is a trade-off: it sacrifices a few cycles of
365/// overhead to save a small amount of code. However, it's possible for
366/// runtimes to detect and special-case classes that use "standard"
367/// behavior; if that's dynamically a large proportion of all objects, using
368/// the entrypoint will also be faster than using a message send.
369///
370/// If the runtime does support a required entrypoint, then this method will
371/// generate a call and return the resulting value. Otherwise it will return
372/// None and the caller can generate a msgSend instead.
373static Optional<llvm::Value *>
374tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
375 llvm::Value *Receiver,
376 const CallArgList& Args, Selector Sel,
377 const ObjCMethodDecl *method,
378 bool isClassMessage) {
379 auto &CGM = CGF.CGM;
380 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
381 return None;
382
383 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
384 switch (Sel.getMethodFamily()) {
385 case OMF_alloc:
386 if (isClassMessage &&
387 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
388 ResultType->isObjCObjectPointerType()) {
389 // [Foo alloc] -> objc_alloc(Foo) or
390 // [self alloc] -> objc_alloc(self)
391 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
392 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
393 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
394 // [self allocWithZone:nil] -> objc_allocWithZone(self)
395 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
396 Args.size() == 1 && Args.front().getType()->isPointerType() &&
397 Sel.getNameForSlot(0) == "allocWithZone") {
398 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
399 if (isa<llvm::ConstantPointerNull>(arg))
400 return CGF.EmitObjCAllocWithZone(Receiver,
401 CGF.ConvertType(ResultType));
402 return None;
403 }
404 }
405 break;
406
407 case OMF_autorelease:
408 if (ResultType->isObjCObjectPointerType() &&
409 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
410 Runtime.shouldUseARCFunctionsForRetainRelease())
411 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
412 break;
413
414 case OMF_retain:
415 if (ResultType->isObjCObjectPointerType() &&
416 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
417 Runtime.shouldUseARCFunctionsForRetainRelease())
418 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
419 break;
420
421 case OMF_release:
422 if (ResultType->isVoidType() &&
423 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
424 Runtime.shouldUseARCFunctionsForRetainRelease()) {
425 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
426 return nullptr;
427 }
428 break;
429
430 default:
431 break;
432 }
433 return None;
434}
435
436CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
437 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
438 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
439 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
440 bool isClassMessage) {
441 if (Optional<llvm::Value *> SpecializedResult =
442 tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
443 Sel, Method, isClassMessage)) {
444 return RValue::get(SpecializedResult.getValue());
445 }
446 return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
447 Method);
448}
449
450static void AppendFirstImpliedRuntimeProtocols(
451 const ObjCProtocolDecl *PD,
452 llvm::UniqueVector<const ObjCProtocolDecl *> &PDs) {
453 if (!PD->isNonRuntimeProtocol()) {
454 const auto *Can = PD->getCanonicalDecl();
455 PDs.insert(Can);
456 return;
457 }
458
459 for (const auto *ParentPD : PD->protocols())
460 AppendFirstImpliedRuntimeProtocols(ParentPD, PDs);
461}
462
463std::vector<const ObjCProtocolDecl *>
464CGObjCRuntime::GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
465 ObjCProtocolDecl::protocol_iterator end) {
466 std::vector<const ObjCProtocolDecl *> RuntimePds;
467 llvm::DenseSet<const ObjCProtocolDecl *> NonRuntimePDs;
468
469 for (; begin != end; ++begin) {
470 const auto *It = *begin;
471 const auto *Can = It->getCanonicalDecl();
472 if (Can->isNonRuntimeProtocol())
473 NonRuntimePDs.insert(Can);
474 else
475 RuntimePds.push_back(Can);
476 }
477
478 // If there are no non-runtime protocols then we can just stop now.
479 if (NonRuntimePDs.empty())
480 return RuntimePds;
481
482 // Else we have to search through the non-runtime protocol's inheritancy
483 // hierarchy DAG stopping whenever a branch either finds a runtime protocol or
484 // a non-runtime protocol without any parents. These are the "first-implied"
485 // protocols from a non-runtime protocol.
486 llvm::UniqueVector<const ObjCProtocolDecl *> FirstImpliedProtos;
487 for (const auto *PD : NonRuntimePDs)
488 AppendFirstImpliedRuntimeProtocols(PD, FirstImpliedProtos);
489
490 // Walk the Runtime list to get all protocols implied via the inclusion of
491 // this protocol, e.g. all protocols it inherits from including itself.
492 llvm::DenseSet<const ObjCProtocolDecl *> AllImpliedProtocols;
493 for (const auto *PD : RuntimePds) {
494 const auto *Can = PD->getCanonicalDecl();
495 AllImpliedProtocols.insert(Can);
496 Can->getImpliedProtocols(AllImpliedProtocols);
497 }
498
499 // Similar to above, walk the list of first-implied protocols to find the set
500 // all the protocols implied excluding the listed protocols themselves since
501 // they are not yet a part of the `RuntimePds` list.
502 for (const auto *PD : FirstImpliedProtos) {
503 PD->getImpliedProtocols(AllImpliedProtocols);
504 }
505
506 // From the first-implied list we have to finish building the final protocol
507 // list. If a protocol in the first-implied list was already implied via some
508 // inheritance path through some other protocols then it would be redundant to
509 // add it here and so we skip over it.
510 for (const auto *PD : FirstImpliedProtos) {
511 if (!AllImpliedProtocols.contains(PD)) {
512 RuntimePds.push_back(PD);
513 }
514 }
515
516 return RuntimePds;
517}
518
519/// Instead of '[[MyClass alloc] init]', try to generate
520/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
521/// caller side, as well as the optimized objc_alloc.
522static Optional<llvm::Value *>
523tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
524 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
525 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
526 return None;
527
528 // Match the exact pattern '[[MyClass alloc] init]'.
529 Selector Sel = OME->getSelector();
530 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
531 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
532 Sel.getNameForSlot(0) != "init")
533 return None;
534
535 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'
536 // with 'cls' a Class.
537 auto *SubOME =
538 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
539 if (!SubOME)
540 return None;
541 Selector SubSel = SubOME->getSelector();
542
543 if (!SubOME->getType()->isObjCObjectPointerType() ||
544 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
545 return None;
546
547 llvm::Value *Receiver = nullptr;
548 switch (SubOME->getReceiverKind()) {
549 case ObjCMessageExpr::Instance:
550 if (!SubOME->getInstanceReceiver()->getType()->isObjCClassType())
551 return None;
552 Receiver = CGF.EmitScalarExpr(SubOME->getInstanceReceiver());
553 break;
554
555 case ObjCMessageExpr::Class: {
556 QualType ReceiverType = SubOME->getClassReceiver();
557 const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
558 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
559 assert(ID && "null interface should be impossible here");
560 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
561 break;
562 }
563 case ObjCMessageExpr::SuperInstance:
564 case ObjCMessageExpr::SuperClass:
565 return None;
566 }
567
568 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
569}
570
571RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
572 ReturnValueSlot Return) {
573 // Only the lookup mechanism and first two arguments of the method
574 // implementation vary between runtimes. We can get the receiver and
575 // arguments in generic code.
576
577 bool isDelegateInit = E->isDelegateInitCall();
578
579 const ObjCMethodDecl *method = E->getMethodDecl();
580
581 // If the method is -retain, and the receiver's being loaded from
582 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
583 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
584 method->getMethodFamily() == OMF_retain) {
585 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
586 LValue lvalue = EmitLValue(lvalueExpr);
587 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
588 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
589 }
590 }
591
592 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
593 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
594
595 // We don't retain the receiver in delegate init calls, and this is
596 // safe because the receiver value is always loaded from 'self',
597 // which we zero out. We don't want to Block_copy block receivers,
598 // though.
599 bool retainSelf =
600 (!isDelegateInit &&
601 CGM.getLangOpts().ObjCAutoRefCount &&
602 method &&
603 method->hasAttr<NSConsumesSelfAttr>());
604
605 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
606 bool isSuperMessage = false;
607 bool isClassMessage = false;
608 ObjCInterfaceDecl *OID = nullptr;
609 // Find the receiver
610 QualType ReceiverType;
611 llvm::Value *Receiver = nullptr;
612 switch (E->getReceiverKind()) {
613 case ObjCMessageExpr::Instance:
614 ReceiverType = E->getInstanceReceiver()->getType();
615 isClassMessage = ReceiverType->isObjCClassType();
616 if (retainSelf) {
617 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
618 E->getInstanceReceiver());
619 Receiver = ter.getPointer();
620 if (ter.getInt()) retainSelf = false;
621 } else
622 Receiver = EmitScalarExpr(E->getInstanceReceiver());
623 break;
624
625 case ObjCMessageExpr::Class: {
626 ReceiverType = E->getClassReceiver();
627 OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
628 assert(OID && "Invalid Objective-C class message send");
629 Receiver = Runtime.GetClass(*this, OID);
630 isClassMessage = true;
631 break;
632 }
633
634 case ObjCMessageExpr::SuperInstance:
635 ReceiverType = E->getSuperType();
636 Receiver = LoadObjCSelf();
637 isSuperMessage = true;
638 break;
639
640 case ObjCMessageExpr::SuperClass:
641 ReceiverType = E->getSuperType();
642 Receiver = LoadObjCSelf();
643 isSuperMessage = true;
644 isClassMessage = true;
645 break;
646 }
647
648 if (retainSelf)
649 Receiver = EmitARCRetainNonBlock(Receiver);
650
651 // In ARC, we sometimes want to "extend the lifetime"
652 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
653 // messages.
654 if (getLangOpts().ObjCAutoRefCount && method &&
655 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
656 shouldExtendReceiverForInnerPointerMessage(E))
657 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
658
659 QualType ResultType = method ? method->getReturnType() : E->getType();
660
661 CallArgList Args;
662 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
663
664 // For delegate init calls in ARC, do an unsafe store of null into
665 // self. This represents the call taking direct ownership of that
666 // value. We have to do this after emitting the other call
667 // arguments because they might also reference self, but we don't
668 // have to worry about any of them modifying self because that would
669 // be an undefined read and write of an object in unordered
670 // expressions.
671 if (isDelegateInit) {
672 assert(getLangOpts().ObjCAutoRefCount &&
673 "delegate init calls should only be marked in ARC");
674
675 // Do an unsafe store of null into self.
676 Address selfAddr =
677 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
678 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
679 }
680
681 RValue result;
682 if (isSuperMessage) {
683 // super is only valid in an Objective-C method
684 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
685 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
686 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
687 E->getSelector(),
688 OMD->getClassInterface(),
689 isCategoryImpl,
690 Receiver,
691 isClassMessage,
692 Args,
693 method);
694 } else {
695 // Call runtime methods directly if we can.
696 result = Runtime.GeneratePossiblySpecializedMessageSend(
697 *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
698 method, isClassMessage);
699 }
700
701 // For delegate init calls in ARC, implicitly store the result of
702 // the call back into self. This takes ownership of the value.
703 if (isDelegateInit) {
704 Address selfAddr =
705 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
706 llvm::Value *newSelf = result.getScalarVal();
707
708 // The delegate return type isn't necessarily a matching type; in
709 // fact, it's quite likely to be 'id'.
710 llvm::Type *selfTy = selfAddr.getElementType();
711 newSelf = Builder.CreateBitCast(newSelf, selfTy);
712
713 Builder.CreateStore(newSelf, selfAddr);
714 }
715
716 return AdjustObjCObjectType(*this, E->getType(), result);
717}
718
719namespace {
720struct FinishARCDealloc final : EHScopeStack::Cleanup {
721 void Emit(CodeGenFunction &CGF, Flags flags) override {
722 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
723
724 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
725 const ObjCInterfaceDecl *iface = impl->getClassInterface();
726 if (!iface->getSuperClass()) return;
727
728 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
729
730 // Call [super dealloc] if we have a superclass.
731 llvm::Value *self = CGF.LoadObjCSelf();
732
733 CallArgList args;
734 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
735 CGF.getContext().VoidTy,
736 method->getSelector(),
737 iface,
738 isCategory,
739 self,
740 /*is class msg*/ false,
741 args,
742 method);
743 }
744};
745}
746
747/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
748/// the LLVM function and sets the other context used by
749/// CodeGenFunction.
750void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
751 const ObjCContainerDecl *CD) {
752 SourceLocation StartLoc = OMD->getBeginLoc();
753 FunctionArgList args;
754 // Check if we should generate debug info for this method.
755 if (OMD->hasAttr<NoDebugAttr>())
756 DebugInfo = nullptr; // disable debug info indefinitely for this function
757
758 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
759
760 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
761 if (OMD->isDirectMethod()) {
762 Fn->setVisibility(llvm::Function::HiddenVisibility);
763 CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
764 CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
765 } else {
766 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
767 }
768
769 args.push_back(OMD->getSelfDecl());
770 args.push_back(OMD->getCmdDecl());
771
772 args.append(OMD->param_begin(), OMD->param_end());
773
774 CurGD = OMD;
775 CurEHLocation = OMD->getEndLoc();
776
777 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
778 OMD->getLocation(), StartLoc);
779
780 if (OMD->isDirectMethod()) {
781 // This function is a direct call, it has to implement a nil check
782 // on entry.
783 //
784 // TODO: possibly have several entry points to elide the check
785 CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
786 }
787
788 // In ARC, certain methods get an extra cleanup.
789 if (CGM.getLangOpts().ObjCAutoRefCount &&
790 OMD->isInstanceMethod() &&
791 OMD->getSelector().isUnarySelector()) {
792 const IdentifierInfo *ident =
793 OMD->getSelector().getIdentifierInfoForSlot(0);
794 if (ident->isStr("dealloc"))
795 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
796 }
797}
798
799static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
800 LValue lvalue, QualType type);
801
802/// Generate an Objective-C method. An Objective-C method is a C function with
803/// its pointer, name, and types registered in the class structure.
804void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
805 StartObjCMethod(OMD, OMD->getClassInterface());
806 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
807 assert(isa<CompoundStmt>(OMD->getBody()));
808 incrementProfileCounter(OMD->getBody());
809 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
810 FinishFunction(OMD->getBodyRBrace());
811}
812
813/// emitStructGetterCall - Call the runtime function to load a property
814/// into the return value slot.
815static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
816 bool isAtomic, bool hasStrong) {
817 ASTContext &Context = CGF.getContext();
818
819 Address src =
820 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
821 .getAddress(CGF);
822
823 // objc_copyStruct (ReturnValue, &structIvar,
824 // sizeof (Type of Ivar), isAtomic, false);
825 CallArgList args;
826
827 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
828 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
829
830 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
831 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
832
833 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
834 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
835 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
836 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
837
838 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
839 CGCallee callee = CGCallee::forDirect(fn);
840 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
841 callee, ReturnValueSlot(), args);
842}
843
844/// Determine whether the given architecture supports unaligned atomic
845/// accesses. They don't have to be fast, just faster than a function
846/// call and a mutex.
847static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
848 // FIXME: Allow unaligned atomic load/store on x86. (It is not
849 // currently supported by the backend.)
850 return 0;
851}
852
853/// Return the maximum size that permits atomic accesses for the given
854/// architecture.
855static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
856 llvm::Triple::ArchType arch) {
857 // ARM has 8-byte atomic accesses, but it's not clear whether we
858 // want to rely on them here.
859
860 // In the default case, just assume that any size up to a pointer is
861 // fine given adequate alignment.
862 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
863}
864
865namespace {
866 class PropertyImplStrategy {
867 public:
868 enum StrategyKind {
869 /// The 'native' strategy is to use the architecture's provided
870 /// reads and writes.
871 Native,
872
873 /// Use objc_setProperty and objc_getProperty.
874 GetSetProperty,
875
876 /// Use objc_setProperty for the setter, but use expression
877 /// evaluation for the getter.
878 SetPropertyAndExpressionGet,
879
880 /// Use objc_copyStruct.
881 CopyStruct,
882
883 /// The 'expression' strategy is to emit normal assignment or
884 /// lvalue-to-rvalue expressions.
885 Expression
886 };
887
888 StrategyKind getKind() const { return StrategyKind(Kind); }
889
890 bool hasStrongMember() const { return HasStrong; }
891 bool isAtomic() const { return IsAtomic; }
892 bool isCopy() const { return IsCopy; }
893
894 CharUnits getIvarSize() const { return IvarSize; }
895 CharUnits getIvarAlignment() const { return IvarAlignment; }
896
897 PropertyImplStrategy(CodeGenModule &CGM,
898 const ObjCPropertyImplDecl *propImpl);
899
900 private:
901 unsigned Kind : 8;
902 unsigned IsAtomic : 1;
903 unsigned IsCopy : 1;
904 unsigned HasStrong : 1;
905
906 CharUnits IvarSize;
907 CharUnits IvarAlignment;
908 };
909}
910
911/// Pick an implementation strategy for the given property synthesis.
912PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
913 const ObjCPropertyImplDecl *propImpl) {
914 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
915 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
916
917 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
918 IsAtomic = prop->isAtomic();
919 HasStrong = false; // doesn't matter here.
920
921 // Evaluate the ivar's size and alignment.
922 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
923 QualType ivarType = ivar->getType();
924 auto TInfo = CGM.getContext().getTypeInfoInChars(ivarType);
925 IvarSize = TInfo.Width;
926 IvarAlignment = TInfo.Align;
927
928 // If we have a copy property, we always have to use getProperty/setProperty.
929 // TODO: we could actually use setProperty and an expression for non-atomics.
930 if (IsCopy) {
931 Kind = GetSetProperty;
932 return;
933 }
934
935 // Handle retain.
936 if (setterKind == ObjCPropertyDecl::Retain) {
937 // In GC-only, there's nothing special that needs to be done.
938 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
939 // fallthrough
940
941 // In ARC, if the property is non-atomic, use expression emission,
942 // which translates to objc_storeStrong. This isn't required, but
943 // it's slightly nicer.
944 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
945 // Using standard expression emission for the setter is only
946 // acceptable if the ivar is __strong, which won't be true if
947 // the property is annotated with __attribute__((NSObject)).
948 // TODO: falling all the way back to objc_setProperty here is
949 // just laziness, though; we could still use objc_storeStrong
950 // if we hacked it right.
951 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
952 Kind = Expression;
953 else
954 Kind = SetPropertyAndExpressionGet;
955 return;
956
957 // Otherwise, we need to at least use setProperty. However, if
958 // the property isn't atomic, we can use normal expression
959 // emission for the getter.
960 } else if (!IsAtomic) {
961 Kind = SetPropertyAndExpressionGet;
962 return;
963
964 // Otherwise, we have to use both setProperty and getProperty.
965 } else {
966 Kind = GetSetProperty;
967 return;
968 }
969 }
970
971 // If we're not atomic, just use expression accesses.
972 if (!IsAtomic) {
973 Kind = Expression;
974 return;
975 }
976
977 // Properties on bitfield ivars need to be emitted using expression
978 // accesses even if they're nominally atomic.
979 if (ivar->isBitField()) {
980 Kind = Expression;
981 return;
982 }
983
984 // GC-qualified or ARC-qualified ivars need to be emitted as
985 // expressions. This actually works out to being atomic anyway,
986 // except for ARC __strong, but that should trigger the above code.
987 if (ivarType.hasNonTrivialObjCLifetime() ||
988 (CGM.getLangOpts().getGC() &&
989 CGM.getContext().getObjCGCAttrKind(ivarType))) {
990 Kind = Expression;
991 return;
992 }
993
994 // Compute whether the ivar has strong members.
995 if (CGM.getLangOpts().getGC())
996 if (const RecordType *recordType = ivarType->getAs<RecordType>())
997 HasStrong = recordType->getDecl()->hasObjectMember();
998
999 // We can never access structs with object members with a native
1000 // access, because we need to use write barriers. This is what
1001 // objc_copyStruct is for.
1002 if (HasStrong) {
1003 Kind = CopyStruct;
1004 return;
1005 }
1006
1007 // Otherwise, this is target-dependent and based on the size and
1008 // alignment of the ivar.
1009
1010 // If the size of the ivar is not a power of two, give up. We don't
1011 // want to get into the business of doing compare-and-swaps.
1012 if (!IvarSize.isPowerOfTwo()) {
1013 Kind = CopyStruct;
1014 return;
1015 }
1016
1017 llvm::Triple::ArchType arch =
1018 CGM.getTarget().getTriple().getArch();
1019
1020 // Most architectures require memory to fit within a single cache
1021 // line, so the alignment has to be at least the size of the access.
1022 // Otherwise we have to grab a lock.
1023 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
1024 Kind = CopyStruct;
1025 return;
1026 }
1027
1028 // If the ivar's size exceeds the architecture's maximum atomic
1029 // access size, we have to use CopyStruct.
1030 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
1031 Kind = CopyStruct;
1032 return;
1033 }
1034
1035 // Otherwise, we can use native loads and stores.
1036 Kind = Native;
1037}
1038
1039/// Generate an Objective-C property getter function.
1040///
1041/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1042/// is illegal within a category.
1043void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
1044 const ObjCPropertyImplDecl *PID) {
1045 llvm::Constant *AtomicHelperFn =
1046 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
1047 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
1048 assert(OMD && "Invalid call to generate getter (empty method)");
1049 StartObjCMethod(OMD, IMP->getClassInterface());
1050
1051 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
1052
1053 FinishFunction(OMD->getEndLoc());
1054}
1055
1056static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
1057 const Expr *getter = propImpl->getGetterCXXConstructor();
1058 if (!getter) return true;
1059
1060 // Sema only makes only of these when the ivar has a C++ class type,
1061 // so the form is pretty constrained.
1062
1063 // If the property has a reference type, we might just be binding a
1064 // reference, in which case the result will be a gl-value. We should
1065 // treat this as a non-trivial operation.
1066 if (getter->isGLValue())
1067 return false;
1068
1069 // If we selected a trivial copy-constructor, we're okay.
1070 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1071 return (construct->getConstructor()->isTrivial());
1072
1073 // The constructor might require cleanups (in which case it's never
1074 // trivial).
1075 assert(isa<ExprWithCleanups>(getter));
1076 return false;
1077}
1078
1079/// emitCPPObjectAtomicGetterCall - Call the runtime function to
1080/// copy the ivar into the resturn slot.
1081static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
1082 llvm::Value *returnAddr,
1083 ObjCIvarDecl *ivar,
1084 llvm::Constant *AtomicHelperFn) {
1085 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1086 // AtomicHelperFn);
1087 CallArgList args;
1088
1089 // The 1st argument is the return Slot.
1090 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
1091
1092 // The 2nd argument is the address of the ivar.
1093 llvm::Value *ivarAddr =
1094 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1095 .getPointer(CGF);
1096 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1097 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1098
1099 // Third argument is the helper function.
1100 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1101
1102 llvm::FunctionCallee copyCppAtomicObjectFn =
1103 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
1104 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
1105 CGF.EmitCall(
1106 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1107 callee, ReturnValueSlot(), args);
1108}
1109
1110void
1111CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1112 const ObjCPropertyImplDecl *propImpl,
1113 const ObjCMethodDecl *GetterMethodDecl,
1114 llvm::Constant *AtomicHelperFn) {
1115 // If there's a non-trivial 'get' expression, we just have to emit that.
1116 if (!hasTrivialGetExpr(propImpl)) {
1117 if (!AtomicHelperFn) {
1118 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1119 propImpl->getGetterCXXConstructor(),
1120 /* NRVOCandidate=*/nullptr);
1121 EmitReturnStmt(*ret);
1122 }
1123 else {
1124 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1125 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
1126 ivar, AtomicHelperFn);
1127 }
1128 return;
1129 }
1130
1131 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1132 QualType propType = prop->getType();
1133 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
1134
1135 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1136
1137 // Pick an implementation strategy.
1138 PropertyImplStrategy strategy(CGM, propImpl);
1139 switch (strategy.getKind()) {
1140 case PropertyImplStrategy::Native: {
1141 // We don't need to do anything for a zero-size struct.
1142 if (strategy.getIvarSize().isZero())
1143 return;
1144
1145 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1146
1147 // Currently, all atomic accesses have to be through integer
1148 // types, so there's no point in trying to pick a prettier type.
1149 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1150 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
1151 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1152
1153 // Perform an atomic load. This does not impose ordering constraints.
1154 Address ivarAddr = LV.getAddress(*this);
1155 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1156 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
1157 load->setAtomic(llvm::AtomicOrdering::Unordered);
1158
1159 // Store that value into the return address. Doing this with a
1160 // bitcast is likely to produce some pretty ugly IR, but it's not
1161 // the *most* terrible thing in the world.
1162 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1163 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1164 llvm::Value *ivarVal = load;
1165 if (ivarSize > retTySize) {
1166 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1167 ivarVal = Builder.CreateTrunc(load, newTy);
1168 bitcastType = newTy->getPointerTo();
1169 }
1170 Builder.CreateStore(ivarVal,
1171 Builder.CreateBitCast(ReturnValue, bitcastType));
1172
1173 // Make sure we don't do an autorelease.
1174 AutoreleaseResult = false;
1175 return;
1176 }
1177
1178 case PropertyImplStrategy::GetSetProperty: {
1179 llvm::FunctionCallee getPropertyFn =
1180 CGM.getObjCRuntime().GetPropertyGetFunction();
1181 if (!getPropertyFn) {
1182 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
1183 return;
1184 }
1185 CGCallee callee = CGCallee::forDirect(getPropertyFn);
1186
1187 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1188 // FIXME: Can't this be simpler? This might even be worse than the
1189 // corresponding gcc code.
1190 llvm::Value *cmd =
1191 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
1192 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1193 llvm::Value *ivarOffset =
1194 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1195
1196 CallArgList args;
1197 args.add(RValue::get(self), getContext().getObjCIdType());
1198 args.add(RValue::get(cmd), getContext().getObjCSelType());
1199 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1200 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1201 getContext().BoolTy);
1202
1203 // FIXME: We shouldn't need to get the function info here, the
1204 // runtime already should have computed it to build the function.
1205 llvm::CallBase *CallInstruction;
1206 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1207 getContext().getObjCIdType(), args),
1208 callee, ReturnValueSlot(), args, &CallInstruction);
1209 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1210 call->setTailCall();
1211
1212 // We need to fix the type here. Ivars with copy & retain are
1213 // always objects so we don't need to worry about complex or
1214 // aggregates.
1215 RV = RValue::get(Builder.CreateBitCast(
1216 RV.getScalarVal(),
1217 getTypes().ConvertType(getterMethod->getReturnType())));
1218
1219 EmitReturnOfRValue(RV, propType);
1220
1221 // objc_getProperty does an autorelease, so we should suppress ours.
1222 AutoreleaseResult = false;
1223
1224 return;
1225 }
1226
1227 case PropertyImplStrategy::CopyStruct:
1228 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1229 strategy.hasStrongMember());
1230 return;
1231
1232 case PropertyImplStrategy::Expression:
1233 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1234 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1235
1236 QualType ivarType = ivar->getType();
1237 switch (getEvaluationKind(ivarType)) {
1238 case TEK_Complex: {
1239 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
1240 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
1241 /*init*/ true);
1242 return;
1243 }
1244 case TEK_Aggregate: {
1245 // The return value slot is guaranteed to not be aliased, but
1246 // that's not necessarily the same as "on the stack", so
1247 // we still potentially need objc_memmove_collectable.
1248 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
1249 /* Src= */ LV, ivarType, getOverlapForReturnValue());
1250 return;
1251 }
1252 case TEK_Scalar: {
1253 llvm::Value *value;
1254 if (propType->isReferenceType()) {
1255 value = LV.getAddress(*this).getPointer();
1256 } else {
1257 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1258 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1259 if (getLangOpts().ObjCAutoRefCount) {
1260 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1261 } else {
1262 value = EmitARCLoadWeak(LV.getAddress(*this));
1263 }
1264
1265 // Otherwise we want to do a simple load, suppressing the
1266 // final autorelease.
1267 } else {
1268 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
1269 AutoreleaseResult = false;
1270 }
1271
1272 value = Builder.CreateBitCast(
1273 value, ConvertType(GetterMethodDecl->getReturnType()));
1274 }
1275
1276 EmitReturnOfRValue(RValue::get(value), propType);
1277 return;
1278 }
1279 }
1280 llvm_unreachable("bad evaluation kind");
1281 }
1282
1283 }
1284 llvm_unreachable("bad @property implementation strategy!");
1285}
1286
1287/// emitStructSetterCall - Call the runtime function to store the value
1288/// from the first formal parameter into the given ivar.
1289static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1290 ObjCIvarDecl *ivar) {
1291 // objc_copyStruct (&structIvar, &Arg,
1292 // sizeof (struct something), true, false);
1293 CallArgList args;
1294
1295 // The first argument is the address of the ivar.
1296 llvm::Value *ivarAddr =
1297 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1298 .getPointer(CGF);
1299 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1300 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1301
1302 // The second argument is the address of the parameter variable.
1303 ParmVarDecl *argVar = *OMD->param_begin();
1304 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1305 argVar->getType().getNonReferenceType(), VK_LValue,
1306 SourceLocation());
1307 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1308 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1309 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1310
1311 // The third argument is the sizeof the type.
1312 llvm::Value *size =
1313 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1314 args.add(RValue::get(size), CGF.getContext().getSizeType());
1315
1316 // The fourth argument is the 'isAtomic' flag.
1317 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
1318
1319 // The fifth argument is the 'hasStrong' flag.
1320 // FIXME: should this really always be false?
1321 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1322
1323 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1324 CGCallee callee = CGCallee::forDirect(fn);
1325 CGF.EmitCall(
1326 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1327 callee, ReturnValueSlot(), args);
1328}
1329
1330/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1331/// the value from the first formal parameter into the given ivar, using
1332/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1333static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1334 ObjCMethodDecl *OMD,
1335 ObjCIvarDecl *ivar,
1336 llvm::Constant *AtomicHelperFn) {
1337 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1338 // AtomicHelperFn);
1339 CallArgList args;
1340
1341 // The first argument is the address of the ivar.
1342 llvm::Value *ivarAddr =
1343 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1344 .getPointer(CGF);
1345 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1346 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1347
1348 // The second argument is the address of the parameter variable.
1349 ParmVarDecl *argVar = *OMD->param_begin();
1350 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1351 argVar->getType().getNonReferenceType(), VK_LValue,
1352 SourceLocation());
1353 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
1354 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1355 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1356
1357 // Third argument is the helper function.
1358 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1359
1360 llvm::FunctionCallee fn =
1361 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1362 CGCallee callee = CGCallee::forDirect(fn);
1363 CGF.EmitCall(
1364 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
1365 callee, ReturnValueSlot(), args);
1366}
1367
1368
1369static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1370 Expr *setter = PID->getSetterCXXAssignment();
1371 if (!setter) return true;
1372
1373 // Sema only makes only of these when the ivar has a C++ class type,
1374 // so the form is pretty constrained.
1375
1376 // An operator call is trivial if the function it calls is trivial.
1377 // This also implies that there's nothing non-trivial going on with
1378 // the arguments, because operator= can only be trivial if it's a
1379 // synthesized assignment operator and therefore both parameters are
1380 // references.
1381 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1382 if (const FunctionDecl *callee
1383 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1384 if (callee->isTrivial())
1385 return true;
1386 return false;
1387 }
1388
1389 assert(isa<ExprWithCleanups>(setter));
1390 return false;
1391}
1392
1393static bool UseOptimizedSetter(CodeGenModule &CGM) {
1394 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1395 return false;
1396 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1397}
1398
1399void
1400CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1401 const ObjCPropertyImplDecl *propImpl,
1402 llvm::Constant *AtomicHelperFn) {
1403 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1404 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
1405
1406 // Just use the setter expression if Sema gave us one and it's
1407 // non-trivial.
1408 if (!hasTrivialSetExpr(propImpl)) {
1409 if (!AtomicHelperFn)
1410 // If non-atomic, assignment is called directly.
1411 EmitStmt(propImpl->getSetterCXXAssignment());
1412 else
1413 // If atomic, assignment is called via a locking api.
1414 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1415 AtomicHelperFn);
1416 return;
1417 }
1418
1419 PropertyImplStrategy strategy(CGM, propImpl);
1420 switch (strategy.getKind()) {
1421 case PropertyImplStrategy::Native: {
1422 // We don't need to do anything for a zero-size struct.
1423 if (strategy.getIvarSize().isZero())
1424 return;
1425
1426 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1427
1428 LValue ivarLValue =
1429 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1430 Address ivarAddr = ivarLValue.getAddress(*this);
1431
1432 // Currently, all atomic accesses have to be through integer
1433 // types, so there's no point in trying to pick a prettier type.
1434 llvm::Type *bitcastType =
1435 llvm::Type::getIntNTy(getLLVMContext(),
1436 getContext().toBits(strategy.getIvarSize()));
1437
1438 // Cast both arguments to the chosen operation type.
1439 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1440 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
1441
1442 // This bitcast load is likely to cause some nasty IR.
1443 llvm::Value *load = Builder.CreateLoad(argAddr);
1444
1445 // Perform an atomic store. There are no memory ordering requirements.
1446 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1447 store->setAtomic(llvm::AtomicOrdering::Unordered);
1448 return;
1449 }
1450
1451 case PropertyImplStrategy::GetSetProperty:
1452 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1453
1454 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1455 llvm::FunctionCallee setPropertyFn = nullptr;
1456 if (UseOptimizedSetter(CGM)) {
1457 // 10.8 and iOS 6.0 code and GC is off
1458 setOptimizedPropertyFn =
1459 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1460 strategy.isAtomic(), strategy.isCopy());
1461 if (!setOptimizedPropertyFn) {
1462 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1463 return;
1464 }
1465 }
1466 else {
1467 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1468 if (!setPropertyFn) {
1469 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1470 return;
1471 }
1472 }
1473
1474 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1475 // <is-atomic>, <is-copy>).
1476 llvm::Value *cmd =
1477 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
1478 llvm::Value *self =
1479 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1480 llvm::Value *ivarOffset =
1481 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1482 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1483 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1484 arg = Builder.CreateBitCast(arg, VoidPtrTy);
1485
1486 CallArgList args;
1487 args.add(RValue::get(self), getContext().getObjCIdType());
1488 args.add(RValue::get(cmd), getContext().getObjCSelType());
1489 if (setOptimizedPropertyFn) {
1490 args.add(RValue::get(arg), getContext().getObjCIdType());
1491 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1492 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
1493 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1494 callee, ReturnValueSlot(), args);
1495 } else {
1496 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1497 args.add(RValue::get(arg), getContext().getObjCIdType());
1498 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1499 getContext().BoolTy);
1500 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1501 getContext().BoolTy);
1502 // FIXME: We shouldn't need to get the function info here, the runtime
1503 // already should have computed it to build the function.
1504 CGCallee callee = CGCallee::forDirect(setPropertyFn);
1505 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
1506 callee, ReturnValueSlot(), args);
1507 }
1508
1509 return;
1510 }
1511
1512 case PropertyImplStrategy::CopyStruct:
1513 emitStructSetterCall(*this, setterMethod, ivar);
1514 return;
1515
1516 case PropertyImplStrategy::Expression:
1517 break;
1518 }
1519
1520 // Otherwise, fake up some ASTs and emit a normal assignment.
1521 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1522 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
1523 VK_LValue, SourceLocation());
1524 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, selfDecl->getType(),
1525 CK_LValueToRValue, &self, VK_RValue,
1526 FPOptionsOverride());
1527 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1528 SourceLocation(), SourceLocation(),
1529 &selfLoad, true, true);
1530
1531 ParmVarDecl *argDecl = *setterMethod->param_begin();
1532 QualType argType = argDecl->getType().getNonReferenceType();
1533 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1534 SourceLocation());
1535 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1536 argType.getUnqualifiedType(), CK_LValueToRValue,
1537 &arg, VK_RValue, FPOptionsOverride());
1538
1539 // The property type can differ from the ivar type in some situations with
1540 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1541 // The following absurdity is just to ensure well-formed IR.
1542 CastKind argCK = CK_NoOp;
1543 if (ivarRef.getType()->isObjCObjectPointerType()) {
1544 if (argLoad.getType()->isObjCObjectPointerType())
1545 argCK = CK_BitCast;
1546 else if (argLoad.getType()->isBlockPointerType())
1547 argCK = CK_BlockPointerToObjCPointerCast;
1548 else
1549 argCK = CK_CPointerToObjCPointerCast;
1550 } else if (ivarRef.getType()->isBlockPointerType()) {
1551 if (argLoad.getType()->isBlockPointerType())
1552 argCK = CK_BitCast;
1553 else
1554 argCK = CK_AnyPointerToBlockPointerCast;
1555 } else if (ivarRef.getType()->isPointerType()) {
1556 argCK = CK_BitCast;
1557 }
1558 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, ivarRef.getType(), argCK,
1559 &argLoad, VK_RValue, FPOptionsOverride());
1560 Expr *finalArg = &argLoad;
1561 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1562 argLoad.getType()))
1563 finalArg = &argCast;
1564
1565 BinaryOperator *assign = BinaryOperator::Create(
1566 getContext(), &ivarRef, finalArg, BO_Assign, ivarRef.getType(), VK_RValue,
1567 OK_Ordinary, SourceLocation(), FPOptionsOverride());
1568 EmitStmt(assign);
1569}
1570
1571/// Generate an Objective-C property setter function.
1572///
1573/// The given Decl must be an ObjCImplementationDecl. \@synthesize
1574/// is illegal within a category.
1575void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1576 const ObjCPropertyImplDecl *PID) {
1577 llvm::Constant *AtomicHelperFn =
1578 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
1579 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
1580 assert(OMD && "Invalid call to generate setter (empty method)");
1581 StartObjCMethod(OMD, IMP->getClassInterface());
1582
1583 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1584
1585 FinishFunction(OMD->getEndLoc());
1586}
1587
1588namespace {
1589 struct DestroyIvar final : EHScopeStack::Cleanup {
1590 private:
1591 llvm::Value *addr;
1592 const ObjCIvarDecl *ivar;
1593 CodeGenFunction::Destroyer *destroyer;
1594 bool useEHCleanupForArray;
1595 public:
1596 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1597 CodeGenFunction::Destroyer *destroyer,
1598 bool useEHCleanupForArray)
1599 : addr(addr), ivar(ivar), destroyer(destroyer),
1600 useEHCleanupForArray(useEHCleanupForArray) {}
1601
1602 void Emit(CodeGenFunction &CGF, Flags flags) override {
1603 LValue lvalue
1604 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1605 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
1606 flags.isForNormalCleanup() && useEHCleanupForArray);
1607 }
1608 };
1609}
1610
1611/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1612static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1613 Address addr,
1614 QualType type) {
1615 llvm::Value *null = getNullForVariable(addr);
1616 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1617}
1618
1619static void emitCXXDestructMethod(CodeGenFunction &CGF,
1620 ObjCImplementationDecl *impl) {
1621 CodeGenFunction::RunCleanupsScope scope(CGF);
1622
1623 llvm::Value *self = CGF.LoadObjCSelf();
1624
1625 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1626 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1627 ivar; ivar = ivar->getNextIvar()) {
1628 QualType type = ivar->getType();
1629
1630 // Check whether the ivar is a destructible type.
1631 QualType::DestructionKind dtorKind = type.isDestructedType();
1632 if (!dtorKind) continue;
1633
1634 CodeGenFunction::Destroyer *destroyer = nullptr;
1635
1636 // Use a call to objc_storeStrong to destroy strong ivars, for the
1637 // general benefit of the tools.
1638 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1639 destroyer = destroyARCStrongWithStore;
1640
1641 // Otherwise use the default for the destruction kind.
1642 } else {
1643 destroyer = CGF.getDestroyer(dtorKind);
1644 }
1645
1646 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1647
1648 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1649 cleanupKind & EHCleanup);
1650 }
1651
1652 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1653}
1654
1655void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1656 ObjCMethodDecl *MD,
1657 bool ctor) {
1658 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1659 StartObjCMethod(MD, IMP->getClassInterface());
1660
1661 // Emit .cxx_construct.
1662 if (ctor) {
1663 // Suppress the final autorelease in ARC.
1664 AutoreleaseResult = false;
1665
1666 for (const auto *IvarInit : IMP->inits()) {
1667 FieldDecl *Field = IvarInit->getAnyMember();
1668 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1669 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1670 LoadObjCSelf(), Ivar, 0);
1671 EmitAggExpr(IvarInit->getInit(),
1672 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
1673 AggValueSlot::DoesNotNeedGCBarriers,
1674 AggValueSlot::IsNotAliased,
1675 AggValueSlot::DoesNotOverlap));
1676 }
1677 // constructor returns 'self'.
1678 CodeGenTypes &Types = CGM.getTypes();
1679 QualType IdTy(CGM.getContext().getObjCIdType());
1680 llvm::Value *SelfAsId =
1681 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1682 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1683
1684 // Emit .cxx_destruct.
1685 } else {
1686 emitCXXDestructMethod(*this, IMP);
1687 }
1688 FinishFunction();
1689}
1690
1691llvm::Value *CodeGenFunction::LoadObjCSelf() {
1692 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1693 DeclRefExpr DRE(getContext(), Self,
1694 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1695 Self->getType(), VK_LValue, SourceLocation());
1696 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
1697}
1698
1699QualType CodeGenFunction::TypeOfSelfObject() {
1700 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1701 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1702 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1703 getContext().getCanonicalType(selfDecl->getType()));
1704 return PTy->getPointeeType();
1705}
1706
1707void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1708 llvm::FunctionCallee EnumerationMutationFnPtr =
1709 CGM.getObjCRuntime().EnumerationMutationFunction();
1710 if (!EnumerationMutationFnPtr) {
1711 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1712 return;
1713 }
1714 CGCallee EnumerationMutationFn =
1715 CGCallee::forDirect(EnumerationMutationFnPtr);
1716
1717 CGDebugInfo *DI = getDebugInfo();
1718 if (DI)
1719 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1720
1721 RunCleanupsScope ForScope(*this);
1722
1723 // The local variable comes into scope immediately.
1724 AutoVarEmission variable = AutoVarEmission::invalid();
1725 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1726 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1727
1728 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1729
1730 // Fast enumeration state.
1731 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1732 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
1733 EmitNullInitialization(StatePtr, StateTy);
1734
1735 // Number of elements in the items array.
1736 static const unsigned NumItems = 16;
1737
1738 // Fetch the countByEnumeratingWithState:objects:count: selector.
1739 IdentifierInfo *II[] = {
1740 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1741 &CGM.getContext().Idents.get("objects"),
1742 &CGM.getContext().Idents.get("count")
1743 };
1744 Selector FastEnumSel =
1745 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1746
1747 QualType ItemsTy =
1748 getContext().getConstantArrayType(getContext().getObjCIdType(),
1749 llvm::APInt(32, NumItems), nullptr,
1750 ArrayType::Normal, 0);
1751 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1752
1753 // Emit the collection pointer. In ARC, we do a retain.
1754 llvm::Value *Collection;
1755 if (getLangOpts().ObjCAutoRefCount) {
1756 Collection = EmitARCRetainScalarExpr(S.getCollection());
1757
1758 // Enter a cleanup to do the release.
1759 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1760 } else {
1761 Collection = EmitScalarExpr(S.getCollection());
1762 }
1763
1764 // The 'continue' label needs to appear within the cleanup for the
1765 // collection object.
1766 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1767
1768 // Send it our message:
1769 CallArgList Args;
1770
1771 // The first argument is a temporary of the enumeration-state type.
1772 Args.add(RValue::get(StatePtr.getPointer()),
1773 getContext().getPointerType(StateTy));
1774
1775 // The second argument is a temporary array with space for NumItems
1776 // pointers. We'll actually be loading elements from the array
1777 // pointer written into the control state; this buffer is so that
1778 // collections that *aren't* backed by arrays can still queue up
1779 // batches of elements.
1780 Args.add(RValue::get(ItemsPtr.getPointer()),
1781 getContext().getPointerType(ItemsTy));
1782
1783 // The third argument is the capacity of that temporary array.
1784 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1785 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1786 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
1787
1788 // Start the enumeration.
1789 RValue CountRV =
1790 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1791 getContext().getNSUIntegerType(),
1792 FastEnumSel, Collection, Args);
1793
1794 // The initial number of objects that were returned in the buffer.
1795 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1796
1797 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1798 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1799
1800 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
1801
1802 // If the limit pointer was zero to begin with, the collection is
1803 // empty; skip all this. Set the branch weight assuming this has the same
1804 // probability of exiting the loop as any other loop exit.
1805 uint64_t EntryCount = getCurrentProfileCount();
1806 Builder.CreateCondBr(
1807 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1808 LoopInitBB,
1809 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
1810
1811 // Otherwise, initialize the loop.
1812 EmitBlock(LoopInitBB);
1813
1814 // Save the initial mutations value. This is the value at an
1815 // address that was written into the state object by
1816 // countByEnumeratingWithState:objects:count:.
1817 Address StateMutationsPtrPtr =
1818 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1819 llvm::Value *StateMutationsPtr
1820 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1821
1822 llvm::Type *UnsignedLongTy = ConvertType(getContext().UnsignedLongTy);
1823 llvm::Value *initialMutations =
1824 Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1825 getPointerAlign(), "forcoll.initial-mutations");
1826
1827 // Start looping. This is the point we return to whenever we have a
1828 // fresh, non-empty batch of objects.
1829 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1830 EmitBlock(LoopBodyBB);
1831
1832 // The current index into the buffer.
1833 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
1834 index->addIncoming(zero, LoopInitBB);
1835
1836 // The current buffer size.
1837 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
1838 count->addIncoming(initialBufferLimit, LoopInitBB);
1839
1840 incrementProfileCounter(&S);
1841
1842 // Check whether the mutations value has changed from where it was
1843 // at start. StateMutationsPtr should actually be invariant between
1844 // refreshes.
1845 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1846 llvm::Value *currentMutations
1847 = Builder.CreateAlignedLoad(UnsignedLongTy, StateMutationsPtr,
1848 getPointerAlign(), "statemutations");
1849
1850 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1851 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1852
1853 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1854 WasNotMutatedBB, WasMutatedBB);
1855
1856 // If so, call the enumeration-mutation function.
1857 EmitBlock(WasMutatedBB);
1858 llvm::Type *ObjCIdType = ConvertType(getContext().getObjCIdType());
1859 llvm::Value *V =
1860 Builder.CreateBitCast(Collection, ObjCIdType);
1861 CallArgList Args2;
1862 Args2.add(RValue::get(V), getContext().getObjCIdType());
1863 // FIXME: We shouldn't need to get the function info here, the runtime already
1864 // should have computed it to build the function.
1865 EmitCall(
1866 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
1867 EnumerationMutationFn, ReturnValueSlot(), Args2);
1868
1869 // Otherwise, or if the mutation function returns, just continue.
1870 EmitBlock(WasNotMutatedBB);
1871
1872 // Initialize the element variable.
1873 RunCleanupsScope elementVariableScope(*this);
1874 bool elementIsVariable;
1875 LValue elementLValue;
1876 QualType elementType;
1877 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1878 // Initialize the variable, in case it's a __block variable or something.
1879 EmitAutoVarInit(variable);
1880
1881 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1882 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1883 D->getType(), VK_LValue, SourceLocation());
1884 elementLValue = EmitLValue(&tempDRE);
1885 elementType = D->getType();
1886 elementIsVariable = true;
1887
1888 if (D->isARCPseudoStrong())
1889 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1890 } else {
1891 elementLValue = LValue(); // suppress warning
1892 elementType = cast<Expr>(S.getElement())->getType();
1893 elementIsVariable = false;
1894 }
1895 llvm::Type *convertedElementType = ConvertType(elementType);
1896
1897 // Fetch the buffer out of the enumeration state.
1898 // TODO: this pointer should actually be invariant between
1899 // refreshes, which would help us do certain loop optimizations.
1900 Address StateItemsPtr =
1901 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1902 llvm::Value *EnumStateItems =
1903 Builder.CreateLoad(StateItemsPtr, "stateitems");
1904
1905 // Fetch the value at the current index from the buffer.
1906 llvm::Value *CurrentItemPtr =
1907 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1908 llvm::Value *CurrentItem =
1909 Builder.CreateAlignedLoad(ObjCIdType, CurrentItemPtr, getPointerAlign());
1910
1911 if (SanOpts.has(SanitizerKind::ObjCCast)) {
1912 // Before using an item from the collection, check that the implicit cast
1913 // from id to the element type is valid. This is done with instrumentation
1914 // roughly corresponding to:
1915 //
1916 // if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
1917 const ObjCObjectPointerType *ObjPtrTy =
1918 elementType->getAsObjCInterfacePointerType();
1919 const ObjCInterfaceType *InterfaceTy =
1920 ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
1921 if (InterfaceTy) {
1922 SanitizerScope SanScope(this);
1923 auto &C = CGM.getContext();
1924 assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
1925 Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
1926 CallArgList IsKindOfClassArgs;
1927 llvm::Value *Cls =
1928 CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
1929 IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
1930 llvm::Value *IsClass =
1931 CGM.getObjCRuntime()
1932 .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
1933 IsKindOfClassSel, CurrentItem,
1934 IsKindOfClassArgs)
1935 .getScalarVal();
1936 llvm::Constant *StaticData[] = {
1937 EmitCheckSourceLocation(S.getBeginLoc()),
1938 EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
1939 EmitCheck({{IsClass, SanitizerKind::ObjCCast}},
1940 SanitizerHandler::InvalidObjCCast,
1941 ArrayRef<llvm::Constant *>(StaticData), CurrentItem);
1942 }
1943 }
1944
1945 // Cast that value to the right type.
1946 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1947 "currentitem");
1948
1949 // Make sure we have an l-value. Yes, this gets evaluated every
1950 // time through the loop.
1951 if (!elementIsVariable) {
1952 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1953 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1954 } else {
1955 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1956 /*isInit*/ true);
1957 }
1958
1959 // If we do have an element variable, this assignment is the end of
1960 // its initialization.
1961 if (elementIsVariable)
1962 EmitAutoVarCleanups(variable);
1963
1964 // Perform the loop body, setting up break and continue labels.
1965 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1966 {
1967 RunCleanupsScope Scope(*this);
1968 EmitStmt(S.getBody());
1969 }
1970 BreakContinueStack.pop_back();
1971
1972 // Destroy the element variable now.
1973 elementVariableScope.ForceCleanup();
1974
1975 // Check whether there are more elements.
1976 EmitBlock(AfterBody.getBlock());
1977
1978 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1979
1980 // First we check in the local buffer.
1981 llvm::Value *indexPlusOne =
1982 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
1983
1984 // If we haven't overrun the buffer yet, we can continue.
1985 // Set the branch weights based on the simplifying assumption that this is
1986 // like a while-loop, i.e., ignoring that the false branch fetches more
1987 // elements and then returns to the loop.
1988 Builder.CreateCondBr(
1989 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
1990 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
1991
1992 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1993 count->addIncoming(count, AfterBody.getBlock());
1994
1995 // Otherwise, we have to fetch more elements.
1996 EmitBlock(FetchMoreBB);
1997
1998 CountRV =
1999 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2000 getContext().getNSUIntegerType(),
2001 FastEnumSel, Collection, Args);
2002
2003 // If we got a zero count, we're done.
2004 llvm::Value *refetchCount = CountRV.getScalarVal();
2005
2006 // (note that the message send might split FetchMoreBB)
2007 index->addIncoming(zero, Builder.GetInsertBlock());
2008 count->addIncoming(refetchCount, Builder.GetInsertBlock());
2009
2010 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
2011 EmptyBB, LoopBodyBB);
2012
2013 // No more elements.
2014 EmitBlock(EmptyBB);
2015
2016 if (!elementIsVariable) {
2017 // If the element was not a declaration, set it to be null.
2018
2019 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
2020 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
2021