1 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This abstract class defines the interface for Objective-C runtime-specific
10 // code generation.  It provides some concrete helper methods for functionality
11 // shared between all (or most) of the Objective-C runtimes supported by clang.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CGObjCRuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "clang/CodeGen/CodeGenABITypes.h"
25 #include "llvm/Support/SaveAndRestore.h"
26 
27 using namespace clang;
28 using namespace CodeGen;
29 
30 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
31                                               const ObjCInterfaceDecl *OID,
32                                               const ObjCIvarDecl *Ivar) {
33   return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
34          CGM.getContext().getCharWidth();
35 }
36 
37 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
38                                               const ObjCImplementationDecl *OID,
39                                               const ObjCIvarDecl *Ivar) {
40   return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
41                                                Ivar) /
42          CGM.getContext().getCharWidth();
43 }
44 
45 unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
46     CodeGen::CodeGenModule &CGM,
47     const ObjCInterfaceDecl *ID,
48     const ObjCIvarDecl *Ivar) {
49   return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
50                                                Ivar);
51 }
52 
53 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
54                                                const ObjCInterfaceDecl *OID,
55                                                llvm::Value *BaseValue,
56                                                const ObjCIvarDecl *Ivar,
57                                                unsigned CVRQualifiers,
58                                                llvm::Value *Offset) {
59   // Compute (type*) ( (char *) BaseValue + Offset)
60   QualType InterfaceTy{OID->getTypeForDecl(), 0};
61   QualType ObjectPtrTy =
62       CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
63   QualType IvarTy =
64       Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
65   llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
66   llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
67   V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr");
68 
69   if (!Ivar->isBitField()) {
70     V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
71     LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
72     return LV;
73   }
74 
75   // We need to compute an access strategy for this bit-field. We are given the
76   // offset to the first byte in the bit-field, the sub-byte offset is taken
77   // from the original layout. We reuse the normal bit-field access strategy by
78   // treating this as an access to a struct where the bit-field is in byte 0,
79   // and adjust the containing type size as appropriate.
80   //
81   // FIXME: Note that currently we make a very conservative estimate of the
82   // alignment of the bit-field, because (a) it is not clear what guarantees the
83   // runtime makes us, and (b) we don't have a way to specify that the struct is
84   // at an alignment plus offset.
85   //
86   // Note, there is a subtle invariant here: we can only call this routine on
87   // non-synthesized ivars but we may be called for synthesized ivars.  However,
88   // a synthesized ivar can never be a bit-field, so this is safe.
89   uint64_t FieldBitOffset =
90       CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
91   uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
92   uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
93   uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
94   CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
95       llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
96   CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
97 
98   // Allocate a new CGBitFieldInfo object to describe this access.
99   //
100   // FIXME: This is incredibly wasteful, these should be uniqued or part of some
101   // layout object. However, this is blocked on other cleanups to the
102   // Objective-C code, so for now we just live with allocating a bunch of these
103   // objects.
104   CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
105     CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
106                              CGF.CGM.getContext().toBits(StorageSize),
107                              CharUnits::fromQuantity(0)));
108 
109   Address Addr = Address(V, CGF.Int8Ty, Alignment);
110   Addr = CGF.Builder.CreateElementBitCast(Addr,
111                                    llvm::Type::getIntNTy(CGF.getLLVMContext(),
112                                                          Info->StorageSize));
113   return LValue::MakeBitfield(Addr, *Info, IvarTy,
114                               LValueBaseInfo(AlignmentSource::Decl),
115                               TBAAAccessInfo());
116 }
117 
118 namespace {
119   struct CatchHandler {
120     const VarDecl *Variable;
121     const Stmt *Body;
122     llvm::BasicBlock *Block;
123     llvm::Constant *TypeInfo;
124     /// Flags used to differentiate cleanups and catchalls in Windows SEH
125     unsigned Flags;
126   };
127 
128   struct CallObjCEndCatch final : EHScopeStack::Cleanup {
129     CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
130         : MightThrow(MightThrow), Fn(Fn) {}
131     bool MightThrow;
132     llvm::FunctionCallee Fn;
133 
134     void Emit(CodeGenFunction &CGF, Flags flags) override {
135       if (MightThrow)
136         CGF.EmitRuntimeCallOrInvoke(Fn);
137       else
138         CGF.EmitNounwindRuntimeCall(Fn);
139     }
140   };
141 }
142 
143 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
144                                      const ObjCAtTryStmt &S,
145                                      llvm::FunctionCallee beginCatchFn,
146                                      llvm::FunctionCallee endCatchFn,
147                                      llvm::FunctionCallee exceptionRethrowFn) {
148   // Jump destination for falling out of catch bodies.
149   CodeGenFunction::JumpDest Cont;
150   if (S.getNumCatchStmts())
151     Cont = CGF.getJumpDestInCurrentScope("eh.cont");
152 
153   bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
154 
155   CodeGenFunction::FinallyInfo FinallyInfo;
156   if (!useFunclets)
157     if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
158       FinallyInfo.enter(CGF, Finally->getFinallyBody(),
159                         beginCatchFn, endCatchFn, exceptionRethrowFn);
160 
161   SmallVector<CatchHandler, 8> Handlers;
162 
163 
164   // Enter the catch, if there is one.
165   if (S.getNumCatchStmts()) {
166     for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) {
167       const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
168 
169       Handlers.push_back(CatchHandler());
170       CatchHandler &Handler = Handlers.back();
171       Handler.Variable = CatchDecl;
172       Handler.Body = CatchStmt->getCatchBody();
173       Handler.Block = CGF.createBasicBlock("catch");
174       Handler.Flags = 0;
175 
176       // @catch(...) always matches.
177       if (!CatchDecl) {
178         auto catchAll = getCatchAllTypeInfo();
179         Handler.TypeInfo = catchAll.RTTI;
180         Handler.Flags = catchAll.Flags;
181         // Don't consider any other catches.
182         break;
183       }
184 
185       Handler.TypeInfo = GetEHType(CatchDecl->getType());
186     }
187 
188     EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
189     for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
190       Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block);
191   }
192 
193   if (useFunclets)
194     if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
195         CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
196         if (!CGF.CurSEHParent)
197             CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl);
198         // Outline the finally block.
199         const Stmt *FinallyBlock = Finally->getFinallyBody();
200         HelperCGF.startOutlinedSEHHelper(CGF, /*isFilter*/false, FinallyBlock);
201 
202         // Emit the original filter expression, convert to i32, and return.
203         HelperCGF.EmitStmt(FinallyBlock);
204 
205         HelperCGF.FinishFunction(FinallyBlock->getEndLoc());
206 
207         llvm::Function *FinallyFunc = HelperCGF.CurFn;
208 
209 
210         // Push a cleanup for __finally blocks.
211         CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc);
212     }
213 
214 
215   // Emit the try body.
216   CGF.EmitStmt(S.getTryBody());
217 
218   // Leave the try.
219   if (S.getNumCatchStmts())
220     CGF.popCatchScope();
221 
222   // Remember where we were.
223   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
224 
225   // Emit the handlers.
226   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
227     CatchHandler &Handler = Handlers[I];
228 
229     CGF.EmitBlock(Handler.Block);
230     llvm::CatchPadInst *CPI = nullptr;
231     SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(CGF.CurrentFuncletPad);
232     if (useFunclets)
233       if ((CPI = dyn_cast_or_null<llvm::CatchPadInst>(Handler.Block->getFirstNonPHI()))) {
234         CGF.CurrentFuncletPad = CPI;
235         CPI->setOperand(2, CGF.getExceptionSlot().getPointer());
236       }
237     llvm::Value *RawExn = CGF.getExceptionFromSlot();
238 
239     // Enter the catch.
240     llvm::Value *Exn = RawExn;
241     if (beginCatchFn)
242       Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
243 
244     CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
245 
246     if (endCatchFn) {
247       // Add a cleanup to leave the catch.
248       bool EndCatchMightThrow = (Handler.Variable == nullptr);
249 
250       CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
251                                                 EndCatchMightThrow,
252                                                 endCatchFn);
253     }
254 
255     // Bind the catch parameter if it exists.
256     if (const VarDecl *CatchParam = Handler.Variable) {
257       llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
258       llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
259 
260       CGF.EmitAutoVarDecl(*CatchParam);
261       EmitInitOfCatchParam(CGF, CastExn, CatchParam);
262     }
263     if (CPI)
264         CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
265 
266     CGF.ObjCEHValueStack.push_back(Exn);
267     CGF.EmitStmt(Handler.Body);
268     CGF.ObjCEHValueStack.pop_back();
269 
270     // Leave any cleanups associated with the catch.
271     cleanups.ForceCleanup();
272 
273     CGF.EmitBranchThroughCleanup(Cont);
274   }
275 
276   // Go back to the try-statement fallthrough.
277   CGF.Builder.restoreIP(SavedIP);
278 
279   // Pop out of the finally.
280   if (!useFunclets && S.getFinallyStmt())
281     FinallyInfo.exit(CGF);
282 
283   if (Cont.isValid())
284     CGF.EmitBlock(Cont.getBlock());
285 }
286 
287 void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
288                                          llvm::Value *exn,
289                                          const VarDecl *paramDecl) {
290 
291   Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
292 
293   switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
294   case Qualifiers::OCL_Strong:
295     exn = CGF.EmitARCRetainNonBlock(exn);
296     LLVM_FALLTHROUGH;
297 
298   case Qualifiers::OCL_None:
299   case Qualifiers::OCL_ExplicitNone:
300   case Qualifiers::OCL_Autoreleasing:
301     CGF.Builder.CreateStore(exn, paramAddr);
302     return;
303 
304   case Qualifiers::OCL_Weak:
305     CGF.EmitARCInitWeak(paramAddr, exn);
306     return;
307   }
308   llvm_unreachable("invalid ownership qualifier");
309 }
310 
311 namespace {
312   struct CallSyncExit final : EHScopeStack::Cleanup {
313     llvm::FunctionCallee SyncExitFn;
314     llvm::Value *SyncArg;
315     CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg)
316         : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
317 
318     void Emit(CodeGenFunction &CGF, Flags flags) override {
319       CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg);
320     }
321   };
322 }
323 
324 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
325                                            const ObjCAtSynchronizedStmt &S,
326                                            llvm::FunctionCallee syncEnterFn,
327                                            llvm::FunctionCallee syncExitFn) {
328   CodeGenFunction::RunCleanupsScope cleanups(CGF);
329 
330   // Evaluate the lock operand.  This is guaranteed to dominate the
331   // ARC release and lock-release cleanups.
332   const Expr *lockExpr = S.getSynchExpr();
333   llvm::Value *lock;
334   if (CGF.getLangOpts().ObjCAutoRefCount) {
335     lock = CGF.EmitARCRetainScalarExpr(lockExpr);
336     lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
337   } else {
338     lock = CGF.EmitScalarExpr(lockExpr);
339   }
340   lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
341 
342   // Acquire the lock.
343   CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
344 
345   // Register an all-paths cleanup to release the lock.
346   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
347 
348   // Emit the body of the statement.
349   CGF.EmitStmt(S.getSynchBody());
350 }
351 
352 /// Compute the pointer-to-function type to which a message send
353 /// should be casted in order to correctly call the given method
354 /// with the given arguments.
355 ///
356 /// \param method - may be null
357 /// \param resultType - the result type to use if there's no method
358 /// \param callArgs - the actual arguments, including implicit ones
359 CGObjCRuntime::MessageSendInfo
360 CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
361                                   QualType resultType,
362                                   CallArgList &callArgs) {
363   // If there's a method, use information from that.
364   if (method) {
365     const CGFunctionInfo &signature =
366       CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
367 
368     llvm::PointerType *signatureType =
369       CGM.getTypes().GetFunctionType(signature)->getPointerTo();
370 
371     const CGFunctionInfo &signatureForCall =
372       CGM.getTypes().arrangeCall(signature, callArgs);
373 
374     return MessageSendInfo(signatureForCall, signatureType);
375   }
376 
377   // There's no method;  just use a default CC.
378   const CGFunctionInfo &argsInfo =
379     CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
380 
381   // Derive the signature to call from that.
382   llvm::PointerType *signatureType =
383     CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
384   return MessageSendInfo(argsInfo, signatureType);
385 }
386 
387 bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF,
388                                              const ObjCMethodDecl *method,
389                                              bool isSuper,
390                                        const ObjCInterfaceDecl *classReceiver,
391                                              llvm::Value *receiver) {
392   // Super dispatch assumes that self is non-null; even the messenger
393   // doesn't have a null check internally.
394   if (isSuper)
395     return false;
396 
397   // If this is a direct dispatch of a class method, check whether the class,
398   // or anything in its hierarchy, was weak-linked.
399   if (classReceiver && method && method->isClassMethod())
400     return isWeakLinkedClass(classReceiver);
401 
402   // If we're emitting a method, and self is const (meaning just ARC, for now),
403   // and the receiver is a load of self, then self is a valid object.
404   if (auto curMethod =
405                dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
406     auto self = curMethod->getSelfDecl();
407     if (self->getType().isConstQualified()) {
408       if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) {
409         llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer();
410         if (selfAddr == LI->getPointerOperand()) {
411           return false;
412         }
413       }
414     }
415   }
416 
417   // Otherwise, assume it can be null.
418   return true;
419 }
420 
421 bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
422   do {
423     if (ID->isWeakImported())
424       return true;
425   } while ((ID = ID->getSuperClass()));
426 
427   return false;
428 }
429 
430 void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
431                                               const ObjCMethodDecl *method,
432                                               const CallArgList &callArgs) {
433   CallArgList::const_iterator I = callArgs.begin();
434   for (auto i = method->param_begin(), e = method->param_end();
435          i != e; ++i, ++I) {
436     const ParmVarDecl *param = (*i);
437     if (param->hasAttr<NSConsumedAttr>()) {
438       RValue RV = I->getRValue(CGF);
439       assert(RV.isScalar() &&
440              "NullReturnState::complete - arg not on object");
441       CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
442     } else {
443       QualType QT = param->getType();
444       auto *RT = QT->getAs<RecordType>();
445       if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
446         RValue RV = I->getRValue(CGF);
447         QualType::DestructionKind DtorKind = QT.isDestructedType();
448         switch (DtorKind) {
449         case QualType::DK_cxx_destructor:
450           CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
451           break;
452         case QualType::DK_nontrivial_c_struct:
453           CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
454           break;
455         default:
456           llvm_unreachable("unexpected dtor kind");
457           break;
458         }
459       }
460     }
461   }
462 }
463 
464 llvm::Constant *
465 clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM,
466                                        const ObjCProtocolDecl *protocol) {
467   return CGM.getObjCRuntime().GetOrEmitProtocol(protocol);
468 }
469 
470 std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD,
471                                                   bool includeCategoryName) {
472   std::string buffer;
473   llvm::raw_string_ostream out(buffer);
474   CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out,
475                                        /*includePrefixByte=*/true,
476                                        includeCategoryName);
477   return buffer;
478 }
479