Bug Summary

File:tools/clang/lib/CodeGen/CGObjC.cpp
Warning:line 2700, column 3
Undefined or garbage value returned to caller

Annotated Source Code

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