1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Hacks and fun related to the code rewriter.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Frontend/ASTConsumers.h"
15 #include "clang/AST/AST.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Rewrite/Core/Rewriter.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
32 #ifdef CLANG_ENABLE_OBJC_REWRITER
34 using namespace clang;
38 class RewriteObjC : public ASTConsumer {
42 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
47 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
49 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
51 BLOCK_BYREF_CURRENT_MAX = 256
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
62 static const int OBJC_ABI_VERSION = 7;
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
69 TranslationUnitDecl *TUDecl;
71 const char *MainFileStart, *MainFileEnd;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
81 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
86 // ObjC foreach break/continue generation support.
89 unsigned TryFinallyContainsReturnDiag;
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperConstructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
109 /* Misc. containers needed for meta-data rewrite. */
110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
123 // Block expressions.
124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
130 // Block related declarations.
131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
146 // Needed for header files being rewritten
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
151 bool DisableReplaceStmt;
152 class DisableReplaceStmtScope {
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
165 void InitializeCommon(ASTContext &context);
169 // Top Level Driver code.
170 bool HandleTopLevelDecl(DeclGroupRef D) override {
171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173 if (!Class->isThisDeclarationADefinition()) {
174 RewriteForwardClassDecl(D);
179 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
186 HandleTopLevelSingleDecl(*I);
190 void HandleTopLevelSingleDecl(Decl *D);
191 void HandleDeclInMainFile(Decl *D);
192 RewriteObjC(std::string inFile, raw_ostream *OS,
193 DiagnosticsEngine &D, const LangOptions &LOpts,
194 bool silenceMacroWarn);
198 void HandleTranslationUnit(ASTContext &C) override;
200 void ReplaceStmt(Stmt *Old, Stmt *New) {
201 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
204 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
205 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
207 Stmt *ReplacingStmt = ReplacedNodes[Old];
209 return; // We can't rewrite the same node twice.
211 if (DisableReplaceStmt)
214 // Measure the old text.
215 int Size = Rewrite.getRangeSize(SrcRange);
217 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
218 << Old->getSourceRange();
223 llvm::raw_string_ostream S(SStr);
224 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
225 const std::string &Str = S.str();
227 // If replacement succeeded or warning disabled return with no warning.
228 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
229 ReplacedNodes[Old] = New;
232 if (SilenceRewriteMacroWarning)
234 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
235 << Old->getSourceRange();
238 void InsertText(SourceLocation Loc, StringRef Str,
239 bool InsertAfter = true) {
240 // If insertion succeeded or warning disabled return with no warning.
241 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
242 SilenceRewriteMacroWarning)
245 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
248 void ReplaceText(SourceLocation Start, unsigned OrigLength,
250 // If removal succeeded or warning disabled return with no warning.
251 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
252 SilenceRewriteMacroWarning)
255 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
258 // Syntactic Rewriting.
259 void RewriteRecordBody(RecordDecl *RD);
260 void RewriteInclude();
261 void RewriteForwardClassDecl(DeclGroupRef D);
262 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
263 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
264 const std::string &typedefString);
265 void RewriteImplementations();
266 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
267 ObjCImplementationDecl *IMD,
268 ObjCCategoryImplDecl *CID);
269 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
270 void RewriteImplementationDecl(Decl *Dcl);
271 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
272 ObjCMethodDecl *MDecl, std::string &ResultStr);
273 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
274 const FunctionType *&FPRetType);
275 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
276 ValueDecl *VD, bool def=false);
277 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
278 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
279 void RewriteForwardProtocolDecl(DeclGroupRef D);
280 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
281 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
282 void RewriteProperty(ObjCPropertyDecl *prop);
283 void RewriteFunctionDecl(FunctionDecl *FD);
284 void RewriteBlockPointerType(std::string& Str, QualType Type);
285 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
286 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
287 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
288 void RewriteTypeOfDecl(VarDecl *VD);
289 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
291 // Expression Rewriting.
292 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
293 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
294 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
295 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
296 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
297 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
298 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
299 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
300 void RewriteTryReturnStmts(Stmt *S);
301 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
302 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
303 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
304 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
305 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
306 SourceLocation OrigEnd);
307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
309 void RewriteCastExpr(CStyleCastExpr *CE);
312 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
314 // Block specific rewrite rules.
315 void RewriteBlockPointerDecl(NamedDecl *VD);
316 void RewriteByRefVar(VarDecl *VD);
317 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
318 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
319 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
321 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
322 std::string &Result);
324 void Initialize(ASTContext &context) override = 0;
326 // Metadata Rewriting.
327 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
328 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
331 std::string &Result) = 0;
332 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
333 std::string &Result) = 0;
334 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
337 std::string &Result) = 0;
338 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
339 std::string &Result) = 0;
341 // Rewriting ivar access
342 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
343 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
344 std::string &Result) = 0;
346 // Misc. AST transformation routines. Sometimes they end up calling
347 // rewriting routines on the new ASTs.
348 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
349 Expr **args, unsigned nargs,
350 SourceLocation StartLoc=SourceLocation(),
351 SourceLocation EndLoc=SourceLocation());
352 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
353 QualType msgSendType,
355 SmallVectorImpl<QualType> &ArgTypes,
356 SmallVectorImpl<Expr*> &MsgExprs,
357 ObjCMethodDecl *Method);
358 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
362 void SynthCountByEnumWithState(std::string &buf);
363 void SynthMsgSendFunctionDecl();
364 void SynthMsgSendSuperFunctionDecl();
365 void SynthMsgSendStretFunctionDecl();
366 void SynthMsgSendFpretFunctionDecl();
367 void SynthMsgSendSuperStretFunctionDecl();
368 void SynthGetClassFunctionDecl();
369 void SynthGetMetaClassFunctionDecl();
370 void SynthGetSuperClassFunctionDecl();
371 void SynthSelGetUidFunctionDecl();
372 void SynthSuperConstructorFunctionDecl();
374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
375 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
376 StringRef funcName, std::string Tag);
377 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
378 StringRef funcName, std::string Tag);
379 std::string SynthesizeBlockImpl(BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 int i, StringRef funcName,
385 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
386 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
388 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
389 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
390 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
392 // Misc. helper routines.
393 QualType getProtocolType();
394 void WarnAboutReturnGotoStmts(Stmt *S);
395 void HasReturnStmts(Stmt *S, bool &hasReturns);
396 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
397 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
398 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
401 void CollectBlockDeclRefInfo(BlockExpr *Exp);
402 void GetBlockDeclRefExprs(Stmt *S);
403 void GetInnerBlockDeclRefExprs(Stmt *S,
404 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
405 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
407 // We avoid calling Type::isBlockPointerType(), since it operates on the
408 // canonical type. We only care if the top-level type is a closure pointer.
409 bool isTopLevelBlockPointerType(QualType T) {
410 return isa<BlockPointerType>(T);
413 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
414 /// to a function pointer type and upon success, returns true; false
416 bool convertBlockPointerToFunctionPointer(QualType &T) {
417 if (isTopLevelBlockPointerType(T)) {
418 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
419 T = Context->getPointerType(BPT->getPointeeType());
425 bool needToScanForQualifiers(QualType T);
426 QualType getSuperStructType();
427 QualType getConstantStringStructType();
428 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
429 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431 void convertToUnqualifiedObjCType(QualType &T) {
432 if (T->isObjCQualifiedIdType())
433 T = Context->getObjCIdType();
434 else if (T->isObjCQualifiedClassType())
435 T = Context->getObjCClassType();
436 else if (T->isObjCObjectPointerType() &&
437 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
438 if (const ObjCObjectPointerType * OBJPT =
439 T->getAsObjCInterfacePointerType()) {
440 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
441 T = QualType(IFaceT, 0);
442 T = Context->getPointerType(T);
447 // FIXME: This predicate seems like it would be useful to add to ASTContext.
448 bool isObjCType(QualType T) {
449 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
452 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
454 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
455 OCT == Context->getCanonicalType(Context->getObjCClassType()))
458 if (const PointerType *PT = OCT->getAs<PointerType>()) {
459 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
460 PT->getPointeeType()->isObjCQualifiedIdType())
465 bool PointerTypeTakesAnyBlockArguments(QualType QT);
466 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
467 void GetExtentOfArgList(const char *Name, const char *&LParen,
468 const char *&RParen);
470 void QuoteDoublequotes(std::string &From, std::string &To) {
471 for (unsigned i = 0; i < From.length(); i++) {
479 QualType getSimpleFunctionType(QualType result,
480 ArrayRef<QualType> args,
481 bool variadic = false) {
482 if (result == Context->getObjCInstanceType())
483 result = Context->getObjCIdType();
484 FunctionProtoType::ExtProtoInfo fpi;
485 fpi.Variadic = variadic;
486 return Context->getFunctionType(result, args, fpi);
489 // Helper function: create a CStyleCastExpr with trivial type source info.
490 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
491 CastKind Kind, Expr *E) {
492 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
493 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
494 TInfo, SourceLocation(), SourceLocation());
497 StringLiteral *getStringLiteral(StringRef Str) {
498 QualType StrType = Context->getConstantArrayType(
499 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
501 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
502 /*Pascal=*/false, StrType, SourceLocation());
506 class RewriteObjCFragileABI : public RewriteObjC {
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
515 ~RewriteObjCFragileABI() {}
516 void Initialize(ASTContext &context) override;
518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
525 std::string &Result);
526 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix, StringRef ClassName,
528 std::string &Result) override;
529 void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result) override;
532 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result) override;
534 void RewriteMetaDataIntoBuffer(std::string &Result) override;
535 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result) override;
539 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result) override;
541 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
545 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 if (const FunctionProtoType *fproto
548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
549 for (const auto &I : fproto->param_types())
550 if (isTopLevelBlockPointerType(I)) {
551 // All the args are checked/rewritten. Don't call twice!
552 RewriteBlockPointerDecl(D);
558 void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
559 const PointerType *PT = funcType->getAs<PointerType>();
560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
561 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564 static bool IsHeaderFile(const std::string &Filename) {
565 std::string::size_type DotPos = Filename.rfind('.');
567 if (DotPos == std::string::npos) {
572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
574 // C++ header: .hh or .H;
575 return Ext == "h" || Ext == "hh" || Ext == "H";
578 RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
579 DiagnosticsEngine &D, const LangOptions &LOpts,
580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
583 IsHeader = IsHeaderFile(inFile);
584 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
585 "rewriting sub-expression within a macro (may not be correct)");
586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
592 std::unique_ptr<ASTConsumer>
593 clang::CreateObjCRewriter(const std::string &InFile, raw_ostream *OS,
594 DiagnosticsEngine &Diags, const LangOptions &LOpts,
595 bool SilenceRewriteMacroWarning) {
596 return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
597 SilenceRewriteMacroWarning);
600 void RewriteObjC::InitializeCommon(ASTContext &context) {
602 SM = &Context->getSourceManager();
603 TUDecl = Context->getTranslationUnitDecl();
604 MsgSendFunctionDecl = nullptr;
605 MsgSendSuperFunctionDecl = nullptr;
606 MsgSendStretFunctionDecl = nullptr;
607 MsgSendSuperStretFunctionDecl = nullptr;
608 MsgSendFpretFunctionDecl = nullptr;
609 GetClassFunctionDecl = nullptr;
610 GetMetaClassFunctionDecl = nullptr;
611 GetSuperClassFunctionDecl = nullptr;
612 SelGetUidFunctionDecl = nullptr;
613 CFStringFunctionDecl = nullptr;
614 ConstantStringClassReference = nullptr;
615 NSStringRecord = nullptr;
616 CurMethodDef = nullptr;
617 CurFunctionDef = nullptr;
618 CurFunctionDeclToDeclareForBlock = nullptr;
619 GlobalVarDecl = nullptr;
620 SuperStructDecl = nullptr;
621 ProtocolTypeDecl = nullptr;
622 ConstantStringDecl = nullptr;
624 SuperConstructorFunctionDecl = nullptr;
625 NumObjCStringLiterals = 0;
626 PropParentMap = nullptr;
627 CurrentBody = nullptr;
628 DisableReplaceStmt = false;
629 objc_impl_method = false;
631 // Get the ID and start/end of the main file.
632 MainFileID = SM->getMainFileID();
633 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634 MainFileStart = MainBuf->getBufferStart();
635 MainFileEnd = MainBuf->getBufferEnd();
637 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
640 //===----------------------------------------------------------------------===//
641 // Top Level Driver Code
642 //===----------------------------------------------------------------------===//
644 void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
645 if (Diags.hasErrorOccurred())
648 // Two cases: either the decl could be in the main file, or it could be in a
649 // #included file. If the former, rewrite it now. If the later, check to see
650 // if we rewrote the #include/#import.
651 SourceLocation Loc = D->getLocation();
652 Loc = SM->getExpansionLoc(Loc);
654 // If this is for a builtin, ignore it.
655 if (Loc.isInvalid()) return;
657 // Look for built-in declarations that we need to refer during the rewrite.
658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
659 RewriteFunctionDecl(FD);
660 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
661 // declared in <Foundation/NSString.h>
662 if (FVD->getName() == "_NSConstantStringClassReference") {
663 ConstantStringClassReference = FVD;
666 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667 if (ID->isThisDeclarationADefinition())
668 RewriteInterfaceDecl(ID);
669 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670 RewriteCategoryDecl(CD);
671 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
674 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675 // Recurse into linkage specifications
676 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677 DIEnd = LSD->decls_end();
679 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
682 SourceLocation StartLoc = IFace->getLocStart();
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
692 } while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
698 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
701 SourceLocation StartLoc = Proto->getLocStart();
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
711 } while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
717 HandleTopLevelSingleDecl(*DI);
721 // If we have a decl in the main file, see if we should rewrite it.
722 if (SM->isWrittenInMainFile(Loc))
723 return HandleDeclInMainFile(D);
726 //===----------------------------------------------------------------------===//
727 // Syntactic (non-AST) Rewriting Code
728 //===----------------------------------------------------------------------===//
730 void RewriteObjC::RewriteInclude() {
731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732 StringRef MainBuf = SM->getBufferData(MainFileID);
733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
735 size_t ImportLen = strlen("import");
737 // Loop over the whole file, looking for includes.
738 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr == '#') {
740 if (++BufPtr == MainBufEnd)
742 while (*BufPtr == ' ' || *BufPtr == '\t')
743 if (++BufPtr == MainBufEnd)
745 if (!strncmp(BufPtr, "import", ImportLen)) {
746 // replace import with include
747 SourceLocation ImportLoc =
748 LocStart.getLocWithOffset(BufPtr-MainBufStart);
749 ReplaceText(ImportLoc, ImportLen, "include");
756 static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
766 void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
771 SourceLocation startLoc = PID->getLocStart();
772 InsertText(startLoc, "// ");
773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777 SourceLocation onePastSemiLoc =
778 startLoc.getLocWithOffset(semiBuf-startBuf+1);
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
783 // Generate the 'getter' function.
784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
789 unsigned Attributes = PD->getPropertyAttributes();
790 if (!PD->getGetterMethodDecl()->isDefined()) {
791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793 ObjCPropertyDecl::OBJC_PR_copy));
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 const FunctionType *FPRetType = nullptr;
810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
814 Getr += ")"; // close the precedence "scope" for "*".
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
821 std::string ParamStr =
822 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
825 if (FT->isVariadic()) {
826 if (FT->getNumParams())
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
837 RewriteIvarOffsetComputation(OID, Getr);
841 Getr += "return " + getIvarAccessString(OID);
843 InsertText(onePastSemiLoc, Getr);
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
849 // Generate the 'setter' function.
851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
863 // Synthesize an explicit cast to initialize the ivar.
864 // See objc-act.c:objc_synthesize_new_setter() for details.
865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
867 RewriteIvarOffsetComputation(OID, Setr);
869 Setr += PD->getName();
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
881 Setr += getIvarAccessString(OID) + " = ";
882 Setr += PD->getName();
885 InsertText(onePastSemiLoc, Setr);
888 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
901 void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
902 const std::string &typedefString) {
903 SourceLocation startLoc = ClassDecl->getLocStart();
904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
910 void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
911 std::string typedefString;
912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
914 if (I == D.begin()) {
915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
920 typedefString += ";\n";
922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
924 DeclGroupRef::iterator I = D.begin();
925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
928 void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
929 std::string typedefString;
930 for (unsigned i = 0; i < D.size(); i++) {
931 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
933 typedefString += "// @class ";
934 typedefString += ForwardDecl->getNameAsString();
935 typedefString += ";\n";
937 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
942 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
943 // When method is a synthesized one, such as a getter/setter there is
944 // nothing to rewrite.
945 if (Method->isImplicit())
947 SourceLocation LocStart = Method->getLocStart();
948 SourceLocation LocEnd = Method->getLocEnd();
950 if (SM->getExpansionLineNumber(LocEnd) >
951 SM->getExpansionLineNumber(LocStart)) {
952 InsertText(LocStart, "#if 0\n");
953 ReplaceText(LocEnd, 1, ";\n#endif\n");
955 InsertText(LocStart, "// ");
959 void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
960 SourceLocation Loc = prop->getAtLoc();
962 ReplaceText(Loc, 0, "// ");
963 // FIXME: handle properties that are declared across multiple lines.
966 void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
967 SourceLocation LocStart = CatDecl->getLocStart();
969 // FIXME: handle category headers that are declared across multiple lines.
970 ReplaceText(LocStart, 0, "// ");
972 for (auto *I : CatDecl->properties())
974 for (auto *I : CatDecl->instance_methods())
975 RewriteMethodDeclaration(I);
976 for (auto *I : CatDecl->class_methods())
977 RewriteMethodDeclaration(I);
979 // Lastly, comment out the @end.
980 ReplaceText(CatDecl->getAtEndRange().getBegin(),
981 strlen("@end"), "/* @end */");
984 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
985 SourceLocation LocStart = PDecl->getLocStart();
986 assert(PDecl->isThisDeclarationADefinition());
988 // FIXME: handle protocol headers that are declared across multiple lines.
989 ReplaceText(LocStart, 0, "// ");
991 for (auto *I : PDecl->instance_methods())
992 RewriteMethodDeclaration(I);
993 for (auto *I : PDecl->class_methods())
994 RewriteMethodDeclaration(I);
995 for (auto *I : PDecl->properties())
998 // Lastly, comment out the @end.
999 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1000 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1002 // Must comment out @optional/@required
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
1005 for (const char *p = startBuf; p < endBuf; p++) {
1006 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1007 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1008 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1011 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1012 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1013 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1019 void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020 SourceLocation LocStart = (*D.begin())->getLocStart();
1021 if (LocStart.isInvalid())
1022 llvm_unreachable("Invalid SourceLocation");
1023 // FIXME: handle forward protocol that are declared across multiple lines.
1024 ReplaceText(LocStart, 0, "// ");
1028 RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1029 SourceLocation LocStart = DG[0]->getLocStart();
1030 if (LocStart.isInvalid())
1031 llvm_unreachable("Invalid SourceLocation");
1032 // FIXME: handle forward protocol that are declared across multiple lines.
1033 ReplaceText(LocStart, 0, "// ");
1036 void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037 const FunctionType *&FPRetType) {
1038 if (T->isObjCQualifiedIdType())
1040 else if (T->isFunctionPointerType() ||
1041 T->isBlockPointerType()) {
1042 // needs special handling, since pointer-to-functions have special
1043 // syntax (where a decaration models use).
1044 QualType retType = T;
1046 if (const PointerType* PT = retType->getAs<PointerType>())
1047 PointeeTy = PT->getPointeeType();
1048 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1049 PointeeTy = BPT->getPointeeType();
1050 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1052 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1056 ResultStr += T.getAsString(Context->getPrintingPolicy());
1059 void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060 ObjCMethodDecl *OMD,
1061 std::string &ResultStr) {
1062 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1063 const FunctionType *FPRetType = nullptr;
1064 ResultStr += "\nstatic ";
1065 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1068 // Unique method name
1069 std::string NameStr;
1071 if (OMD->isInstanceMethod())
1076 NameStr += IDecl->getNameAsString();
1079 if (ObjCCategoryImplDecl *CID =
1080 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1081 NameStr += CID->getNameAsString();
1084 // Append selector names, replacing ':' with '_'
1086 std::string selString = OMD->getSelector().getAsString();
1087 int len = selString.size();
1088 for (int i = 0; i < len; i++)
1089 if (selString[i] == ':')
1091 NameStr += selString;
1093 // Remember this name for metadata emission
1094 MethodInternalNames[OMD] = NameStr;
1095 ResultStr += NameStr;
1097 // Rewrite arguments
1100 // invisible arguments
1101 if (OMD->isInstanceMethod()) {
1102 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1103 selfTy = Context->getPointerType(selfTy);
1104 if (!LangOpts.MicrosoftExt) {
1105 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1106 ResultStr += "struct ";
1108 // When rewriting for Microsoft, explicitly omit the structure name.
1109 ResultStr += IDecl->getNameAsString();
1113 ResultStr += Context->getObjCClassType().getAsString(
1114 Context->getPrintingPolicy());
1116 ResultStr += " self, ";
1117 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1118 ResultStr += " _cmd";
1120 // Method arguments.
1121 for (const auto *PDecl : OMD->params()) {
1123 if (PDecl->getType()->isObjCQualifiedIdType()) {
1125 ResultStr += PDecl->getNameAsString();
1127 std::string Name = PDecl->getNameAsString();
1128 QualType QT = PDecl->getType();
1129 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1130 (void)convertBlockPointerToFunctionPointer(QT);
1131 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
1140 ResultStr += ")"; // close the precedence "scope" for "*".
1142 // Now, emit the argument types (if any).
1143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1145 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1146 if (i) ResultStr += ", ";
1147 std::string ParamStr =
1148 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1149 ResultStr += ParamStr;
1151 if (FT->isVariadic()) {
1152 if (FT->getNumParams())
1162 void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1163 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1164 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1166 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1168 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1169 std::string ResultStr;
1170 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1171 SourceLocation LocStart = OMD->getLocStart();
1172 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1174 const char *startBuf = SM->getCharacterData(LocStart);
1175 const char *endBuf = SM->getCharacterData(LocEnd);
1176 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1179 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1180 std::string ResultStr;
1181 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1182 SourceLocation LocStart = OMD->getLocStart();
1183 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1185 const char *startBuf = SM->getCharacterData(LocStart);
1186 const char *endBuf = SM->getCharacterData(LocEnd);
1187 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1189 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1190 RewritePropertyImplDecl(I, IMD, CID);
1192 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1195 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1196 std::string ResultStr;
1197 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1198 // we haven't seen a forward decl - generate a typedef.
1199 ResultStr = "#ifndef _REWRITER_typedef_";
1200 ResultStr += ClassDecl->getNameAsString();
1202 ResultStr += "#define _REWRITER_typedef_";
1203 ResultStr += ClassDecl->getNameAsString();
1205 ResultStr += "typedef struct objc_object ";
1206 ResultStr += ClassDecl->getNameAsString();
1207 ResultStr += ";\n#endif\n";
1208 // Mark this typedef as having been generated.
1209 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1211 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1213 for (auto *I : ClassDecl->properties())
1215 for (auto *I : ClassDecl->instance_methods())
1216 RewriteMethodDeclaration(I);
1217 for (auto *I : ClassDecl->class_methods())
1218 RewriteMethodDeclaration(I);
1220 // Lastly, comment out the @end.
1221 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1225 Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1226 SourceRange OldRange = PseudoOp->getSourceRange();
1228 // We just magically know some things about the structure of this
1230 ObjCMessageExpr *OldMsg =
1231 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1232 PseudoOp->getNumSemanticExprs() - 1));
1234 // Because the rewriter doesn't allow us to rewrite rewritten code,
1235 // we need to suppress rewriting the sub-statements.
1238 DisableReplaceStmtScope S(*this);
1240 // Rebuild the base expression if we have one.
1242 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1243 Base = OldMsg->getInstanceReceiver();
1244 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1249 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1250 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1254 // TODO: avoid this copy.
1255 SmallVector<SourceLocation, 1> SelLocs;
1256 OldMsg->getSelectorLocs(SelLocs);
1258 ObjCMessageExpr *NewMsg = nullptr;
1259 switch (OldMsg->getReceiverKind()) {
1260 case ObjCMessageExpr::Class:
1261 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1262 OldMsg->getValueKind(),
1263 OldMsg->getLeftLoc(),
1264 OldMsg->getClassReceiverTypeInfo(),
1265 OldMsg->getSelector(),
1267 OldMsg->getMethodDecl(),
1269 OldMsg->getRightLoc(),
1270 OldMsg->isImplicit());
1273 case ObjCMessageExpr::Instance:
1274 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1275 OldMsg->getValueKind(),
1276 OldMsg->getLeftLoc(),
1278 OldMsg->getSelector(),
1280 OldMsg->getMethodDecl(),
1282 OldMsg->getRightLoc(),
1283 OldMsg->isImplicit());
1286 case ObjCMessageExpr::SuperClass:
1287 case ObjCMessageExpr::SuperInstance:
1288 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1289 OldMsg->getValueKind(),
1290 OldMsg->getLeftLoc(),
1291 OldMsg->getSuperLoc(),
1292 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1293 OldMsg->getSuperType(),
1294 OldMsg->getSelector(),
1296 OldMsg->getMethodDecl(),
1298 OldMsg->getRightLoc(),
1299 OldMsg->isImplicit());
1303 Stmt *Replacement = SynthMessageExpr(NewMsg);
1304 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1308 Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1309 SourceRange OldRange = PseudoOp->getSourceRange();
1311 // We just magically know some things about the structure of this
1313 ObjCMessageExpr *OldMsg =
1314 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1316 // Because the rewriter doesn't allow us to rewrite rewritten code,
1317 // we need to suppress rewriting the sub-statements.
1318 Expr *Base = nullptr;
1320 DisableReplaceStmtScope S(*this);
1322 // Rebuild the base expression if we have one.
1323 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1324 Base = OldMsg->getInstanceReceiver();
1325 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1326 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1330 // Intentionally empty.
1331 SmallVector<SourceLocation, 1> SelLocs;
1332 SmallVector<Expr*, 1> Args;
1334 ObjCMessageExpr *NewMsg = nullptr;
1335 switch (OldMsg->getReceiverKind()) {
1336 case ObjCMessageExpr::Class:
1337 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1338 OldMsg->getValueKind(),
1339 OldMsg->getLeftLoc(),
1340 OldMsg->getClassReceiverTypeInfo(),
1341 OldMsg->getSelector(),
1343 OldMsg->getMethodDecl(),
1345 OldMsg->getRightLoc(),
1346 OldMsg->isImplicit());
1349 case ObjCMessageExpr::Instance:
1350 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1351 OldMsg->getValueKind(),
1352 OldMsg->getLeftLoc(),
1354 OldMsg->getSelector(),
1356 OldMsg->getMethodDecl(),
1358 OldMsg->getRightLoc(),
1359 OldMsg->isImplicit());
1362 case ObjCMessageExpr::SuperClass:
1363 case ObjCMessageExpr::SuperInstance:
1364 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1365 OldMsg->getValueKind(),
1366 OldMsg->getLeftLoc(),
1367 OldMsg->getSuperLoc(),
1368 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1369 OldMsg->getSuperType(),
1370 OldMsg->getSelector(),
1372 OldMsg->getMethodDecl(),
1374 OldMsg->getRightLoc(),
1375 OldMsg->isImplicit());
1379 Stmt *Replacement = SynthMessageExpr(NewMsg);
1380 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1384 /// SynthCountByEnumWithState - To print:
1385 /// ((unsigned int (*)
1386 /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1387 /// (void *)objc_msgSend)((id)l_collection,
1388 /// sel_registerName(
1389 /// "countByEnumeratingWithState:objects:count:"),
1391 /// (id *)__rw_items, (unsigned int)16)
1393 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1394 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1395 "id *, unsigned int))(void *)objc_msgSend)";
1397 buf += "((id)l_collection,\n\t\t";
1398 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1400 buf += "&enumState, "
1401 "(id *)__rw_items, (unsigned int)16)";
1404 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1405 /// statement to exit to its outer synthesized loop.
1407 Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1408 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1410 // replace break with goto __break_label
1413 SourceLocation startLoc = S->getLocStart();
1414 buf = "goto __break_label_";
1415 buf += utostr(ObjCBcLabelNo.back());
1416 ReplaceText(startLoc, strlen("break"), buf);
1421 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1422 /// statement to continue with its inner synthesized loop.
1424 Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1425 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1427 // replace continue with goto __continue_label
1430 SourceLocation startLoc = S->getLocStart();
1431 buf = "goto __continue_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
1433 ReplaceText(startLoc, strlen("continue"), buf);
1438 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1440 /// for ( type elem in collection) { stmts; }
1445 /// struct __objcFastEnumerationState enumState = { 0 };
1446 /// id __rw_items[16];
1447 /// id l_collection = (id)collection;
1448 /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1449 /// objects:__rw_items count:16];
1451 /// unsigned long startMutations = *enumState.mutationsPtr;
1453 /// unsigned long counter = 0;
1455 /// if (startMutations != *enumState.mutationsPtr)
1456 /// objc_enumerationMutation(l_collection);
1457 /// elem = (type)enumState.itemsPtr[counter++];
1459 /// __continue_label: ;
1460 /// } while (counter < limit);
1461 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1462 /// objects:__rw_items count:16]);
1464 /// __break_label: ;
1470 Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1471 SourceLocation OrigEnd) {
1472 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1473 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1474 "ObjCForCollectionStmt Statement stack mismatch");
1475 assert(!ObjCBcLabelNo.empty() &&
1476 "ObjCForCollectionStmt - Label No stack empty");
1478 SourceLocation startLoc = S->getLocStart();
1479 const char *startBuf = SM->getCharacterData(startLoc);
1480 StringRef elementName;
1481 std::string elementTypeAsString;
1484 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1486 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1487 QualType ElementType = cast<ValueDecl>(D)->getType();
1488 if (ElementType->isObjCQualifiedIdType() ||
1489 ElementType->isObjCQualifiedInterfaceType())
1490 // Simply use 'id' for all qualified types.
1491 elementTypeAsString = "id";
1493 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1494 buf += elementTypeAsString;
1496 elementName = D->getName();
1501 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1502 elementName = DR->getDecl()->getName();
1503 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1504 if (VD->getType()->isObjCQualifiedIdType() ||
1505 VD->getType()->isObjCQualifiedInterfaceType())
1506 // Simply use 'id' for all qualified types.
1507 elementTypeAsString = "id";
1509 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1512 // struct __objcFastEnumerationState enumState = { 0 };
1513 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1514 // id __rw_items[16];
1515 buf += "id __rw_items[16];\n\t";
1516 // id l_collection = (id)
1517 buf += "id l_collection = (id)";
1518 // Find start location of 'collection' the hard way!
1519 const char *startCollectionBuf = startBuf;
1520 startCollectionBuf += 3; // skip 'for'
1521 startCollectionBuf = strchr(startCollectionBuf, '(');
1522 startCollectionBuf++; // skip '('
1523 // find 'in' and skip it.
1524 while (*startCollectionBuf != ' ' ||
1525 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1526 (*(startCollectionBuf+3) != ' ' &&
1527 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1528 startCollectionBuf++;
1529 startCollectionBuf += 3;
1531 // Replace: "for (type element in" with string constructed thus far.
1532 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1533 // Replace ')' in for '(' type elem in collection ')' with ';'
1534 SourceLocation rightParenLoc = S->getRParenLoc();
1535 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1536 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1539 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1540 // objects:__rw_items count:16];
1541 // which is synthesized into:
1542 // unsigned int limit =
1543 // ((unsigned int (*)
1544 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1545 // (void *)objc_msgSend)((id)l_collection,
1546 // sel_registerName(
1547 // "countByEnumeratingWithState:objects:count:"),
1548 // (struct __objcFastEnumerationState *)&state,
1549 // (id *)__rw_items, (unsigned int)16);
1550 buf += "unsigned long limit =\n\t\t";
1551 SynthCountByEnumWithState(buf);
1554 /// unsigned long startMutations = *enumState.mutationsPtr;
1556 /// unsigned long counter = 0;
1558 /// if (startMutations != *enumState.mutationsPtr)
1559 /// objc_enumerationMutation(l_collection);
1560 /// elem = (type)enumState.itemsPtr[counter++];
1561 buf += "if (limit) {\n\t";
1562 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1563 buf += "do {\n\t\t";
1564 buf += "unsigned long counter = 0;\n\t\t";
1565 buf += "do {\n\t\t\t";
1566 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1567 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1570 buf += elementTypeAsString;
1571 buf += ")enumState.itemsPtr[counter++];";
1572 // Replace ')' in for '(' type elem in collection ')' with all of these.
1573 ReplaceText(lparenLoc, 1, buf);
1575 /// __continue_label: ;
1576 /// } while (counter < limit);
1577 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1578 /// objects:__rw_items count:16]);
1580 /// __break_label: ;
1587 buf += "__continue_label_";
1588 buf += utostr(ObjCBcLabelNo.back());
1591 buf += "} while (counter < limit);\n\t";
1592 buf += "} while (limit = ";
1593 SynthCountByEnumWithState(buf);
1597 buf += elementTypeAsString;
1599 buf += "__break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
1603 buf += "else\n\t\t";
1606 buf += elementTypeAsString;
1610 // Insert all these *after* the statement body.
1611 // FIXME: If this should support Obj-C++, support CXXTryStmt
1612 if (isa<CompoundStmt>(S->getBody())) {
1613 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1614 InsertText(endBodyLoc, buf);
1616 /* Need to treat single statements specially. For example:
1618 * for (A *a in b) if (stuff()) break;
1619 * for (A *a in b) xxxyy;
1621 * The following code simply scans ahead to the semi to find the actual end.
1623 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1624 const char *semiBuf = strchr(stmtBuf, ';');
1625 assert(semiBuf && "Can't find ';'");
1626 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1627 InsertText(endBodyLoc, buf);
1630 ObjCBcLabelNo.pop_back();
1634 /// RewriteObjCSynchronizedStmt -
1635 /// This routine rewrites @synchronized(expr) stmt;
1637 /// objc_sync_enter(expr);
1638 /// @try stmt @finally { objc_sync_exit(expr); }
1640 Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1641 // Get the start location and compute the semi location.
1642 SourceLocation startLoc = S->getLocStart();
1643 const char *startBuf = SM->getCharacterData(startLoc);
1645 assert((*startBuf == '@') && "bogus @synchronized location");
1648 buf = "objc_sync_enter((id)";
1649 const char *lparenBuf = startBuf;
1650 while (*lparenBuf != '(') lparenBuf++;
1651 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1652 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1653 // the sync expression is typically a message expression that's already
1654 // been rewritten! (which implies the SourceLocation's are invalid).
1655 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1656 const char *endBuf = SM->getCharacterData(endLoc);
1657 while (*endBuf != ')') endBuf--;
1658 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1660 // declare a new scope with two variables, _stack and _rethrow.
1661 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1662 buf += "int buf[18/*32-bit i386*/];\n";
1663 buf += "char *pointers[4];} _stack;\n";
1664 buf += "id volatile _rethrow = 0;\n";
1665 buf += "objc_exception_try_enter(&_stack);\n";
1666 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1667 ReplaceText(rparenLoc, 1, buf);
1668 startLoc = S->getSynchBody()->getLocEnd();
1669 startBuf = SM->getCharacterData(startLoc);
1671 assert((*startBuf == '}') && "bogus @synchronized block");
1672 SourceLocation lastCurlyLoc = startLoc;
1673 buf = "}\nelse {\n";
1674 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1676 buf += "{ /* implicit finally clause */\n";
1677 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1679 std::string syncBuf;
1680 syncBuf += " objc_sync_exit(";
1682 Expr *syncExpr = S->getSynchExpr();
1683 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1685 syncExpr->getType()->isBlockPointerType()
1686 ? CK_BlockPointerToObjCPointerCast
1687 : CK_CPointerToObjCPointerCast;
1688 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1690 std::string syncExprBufS;
1691 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1692 assert(syncExpr != nullptr && "Expected non-null Expr");
1693 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1694 syncBuf += syncExprBuf.str();
1698 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1702 ReplaceText(lastCurlyLoc, 1, buf);
1704 bool hasReturns = false;
1705 HasReturnStmts(S->getSynchBody(), hasReturns);
1707 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1712 void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1714 // Perform a bottom up traversal of all children.
1715 for (Stmt::child_range CI = S->children(); CI; ++CI)
1717 WarnAboutReturnGotoStmts(*CI);
1719 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1720 Diags.Report(Context->getFullLoc(S->getLocStart()),
1721 TryFinallyContainsReturnDiag);
1726 void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1728 // Perform a bottom up traversal of all children.
1729 for (Stmt::child_range CI = S->children(); CI; ++CI)
1731 HasReturnStmts(*CI, hasReturns);
1733 if (isa<ReturnStmt>(S))
1738 void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739 // Perform a bottom up traversal of all children.
1740 for (Stmt::child_range CI = S->children(); CI; ++CI)
1742 RewriteTryReturnStmts(*CI);
1744 if (isa<ReturnStmt>(S)) {
1745 SourceLocation startLoc = S->getLocStart();
1746 const char *startBuf = SM->getCharacterData(startLoc);
1748 const char *semiBuf = strchr(startBuf, ';');
1749 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1750 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1753 buf = "{ objc_exception_try_exit(&_stack); return";
1755 ReplaceText(startLoc, 6, buf);
1756 InsertText(onePastSemiLoc, "}");
1761 void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1762 // Perform a bottom up traversal of all children.
1763 for (Stmt::child_range CI = S->children(); CI; ++CI)
1765 RewriteSyncReturnStmts(*CI, syncExitBuf);
1767 if (isa<ReturnStmt>(S)) {
1768 SourceLocation startLoc = S->getLocStart();
1769 const char *startBuf = SM->getCharacterData(startLoc);
1771 const char *semiBuf = strchr(startBuf, ';');
1772 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1773 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1776 buf = "{ objc_exception_try_exit(&_stack);";
1780 ReplaceText(startLoc, 6, buf);
1781 InsertText(onePastSemiLoc, "}");
1786 Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1787 // Get the start location and compute the semi location.
1788 SourceLocation startLoc = S->getLocStart();
1789 const char *startBuf = SM->getCharacterData(startLoc);
1791 assert((*startBuf == '@') && "bogus @try location");
1794 // declare a new scope with two variables, _stack and _rethrow.
1795 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1796 buf += "int buf[18/*32-bit i386*/];\n";
1797 buf += "char *pointers[4];} _stack;\n";
1798 buf += "id volatile _rethrow = 0;\n";
1799 buf += "objc_exception_try_enter(&_stack);\n";
1800 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1802 ReplaceText(startLoc, 4, buf);
1804 startLoc = S->getTryBody()->getLocEnd();
1805 startBuf = SM->getCharacterData(startLoc);
1807 assert((*startBuf == '}') && "bogus @try block");
1809 SourceLocation lastCurlyLoc = startLoc;
1810 if (S->getNumCatchStmts()) {
1811 startLoc = startLoc.getLocWithOffset(1);
1812 buf = " /* @catch begin */ else {\n";
1813 buf += " id _caught = objc_exception_extract(&_stack);\n";
1814 buf += " objc_exception_try_enter (&_stack);\n";
1815 buf += " if (_setjmp(_stack.buf))\n";
1816 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1817 buf += " else { /* @catch continue */";
1819 InsertText(startLoc, buf);
1820 } else { /* no catch list */
1821 buf = "}\nelse {\n";
1822 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1824 ReplaceText(lastCurlyLoc, 1, buf);
1826 Stmt *lastCatchBody = nullptr;
1827 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1828 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1829 VarDecl *catchDecl = Catch->getCatchParamDecl();
1832 buf = "if ("; // we are generating code for the first catch clause
1835 startLoc = Catch->getLocStart();
1836 startBuf = SM->getCharacterData(startLoc);
1838 assert((*startBuf == '@') && "bogus @catch location");
1840 const char *lParenLoc = strchr(startBuf, '(');
1842 if (Catch->hasEllipsis()) {
1843 // Now rewrite the body...
1844 lastCatchBody = Catch->getCatchBody();
1845 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1846 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1847 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1848 "bogus @catch paren location");
1849 assert((*bodyBuf == '{') && "bogus @catch body location");
1851 buf += "1) { id _tmp = _caught;";
1852 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1853 } else if (catchDecl) {
1854 QualType t = catchDecl->getType();
1855 if (t == Context->getObjCIdType()) {
1857 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1858 } else if (const ObjCObjectPointerType *Ptr =
1859 t->getAs<ObjCObjectPointerType>()) {
1860 // Should be a pointer to a class.
1861 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1863 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1864 buf += IDecl->getNameAsString();
1865 buf += "\"), (struct objc_object *)_caught)) { ";
1866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1869 // Now rewrite the body...
1870 lastCatchBody = Catch->getCatchBody();
1871 SourceLocation rParenLoc = Catch->getRParenLoc();
1872 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1873 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1874 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1875 assert((*rParenBuf == ')') && "bogus @catch paren location");
1876 assert((*bodyBuf == '{') && "bogus @catch body location");
1878 // Here we replace ") {" with "= _caught;" (which initializes and
1879 // declares the @catch parameter).
1880 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1882 llvm_unreachable("@catch rewrite bug");
1885 // Complete the catch list...
1886 if (lastCatchBody) {
1887 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1888 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1889 "bogus @catch body location");
1891 // Insert the last (implicit) else clause *before* the right curly brace.
1892 bodyLoc = bodyLoc.getLocWithOffset(-1);
1893 buf = "} /* last catch end */\n";
1895 buf += " _rethrow = _caught;\n";
1896 buf += " objc_exception_try_exit(&_stack);\n";
1897 buf += "} } /* @catch end */\n";
1898 if (!S->getFinallyStmt())
1900 InsertText(bodyLoc, buf);
1903 lastCurlyLoc = lastCatchBody->getLocEnd();
1905 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1906 startLoc = finalStmt->getLocStart();
1907 startBuf = SM->getCharacterData(startLoc);
1908 assert((*startBuf == '@') && "bogus @finally start");
1910 ReplaceText(startLoc, 8, "/* @finally */");
1912 Stmt *body = finalStmt->getFinallyBody();
1913 SourceLocation startLoc = body->getLocStart();
1914 SourceLocation endLoc = body->getLocEnd();
1915 assert(*SM->getCharacterData(startLoc) == '{' &&
1916 "bogus @finally body location");
1917 assert(*SM->getCharacterData(endLoc) == '}' &&
1918 "bogus @finally body location");
1920 startLoc = startLoc.getLocWithOffset(1);
1921 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1922 endLoc = endLoc.getLocWithOffset(-1);
1923 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1926 lastCurlyLoc = body->getLocEnd();
1928 // Now check for any return/continue/go statements within the @try.
1929 WarnAboutReturnGotoStmts(S->getTryBody());
1930 } else { /* no finally clause - make sure we synthesize an implicit one */
1931 buf = "{ /* implicit finally clause */\n";
1932 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1933 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1935 ReplaceText(lastCurlyLoc, 1, buf);
1937 // Now check for any return/continue/go statements within the @try.
1938 // The implicit finally clause won't called if the @try contains any
1940 bool hasReturns = false;
1941 HasReturnStmts(S->getTryBody(), hasReturns);
1943 RewriteTryReturnStmts(S->getTryBody());
1945 // Now emit the final closing curly brace...
1946 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1947 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1951 // This can't be done with ReplaceStmt(S, ThrowExpr), since
1952 // the throw expression is typically a message expression that's already
1953 // been rewritten! (which implies the SourceLocation's are invalid).
1954 Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1955 // Get the start location and compute the semi location.
1956 SourceLocation startLoc = S->getLocStart();
1957 const char *startBuf = SM->getCharacterData(startLoc);
1959 assert((*startBuf == '@') && "bogus @throw location");
1962 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1963 if (S->getThrowExpr())
1964 buf = "objc_exception_throw(";
1965 else // add an implicit argument
1966 buf = "objc_exception_throw(_caught";
1968 // handle "@ throw" correctly.
1969 const char *wBuf = strchr(startBuf, 'w');
1970 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1971 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1973 const char *semiBuf = strchr(startBuf, ';');
1974 assert((*semiBuf == ';') && "@throw: can't find ';'");
1975 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1976 ReplaceText(semiLoc, 1, ");");
1980 Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1981 // Create a new string expression.
1982 std::string StrEncoding;
1983 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1984 Expr *Replacement = getStringLiteral(StrEncoding);
1985 ReplaceStmt(Exp, Replacement);
1987 // Replace this subexpr in the parent.
1988 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1992 Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1993 if (!SelGetUidFunctionDecl)
1994 SynthSelGetUidFunctionDecl();
1995 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1996 // Create a call to sel_registerName("selName").
1997 SmallVector<Expr*, 8> SelExprs;
1998 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
1999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2000 &SelExprs[0], SelExprs.size());
2001 ReplaceStmt(Exp, SelExp);
2002 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2006 CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
2007 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2008 SourceLocation EndLoc) {
2009 // Get the type, we will need to reference it in a couple spots.
2010 QualType msgSendType = FD->getType();
2012 // Create a reference to the objc_msgSend() declaration.
2013 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2014 VK_LValue, SourceLocation());
2016 // Now, we cast the reference to a pointer to the objc_msgSend type.
2017 QualType pToFunc = Context->getPointerType(msgSendType);
2018 ImplicitCastExpr *ICE =
2019 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2020 DRE, nullptr, VK_RValue);
2022 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2025 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
2026 FT->getCallResultType(*Context),
2031 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2032 const char *&startRef, const char *&endRef) {
2033 while (startBuf < endBuf) {
2034 if (*startBuf == '<')
2035 startRef = startBuf; // mark the start.
2036 if (*startBuf == '>') {
2037 if (startRef && *startRef == '<') {
2038 endRef = startBuf; // mark the end.
2048 static void scanToNextArgument(const char *&argRef) {
2050 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2053 else if (*argRef == '>')
2057 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2060 bool RewriteObjC::needToScanForQualifiers(QualType T) {
2061 if (T->isObjCQualifiedIdType())
2063 if (const PointerType *PT = T->getAs<PointerType>()) {
2064 if (PT->getPointeeType()->isObjCQualifiedIdType())
2067 if (T->isObjCObjectPointerType()) {
2068 T = T->getPointeeType();
2069 return T->isObjCQualifiedInterfaceType();
2071 if (T->isArrayType()) {
2072 QualType ElemTy = Context->getBaseElementType(T);
2073 return needToScanForQualifiers(ElemTy);
2078 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2079 QualType Type = E->getType();
2080 if (needToScanForQualifiers(Type)) {
2081 SourceLocation Loc, EndLoc;
2083 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2084 Loc = ECE->getLParenLoc();
2085 EndLoc = ECE->getRParenLoc();
2087 Loc = E->getLocStart();
2088 EndLoc = E->getLocEnd();
2090 // This will defend against trying to rewrite synthesized expressions.
2091 if (Loc.isInvalid() || EndLoc.isInvalid())
2094 const char *startBuf = SM->getCharacterData(Loc);
2095 const char *endBuf = SM->getCharacterData(EndLoc);
2096 const char *startRef = nullptr, *endRef = nullptr;
2097 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2098 // Get the locations of the startRef, endRef.
2099 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2100 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2101 // Comment out the protocol references.
2102 InsertText(LessLoc, "/*");
2103 InsertText(GreaterLoc, "*/");
2108 void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2111 const FunctionProtoType *proto = nullptr;
2112 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2113 Loc = VD->getLocation();
2114 Type = VD->getType();
2116 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2117 Loc = FD->getLocation();
2118 // Check for ObjC 'id' and class types that have been adorned with protocol
2119 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2120 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2121 assert(funcType && "missing function type");
2122 proto = dyn_cast<FunctionProtoType>(funcType);
2125 Type = proto->getReturnType();
2127 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2128 Loc = FD->getLocation();
2129 Type = FD->getType();
2134 if (needToScanForQualifiers(Type)) {
2135 // Since types are unique, we need to scan the buffer.
2137 const char *endBuf = SM->getCharacterData(Loc);
2138 const char *startBuf = endBuf;
2139 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2140 startBuf--; // scan backward (from the decl location) for return type.
2141 const char *startRef = nullptr, *endRef = nullptr;
2142 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2143 // Get the locations of the startRef, endRef.
2144 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2145 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2146 // Comment out the protocol references.
2147 InsertText(LessLoc, "/*");
2148 InsertText(GreaterLoc, "*/");
2152 return; // most likely, was a variable
2153 // Now check arguments.
2154 const char *startBuf = SM->getCharacterData(Loc);
2155 const char *startFuncBuf = startBuf;
2156 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2157 if (needToScanForQualifiers(proto->getParamType(i))) {
2158 // Since types are unique, we need to scan the buffer.
2160 const char *endBuf = startBuf;
2161 // scan forward (from the decl location) for argument types.
2162 scanToNextArgument(endBuf);
2163 const char *startRef = nullptr, *endRef = nullptr;
2164 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2165 // Get the locations of the startRef, endRef.
2166 SourceLocation LessLoc =
2167 Loc.getLocWithOffset(startRef-startFuncBuf);
2168 SourceLocation GreaterLoc =
2169 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2170 // Comment out the protocol references.
2171 InsertText(LessLoc, "/*");
2172 InsertText(GreaterLoc, "*/");
2174 startBuf = ++endBuf;
2177 // If the function name is derived from a macro expansion, then the
2178 // argument buffer will not follow the name. Need to speak with Chris.
2179 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2180 startBuf++; // scan forward (from the decl location) for argument types.
2186 void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2187 QualType QT = ND->getType();
2188 const Type* TypePtr = QT->getAs<Type>();
2189 if (!isa<TypeOfExprType>(TypePtr))
2191 while (isa<TypeOfExprType>(TypePtr)) {
2192 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2193 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2194 TypePtr = QT->getAs<Type>();
2196 // FIXME. This will not work for multiple declarators; as in:
2197 // __typeof__(a) b,c,d;
2198 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2199 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2200 const char *startBuf = SM->getCharacterData(DeclLoc);
2201 if (ND->getInit()) {
2202 std::string Name(ND->getNameAsString());
2203 TypeAsString += " " + Name + " = ";
2204 Expr *E = ND->getInit();
2205 SourceLocation startLoc;
2206 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2207 startLoc = ECE->getLParenLoc();
2209 startLoc = E->getLocStart();
2210 startLoc = SM->getExpansionLoc(startLoc);
2211 const char *endBuf = SM->getCharacterData(startLoc);
2212 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2215 SourceLocation X = ND->getLocEnd();
2216 X = SM->getExpansionLoc(X);
2217 const char *endBuf = SM->getCharacterData(X);
2218 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2222 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2223 void RewriteObjC::SynthSelGetUidFunctionDecl() {
2224 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2225 SmallVector<QualType, 16> ArgTys;
2226 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2227 QualType getFuncType =
2228 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2229 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2232 SelGetUidIdent, getFuncType,
2233 nullptr, SC_Extern);
2236 void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2237 // declared in <objc/objc.h>
2238 if (FD->getIdentifier() &&
2239 FD->getName() == "sel_registerName") {
2240 SelGetUidFunctionDecl = FD;
2243 RewriteObjCQualifiedInterfaceTypes(FD);
2246 void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2247 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2248 const char *argPtr = TypeString.c_str();
2249 if (!strchr(argPtr, '^')) {
2254 Str += (*argPtr == '^' ? '*' : *argPtr);
2259 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2260 void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2262 QualType Type = VD->getType();
2263 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2264 const char *argPtr = TypeString.c_str();
2279 Str += VD->getNameAsString();
2290 void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2291 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2292 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2293 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2296 QualType Type = proto->getReturnType();
2297 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2299 FdStr += FD->getName();
2301 unsigned numArgs = proto->getNumParams();
2302 for (unsigned i = 0; i < numArgs; i++) {
2303 QualType ArgType = proto->getParamType(i);
2304 RewriteBlockPointerType(FdStr, ArgType);
2309 InsertText(FunLocStart, FdStr);
2310 CurFunctionDeclToDeclareForBlock = nullptr;
2313 // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2314 void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2315 if (SuperConstructorFunctionDecl)
2317 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2318 SmallVector<QualType, 16> ArgTys;
2319 QualType argT = Context->getObjCIdType();
2320 assert(!argT.isNull() && "Can't find 'id' type");
2321 ArgTys.push_back(argT);
2322 ArgTys.push_back(argT);
2323 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2325 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2328 msgSendIdent, msgSendType,
2329 nullptr, SC_Extern);
2332 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2333 void RewriteObjC::SynthMsgSendFunctionDecl() {
2334 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2335 SmallVector<QualType, 16> ArgTys;
2336 QualType argT = Context->getObjCIdType();
2337 assert(!argT.isNull() && "Can't find 'id' type");
2338 ArgTys.push_back(argT);
2339 argT = Context->getObjCSelType();
2340 assert(!argT.isNull() && "Can't find 'SEL' type");
2341 ArgTys.push_back(argT);
2342 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2343 ArgTys, /*isVariadic=*/true);
2344 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2347 msgSendIdent, msgSendType,
2348 nullptr, SC_Extern);
2351 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2352 void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2353 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2354 SmallVector<QualType, 16> ArgTys;
2355 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2356 SourceLocation(), SourceLocation(),
2357 &Context->Idents.get("objc_super"));
2358 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2359 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2360 ArgTys.push_back(argT);
2361 argT = Context->getObjCSelType();
2362 assert(!argT.isNull() && "Can't find 'SEL' type");
2363 ArgTys.push_back(argT);
2364 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2365 ArgTys, /*isVariadic=*/true);
2366 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2369 msgSendIdent, msgSendType,
2370 nullptr, SC_Extern);
2373 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2374 void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2375 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2376 SmallVector<QualType, 16> ArgTys;
2377 QualType argT = Context->getObjCIdType();
2378 assert(!argT.isNull() && "Can't find 'id' type");
2379 ArgTys.push_back(argT);
2380 argT = Context->getObjCSelType();
2381 assert(!argT.isNull() && "Can't find 'SEL' type");
2382 ArgTys.push_back(argT);
2383 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2384 ArgTys, /*isVariadic=*/true);
2385 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2388 msgSendIdent, msgSendType,
2389 nullptr, SC_Extern);
2392 // SynthMsgSendSuperStretFunctionDecl -
2393 // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2394 void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2395 IdentifierInfo *msgSendIdent =
2396 &Context->Idents.get("objc_msgSendSuper_stret");
2397 SmallVector<QualType, 16> ArgTys;
2398 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2399 SourceLocation(), SourceLocation(),
2400 &Context->Idents.get("objc_super"));
2401 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2402 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2403 ArgTys.push_back(argT);
2404 argT = Context->getObjCSelType();
2405 assert(!argT.isNull() && "Can't find 'SEL' type");
2406 ArgTys.push_back(argT);
2407 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2408 ArgTys, /*isVariadic=*/true);
2409 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2413 msgSendType, nullptr,
2417 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2418 void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2420 SmallVector<QualType, 16> ArgTys;
2421 QualType argT = Context->getObjCIdType();
2422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
2424 argT = Context->getObjCSelType();
2425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
2427 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2428 ArgTys, /*isVariadic=*/true);
2429 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432 msgSendIdent, msgSendType,
2433 nullptr, SC_Extern);
2436 // SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2437 void RewriteObjC::SynthGetClassFunctionDecl() {
2438 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2439 SmallVector<QualType, 16> ArgTys;
2440 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2441 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2443 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446 getClassIdent, getClassType,
2447 nullptr, SC_Extern);
2450 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2451 void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2452 IdentifierInfo *getSuperClassIdent =
2453 &Context->Idents.get("class_getSuperclass");
2454 SmallVector<QualType, 16> ArgTys;
2455 ArgTys.push_back(Context->getObjCClassType());
2456 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2458 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2462 getClassType, nullptr,
2466 // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2467 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2468 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2469 SmallVector<QualType, 16> ArgTys;
2470 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2471 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2473 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2476 getClassIdent, getClassType,
2477 nullptr, SC_Extern);
2480 Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2481 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2482 QualType strType = getConstantStringStructType();
2484 std::string S = "__NSConstantStringImpl_";
2486 std::string tmpName = InFileName;
2488 for (i=0; i < tmpName.length(); i++) {
2489 char c = tmpName.at(i);
2490 // replace any non-alphanumeric characters with '_'.
2491 if (!isAlphanumeric(c))
2496 S += utostr(NumObjCStringLiterals++);
2498 Preamble += "static __NSConstantStringImpl " + S;
2499 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2500 Preamble += "0x000007c8,"; // utf8_str
2501 // The pretty printer for StringLiteral handles escape characters properly.
2502 std::string prettyBufS;
2503 llvm::raw_string_ostream prettyBuf(prettyBufS);
2504 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2505 Preamble += prettyBuf.str();
2507 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2509 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2510 SourceLocation(), &Context->Idents.get(S),
2511 strType, nullptr, SC_Static);
2512 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2514 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2515 Context->getPointerType(DRE->getType()),
2516 VK_RValue, OK_Ordinary,
2518 // cast to NSConstantString *
2519 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2520 CK_CPointerToObjCPointerCast, Unop);
2521 ReplaceStmt(Exp, cast);
2522 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2526 // struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2527 QualType RewriteObjC::getSuperStructType() {
2528 if (!SuperStructDecl) {
2529 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2530 SourceLocation(), SourceLocation(),
2531 &Context->Idents.get("objc_super"));
2532 QualType FieldTypes[2];
2534 // struct objc_object *receiver;
2535 FieldTypes[0] = Context->getObjCIdType();
2536 // struct objc_class *super;
2537 FieldTypes[1] = Context->getObjCClassType();
2540 for (unsigned i = 0; i < 2; ++i) {
2541 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2543 SourceLocation(), nullptr,
2544 FieldTypes[i], nullptr,
2545 /*BitWidth=*/nullptr,
2550 SuperStructDecl->completeDefinition();
2552 return Context->getTagDeclType(SuperStructDecl);
2555 QualType RewriteObjC::getConstantStringStructType() {
2556 if (!ConstantStringDecl) {
2557 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2558 SourceLocation(), SourceLocation(),
2559 &Context->Idents.get("__NSConstantStringImpl"));
2560 QualType FieldTypes[4];
2562 // struct objc_object *receiver;
2563 FieldTypes[0] = Context->getObjCIdType();
2565 FieldTypes[1] = Context->IntTy;
2567 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2569 FieldTypes[3] = Context->LongTy;
2572 for (unsigned i = 0; i < 4; ++i) {
2573 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2576 SourceLocation(), nullptr,
2577 FieldTypes[i], nullptr,
2578 /*BitWidth=*/nullptr,
2583 ConstantStringDecl->completeDefinition();
2585 return Context->getTagDeclType(ConstantStringDecl);
2588 CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2589 QualType msgSendType,
2590 QualType returnType,
2591 SmallVectorImpl<QualType> &ArgTypes,
2592 SmallVectorImpl<Expr*> &MsgExprs,
2593 ObjCMethodDecl *Method) {
2594 // Create a reference to the objc_msgSend_stret() declaration.
2595 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2597 VK_LValue, SourceLocation());
2598 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2599 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2600 Context->getPointerType(Context->VoidTy),
2602 // Now do the "normal" pointer to function cast.
2603 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2604 Method ? Method->isVariadic()
2606 castType = Context->getPointerType(castType);
2607 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2610 // Don't forget the parens to enforce the proper binding.
2611 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2613 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2614 CallExpr *STCE = new (Context) CallExpr(
2615 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
2621 Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2622 SourceLocation StartLoc,
2623 SourceLocation EndLoc) {
2624 if (!SelGetUidFunctionDecl)
2625 SynthSelGetUidFunctionDecl();
2626 if (!MsgSendFunctionDecl)
2627 SynthMsgSendFunctionDecl();
2628 if (!MsgSendSuperFunctionDecl)
2629 SynthMsgSendSuperFunctionDecl();
2630 if (!MsgSendStretFunctionDecl)
2631 SynthMsgSendStretFunctionDecl();
2632 if (!MsgSendSuperStretFunctionDecl)
2633 SynthMsgSendSuperStretFunctionDecl();
2634 if (!MsgSendFpretFunctionDecl)
2635 SynthMsgSendFpretFunctionDecl();
2636 if (!GetClassFunctionDecl)
2637 SynthGetClassFunctionDecl();
2638 if (!GetSuperClassFunctionDecl)
2639 SynthGetSuperClassFunctionDecl();
2640 if (!GetMetaClassFunctionDecl)
2641 SynthGetMetaClassFunctionDecl();
2643 // default to objc_msgSend().
2644 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2645 // May need to use objc_msgSend_stret() as well.
2646 FunctionDecl *MsgSendStretFlavor = nullptr;
2647 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2648 QualType resultType = mDecl->getReturnType();
2649 if (resultType->isRecordType())
2650 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2651 else if (resultType->isRealFloatingType())
2652 MsgSendFlavor = MsgSendFpretFunctionDecl;
2655 // Synthesize a call to objc_msgSend().
2656 SmallVector<Expr*, 8> MsgExprs;
2657 switch (Exp->getReceiverKind()) {
2658 case ObjCMessageExpr::SuperClass: {
2659 MsgSendFlavor = MsgSendSuperFunctionDecl;
2660 if (MsgSendStretFlavor)
2661 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2662 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2664 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2666 SmallVector<Expr*, 4> InitExprs;
2668 // set the receiver to self, the first argument to all methods.
2669 InitExprs.push_back(
2670 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2672 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2674 Context->getObjCIdType(),
2677 ); // set the 'receiver'.
2679 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2680 SmallVector<Expr*, 8> ClsExprs;
2681 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2687 // (Class)objc_getClass("CurrentClass")
2688 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2689 Context->getObjCClassType(),
2692 ClsExprs.push_back(ArgExpr);
2693 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2694 &ClsExprs[0], ClsExprs.size(),
2697 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2698 // To turn off a warning, type-cast to 'id'
2699 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2700 NoTypeInfoCStyleCastExpr(Context,
2701 Context->getObjCIdType(),
2703 // struct objc_super
2704 QualType superType = getSuperStructType();
2707 if (LangOpts.MicrosoftExt) {
2708 SynthSuperConstructorFunctionDecl();
2709 // Simulate a constructor call...
2710 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2711 false, superType, VK_LValue,
2713 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2714 superType, VK_LValue,
2716 // The code for super is a little tricky to prevent collision with
2717 // the structure definition in the header. The rewriter has it's own
2718 // internal definition (__rw_objc_super) that is uses. This is why
2719 // we need the cast below. For example:
2720 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2722 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2723 Context->getPointerType(SuperRep->getType()),
2724 VK_RValue, OK_Ordinary,
2726 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2727 Context->getPointerType(superType),
2728 CK_BitCast, SuperRep);
2730 // (struct objc_super) { <exprs from above> }
2732 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2734 TypeSourceInfo *superTInfo
2735 = Context->getTrivialTypeSourceInfo(superType);
2736 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2737 superType, VK_LValue,
2739 // struct objc_super *
2740 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2741 Context->getPointerType(SuperRep->getType()),
2742 VK_RValue, OK_Ordinary,
2745 MsgExprs.push_back(SuperRep);
2749 case ObjCMessageExpr::Class: {
2750 SmallVector<Expr*, 8> ClsExprs;
2751 ObjCInterfaceDecl *Class
2752 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2753 IdentifierInfo *clsName = Class->getIdentifier();
2754 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2755 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2759 MsgExprs.push_back(Cls);
2763 case ObjCMessageExpr::SuperInstance:{
2764 MsgSendFlavor = MsgSendSuperFunctionDecl;
2765 if (MsgSendStretFlavor)
2766 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2767 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2768 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2769 SmallVector<Expr*, 4> InitExprs;
2771 InitExprs.push_back(
2772 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2774 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2776 Context->getObjCIdType(),
2777 VK_RValue, SourceLocation()))
2778 ); // set the 'receiver'.
2780 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2781 SmallVector<Expr*, 8> ClsExprs;
2782 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2783 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2787 // (Class)objc_getClass("CurrentClass")
2788 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2789 Context->getObjCClassType(),
2792 ClsExprs.push_back(ArgExpr);
2793 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2794 &ClsExprs[0], ClsExprs.size(),
2797 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2798 // To turn off a warning, type-cast to 'id'
2799 InitExprs.push_back(
2800 // set 'super class', using class_getSuperclass().
2801 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2803 // struct objc_super
2804 QualType superType = getSuperStructType();
2807 if (LangOpts.MicrosoftExt) {
2808 SynthSuperConstructorFunctionDecl();
2809 // Simulate a constructor call...
2810 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
2811 false, superType, VK_LValue,
2813 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
2814 superType, VK_LValue, SourceLocation());
2815 // The code for super is a little tricky to prevent collision with
2816 // the structure definition in the header. The rewriter has it's own
2817 // internal definition (__rw_objc_super) that is uses. This is why
2818 // we need the cast below. For example:
2819 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2821 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2822 Context->getPointerType(SuperRep->getType()),
2823 VK_RValue, OK_Ordinary,
2825 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2826 Context->getPointerType(superType),
2827 CK_BitCast, SuperRep);
2829 // (struct objc_super) { <exprs from above> }
2831 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2833 TypeSourceInfo *superTInfo
2834 = Context->getTrivialTypeSourceInfo(superType);
2835 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2836 superType, VK_RValue, ILE,
2839 MsgExprs.push_back(SuperRep);
2843 case ObjCMessageExpr::Instance: {
2844 // Remove all type-casts because it may contain objc-style types; e.g.
2846 Expr *recExpr = Exp->getInstanceReceiver();
2847 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2848 recExpr = CE->getSubExpr();
2849 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2850 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2851 ? CK_BlockPointerToObjCPointerCast
2852 : CK_CPointerToObjCPointerCast;
2854 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2856 MsgExprs.push_back(recExpr);
2861 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2862 SmallVector<Expr*, 8> SelExprs;
2863 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2864 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2865 &SelExprs[0], SelExprs.size(),
2868 MsgExprs.push_back(SelExp);
2870 // Now push any user supplied arguments.
2871 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2872 Expr *userExpr = Exp->getArg(i);
2873 // Make all implicit casts explicit...ICE comes in handy:-)
2874 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2875 // Reuse the ICE type, it is exactly what the doctor ordered.
2876 QualType type = ICE->getType();
2877 if (needToScanForQualifiers(type))
2878 type = Context->getObjCIdType();
2879 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2880 (void)convertBlockPointerToFunctionPointer(type);
2881 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2883 if (SubExpr->getType()->isIntegralType(*Context) &&
2884 type->isBooleanType()) {
2885 CK = CK_IntegralToBoolean;
2886 } else if (type->isObjCObjectPointerType()) {
2887 if (SubExpr->getType()->isBlockPointerType()) {
2888 CK = CK_BlockPointerToObjCPointerCast;
2889 } else if (SubExpr->getType()->isPointerType()) {
2890 CK = CK_CPointerToObjCPointerCast;
2898 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2900 // Make id<P...> cast into an 'id' cast.
2901 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2902 if (CE->getType()->isObjCQualifiedIdType()) {
2903 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2904 userExpr = CE->getSubExpr();
2906 if (userExpr->getType()->isIntegralType(*Context)) {
2907 CK = CK_IntegralToPointer;
2908 } else if (userExpr->getType()->isBlockPointerType()) {
2909 CK = CK_BlockPointerToObjCPointerCast;
2910 } else if (userExpr->getType()->isPointerType()) {
2911 CK = CK_CPointerToObjCPointerCast;
2915 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2919 MsgExprs.push_back(userExpr);
2920 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2921 // out the argument in the original expression (since we aren't deleting
2922 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2923 //Exp->setArg(i, 0);
2925 // Generate the funky cast.
2927 SmallVector<QualType, 8> ArgTypes;
2928 QualType returnType;
2930 // Push 'id' and 'SEL', the 2 implicit arguments.
2931 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2932 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2934 ArgTypes.push_back(Context->getObjCIdType());
2935 ArgTypes.push_back(Context->getObjCSelType());
2936 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2937 // Push any user argument types.
2938 for (const auto *PI : OMD->params()) {
2939 QualType t = PI->getType()->isObjCQualifiedIdType()
2940 ? Context->getObjCIdType()
2942 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2943 (void)convertBlockPointerToFunctionPointer(t);
2944 ArgTypes.push_back(t);
2946 returnType = Exp->getType();
2947 convertToUnqualifiedObjCType(returnType);
2948 (void)convertBlockPointerToFunctionPointer(returnType);
2950 returnType = Context->getObjCIdType();
2952 // Get the type, we will need to reference it in a couple spots.
2953 QualType msgSendType = MsgSendFlavor->getType();
2955 // Create a reference to the objc_msgSend() declaration.
2956 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2957 VK_LValue, SourceLocation());
2959 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2960 // If we don't do this cast, we get the following bizarre warning/note:
2961 // xx.m:13: warning: function called through a non-compatible type
2962 // xx.m:13: note: if this code is reached, the program will abort
2963 cast = NoTypeInfoCStyleCastExpr(Context,
2964 Context->getPointerType(Context->VoidTy),
2967 // Now do the "normal" pointer to function cast.
2968 // If we don't have a method decl, force a variadic cast.
2969 const ObjCMethodDecl *MD = Exp->getMethodDecl();
2971 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
2972 castType = Context->getPointerType(castType);
2973 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2976 // Don't forget the parens to enforce the proper binding.
2977 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2979 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2980 CallExpr *CE = new (Context)
2981 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2982 Stmt *ReplacingStmt = CE;
2983 if (MsgSendStretFlavor) {
2984 // We have the method which returns a struct/union. Must also generate
2985 // call to objc_msgSend_stret and hang both varieties on a conditional
2986 // expression which dictate which one to envoke depending on size of
2987 // method's return type.
2989 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2990 msgSendType, returnType,
2992 Exp->getMethodDecl());
2994 // Build sizeof(returnType)
2995 UnaryExprOrTypeTraitExpr *sizeofExpr =
2996 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2997 Context->getTrivialTypeSourceInfo(returnType),
2998 Context->getSizeType(), SourceLocation(),
3000 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3001 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3002 // For X86 it is more complicated and some kind of target specific routine
3003 // is needed to decide what to do.
3005 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3006 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3007 llvm::APInt(IntSize, 8),
3010 BinaryOperator *lessThanExpr =
3011 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3012 VK_RValue, OK_Ordinary, SourceLocation(),
3014 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3015 ConditionalOperator *CondExpr =
3016 new (Context) ConditionalOperator(lessThanExpr,
3017 SourceLocation(), CE,
3018 SourceLocation(), STCE,
3019 returnType, VK_RValue, OK_Ordinary);
3020 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3023 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3024 return ReplacingStmt;
3027 Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3028 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3031 // Now do the actual rewrite.
3032 ReplaceStmt(Exp, ReplacingStmt);
3034 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3035 return ReplacingStmt;
3038 // typedef struct objc_object Protocol;
3039 QualType RewriteObjC::getProtocolType() {
3040 if (!ProtocolTypeDecl) {
3041 TypeSourceInfo *TInfo
3042 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3043 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3044 SourceLocation(), SourceLocation(),
3045 &Context->Idents.get("Protocol"),
3048 return Context->getTypeDeclType(ProtocolTypeDecl);
3051 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3052 /// a synthesized/forward data reference (to the protocol's metadata).
3053 /// The forward references (and metadata) are generated in
3054 /// RewriteObjC::HandleTranslationUnit().
3055 Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3056 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3057 IdentifierInfo *ID = &Context->Idents.get(Name);
3058 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3059 SourceLocation(), ID, getProtocolType(),
3060 nullptr, SC_Extern);
3061 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3062 VK_LValue, SourceLocation());
3063 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3064 Context->getPointerType(DRE->getType()),
3065 VK_RValue, OK_Ordinary, SourceLocation());
3066 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3069 ReplaceStmt(Exp, castExpr);
3070 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3071 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3076 bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3077 const char *endBuf) {
3078 while (startBuf < endBuf) {
3079 if (*startBuf == '#') {
3081 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3083 if (!strncmp(startBuf, "if", strlen("if")) ||
3084 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3085 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3086 !strncmp(startBuf, "define", strlen("define")) ||
3087 !strncmp(startBuf, "undef", strlen("undef")) ||
3088 !strncmp(startBuf, "else", strlen("else")) ||
3089 !strncmp(startBuf, "elif", strlen("elif")) ||
3090 !strncmp(startBuf, "endif", strlen("endif")) ||
3091 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3092 !strncmp(startBuf, "include", strlen("include")) ||
3093 !strncmp(startBuf, "import", strlen("import")) ||
3094 !strncmp(startBuf, "include_next", strlen("include_next")))
3102 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3103 /// an objective-c class with ivars.
3104 void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3105 std::string &Result) {
3106 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3107 assert(CDecl->getName() != "" &&
3108 "Name missing in SynthesizeObjCInternalStruct");
3109 // Do not synthesize more than once.
3110 if (ObjCSynthesizedStructs.count(CDecl))
3112 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3113 int NumIvars = CDecl->ivar_size();
3114 SourceLocation LocStart = CDecl->getLocStart();
3115 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3117 const char *startBuf = SM->getCharacterData(LocStart);
3118 const char *endBuf = SM->getCharacterData(LocEnd);
3120 // If no ivars and no root or if its root, directly or indirectly,
3121 // have no ivars (thus not synthesized) then no need to synthesize this class.
3122 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3123 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3124 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3125 ReplaceText(LocStart, endBuf-startBuf, Result);
3129 // FIXME: This has potential of causing problem. If
3130 // SynthesizeObjCInternalStruct is ever called recursively.
3131 Result += "\nstruct ";
3132 Result += CDecl->getNameAsString();
3133 if (LangOpts.MicrosoftExt)
3137 const char *cursor = strchr(startBuf, '{');
3138 assert((cursor && endBuf)
3139 && "SynthesizeObjCInternalStruct - malformed @interface");
3140 // If the buffer contains preprocessor directives, we do more fine-grained
3141 // rewrites. This is intended to fix code that looks like (which occurs in
3142 // NSURL.h, for example):
3145 // @interface Foo : NSObject
3147 // @interface FooBar : NSObject
3154 // This clause is segregated to avoid breaking the common case.
3155 if (BufferContainsPPDirectives(startBuf, cursor)) {
3156 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3157 CDecl->getAtStartLoc();
3158 const char *endHeader = SM->getCharacterData(L);
3159 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3161 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3162 // advance to the end of the referenced protocols.
3163 while (endHeader < cursor && *endHeader != '>') endHeader++;
3166 // rewrite the original header
3167 ReplaceText(LocStart, endHeader-startBuf, Result);
3169 // rewrite the original header *without* disturbing the '{'
3170 ReplaceText(LocStart, cursor-startBuf, Result);
3172 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3173 Result = "\n struct ";
3174 Result += RCDecl->getNameAsString();
3176 Result += RCDecl->getNameAsString();
3177 Result += "_IVARS;\n";
3179 // insert the super class structure definition.
3180 SourceLocation OnePastCurly =
3181 LocStart.getLocWithOffset(cursor-startBuf+1);
3182 InsertText(OnePastCurly, Result);
3184 cursor++; // past '{'
3186 // Now comment out any visibility specifiers.
3187 while (cursor < endBuf) {
3188 if (*cursor == '@') {
3189 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3191 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3194 // FIXME: presence of @public, etc. inside comment results in
3195 // this transformation as well, which is still correct c-code.
3196 if (!strncmp(cursor, "public", strlen("public")) ||
3197 !strncmp(cursor, "private", strlen("private")) ||
3198 !strncmp(cursor, "package", strlen("package")) ||
3199 !strncmp(cursor, "protected", strlen("protected")))
3200 InsertText(atLoc, "// ");
3202 // FIXME: If there are cases where '<' is used in ivar declaration part
3203 // of user code, then scan the ivar list and use needToScanForQualifiers
3204 // for type checking.
3205 else if (*cursor == '<') {
3206 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3207 InsertText(atLoc, "/* ");
3208 cursor = strchr(cursor, '>');
3210 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3211 InsertText(atLoc, " */");
3212 } else if (*cursor == '^') { // rewrite block specifier.
3213 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3214 ReplaceText(caretLoc, 1, "*");
3218 // Don't forget to add a ';'!!
3219 InsertText(LocEnd.getLocWithOffset(1), ";");
3220 } else { // we don't have any instance variables - insert super struct.
3221 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3222 Result += " {\n struct ";
3223 Result += RCDecl->getNameAsString();
3225 Result += RCDecl->getNameAsString();
3226 Result += "_IVARS;\n};\n";
3227 ReplaceText(LocStart, endBuf-startBuf, Result);
3229 // Mark this struct as having been generated.
3230 if (!ObjCSynthesizedStructs.insert(CDecl).second)
3231 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3234 //===----------------------------------------------------------------------===//
3235 // Meta Data Emission
3236 //===----------------------------------------------------------------------===//
3239 /// RewriteImplementations - This routine rewrites all method implementations
3240 /// and emits meta-data.
3242 void RewriteObjC::RewriteImplementations() {
3243 int ClsDefCount = ClassImplementation.size();
3244 int CatDefCount = CategoryImplementation.size();
3246 // Rewrite implemented methods
3247 for (int i = 0; i < ClsDefCount; i++)
3248 RewriteImplementationDecl(ClassImplementation[i]);
3250 for (int i = 0; i < CatDefCount; i++)
3251 RewriteImplementationDecl(CategoryImplementation[i]);
3254 void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3255 const std::string &Name,
3256 ValueDecl *VD, bool def) {
3257 assert(BlockByRefDeclNo.count(VD) &&
3258 "RewriteByRefString: ByRef decl missing");
3260 ResultStr += "struct ";
3261 ResultStr += "__Block_byref_" + Name +
3262 "_" + utostr(BlockByRefDeclNo[VD]) ;
3265 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3266 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3267 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3271 std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3274 const FunctionType *AFT = CE->getFunctionType();
3275 QualType RT = AFT->getReturnType();
3276 std::string StructRef = "struct " + Tag;
3277 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3278 funcName.str() + "_" + "block_func_" + utostr(i);
3280 BlockDecl *BD = CE->getBlockDecl();
3282 if (isa<FunctionNoProtoType>(AFT)) {
3283 // No user-supplied arguments. Still need to pass in a pointer to the
3284 // block (to reference imported block decl refs).
3285 S += "(" + StructRef + " *__cself)";
3286 } else if (BD->param_empty()) {
3287 S += "(" + StructRef + " *__cself)";
3289 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3290 assert(FT && "SynthesizeBlockFunc: No function proto");
3292 // first add the implicit argument.
3293 S += StructRef + " *__cself, ";
3294 std::string ParamStr;
3295 for (BlockDecl::param_iterator AI = BD->param_begin(),
3296 E = BD->param_end(); AI != E; ++AI) {
3297 if (AI != BD->param_begin()) S += ", ";
3298 ParamStr = (*AI)->getNameAsString();
3299 QualType QT = (*AI)->getType();
3300 (void)convertBlockPointerToFunctionPointer(QT);
3301 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3304 if (FT->isVariadic()) {
3305 if (!BD->param_empty()) S += ", ";
3312 // Create local declarations to avoid rewriting all closure decl ref exprs.
3313 // First, emit a declaration for all "by ref" decls.
3314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3315 E = BlockByRefDecls.end(); I != E; ++I) {
3317 std::string Name = (*I)->getNameAsString();
3318 std::string TypeString;
3319 RewriteByRefString(TypeString, Name, (*I));
3321 Name = TypeString + Name;
3322 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3324 // Next, emit a declaration for all "by copy" declarations.
3325 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3326 E = BlockByCopyDecls.end(); I != E; ++I) {
3328 // Handle nested closure invocation. For example:
3330 // void (^myImportedClosure)(void);
3331 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3333 // void (^anotherClosure)(void);
3334 // anotherClosure = ^(void) {
3335 // myImportedClosure(); // import and invoke the closure
3338 if (isTopLevelBlockPointerType((*I)->getType())) {
3339 RewriteBlockPointerTypeVariable(S, (*I));
3341 RewriteBlockPointerType(S, (*I)->getType());
3343 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3346 std::string Name = (*I)->getNameAsString();
3347 QualType QT = (*I)->getType();
3348 if (HasLocalVariableExternalStorage(*I))
3349 QT = Context->getPointerType(QT);
3350 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3351 S += Name + " = __cself->" +
3352 (*I)->getNameAsString() + "; // bound by copy\n";
3355 std::string RewrittenStr = RewrittenBlockExprs[CE];
3356 const char *cstr = RewrittenStr.c_str();
3357 while (*cstr++ != '{') ;
3363 std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3366 std::string StructRef = "struct " + Tag;
3367 std::string S = "static void __";
3370 S += "_block_copy_" + utostr(i);
3371 S += "(" + StructRef;
3372 S += "*dst, " + StructRef;
3374 for (ValueDecl *VD : ImportedBlockDecls) {
3375 S += "_Block_object_assign((void*)&dst->";
3376 S += VD->getNameAsString();
3377 S += ", (void*)src->";
3378 S += VD->getNameAsString();
3379 if (BlockByRefDeclsPtrSet.count(VD))
3380 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3381 else if (VD->getType()->isBlockPointerType())
3382 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3384 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3388 S += "\nstatic void __";
3390 S += "_block_dispose_" + utostr(i);
3391 S += "(" + StructRef;
3393 for (ValueDecl *VD : ImportedBlockDecls) {
3394 S += "_Block_object_dispose((void*)src->";
3395 S += VD->getNameAsString();
3396 if (BlockByRefDeclsPtrSet.count(VD))
3397 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3398 else if (VD->getType()->isBlockPointerType())
3399 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3401 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3407 std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3409 std::string S = "\nstruct " + Tag;
3410 std::string Constructor = " " + Tag;
3412 S += " {\n struct __block_impl impl;\n";
3413 S += " struct " + Desc;
3416 Constructor += "(void *fp, "; // Invoke function pointer.
3417 Constructor += "struct " + Desc; // Descriptor pointer.
3418 Constructor += " *desc";
3420 if (BlockDeclRefs.size()) {
3421 // Output all "by copy" declarations.
3422 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3423 E = BlockByCopyDecls.end(); I != E; ++I) {
3425 std::string FieldName = (*I)->getNameAsString();
3426 std::string ArgName = "_" + FieldName;
3427 // Handle nested closure invocation. For example:
3429 // void (^myImportedBlock)(void);
3430 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3432 // void (^anotherBlock)(void);
3433 // anotherBlock = ^(void) {
3434 // myImportedBlock(); // import and invoke the closure
3437 if (isTopLevelBlockPointerType((*I)->getType())) {
3438 S += "struct __block_impl *";
3439 Constructor += ", void *" + ArgName;
3441 QualType QT = (*I)->getType();
3442 if (HasLocalVariableExternalStorage(*I))
3443 QT = Context->getPointerType(QT);
3444 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3445 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3446 Constructor += ", " + ArgName;
3448 S += FieldName + ";\n";
3450 // Output all "by ref" declarations.
3451 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3452 E = BlockByRefDecls.end(); I != E; ++I) {
3454 std::string FieldName = (*I)->getNameAsString();
3455 std::string ArgName = "_" + FieldName;
3457 std::string TypeString;
3458 RewriteByRefString(TypeString, FieldName, (*I));
3460 FieldName = TypeString + FieldName;
3461 ArgName = TypeString + ArgName;
3462 Constructor += ", " + ArgName;
3464 S += FieldName + "; // by ref\n";
3466 // Finish writing the constructor.
3467 Constructor += ", int flags=0)";
3468 // Initialize all "by copy" arguments.
3469 bool firsTime = true;
3470 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3471 E = BlockByCopyDecls.end(); I != E; ++I) {
3472 std::string Name = (*I)->getNameAsString();
3474 Constructor += " : ";
3478 Constructor += ", ";
3479 if (isTopLevelBlockPointerType((*I)->getType()))
3480 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3482 Constructor += Name + "(_" + Name + ")";
3484 // Initialize all "by ref" arguments.
3485 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3486 E = BlockByRefDecls.end(); I != E; ++I) {
3487 std::string Name = (*I)->getNameAsString();
3489 Constructor += " : ";
3493 Constructor += ", ";
3494 Constructor += Name + "(_" + Name + "->__forwarding)";
3497 Constructor += " {\n";
3499 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3501 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3502 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3504 Constructor += " Desc = desc;\n";
3506 // Finish writing the constructor.
3507 Constructor += ", int flags=0) {\n";
3509 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3511 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3512 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3513 Constructor += " Desc = desc;\n";
3516 Constructor += "}\n";
3522 std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3523 std::string ImplTag, int i,
3526 std::string S = "\nstatic struct " + DescTag;
3528 S += " {\n unsigned long reserved;\n";
3529 S += " unsigned long Block_size;\n";
3531 S += " void (*copy)(struct ";
3532 S += ImplTag; S += "*, struct ";
3533 S += ImplTag; S += "*);\n";
3535 S += " void (*dispose)(struct ";
3536 S += ImplTag; S += "*);\n";
3540 S += DescTag + "_DATA = { 0, sizeof(struct ";
3543 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3544 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3550 void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3551 StringRef FunName) {
3552 // Insert declaration for the function in which block literal is used.
3553 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3554 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3555 bool RewriteSC = (GlobalVarDecl &&
3557 GlobalVarDecl->getStorageClass() == SC_Static &&
3558 GlobalVarDecl->getType().getCVRQualifiers());
3560 std::string SC(" void __");
3561 SC += GlobalVarDecl->getNameAsString();
3563 InsertText(FunLocStart, SC);
3566 // Insert closures that were part of the function.
3567 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3568 CollectBlockDeclRefInfo(Blocks[i]);
3569 // Need to copy-in the inner copied-in variables not actually used in this
3571 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3572 DeclRefExpr *Exp = InnerDeclRefs[count++];
3573 ValueDecl *VD = Exp->getDecl();
3574 BlockDeclRefs.push_back(Exp);
3575 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
3576 BlockByCopyDeclsPtrSet.insert(VD);
3577 BlockByCopyDecls.push_back(VD);
3579 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
3580 BlockByRefDeclsPtrSet.insert(VD);
3581 BlockByRefDecls.push_back(VD);
3583 // imported objects in the inner blocks not used in the outer
3584 // blocks must be copied/disposed in the outer block as well.
3585 if (VD->hasAttr<BlocksAttr>() ||
3586 VD->getType()->isObjCObjectPointerType() ||
3587 VD->getType()->isBlockPointerType())
3588 ImportedBlockDecls.insert(VD);
3591 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3592 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3594 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3596 InsertText(FunLocStart, CI);
3598 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3600 InsertText(FunLocStart, CF);
3602 if (ImportedBlockDecls.size()) {
3603 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3604 InsertText(FunLocStart, HF);
3606 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3607 ImportedBlockDecls.size() > 0);
3608 InsertText(FunLocStart, BD);
3610 BlockDeclRefs.clear();
3611 BlockByRefDecls.clear();
3612 BlockByRefDeclsPtrSet.clear();
3613 BlockByCopyDecls.clear();
3614 BlockByCopyDeclsPtrSet.clear();
3615 ImportedBlockDecls.clear();
3618 // Must insert any 'const/volatile/static here. Since it has been
3619 // removed as result of rewriting of block literals.
3621 if (GlobalVarDecl->getStorageClass() == SC_Static)
3623 if (GlobalVarDecl->getType().isConstQualified())
3625 if (GlobalVarDecl->getType().isVolatileQualified())
3627 if (GlobalVarDecl->getType().isRestrictQualified())
3629 InsertText(FunLocStart, SC);
3633 InnerDeclRefsCount.clear();
3634 InnerDeclRefs.clear();
3635 RewrittenBlockExprs.clear();
3638 void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3639 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3640 StringRef FuncName = FD->getName();
3642 SynthesizeBlockLiterals(FunLocStart, FuncName);
3645 static void BuildUniqueMethodName(std::string &Name,
3646 ObjCMethodDecl *MD) {
3647 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3648 Name = IFace->getName();
3649 Name += "__" + MD->getSelector().getAsString();
3650 // Convert colons to underscores.
3651 std::string::size_type loc = 0;
3652 while ((loc = Name.find(":", loc)) != std::string::npos)
3653 Name.replace(loc, 1, "_");
3656 void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3657 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3658 //SourceLocation FunLocStart = MD->getLocStart();
3659 SourceLocation FunLocStart = MD->getLocStart();
3660 std::string FuncName;
3661 BuildUniqueMethodName(FuncName, MD);
3662 SynthesizeBlockLiterals(FunLocStart, FuncName);
3665 void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3666 for (Stmt::child_range CI = S->children(); CI; ++CI)
3668 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3669 GetBlockDeclRefExprs(CBE->getBody());
3671 GetBlockDeclRefExprs(*CI);
3673 // Handle specific things.
3674 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3675 if (DRE->refersToEnclosingVariableOrCapture() ||
3676 HasLocalVariableExternalStorage(DRE->getDecl()))
3677 // FIXME: Handle enums.
3678 BlockDeclRefs.push_back(DRE);
3683 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3684 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3685 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3686 for (Stmt::child_range CI = S->children(); CI; ++CI)
3688 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3689 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3690 GetInnerBlockDeclRefExprs(CBE->getBody(),
3695 GetInnerBlockDeclRefExprs(*CI,
3700 // Handle specific things.
3701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3702 if (DRE->refersToEnclosingVariableOrCapture() ||
3703 HasLocalVariableExternalStorage(DRE->getDecl())) {
3704 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3705 InnerBlockDeclRefs.push_back(DRE);
3706 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3707 if (Var->isFunctionOrMethodVarDecl())
3708 ImportedLocalExternalDecls.insert(Var);
3715 /// convertFunctionTypeOfBlocks - This routine converts a function type
3716 /// whose result type may be a block pointer or whose argument type(s)
3717 /// might be block pointers to an equivalent function type replacing
3718 /// all block pointers to function pointers.
3719 QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3720 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3721 // FTP will be null for closures that don't take arguments.
3722 // Generate a funky cast.
3723 SmallVector<QualType, 8> ArgTypes;
3724 QualType Res = FT->getReturnType();
3725 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3728 for (auto &I : FTP->param_types()) {
3730 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3731 if (convertBlockPointerToFunctionPointer(t))
3732 HasBlockType = true;
3733 ArgTypes.push_back(t);
3737 // FIXME. Does this work if block takes no argument but has a return type
3738 // which is of block type?
3740 FuncType = getSimpleFunctionType(Res, ArgTypes);
3741 else FuncType = QualType(FT, 0);
3745 Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3746 // Navigate to relevant type information.
3747 const BlockPointerType *CPT = nullptr;
3749 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3750 CPT = DRE->getType()->getAs<BlockPointerType>();
3751 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3752 CPT = MExpr->getType()->getAs<BlockPointerType>();
3754 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3755 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3757 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3758 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3759 else if (const ConditionalOperator *CEXPR =
3760 dyn_cast<ConditionalOperator>(BlockExp)) {
3761 Expr *LHSExp = CEXPR->getLHS();
3762 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3763 Expr *RHSExp = CEXPR->getRHS();
3764 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3765 Expr *CONDExp = CEXPR->getCond();
3766 ConditionalOperator *CondExpr =
3767 new (Context) ConditionalOperator(CONDExp,
3768 SourceLocation(), cast<Expr>(LHSStmt),
3769 SourceLocation(), cast<Expr>(RHSStmt),
3770 Exp->getType(), VK_RValue, OK_Ordinary);
3772 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3773 CPT = IRE->getType()->getAs<BlockPointerType>();
3774 } else if (const PseudoObjectExpr *POE
3775 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3776 CPT = POE->getType()->castAs<BlockPointerType>();
3778 assert(1 && "RewriteBlockClass: Bad type");
3780 assert(CPT && "RewriteBlockClass: Bad type");
3781 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3782 assert(FT && "RewriteBlockClass: Bad type");
3783 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3784 // FTP will be null for closures that don't take arguments.
3786 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3787 SourceLocation(), SourceLocation(),
3788 &Context->Idents.get("__block_impl"));
3789 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3791 // Generate a funky cast.
3792 SmallVector<QualType, 8> ArgTypes;
3794 // Push the block argument type.
3795 ArgTypes.push_back(PtrBlock);
3797 for (auto &I : FTP->param_types()) {
3799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3800 if (!convertBlockPointerToFunctionPointer(t))
3801 convertToUnqualifiedObjCType(t);
3802 ArgTypes.push_back(t);
3805 // Now do the pointer to function cast.
3806 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3808 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3810 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3812 const_cast<Expr*>(BlockExp));
3813 // Don't forget the parens to enforce the proper binding.
3814 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3818 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3820 &Context->Idents.get("FuncPtr"),
3821 Context->VoidPtrTy, nullptr,
3822 /*BitWidth=*/nullptr, /*Mutable=*/true,
3824 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3825 FD->getType(), VK_LValue,
3829 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3831 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3833 SmallVector<Expr*, 8> BlkExprs;
3834 // Add the implicit argument.
3835 BlkExprs.push_back(BlkCast);
3836 // Add the user arguments.
3837 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3838 E = Exp->arg_end(); I != E; ++I) {
3839 BlkExprs.push_back(*I);
3841 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
3842 Exp->getType(), VK_RValue,
3847 // We need to return the rewritten expression to handle cases where the
3848 // BlockDeclRefExpr is embedded in another expression being rewritten.
3855 // void (^myblock)() = ^() {
3856 // [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3860 Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3861 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3862 // for each DeclRefExp where BYREFVAR is name of the variable.
3863 ValueDecl *VD = DeclRefExp->getDecl();
3864 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3865 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
3867 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3869 &Context->Idents.get("__forwarding"),
3870 Context->VoidPtrTy, nullptr,
3871 /*BitWidth=*/nullptr, /*Mutable=*/true,
3873 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3874 FD, SourceLocation(),
3875 FD->getType(), VK_LValue,
3878 StringRef Name = VD->getName();
3879 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3880 &Context->Idents.get(Name),
3881 Context->VoidPtrTy, nullptr,
3882 /*BitWidth=*/nullptr, /*Mutable=*/true,
3884 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3885 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3889 // Need parens to enforce precedence.
3890 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3891 DeclRefExp->getExprLoc(),
3893 ReplaceStmt(DeclRefExp, PE);
3897 // Rewrites the imported local variable V with external storage
3898 // (static, extern, etc.) as *V
3900 Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3901 ValueDecl *VD = DRE->getDecl();
3902 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3903 if (!ImportedLocalExternalDecls.count(Var))
3905 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3906 VK_LValue, OK_Ordinary,
3907 DRE->getLocation());
3908 // Need parens to enforce precedence.
3909 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3911 ReplaceStmt(DRE, PE);
3915 void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3916 SourceLocation LocStart = CE->getLParenLoc();
3917 SourceLocation LocEnd = CE->getRParenLoc();
3919 // Need to avoid trying to rewrite synthesized casts.
3920 if (LocStart.isInvalid())
3922 // Need to avoid trying to rewrite casts contained in macros.
3923 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3926 const char *startBuf = SM->getCharacterData(LocStart);
3927 const char *endBuf = SM->getCharacterData(LocEnd);
3928 QualType QT = CE->getType();
3929 const Type* TypePtr = QT->getAs<Type>();
3930 if (isa<TypeOfExprType>(TypePtr)) {
3931 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3932 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3933 std::string TypeAsString = "(";
3934 RewriteBlockPointerType(TypeAsString, QT);
3935 TypeAsString += ")";
3936 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3939 // advance the location to startArgList.
3940 const char *argPtr = startBuf;
3942 while (*argPtr++ && (argPtr < endBuf)) {
3945 // Replace the '^' with '*'.
3946 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3947 ReplaceText(LocStart, 1, "*");
3954 void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3955 SourceLocation DeclLoc = FD->getLocation();
3956 unsigned parenCount = 0;
3958 // We have 1 or more arguments that have closure pointers.
3959 const char *startBuf = SM->getCharacterData(DeclLoc);
3960 const char *startArgList = strchr(startBuf, '(');
3962 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3965 // advance the location to startArgList.
3966 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3967 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3969 const char *argPtr = startArgList;
3971 while (*argPtr++ && parenCount) {
3974 // Replace the '^' with '*'.
3975 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3976 ReplaceText(DeclLoc, 1, "*");
3989 bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3990 const FunctionProtoType *FTP;
3991 const PointerType *PT = QT->getAs<PointerType>();
3993 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3995 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3996 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3997 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4000 for (const auto &I : FTP->param_types())
4001 if (isTopLevelBlockPointerType(I))
4007 bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4008 const FunctionProtoType *FTP;
4009 const PointerType *PT = QT->getAs<PointerType>();
4011 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4013 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4014 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4015 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4018 for (const auto &I : FTP->param_types()) {
4019 if (I->isObjCQualifiedIdType())
4021 if (I->isObjCObjectPointerType() &&
4022 I->getPointeeType()->isObjCQualifiedInterfaceType())
4030 void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4031 const char *&RParen) {
4032 const char *argPtr = strchr(Name, '(');
4033 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4035 LParen = argPtr; // output the start.
4036 argPtr++; // skip past the left paren.
4037 unsigned parenCount = 1;
4039 while (*argPtr && parenCount) {
4041 case '(': parenCount++; break;
4042 case ')': parenCount--; break;
4045 if (parenCount) argPtr++;
4047 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4048 RParen = argPtr; // output the end
4051 void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4053 RewriteBlockPointerFunctionArgs(FD);
4056 // Handle Variables and Typedefs.
4057 SourceLocation DeclLoc = ND->getLocation();
4059 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4060 DeclT = VD->getType();
4061 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4062 DeclT = TDD->getUnderlyingType();
4063 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4064 DeclT = FD->getType();
4066 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4068 const char *startBuf = SM->getCharacterData(DeclLoc);
4069 const char *endBuf = startBuf;
4070 // scan backward (from the decl location) for the end of the previous decl.
4071 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4073 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4075 unsigned OrigLength=0;
4076 // *startBuf != '^' if we are dealing with a pointer to function that
4077 // may take block argument types (which will be handled below).
4078 if (*startBuf == '^') {
4079 // Replace the '^' with '*', computing a negative offset.
4084 while (*startBuf != ')') {
4092 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4093 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4094 // Replace the '^' with '*' for arguments.
4095 // Replace id<P> with id/*<>*/
4096 DeclLoc = ND->getLocation();
4097 startBuf = SM->getCharacterData(DeclLoc);
4098 const char *argListBegin, *argListEnd;
4099 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4100 while (argListBegin < argListEnd) {
4101 if (*argListBegin == '^')
4103 else if (*argListBegin == '<') {
4105 buf += *argListBegin++;
4107 while (*argListBegin != '>') {
4108 buf += *argListBegin++;
4111 buf += *argListBegin;
4115 buf += *argListBegin;
4122 ReplaceText(Start, OrigLength, buf);
4128 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4129 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4130 /// struct Block_byref_id_object *src) {
4131 /// _Block_object_assign (&_dest->object, _src->object,
4132 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4133 /// [|BLOCK_FIELD_IS_WEAK]) // object
4134 /// _Block_object_assign(&_dest->object, _src->object,
4135 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4136 /// [|BLOCK_FIELD_IS_WEAK]) // block
4139 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4140 /// _Block_object_dispose(_src->object,
4141 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4142 /// [|BLOCK_FIELD_IS_WEAK]) // object
4143 /// _Block_object_dispose(_src->object,
4144 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4145 /// [|BLOCK_FIELD_IS_WEAK]) // block
4148 std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4151 if (CopyDestroyCache.count(flag))
4153 CopyDestroyCache.insert(flag);
4154 S = "static void __Block_byref_id_object_copy_";
4156 S += "(void *dst, void *src) {\n";
4158 // offset into the object pointer is computed as:
4159 // void * + void* + int + int + void* + void *
4161 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4162 unsigned VoidPtrSize =
4163 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4165 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4166 S += " _Block_object_assign((char*)dst + ";
4167 S += utostr(offset);
4168 S += ", *(void * *) ((char*)src + ";
4169 S += utostr(offset);
4174 S += "static void __Block_byref_id_object_dispose_";
4176 S += "(void *src) {\n";
4177 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4178 S += utostr(offset);
4185 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
4186 /// the declaration into:
4187 /// struct __Block_byref_ND {
4188 /// void *__isa; // NULL for everything except __weak pointers
4189 /// struct __Block_byref_ND *__forwarding;
4190 /// int32_t __flags;
4192 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4193 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4197 /// It then replaces declaration of ND variable with:
4198 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4199 /// __size=sizeof(struct __Block_byref_ND),
4200 /// ND=initializer-if-any};
4203 void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4204 // Insert declaration for the function in which block literal is
4206 if (CurFunctionDeclToDeclareForBlock)
4207 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4210 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4211 if (DeclLoc.isInvalid())
4212 // If type location is missing, it is because of missing type (a warning).
4213 // Use variable's location which is good for this case.
4214 DeclLoc = ND->getLocation();
4215 const char *startBuf = SM->getCharacterData(DeclLoc);
4216 SourceLocation X = ND->getLocEnd();
4217 X = SM->getExpansionLoc(X);
4218 const char *endBuf = SM->getCharacterData(X);
4219 std::string Name(ND->getNameAsString());
4220 std::string ByrefType;
4221 RewriteByRefString(ByrefType, Name, ND, true);
4222 ByrefType += " {\n";
4223 ByrefType += " void *__isa;\n";
4224 RewriteByRefString(ByrefType, Name, ND);
4225 ByrefType += " *__forwarding;\n";
4226 ByrefType += " int __flags;\n";
4227 ByrefType += " int __size;\n";
4228 // Add void *__Block_byref_id_object_copy;
4229 // void *__Block_byref_id_object_dispose; if needed.
4230 QualType Ty = ND->getType();
4231 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4232 if (HasCopyAndDispose) {
4233 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4234 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4238 (void)convertBlockPointerToFunctionPointer(T);
4239 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4241 ByrefType += " " + Name + ";\n";
4242 ByrefType += "};\n";
4243 // Insert this type in global scope. It is needed by helper function.
4244 SourceLocation FunLocStart;
4246 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4248 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4249 FunLocStart = CurMethodDef->getLocStart();
4251 InsertText(FunLocStart, ByrefType);
4252 if (Ty.isObjCGCWeak()) {
4253 flag |= BLOCK_FIELD_IS_WEAK;
4257 if (HasCopyAndDispose) {
4258 flag = BLOCK_BYREF_CALLER;
4259 QualType Ty = ND->getType();
4260 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4261 if (Ty->isBlockPointerType())
4262 flag |= BLOCK_FIELD_IS_BLOCK;
4264 flag |= BLOCK_FIELD_IS_OBJECT;
4265 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4267 InsertText(FunLocStart, HF);
4270 // struct __Block_byref_ND ND =
4271 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4272 // initializer-if-any};
4273 bool hasInit = (ND->getInit() != nullptr);
4275 if (HasCopyAndDispose)
4276 flags |= BLOCK_HAS_COPY_DISPOSE;
4277 Name = ND->getNameAsString();
4279 RewriteByRefString(ByrefType, Name, ND);
4280 std::string ForwardingCastType("(");
4281 ForwardingCastType += ByrefType + " *)";
4283 ByrefType += " " + Name + " = {(void*)";
4284 ByrefType += utostr(isa);
4285 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4286 ByrefType += utostr(flags);
4288 ByrefType += "sizeof(";
4289 RewriteByRefString(ByrefType, Name, ND);
4291 if (HasCopyAndDispose) {
4292 ByrefType += ", __Block_byref_id_object_copy_";
4293 ByrefType += utostr(flag);
4294 ByrefType += ", __Block_byref_id_object_dispose_";
4295 ByrefType += utostr(flag);
4297 ByrefType += "};\n";
4298 unsigned nameSize = Name.size();
4299 // for block or function pointer declaration. Name is aleady
4300 // part of the declaration.
4301 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4303 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4306 SourceLocation startLoc;
4307 Expr *E = ND->getInit();
4308 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4309 startLoc = ECE->getLParenLoc();
4311 startLoc = E->getLocStart();
4312 startLoc = SM->getExpansionLoc(startLoc);
4313 endBuf = SM->getCharacterData(startLoc);
4314 ByrefType += " " + Name;
4315 ByrefType += " = {(void*)";
4316 ByrefType += utostr(isa);
4317 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4318 ByrefType += utostr(flags);
4320 ByrefType += "sizeof(";
4321 RewriteByRefString(ByrefType, Name, ND);
4323 if (HasCopyAndDispose) {
4324 ByrefType += "__Block_byref_id_object_copy_";
4325 ByrefType += utostr(flag);
4326 ByrefType += ", __Block_byref_id_object_dispose_";
4327 ByrefType += utostr(flag);
4330 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4332 // Complete the newly synthesized compound expression by inserting a right
4333 // curly brace before the end of the declaration.
4334 // FIXME: This approach avoids rewriting the initializer expression. It
4335 // also assumes there is only one declarator. For example, the following
4336 // isn't currently supported by this routine (in general):
4338 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4340 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4341 const char *semiBuf = strchr(startInitializerBuf, ';');
4342 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4343 SourceLocation semiLoc =
4344 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4346 InsertText(semiLoc, "}");
4351 void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4352 // Add initializers for any closure decl refs.
4353 GetBlockDeclRefExprs(Exp->getBody());
4354 if (BlockDeclRefs.size()) {
4355 // Unique all "by copy" declarations.
4356 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4357 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4358 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4359 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4360 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4363 // Unique all "by ref" declarations.
4364 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4365 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4366 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4367 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4368 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4371 // Find any imported blocks...they will need special attention.
4372 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4373 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4374 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4375 BlockDeclRefs[i]->getType()->isBlockPointerType())
4376 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4380 FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4381 IdentifierInfo *ID = &Context->Idents.get(name);
4382 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4383 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4384 SourceLocation(), ID, FType, nullptr, SC_Extern,
4388 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4389 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4390 const BlockDecl *block = Exp->getBlockDecl();
4391 Blocks.push_back(Exp);
4393 CollectBlockDeclRefInfo(Exp);
4395 // Add inner imported variables now used in current block.
4396 int countOfInnerDecls = 0;
4397 if (!InnerBlockDeclRefs.empty()) {
4398 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4399 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4400 ValueDecl *VD = Exp->getDecl();
4401 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
4402 // We need to save the copied-in variables in nested
4403 // blocks because it is needed at the end for some of the API generations.
4404 // See SynthesizeBlockLiterals routine.
4405 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4406 BlockDeclRefs.push_back(Exp);
4407 BlockByCopyDeclsPtrSet.insert(VD);
4408 BlockByCopyDecls.push_back(VD);
4410 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
4411 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4412 BlockDeclRefs.push_back(Exp);
4413 BlockByRefDeclsPtrSet.insert(VD);
4414 BlockByRefDecls.push_back(VD);
4417 // Find any imported blocks...they will need special attention.
4418 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4419 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4420 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4421 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4422 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4424 InnerDeclRefsCount.push_back(countOfInnerDecls);
4426 std::string FuncName;
4429 FuncName = CurFunctionDef->getNameAsString();
4430 else if (CurMethodDef)
4431 BuildUniqueMethodName(FuncName, CurMethodDef);
4432 else if (GlobalVarDecl)
4433 FuncName = std::string(GlobalVarDecl->getNameAsString());
4435 std::string BlockNumber = utostr(Blocks.size()-1);
4437 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4438 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4440 // Get a pointer to the function type so we can cast appropriately.
4441 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4442 QualType FType = Context->getPointerType(BFT);
4447 // Simulate a constructor call...
4448 FD = SynthBlockInitFunctionDecl(Tag);
4449 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
4452 SmallVector<Expr*, 4> InitExprs;
4454 // Initialize the block function.
4455 FD = SynthBlockInitFunctionDecl(Func);
4456 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4457 VK_LValue, SourceLocation());
4458 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4460 InitExprs.push_back(castExpr);
4462 // Initialize the block descriptor.
4463 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4465 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4466 SourceLocation(), SourceLocation(),
4467 &Context->Idents.get(DescData.c_str()),
4468 Context->VoidPtrTy, nullptr,
4470 UnaryOperator *DescRefExpr =
4471 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
4476 Context->getPointerType(Context->VoidPtrTy),
4477 VK_RValue, OK_Ordinary,
4479 InitExprs.push_back(DescRefExpr);
4481 // Add initializers for any closure decl refs.
4482 if (BlockDeclRefs.size()) {
4484 // Output all "by copy" declarations.
4485 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4486 E = BlockByCopyDecls.end(); I != E; ++I) {
4487 if (isObjCType((*I)->getType())) {
4488 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4489 FD = SynthBlockInitFunctionDecl((*I)->getName());
4490 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4492 if (HasLocalVariableExternalStorage(*I)) {
4493 QualType QT = (*I)->getType();
4494 QT = Context->getPointerType(QT);
4495 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4496 OK_Ordinary, SourceLocation());
4498 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4499 FD = SynthBlockInitFunctionDecl((*I)->getName());
4500 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4502 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4505 FD = SynthBlockInitFunctionDecl((*I)->getName());
4506 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4508 if (HasLocalVariableExternalStorage(*I)) {
4509 QualType QT = (*I)->getType();
4510 QT = Context->getPointerType(QT);
4511 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4512 OK_Ordinary, SourceLocation());
4516 InitExprs.push_back(Exp);
4518 // Output all "by ref" declarations.
4519 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4520 E = BlockByRefDecls.end(); I != E; ++I) {
4521 ValueDecl *ND = (*I);
4522 std::string Name(ND->getNameAsString());
4523 std::string RecName;
4524 RewriteByRefString(RecName, Name, ND, true);
4525 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4526 + sizeof("struct"));
4527 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4528 SourceLocation(), SourceLocation(),
4530 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4531 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4533 FD = SynthBlockInitFunctionDecl((*I)->getName());
4534 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
4536 bool isNestedCapturedVar = false;
4538 for (const auto &CI : block->captures()) {
4539 const VarDecl *variable = CI.getVariable();
4540 if (variable == ND && CI.isNested()) {
4541 assert (CI.isByRef() &&
4542 "SynthBlockInitExpr - captured block variable is not byref");
4543 isNestedCapturedVar = true;
4547 // captured nested byref variable has its address passed. Do not take
4548 // its address again.
4549 if (!isNestedCapturedVar)
4550 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4551 Context->getPointerType(Exp->getType()),
4552 VK_RValue, OK_Ordinary, SourceLocation());
4553 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4554 InitExprs.push_back(Exp);
4557 if (ImportedBlockDecls.size()) {
4558 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4559 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4561 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4562 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4563 Context->IntTy, SourceLocation());
4564 InitExprs.push_back(FlagExp);
4566 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
4567 FType, VK_LValue, SourceLocation());
4568 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4569 Context->getPointerType(NewRep->getType()),
4570 VK_RValue, OK_Ordinary, SourceLocation());
4571 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4573 BlockDeclRefs.clear();
4574 BlockByRefDecls.clear();
4575 BlockByRefDeclsPtrSet.clear();
4576 BlockByCopyDecls.clear();
4577 BlockByCopyDeclsPtrSet.clear();
4578 ImportedBlockDecls.clear();
4582 bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4583 if (const ObjCForCollectionStmt * CS =
4584 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4585 return CS->getElement() == DS;
4589 //===----------------------------------------------------------------------===//
4590 // Function Body / Expression rewriting
4591 //===----------------------------------------------------------------------===//
4593 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4594 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4595 isa<DoStmt>(S) || isa<ForStmt>(S))
4597 else if (isa<ObjCForCollectionStmt>(S)) {
4599 ObjCBcLabelNo.push_back(++BcLabelCount);
4602 // Pseudo-object operations and ivar references need special
4603 // treatment because we're going to recursively rewrite them.
4604 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4605 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4606 return RewritePropertyOrImplicitSetter(PseudoOp);
4608 return RewritePropertyOrImplicitGetter(PseudoOp);
4610 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4611 return RewriteObjCIvarRefExpr(IvarRefExpr);
4614 SourceRange OrigStmtRange = S->getSourceRange();
4616 // Perform a bottom up rewrite of all children.
4617 for (Stmt::child_range CI = S->children(); CI; ++CI)
4619 Stmt *childStmt = (*CI);
4620 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4626 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4627 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4628 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4629 InnerContexts.insert(BE->getBlockDecl());
4630 ImportedLocalExternalDecls.clear();
4631 GetInnerBlockDeclRefExprs(BE->getBody(),
4632 InnerBlockDeclRefs, InnerContexts);
4633 // Rewrite the block body in place.
4634 Stmt *SaveCurrentBody = CurrentBody;
4635 CurrentBody = BE->getBody();
4636 PropParentMap = nullptr;
4637 // block literal on rhs of a property-dot-sytax assignment
4638 // must be replaced by its synthesize ast so getRewrittenText
4639 // works as expected. In this case, what actually ends up on RHS
4640 // is the blockTranscribed which is the helper function for the
4641 // block literal; as in: self.c = ^() {[ace ARR];};
4642 bool saveDisableReplaceStmt = DisableReplaceStmt;
4643 DisableReplaceStmt = false;
4644 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4645 DisableReplaceStmt = saveDisableReplaceStmt;
4646 CurrentBody = SaveCurrentBody;
4647 PropParentMap = nullptr;
4648 ImportedLocalExternalDecls.clear();
4649 // Now we snarf the rewritten text and stash it away for later use.
4650 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4651 RewrittenBlockExprs[BE] = Str;
4653 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4655 //blockTranscribed->dump();
4656 ReplaceStmt(S, blockTranscribed);
4657 return blockTranscribed;
4659 // Handle specific things.
4660 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4661 return RewriteAtEncode(AtEncode);
4663 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4664 return RewriteAtSelector(AtSelector);
4666 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4667 return RewriteObjCStringLiteral(AtString);
4669 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4671 // Before we rewrite it, put the original message expression in a comment.
4672 SourceLocation startLoc = MessExpr->getLocStart();
4673 SourceLocation endLoc = MessExpr->getLocEnd();
4675 const char *startBuf = SM->getCharacterData(startLoc);
4676 const char *endBuf = SM->getCharacterData(endLoc);
4678 std::string messString;
4679 messString += "// ";
4680 messString.append(startBuf, endBuf-startBuf+1);
4683 // FIXME: Missing definition of
4684 // InsertText(clang::SourceLocation, char const*, unsigned int).
4685 // InsertText(startLoc, messString.c_str(), messString.size());
4686 // Tried this, but it didn't work either...
4687 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4689 return RewriteMessageExpr(MessExpr);
4692 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4693 return RewriteObjCTryStmt(StmtTry);
4695 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4696 return RewriteObjCSynchronizedStmt(StmtTry);
4698 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4699 return RewriteObjCThrowStmt(StmtThrow);
4701 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4702 return RewriteObjCProtocolExpr(ProtocolExp);
4704 if (ObjCForCollectionStmt *StmtForCollection =
4705 dyn_cast<ObjCForCollectionStmt>(S))
4706 return RewriteObjCForCollectionStmt(StmtForCollection,
4707 OrigStmtRange.getEnd());
4708 if (BreakStmt *StmtBreakStmt =
4709 dyn_cast<BreakStmt>(S))
4710 return RewriteBreakStmt(StmtBreakStmt);
4711 if (ContinueStmt *StmtContinueStmt =
4712 dyn_cast<ContinueStmt>(S))
4713 return RewriteContinueStmt(StmtContinueStmt);
4715 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4717 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4718 // FIXME: What we're doing here is modifying the type-specifier that
4719 // precedes the first Decl. In the future the DeclGroup should have
4720 // a separate type-specifier that we can rewrite.
4721 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4722 // the context of an ObjCForCollectionStmt. For example:
4723 // NSArray *someArray;
4724 // for (id <FooProtocol> index in someArray) ;
4725 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4726 // and it depends on the original text locations/positions.
4727 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4728 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4730 // Blocks rewrite rules.
4731 for (auto *SD : DS->decls()) {
4732 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4733 if (isTopLevelBlockPointerType(ND->getType()))
4734 RewriteBlockPointerDecl(ND);
4735 else if (ND->getType()->isFunctionPointerType())
4736 CheckFunctionPointerDecl(ND->getType(), ND);
4737 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4738 if (VD->hasAttr<BlocksAttr>()) {
4739 static unsigned uniqueByrefDeclCount = 0;
4740 assert(!BlockByRefDeclNo.count(ND) &&
4741 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4742 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4743 RewriteByRefVar(VD);
4746 RewriteTypeOfDecl(VD);
4749 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4750 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4751 RewriteBlockPointerDecl(TD);
4752 else if (TD->getUnderlyingType()->isFunctionPointerType())
4753 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4758 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4759 RewriteObjCQualifiedInterfaceTypes(CE);
4761 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4762 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4763 assert(!Stmts.empty() && "Statement stack is empty");
4764 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4765 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4766 && "Statement stack mismatch");
4769 // Handle blocks rewriting.
4770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4771 ValueDecl *VD = DRE->getDecl();
4772 if (VD->hasAttr<BlocksAttr>())
4773 return RewriteBlockDeclRefExpr(DRE);
4774 if (HasLocalVariableExternalStorage(VD))
4775 return RewriteLocalVariableExternalStorage(DRE);
4778 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4779 if (CE->getCallee()->getType()->isBlockPointerType()) {
4780 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4781 ReplaceStmt(S, BlockCall);
4785 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4786 RewriteCastExpr(CE);
4789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4790 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4793 // Get the new text.
4795 llvm::raw_string_ostream Buf(SStr);
4796 Replacement->printPretty(Buf);
4797 const std::string &Str = Buf.str();
4799 printf("CAST = %s\n", &Str[0]);
4800 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4805 // Return this stmt unmodified.
4809 void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4810 for (auto *FD : RD->fields()) {
4811 if (isTopLevelBlockPointerType(FD->getType()))
4812 RewriteBlockPointerDecl(FD);
4813 if (FD->getType()->isObjCQualifiedIdType() ||
4814 FD->getType()->isObjCQualifiedInterfaceType())
4815 RewriteObjCQualifiedInterfaceTypes(FD);
4819 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
4820 /// main file of the input.
4821 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4822 switch (D->getKind()) {
4823 case Decl::Function: {
4824 FunctionDecl *FD = cast<FunctionDecl>(D);
4825 if (FD->isOverloadedOperator())
4828 // Since function prototypes don't have ParmDecl's, we check the function
4829 // prototype. This enables us to rewrite function declarations and
4830 // definitions using the same code.
4831 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4833 if (!FD->isThisDeclarationADefinition())
4836 // FIXME: If this should support Obj-C++, support CXXTryStmt
4837 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4838 CurFunctionDef = FD;
4839 CurFunctionDeclToDeclareForBlock = FD;
4842 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4844 CurrentBody = nullptr;
4845 if (PropParentMap) {
4846 delete PropParentMap;
4847 PropParentMap = nullptr;
4849 // This synthesizes and inserts the block "impl" struct, invoke function,
4850 // and any copy/dispose helper functions.
4851 InsertBlockLiteralsWithinFunction(FD);
4852 CurFunctionDef = nullptr;
4853 CurFunctionDeclToDeclareForBlock = nullptr;
4857 case Decl::ObjCMethod: {
4858 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4859 if (CompoundStmt *Body = MD->getCompoundBody()) {
4863 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4865 CurrentBody = nullptr;
4866 if (PropParentMap) {
4867 delete PropParentMap;
4868 PropParentMap = nullptr;
4870 InsertBlockLiteralsWithinMethod(MD);
4871 CurMethodDef = nullptr;
4875 case Decl::ObjCImplementation: {
4876 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4877 ClassImplementation.push_back(CI);
4880 case Decl::ObjCCategoryImpl: {
4881 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4882 CategoryImplementation.push_back(CI);
4886 VarDecl *VD = cast<VarDecl>(D);
4887 RewriteObjCQualifiedInterfaceTypes(VD);
4888 if (isTopLevelBlockPointerType(VD->getType()))
4889 RewriteBlockPointerDecl(VD);
4890 else if (VD->getType()->isFunctionPointerType()) {
4891 CheckFunctionPointerDecl(VD->getType(), VD);
4892 if (VD->getInit()) {
4893 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4894 RewriteCastExpr(CE);
4897 } else if (VD->getType()->isRecordType()) {
4898 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4899 if (RD->isCompleteDefinition())
4900 RewriteRecordBody(RD);
4902 if (VD->getInit()) {
4904 CurrentBody = VD->getInit();
4905 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4906 CurrentBody = nullptr;
4907 if (PropParentMap) {
4908 delete PropParentMap;
4909 PropParentMap = nullptr;
4911 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4912 GlobalVarDecl = nullptr;
4914 // This is needed for blocks.
4915 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4916 RewriteCastExpr(CE);
4921 case Decl::TypeAlias:
4922 case Decl::Typedef: {
4923 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4924 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4925 RewriteBlockPointerDecl(TD);
4926 else if (TD->getUnderlyingType()->isFunctionPointerType())
4927 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4931 case Decl::CXXRecord:
4932 case Decl::Record: {
4933 RecordDecl *RD = cast<RecordDecl>(D);
4934 if (RD->isCompleteDefinition())
4935 RewriteRecordBody(RD);
4944 void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4945 if (Diags.hasErrorOccurred())
4950 // Here's a great place to add any extra declarations that may be needed.
4951 // Write out meta data for each @protocol(<expr>).
4952 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4953 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4955 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4956 if (ClassImplementation.size() || CategoryImplementation.size())
4957 RewriteImplementations();
4959 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4961 if (const RewriteBuffer *RewriteBuf =
4962 Rewrite.getRewriteBufferFor(MainFileID)) {
4963 //printf("Changed:\n");
4964 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4966 llvm::errs() << "No changes\n";
4969 if (ClassImplementation.size() || CategoryImplementation.size() ||
4970 ProtocolExprDecls.size()) {
4971 // Rewrite Objective-c meta data*
4972 std::string ResultStr;
4973 RewriteMetaDataIntoBuffer(ResultStr);
4975 *OutFile << ResultStr;
4980 void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4981 InitializeCommon(context);
4983 // declaring objc_selector outside the parameter list removes a silly
4984 // scope related warning...
4986 Preamble = "#pragma once\n";
4987 Preamble += "struct objc_selector; struct objc_class;\n";
4988 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4989 Preamble += "struct objc_object *superClass; ";
4990 if (LangOpts.MicrosoftExt) {
4991 // Add a constructor for creating temporary objects.
4992 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4994 Preamble += "object(o), superClass(s) {} ";
4997 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4998 Preamble += "typedef struct objc_object Protocol;\n";
4999 Preamble += "#define _REWRITER_typedef_Protocol\n";
5000 Preamble += "#endif\n";
5001 if (LangOpts.MicrosoftExt) {
5002 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5003 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5005 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5006 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5007 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5008 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5009 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5010 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5011 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5012 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5013 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5014 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5015 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5016 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5017 Preamble += "(const char *);\n";
5018 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5019 Preamble += "(struct objc_class *);\n";
5020 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5021 Preamble += "(const char *);\n";
5022 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5023 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5024 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5025 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5026 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5027 Preamble += "(struct objc_class *, struct objc_object *);\n";
5028 // @synchronized hooks.
5029 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5030 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
5031 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5032 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5033 Preamble += "struct __objcFastEnumerationState {\n\t";
5034 Preamble += "unsigned long state;\n\t";
5035 Preamble += "void **itemsPtr;\n\t";
5036 Preamble += "unsigned long *mutationsPtr;\n\t";
5037 Preamble += "unsigned long extra[5];\n};\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5039 Preamble += "#define __FASTENUMERATIONSTATE\n";
5040 Preamble += "#endif\n";
5041 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5042 Preamble += "struct __NSConstantStringImpl {\n";
5043 Preamble += " int *isa;\n";
5044 Preamble += " int flags;\n";
5045 Preamble += " char *str;\n";
5046 Preamble += " long length;\n";
5048 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5049 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5050 Preamble += "#else\n";
5051 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5052 Preamble += "#endif\n";
5053 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5054 Preamble += "#endif\n";
5056 Preamble += "#ifndef BLOCK_IMPL\n";
5057 Preamble += "#define BLOCK_IMPL\n";
5058 Preamble += "struct __block_impl {\n";
5059 Preamble += " void *isa;\n";
5060 Preamble += " int Flags;\n";
5061 Preamble += " int Reserved;\n";
5062 Preamble += " void *FuncPtr;\n";
5064 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5065 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5066 Preamble += "extern \"C\" __declspec(dllexport) "
5067 "void _Block_object_assign(void *, const void *, const int);\n";
5068 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5069 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5070 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5071 Preamble += "#else\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5076 Preamble += "#endif\n";
5077 Preamble += "#endif\n";
5078 if (LangOpts.MicrosoftExt) {
5079 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5080 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5081 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5082 Preamble += "#define __attribute__(X)\n";
5083 Preamble += "#endif\n";
5084 Preamble += "#define __weak\n";
5087 Preamble += "#define __block\n";
5088 Preamble += "#define __weak\n";
5090 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5091 // as this avoids warning in any 64bit/32bit compilation model.
5092 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5095 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5097 void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5098 std::string &Result) {
5099 if (ivar->isBitField()) {
5100 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5101 // place all bitfields at offset 0.
5104 Result += "__OFFSETOFIVAR__(struct ";
5105 Result += ivar->getContainingInterface()->getNameAsString();
5106 if (LangOpts.MicrosoftExt)
5109 Result += ivar->getNameAsString();
5114 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5115 void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5116 ObjCProtocolDecl *PDecl, StringRef prefix,
5117 StringRef ClassName, std::string &Result) {
5118 static bool objc_protocol_methods = false;
5120 // Output struct protocol_methods holder of method selector and type.
5121 if (!objc_protocol_methods && PDecl->hasDefinition()) {
5122 /* struct protocol_methods {
5127 Result += "\nstruct _protocol_methods {\n";
5128 Result += "\tstruct objc_selector *_cmd;\n";
5129 Result += "\tchar *method_types;\n";
5132 objc_protocol_methods = true;
5134 // Do not synthesize the protocol more than once.
5135 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5138 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5141 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5142 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5143 PDecl->instmeth_end());
5144 /* struct _objc_protocol_method_list {
5145 int protocol_method_count;
5146 struct protocol_methods protocols[];
5149 Result += "\nstatic struct {\n";
5150 Result += "\tint protocol_method_count;\n";
5151 Result += "\tstruct _protocol_methods protocol_methods[";
5152 Result += utostr(NumMethods);
5153 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5154 Result += PDecl->getNameAsString();
5155 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5156 "{\n\t" + utostr(NumMethods) + "\n";
5158 // Output instance methods declared in this protocol.
5159 for (ObjCProtocolDecl::instmeth_iterator
5160 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5162 if (I == PDecl->instmeth_begin())
5163 Result += "\t ,{{(struct objc_selector *)\"";
5165 Result += "\t ,{(struct objc_selector *)\"";
5166 Result += (*I)->getSelector().getAsString();
5167 std::string MethodTypeString;
5168 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5170 Result += MethodTypeString;
5173 Result += "\t }\n};\n";
5176 // Output class methods declared in this protocol.
5177 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5178 PDecl->classmeth_end());
5179 if (NumMethods > 0) {
5180 /* struct _objc_protocol_method_list {
5181 int protocol_method_count;
5182 struct protocol_methods protocols[];
5185 Result += "\nstatic struct {\n";
5186 Result += "\tint protocol_method_count;\n";
5187 Result += "\tstruct _protocol_methods protocol_methods[";
5188 Result += utostr(NumMethods);
5189 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5190 Result += PDecl->getNameAsString();
5191 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5193 Result += utostr(NumMethods);
5196 // Output instance methods declared in this protocol.
5197 for (ObjCProtocolDecl::classmeth_iterator
5198 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5200 if (I == PDecl->classmeth_begin())
5201 Result += "\t ,{{(struct objc_selector *)\"";
5203 Result += "\t ,{(struct objc_selector *)\"";
5204 Result += (*I)->getSelector().getAsString();
5205 std::string MethodTypeString;
5206 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5208 Result += MethodTypeString;
5211 Result += "\t }\n};\n";
5215 /* struct _objc_protocol {
5216 // Objective-C 1.0 extensions
5217 struct _objc_protocol_extension *isa;
5218 char *protocol_name;
5219 struct _objc_protocol **protocol_list;
5220 struct _objc_protocol_method_list *instance_methods;
5221 struct _objc_protocol_method_list *class_methods;
5224 static bool objc_protocol = false;
5225 if (!objc_protocol) {
5226 Result += "\nstruct _objc_protocol {\n";
5227 Result += "\tstruct _objc_protocol_extension *isa;\n";
5228 Result += "\tchar *protocol_name;\n";
5229 Result += "\tstruct _objc_protocol **protocol_list;\n";
5230 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5231 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5234 objc_protocol = true;
5237 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5238 Result += PDecl->getNameAsString();
5239 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5241 Result += PDecl->getNameAsString();
5242 Result += "\", 0, ";
5243 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5244 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5245 Result += PDecl->getNameAsString();
5250 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5251 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5252 Result += PDecl->getNameAsString();
5259 // Mark this protocol as having been generated.
5260 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
5261 llvm_unreachable("protocol already synthesized");
5265 void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5266 const ObjCList<ObjCProtocolDecl> &Protocols,
5267 StringRef prefix, StringRef ClassName,
5268 std::string &Result) {
5269 if (Protocols.empty()) return;
5271 for (unsigned i = 0; i != Protocols.size(); i++)
5272 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5274 // Output the top lovel protocol meta-data for the class.
5275 /* struct _objc_protocol_list {
5276 struct _objc_protocol_list *next;
5278 struct _objc_protocol *class_protocols[];
5281 Result += "\nstatic struct {\n";
5282 Result += "\tstruct _objc_protocol_list *next;\n";
5283 Result += "\tint protocol_count;\n";
5284 Result += "\tstruct _objc_protocol *class_protocols[";
5285 Result += utostr(Protocols.size());
5286 Result += "];\n} _OBJC_";
5288 Result += "_PROTOCOLS_";
5289 Result += ClassName;
5290 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5292 Result += utostr(Protocols.size());
5295 Result += "\t,{&_OBJC_PROTOCOL_";
5296 Result += Protocols[0]->getNameAsString();
5299 for (unsigned i = 1; i != Protocols.size(); i++) {
5300 Result += "\t ,&_OBJC_PROTOCOL_";
5301 Result += Protocols[i]->getNameAsString();
5304 Result += "\t }\n};\n";
5307 void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5308 std::string &Result) {
5309 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5311 // Explicitly declared @interface's are already synthesized.
5312 if (CDecl->isImplicitInterfaceDecl()) {
5313 // FIXME: Implementation of a class with no @interface (legacy) does not
5314 // produce correct synthesis as yet.
5315 RewriteObjCInternalStruct(CDecl, Result);
5318 // Build _objc_ivar_list metadata for classes ivars if needed
5319 unsigned NumIvars = !IDecl->ivar_empty()
5320 ? IDecl->ivar_size()
5321 : (CDecl ? CDecl->ivar_size() : 0);
5323 static bool objc_ivar = false;
5325 /* struct _objc_ivar {
5331 Result += "\nstruct _objc_ivar {\n";
5332 Result += "\tchar *ivar_name;\n";
5333 Result += "\tchar *ivar_type;\n";
5334 Result += "\tint ivar_offset;\n";
5342 struct _objc_ivar ivar_list[nIvars];
5345 Result += "\nstatic struct {\n";
5346 Result += "\tint ivar_count;\n";
5347 Result += "\tstruct _objc_ivar ivar_list[";
5348 Result += utostr(NumIvars);
5349 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5350 Result += IDecl->getNameAsString();
5351 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5353 Result += utostr(NumIvars);
5356 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5357 SmallVector<ObjCIvarDecl *, 8> IVars;
5358 if (!IDecl->ivar_empty()) {
5359 for (auto *IV : IDecl->ivars())
5360 IVars.push_back(IV);
5361 IVI = IDecl->ivar_begin();
5362 IVE = IDecl->ivar_end();
5364 IVI = CDecl->ivar_begin();
5365 IVE = CDecl->ivar_end();
5367 Result += "\t,{{\"";
5368 Result += IVI->getNameAsString();
5370 std::string TmpString, StrEncoding;
5371 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5372 QuoteDoublequotes(TmpString, StrEncoding);
5373 Result += StrEncoding;
5375 RewriteIvarOffsetComputation(*IVI, Result);
5377 for (++IVI; IVI != IVE; ++IVI) {
5378 Result += "\t ,{\"";
5379 Result += IVI->getNameAsString();
5381 std::string TmpString, StrEncoding;
5382 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
5383 QuoteDoublequotes(TmpString, StrEncoding);
5384 Result += StrEncoding;
5386 RewriteIvarOffsetComputation(*IVI, Result);
5390 Result += "\t }\n};\n";
5393 // Build _objc_method_list for class's instance methods if needed
5394 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5396 // If any of our property implementations have associated getters or
5397 // setters, produce metadata for them as well.
5398 for (const auto *Prop : IDecl->property_impls()) {
5399 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5401 if (!Prop->getPropertyIvarDecl())
5403 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5406 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5407 if (!Getter->isDefined())
5408 InstanceMethods.push_back(Getter);
5409 if (PD->isReadOnly())
5411 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5412 if (!Setter->isDefined())
5413 InstanceMethods.push_back(Setter);
5415 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5416 true, "", IDecl->getName(), Result);
5418 // Build _objc_method_list for class's class methods if needed
5419 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5420 false, "", IDecl->getName(), Result);
5422 // Protocols referenced in class declaration?
5423 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5424 "CLASS", CDecl->getName(), Result);
5426 // Declaration of class/meta-class metadata
5427 /* struct _objc_class {
5428 struct _objc_class *isa; // or const char *root_class_name when metadata
5429 const char *super_class_name;
5434 struct _objc_ivar_list *ivars;
5435 struct _objc_method_list *methods;
5436 struct objc_cache *cache;
5437 struct objc_protocol_list *protocols;
5438 const char *ivar_layout;
5439 struct _objc_class_ext *ext;
5442 static bool objc_class = false;
5444 Result += "\nstruct _objc_class {\n";
5445 Result += "\tstruct _objc_class *isa;\n";
5446 Result += "\tconst char *super_class_name;\n";
5447 Result += "\tchar *name;\n";
5448 Result += "\tlong version;\n";
5449 Result += "\tlong info;\n";
5450 Result += "\tlong instance_size;\n";
5451 Result += "\tstruct _objc_ivar_list *ivars;\n";
5452 Result += "\tstruct _objc_method_list *methods;\n";
5453 Result += "\tstruct objc_cache *cache;\n";
5454 Result += "\tstruct _objc_protocol_list *protocols;\n";
5455 Result += "\tconst char *ivar_layout;\n";
5456 Result += "\tstruct _objc_class_ext *ext;\n";
5461 // Meta-class metadata generation.
5462 ObjCInterfaceDecl *RootClass = nullptr;
5463 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5464 while (SuperClass) {
5465 RootClass = SuperClass;
5466 SuperClass = SuperClass->getSuperClass();
5468 SuperClass = CDecl->getSuperClass();
5470 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5471 Result += CDecl->getNameAsString();
5472 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5473 "{\n\t(struct _objc_class *)\"";
5474 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5479 Result += SuperClass->getNameAsString();
5481 Result += CDecl->getNameAsString();
5485 Result += ", 0, \"";
5486 Result += CDecl->getNameAsString();
5489 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5490 // 'info' field is initialized to CLS_META(2) for metaclass
5491 Result += ", 0,2, sizeof(struct _objc_class), 0";
5492 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5493 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5494 Result += IDecl->getNameAsString();
5499 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5500 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5501 Result += CDecl->getNameAsString();
5505 Result += "\t,0,0,0,0\n";
5508 // class metadata generation.
5509 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5510 Result += CDecl->getNameAsString();
5511 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5512 "{\n\t&_OBJC_METACLASS_";
5513 Result += CDecl->getNameAsString();
5516 Result += SuperClass->getNameAsString();
5518 Result += CDecl->getNameAsString();
5522 Result += ", 0, \"";
5523 Result += CDecl->getNameAsString();
5526 // 'info' field is initialized to CLS_CLASS(1) for class
5528 if (!ObjCSynthesizedStructs.count(CDecl))
5531 // class has size. Must synthesize its size.
5532 Result += ",sizeof(struct ";
5533 Result += CDecl->getNameAsString();
5534 if (LangOpts.MicrosoftExt)
5539 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5540 Result += CDecl->getNameAsString();
5545 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5546 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5547 Result += CDecl->getNameAsString();
5548 Result += ", 0\n\t";
5552 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5553 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5554 Result += CDecl->getNameAsString();
5555 Result += ", 0,0\n";
5558 Result += ",0,0,0\n";
5562 void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5563 int ClsDefCount = ClassImplementation.size();
5564 int CatDefCount = CategoryImplementation.size();
5566 // For each implemented class, write out all its meta data.
5567 for (int i = 0; i < ClsDefCount; i++)
5568 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5570 // For each implemented category, write out all its meta data.
5571 for (int i = 0; i < CatDefCount; i++)
5572 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5574 // Write objc_symtab metadata
5582 void *defs[cls_def_cnt + cat_def_cnt];
5586 Result += "\nstruct _objc_symtab {\n";
5587 Result += "\tlong sel_ref_cnt;\n";
5588 Result += "\tSEL *refs;\n";
5589 Result += "\tshort cls_def_cnt;\n";
5590 Result += "\tshort cat_def_cnt;\n";
5591 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5594 Result += "static struct _objc_symtab "
5595 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5596 Result += "\t0, 0, " + utostr(ClsDefCount)
5597 + ", " + utostr(CatDefCount) + "\n";
5598 for (int i = 0; i < ClsDefCount; i++) {
5599 Result += "\t,&_OBJC_CLASS_";
5600 Result += ClassImplementation[i]->getNameAsString();
5604 for (int i = 0; i < CatDefCount; i++) {
5605 Result += "\t,&_OBJC_CATEGORY_";
5606 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5608 Result += CategoryImplementation[i]->getNameAsString();
5614 // Write objc_module metadata
5617 struct _objc_module {
5621 struct _objc_symtab *symtab;
5625 Result += "\nstruct _objc_module {\n";
5626 Result += "\tlong version;\n";
5627 Result += "\tlong size;\n";
5628 Result += "\tconst char *name;\n";
5629 Result += "\tstruct _objc_symtab *symtab;\n";
5631 Result += "static struct _objc_module "
5632 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5633 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5634 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5637 if (LangOpts.MicrosoftExt) {
5638 if (ProtocolExprDecls.size()) {
5639 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5640 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5641 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5642 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5643 Result += ProtDecl->getNameAsString();
5644 Result += " = &_OBJC_PROTOCOL_";
5645 Result += ProtDecl->getNameAsString();
5648 Result += "#pragma data_seg(pop)\n\n";
5650 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5651 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5652 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5653 Result += "&_OBJC_MODULES;\n";
5654 Result += "#pragma data_seg(pop)\n\n";
5658 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5660 void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5661 std::string &Result) {
5662 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5663 // Find category declaration for this implementation.
5664 ObjCCategoryDecl *CDecl
5665 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
5667 std::string FullCategoryName = ClassDecl->getNameAsString();
5668 FullCategoryName += '_';
5669 FullCategoryName += IDecl->getNameAsString();
5671 // Build _objc_method_list for class's instance methods if needed
5672 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
5674 // If any of our property implementations have associated getters or
5675 // setters, produce metadata for them as well.
5676 for (const auto *Prop : IDecl->property_impls()) {
5677 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5679 if (!Prop->getPropertyIvarDecl())
5681 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
5684 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5685 InstanceMethods.push_back(Getter);
5686 if (PD->isReadOnly())
5688 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5689 InstanceMethods.push_back(Setter);
5691 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5692 true, "CATEGORY_", FullCategoryName.c_str(),
5695 // Build _objc_method_list for class's class methods if needed
5696 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5697 false, "CATEGORY_", FullCategoryName.c_str(),
5700 // Protocols referenced in class declaration?
5701 // Null CDecl is case of a category implementation with no category interface
5703 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5704 FullCategoryName, Result);
5705 /* struct _objc_category {
5706 char *category_name;
5708 struct _objc_method_list *instance_methods;
5709 struct _objc_method_list *class_methods;
5710 struct _objc_protocol_list *protocols;
5711 // Objective-C 1.0 extensions
5712 uint32_t size; // sizeof (struct _objc_category)
5713 struct _objc_property_list *instance_properties; // category's own
5718 static bool objc_category = false;
5719 if (!objc_category) {
5720 Result += "\nstruct _objc_category {\n";
5721 Result += "\tchar *category_name;\n";
5722 Result += "\tchar *class_name;\n";
5723 Result += "\tstruct _objc_method_list *instance_methods;\n";
5724 Result += "\tstruct _objc_method_list *class_methods;\n";
5725 Result += "\tstruct _objc_protocol_list *protocols;\n";
5726 Result += "\tunsigned int size;\n";
5727 Result += "\tstruct _objc_property_list *instance_properties;\n";
5729 objc_category = true;
5731 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5732 Result += FullCategoryName;
5733 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5734 Result += IDecl->getNameAsString();
5735 Result += "\"\n\t, \"";
5736 Result += ClassDecl->getNameAsString();
5739 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5740 Result += "\t, (struct _objc_method_list *)"
5741 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5742 Result += FullCategoryName;
5746 Result += "\t, 0\n";
5747 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5748 Result += "\t, (struct _objc_method_list *)"
5749 "&_OBJC_CATEGORY_CLASS_METHODS_";
5750 Result += FullCategoryName;
5754 Result += "\t, 0\n";
5756 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5757 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5758 Result += FullCategoryName;
5762 Result += "\t, 0\n";
5763 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5766 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5768 template<typename MethodIterator>
5769 void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5770 MethodIterator MethodEnd,
5771 bool IsInstanceMethod,
5773 StringRef ClassName,
5774 std::string &Result) {
5775 if (MethodBegin == MethodEnd) return;
5777 if (!objc_impl_method) {
5778 /* struct _objc_method {
5784 Result += "\nstruct _objc_method {\n";
5785 Result += "\tSEL _cmd;\n";
5786 Result += "\tchar *method_types;\n";
5787 Result += "\tvoid *_imp;\n";
5790 objc_impl_method = true;
5793 // Build _objc_method_list for class's methods if needed
5796 struct _objc_method_list *next_method;
5798 struct _objc_method method_list[];
5801 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5802 Result += "\nstatic struct {\n";
5803 Result += "\tstruct _objc_method_list *next_method;\n";
5804 Result += "\tint method_count;\n";
5805 Result += "\tstruct _objc_method method_list[";
5806 Result += utostr(NumMethods);
5807 Result += "];\n} _OBJC_";
5809 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5810 Result += "_METHODS_";
5811 Result += ClassName;
5812 Result += " __attribute__ ((used, section (\"__OBJC, __";
5813 Result += IsInstanceMethod ? "inst" : "cls";
5814 Result += "_meth\")))= ";
5815 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5817 Result += "\t,{{(SEL)\"";
5818 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5819 std::string MethodTypeString;
5820 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5822 Result += MethodTypeString;
5823 Result += "\", (void *)";
5824 Result += MethodInternalNames[*MethodBegin];
5826 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5827 Result += "\t ,{(SEL)\"";
5828 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5829 std::string MethodTypeString;
5830 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5832 Result += MethodTypeString;
5833 Result += "\", (void *)";
5834 Result += MethodInternalNames[*MethodBegin];
5837 Result += "\t }\n};\n";
5840 Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5841 SourceRange OldRange = IV->getSourceRange();
5842 Expr *BaseExpr = IV->getBase();
5844 // Rewrite the base, but without actually doing replaces.
5846 DisableReplaceStmtScope S(*this);
5847 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5848 IV->setBase(BaseExpr);
5851 ObjCIvarDecl *D = IV->getDecl();
5853 Expr *Replacement = IV;
5855 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5856 const ObjCInterfaceType *iFaceDecl =
5857 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5858 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5859 // lookup which class implements the instance variable.
5860 ObjCInterfaceDecl *clsDeclared = nullptr;
5861 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5863 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5865 // Synthesize an explicit cast to gain access to the ivar.
5866 std::string RecName = clsDeclared->getIdentifier()->getName();
5868 IdentifierInfo *II = &Context->Idents.get(RecName);
5869 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5870 SourceLocation(), SourceLocation(),
5872 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5873 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5874 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5877 // Don't forget the parens to enforce the proper binding.
5878 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5881 if (IV->isFreeIvar() &&
5882 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
5883 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5886 VK_LValue, OK_Ordinary);
5892 } else { // we are outside a method.
5893 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5895 // Explicit ivar refs need to have a cast inserted.
5896 // FIXME: consider sharing some of this code with the code above.
5897 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5898 const ObjCInterfaceType *iFaceDecl =
5899 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5900 // lookup which class implements the instance variable.
5901 ObjCInterfaceDecl *clsDeclared = nullptr;
5902 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5904 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5906 // Synthesize an explicit cast to gain access to the ivar.
5907 std::string RecName = clsDeclared->getIdentifier()->getName();
5909 IdentifierInfo *II = &Context->Idents.get(RecName);
5910 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5911 SourceLocation(), SourceLocation(),
5913 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5914 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5915 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5918 // Don't forget the parens to enforce the proper binding.
5919 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5920 IV->getBase()->getLocEnd(), castExpr);
5921 // Cannot delete IV->getBase(), since PE points to it.
5922 // Replace the old base with the cast. This is important when doing
5923 // embedded rewrites. For example, [newInv->_container addObject:0].
5928 ReplaceStmtWithRange(IV, Replacement, OldRange);