| //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===// |
| // |
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| // See https://llvm.org/LICENSE.txt for license information. |
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| // |
| //===----------------------------------------------------------------------===// |
| // |
| // Hacks and fun related to the code rewriter. |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #include "clang/Rewrite/Frontend/ASTConsumers.h" |
| #include "clang/AST/AST.h" |
| #include "clang/AST/ASTConsumer.h" |
| #include "clang/AST/Attr.h" |
| #include "clang/AST/ParentMap.h" |
| #include "clang/Basic/CharInfo.h" |
| #include "clang/Basic/Diagnostic.h" |
| #include "clang/Basic/IdentifierTable.h" |
| #include "clang/Basic/SourceManager.h" |
| #include "clang/Config/config.h" |
| #include "clang/Lex/Lexer.h" |
| #include "clang/Rewrite/Core/Rewriter.h" |
| #include "llvm/ADT/DenseSet.h" |
| #include "llvm/ADT/SmallPtrSet.h" |
| #include "llvm/ADT/StringExtras.h" |
| #include "llvm/Support/MemoryBuffer.h" |
| #include "llvm/Support/raw_ostream.h" |
| #include <memory> |
| |
| #if CLANG_ENABLE_OBJC_REWRITER |
| |
| using namespace clang; |
| using llvm::utostr; |
| |
| namespace { |
| class RewriteObjC : public ASTConsumer { |
| protected: |
| enum { |
| BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), |
| block, ... */ |
| BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ |
| BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the |
| __block variable */ |
| BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy |
| helpers */ |
| BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose |
| support routines */ |
| BLOCK_BYREF_CURRENT_MAX = 256 |
| }; |
| |
| enum { |
| BLOCK_NEEDS_FREE = (1 << 24), |
| BLOCK_HAS_COPY_DISPOSE = (1 << 25), |
| BLOCK_HAS_CXX_OBJ = (1 << 26), |
| BLOCK_IS_GC = (1 << 27), |
| BLOCK_IS_GLOBAL = (1 << 28), |
| BLOCK_HAS_DESCRIPTOR = (1 << 29) |
| }; |
| static const int OBJC_ABI_VERSION = 7; |
| |
| Rewriter Rewrite; |
| DiagnosticsEngine &Diags; |
| const LangOptions &LangOpts; |
| ASTContext *Context; |
| SourceManager *SM; |
| TranslationUnitDecl *TUDecl; |
| FileID MainFileID; |
| const char *MainFileStart, *MainFileEnd; |
| Stmt *CurrentBody; |
| ParentMap *PropParentMap; // created lazily. |
| std::string InFileName; |
| std::unique_ptr<raw_ostream> OutFile; |
| std::string Preamble; |
| |
| TypeDecl *ProtocolTypeDecl; |
| VarDecl *GlobalVarDecl; |
| unsigned RewriteFailedDiag; |
| // ObjC string constant support. |
| unsigned NumObjCStringLiterals; |
| VarDecl *ConstantStringClassReference; |
| RecordDecl *NSStringRecord; |
| |
| // ObjC foreach break/continue generation support. |
| int BcLabelCount; |
| |
| unsigned TryFinallyContainsReturnDiag; |
| // Needed for super. |
| ObjCMethodDecl *CurMethodDef; |
| RecordDecl *SuperStructDecl; |
| RecordDecl *ConstantStringDecl; |
| |
| FunctionDecl *MsgSendFunctionDecl; |
| FunctionDecl *MsgSendSuperFunctionDecl; |
| FunctionDecl *MsgSendStretFunctionDecl; |
| FunctionDecl *MsgSendSuperStretFunctionDecl; |
| FunctionDecl *MsgSendFpretFunctionDecl; |
| FunctionDecl *GetClassFunctionDecl; |
| FunctionDecl *GetMetaClassFunctionDecl; |
| FunctionDecl *GetSuperClassFunctionDecl; |
| FunctionDecl *SelGetUidFunctionDecl; |
| FunctionDecl *CFStringFunctionDecl; |
| FunctionDecl *SuperConstructorFunctionDecl; |
| FunctionDecl *CurFunctionDef; |
| FunctionDecl *CurFunctionDeclToDeclareForBlock; |
| |
| /* Misc. containers needed for meta-data rewrite. */ |
| SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; |
| SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; |
| llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; |
| llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; |
| llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls; |
| llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; |
| SmallVector<Stmt *, 32> Stmts; |
| SmallVector<int, 8> ObjCBcLabelNo; |
| // Remember all the @protocol(<expr>) expressions. |
| llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; |
| |
| llvm::DenseSet<uint64_t> CopyDestroyCache; |
| |
| // Block expressions. |
| SmallVector<BlockExpr *, 32> Blocks; |
| SmallVector<int, 32> InnerDeclRefsCount; |
| SmallVector<DeclRefExpr *, 32> InnerDeclRefs; |
| |
| SmallVector<DeclRefExpr *, 32> BlockDeclRefs; |
| |
| // Block related declarations. |
| SmallVector<ValueDecl *, 8> BlockByCopyDecls; |
| llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet; |
| SmallVector<ValueDecl *, 8> BlockByRefDecls; |
| llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet; |
| llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; |
| llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; |
| llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; |
| |
| llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; |
| |
| // This maps an original source AST to it's rewritten form. This allows |
| // us to avoid rewriting the same node twice (which is very uncommon). |
| // This is needed to support some of the exotic property rewriting. |
| llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes; |
| |
| // Needed for header files being rewritten |
| bool IsHeader; |
| bool SilenceRewriteMacroWarning; |
| bool objc_impl_method; |
| |
| bool DisableReplaceStmt; |
| class DisableReplaceStmtScope { |
| RewriteObjC &R; |
| bool SavedValue; |
| |
| public: |
| DisableReplaceStmtScope(RewriteObjC &R) |
| : R(R), SavedValue(R.DisableReplaceStmt) { |
| R.DisableReplaceStmt = true; |
| } |
| |
| ~DisableReplaceStmtScope() { |
| R.DisableReplaceStmt = SavedValue; |
| } |
| }; |
| |
| void InitializeCommon(ASTContext &context); |
| |
| public: |
| // Top Level Driver code. |
| bool HandleTopLevelDecl(DeclGroupRef D) override { |
| for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { |
| if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) { |
| if (!Class->isThisDeclarationADefinition()) { |
| RewriteForwardClassDecl(D); |
| break; |
| } |
| } |
| |
| if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) { |
| if (!Proto->isThisDeclarationADefinition()) { |
| RewriteForwardProtocolDecl(D); |
| break; |
| } |
| } |
| |
| HandleTopLevelSingleDecl(*I); |
| } |
| return true; |
| } |
| |
| void HandleTopLevelSingleDecl(Decl *D); |
| void HandleDeclInMainFile(Decl *D); |
| RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, |
| DiagnosticsEngine &D, const LangOptions &LOpts, |
| bool silenceMacroWarn); |
| |
| ~RewriteObjC() override {} |
| |
| void HandleTranslationUnit(ASTContext &C) override; |
| |
| void ReplaceStmt(Stmt *Old, Stmt *New) { |
| ReplaceStmtWithRange(Old, New, Old->getSourceRange()); |
| } |
| |
| void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { |
| assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's"); |
| |
| Stmt *ReplacingStmt = ReplacedNodes[Old]; |
| if (ReplacingStmt) |
| return; // We can't rewrite the same node twice. |
| |
| if (DisableReplaceStmt) |
| return; |
| |
| // Measure the old text. |
| int Size = Rewrite.getRangeSize(SrcRange); |
| if (Size == -1) { |
| Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) |
| << Old->getSourceRange(); |
| return; |
| } |
| // Get the new text. |
| std::string SStr; |
| llvm::raw_string_ostream S(SStr); |
| New->printPretty(S, nullptr, PrintingPolicy(LangOpts)); |
| const std::string &Str = S.str(); |
| |
| // If replacement succeeded or warning disabled return with no warning. |
| if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { |
| ReplacedNodes[Old] = New; |
| return; |
| } |
| if (SilenceRewriteMacroWarning) |
| return; |
| Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) |
| << Old->getSourceRange(); |
| } |
| |
| void InsertText(SourceLocation Loc, StringRef Str, |
| bool InsertAfter = true) { |
| // If insertion succeeded or warning disabled return with no warning. |
| if (!Rewrite.InsertText(Loc, Str, InsertAfter) || |
| SilenceRewriteMacroWarning) |
| return; |
| |
| Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); |
| } |
| |
| void ReplaceText(SourceLocation Start, unsigned OrigLength, |
| StringRef Str) { |
| // If removal succeeded or warning disabled return with no warning. |
| if (!Rewrite.ReplaceText(Start, OrigLength, Str) || |
| SilenceRewriteMacroWarning) |
| return; |
| |
| Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); |
| } |
| |
| // Syntactic Rewriting. |
| void RewriteRecordBody(RecordDecl *RD); |
| void RewriteInclude(); |
| void RewriteForwardClassDecl(DeclGroupRef D); |
| void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); |
| void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, |
| const std::string &typedefString); |
| void RewriteImplementations(); |
| void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| ObjCImplementationDecl *IMD, |
| ObjCCategoryImplDecl *CID); |
| void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); |
| void RewriteImplementationDecl(Decl *Dcl); |
| void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, |
| ObjCMethodDecl *MDecl, std::string &ResultStr); |
| void RewriteTypeIntoString(QualType T, std::string &ResultStr, |
| const FunctionType *&FPRetType); |
| void RewriteByRefString(std::string &ResultStr, const std::string &Name, |
| ValueDecl *VD, bool def=false); |
| void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); |
| void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); |
| void RewriteForwardProtocolDecl(DeclGroupRef D); |
| void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG); |
| void RewriteMethodDeclaration(ObjCMethodDecl *Method); |
| void RewriteProperty(ObjCPropertyDecl *prop); |
| void RewriteFunctionDecl(FunctionDecl *FD); |
| void RewriteBlockPointerType(std::string& Str, QualType Type); |
| void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD); |
| void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); |
| void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); |
| void RewriteTypeOfDecl(VarDecl *VD); |
| void RewriteObjCQualifiedInterfaceTypes(Expr *E); |
| |
| // Expression Rewriting. |
| Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); |
| Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); |
| Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo); |
| Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo); |
| Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); |
| Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); |
| Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); |
| Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); |
| void RewriteTryReturnStmts(Stmt *S); |
| void RewriteSyncReturnStmts(Stmt *S, std::string buf); |
| Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); |
| Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); |
| Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); |
| Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| SourceLocation OrigEnd); |
| Stmt *RewriteBreakStmt(BreakStmt *S); |
| Stmt *RewriteContinueStmt(ContinueStmt *S); |
| void RewriteCastExpr(CStyleCastExpr *CE); |
| |
| // Block rewriting. |
| void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); |
| |
| // Block specific rewrite rules. |
| void RewriteBlockPointerDecl(NamedDecl *VD); |
| void RewriteByRefVar(VarDecl *VD); |
| Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); |
| Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); |
| void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); |
| |
| void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, |
| std::string &Result); |
| |
| void Initialize(ASTContext &context) override = 0; |
| |
| // Metadata Rewriting. |
| virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0; |
| virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots, |
| StringRef prefix, |
| StringRef ClassName, |
| std::string &Result) = 0; |
| virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, |
| std::string &Result) = 0; |
| virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, |
| StringRef prefix, |
| StringRef ClassName, |
| std::string &Result) = 0; |
| virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| std::string &Result) = 0; |
| |
| // Rewriting ivar access |
| virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0; |
| virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, |
| std::string &Result) = 0; |
| |
| // Misc. AST transformation routines. Sometimes they end up calling |
| // rewriting routines on the new ASTs. |
| CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, |
| ArrayRef<Expr *> Args, |
| SourceLocation StartLoc=SourceLocation(), |
| SourceLocation EndLoc=SourceLocation()); |
| CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, |
| QualType msgSendType, |
| QualType returnType, |
| SmallVectorImpl<QualType> &ArgTypes, |
| SmallVectorImpl<Expr*> &MsgExprs, |
| ObjCMethodDecl *Method); |
| Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, |
| SourceLocation StartLoc=SourceLocation(), |
| SourceLocation EndLoc=SourceLocation()); |
| |
| void SynthCountByEnumWithState(std::string &buf); |
| void SynthMsgSendFunctionDecl(); |
| void SynthMsgSendSuperFunctionDecl(); |
| void SynthMsgSendStretFunctionDecl(); |
| void SynthMsgSendFpretFunctionDecl(); |
| void SynthMsgSendSuperStretFunctionDecl(); |
| void SynthGetClassFunctionDecl(); |
| void SynthGetMetaClassFunctionDecl(); |
| void SynthGetSuperClassFunctionDecl(); |
| void SynthSelGetUidFunctionDecl(); |
| void SynthSuperConstructorFunctionDecl(); |
| |
| std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); |
| std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| StringRef funcName, std::string Tag); |
| std::string SynthesizeBlockFunc(BlockExpr *CE, int i, |
| StringRef funcName, std::string Tag); |
| std::string SynthesizeBlockImpl(BlockExpr *CE, |
| std::string Tag, std::string Desc); |
| std::string SynthesizeBlockDescriptor(std::string DescTag, |
| std::string ImplTag, |
| int i, StringRef funcName, |
| unsigned hasCopy); |
| Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); |
| void SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| StringRef FunName); |
| FunctionDecl *SynthBlockInitFunctionDecl(StringRef name); |
| Stmt *SynthBlockInitExpr(BlockExpr *Exp, |
| const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs); |
| |
| // Misc. helper routines. |
| QualType getProtocolType(); |
| void WarnAboutReturnGotoStmts(Stmt *S); |
| void HasReturnStmts(Stmt *S, bool &hasReturns); |
| void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); |
| void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); |
| void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); |
| |
| bool IsDeclStmtInForeachHeader(DeclStmt *DS); |
| void CollectBlockDeclRefInfo(BlockExpr *Exp); |
| void GetBlockDeclRefExprs(Stmt *S); |
| void GetInnerBlockDeclRefExprs(Stmt *S, |
| SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, |
| llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts); |
| |
| // We avoid calling Type::isBlockPointerType(), since it operates on the |
| // canonical type. We only care if the top-level type is a closure pointer. |
| bool isTopLevelBlockPointerType(QualType T) { |
| return isa<BlockPointerType>(T); |
| } |
| |
| /// convertBlockPointerToFunctionPointer - Converts a block-pointer type |
| /// to a function pointer type and upon success, returns true; false |
| /// otherwise. |
| bool convertBlockPointerToFunctionPointer(QualType &T) { |
| if (isTopLevelBlockPointerType(T)) { |
| const auto *BPT = T->castAs<BlockPointerType>(); |
| T = Context->getPointerType(BPT->getPointeeType()); |
| return true; |
| } |
| return false; |
| } |
| |
| bool needToScanForQualifiers(QualType T); |
| QualType getSuperStructType(); |
| QualType getConstantStringStructType(); |
| QualType convertFunctionTypeOfBlocks(const FunctionType *FT); |
| bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); |
| |
| void convertToUnqualifiedObjCType(QualType &T) { |
| if (T->isObjCQualifiedIdType()) |
| T = Context->getObjCIdType(); |
| else if (T->isObjCQualifiedClassType()) |
| T = Context->getObjCClassType(); |
| else if (T->isObjCObjectPointerType() && |
| T->getPointeeType()->isObjCQualifiedInterfaceType()) { |
| if (const ObjCObjectPointerType * OBJPT = |
| T->getAsObjCInterfacePointerType()) { |
| const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType(); |
| T = QualType(IFaceT, 0); |
| T = Context->getPointerType(T); |
| } |
| } |
| } |
| |
| // FIXME: This predicate seems like it would be useful to add to ASTContext. |
| bool isObjCType(QualType T) { |
| if (!LangOpts.ObjC) |
| return false; |
| |
| QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); |
| |
| if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || |
| OCT == Context->getCanonicalType(Context->getObjCClassType())) |
| return true; |
| |
| if (const PointerType *PT = OCT->getAs<PointerType>()) { |
| if (isa<ObjCInterfaceType>(PT->getPointeeType()) || |
| PT->getPointeeType()->isObjCQualifiedIdType()) |
| return true; |
| } |
| return false; |
| } |
| bool PointerTypeTakesAnyBlockArguments(QualType QT); |
| bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); |
| void GetExtentOfArgList(const char *Name, const char *&LParen, |
| const char *&RParen); |
| |
| void QuoteDoublequotes(std::string &From, std::string &To) { |
| for (unsigned i = 0; i < From.length(); i++) { |
| if (From[i] == '"') |
| To += "\\\""; |
| else |
| To += From[i]; |
| } |
| } |
| |
| QualType getSimpleFunctionType(QualType result, |
| ArrayRef<QualType> args, |
| bool variadic = false) { |
| if (result == Context->getObjCInstanceType()) |
| result = Context->getObjCIdType(); |
| FunctionProtoType::ExtProtoInfo fpi; |
| fpi.Variadic = variadic; |
| return Context->getFunctionType(result, args, fpi); |
| } |
| |
| // Helper function: create a CStyleCastExpr with trivial type source info. |
| CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, |
| CastKind Kind, Expr *E) { |
| TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); |
| return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr, |
| FPOptionsOverride(), TInfo, |
| SourceLocation(), SourceLocation()); |
| } |
| |
| StringLiteral *getStringLiteral(StringRef Str) { |
| QualType StrType = Context->getConstantArrayType( |
| Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr, |
| ArrayType::Normal, 0); |
| return StringLiteral::Create(*Context, Str, StringLiteral::Ascii, |
| /*Pascal=*/false, StrType, SourceLocation()); |
| } |
| }; |
| |
| class RewriteObjCFragileABI : public RewriteObjC { |
| public: |
| RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS, |
| DiagnosticsEngine &D, const LangOptions &LOpts, |
| bool silenceMacroWarn) |
| : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {} |
| |
| ~RewriteObjCFragileABI() override {} |
| void Initialize(ASTContext &context) override; |
| |
| // Rewriting metadata |
| template<typename MethodIterator> |
| void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, |
| MethodIterator MethodEnd, |
| bool IsInstanceMethod, |
| StringRef prefix, |
| StringRef ClassName, |
| std::string &Result); |
| void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, |
| StringRef prefix, StringRef ClassName, |
| std::string &Result) override; |
| void RewriteObjCProtocolListMetaData( |
| const ObjCList<ObjCProtocolDecl> &Prots, |
| StringRef prefix, StringRef ClassName, std::string &Result) override; |
| void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| std::string &Result) override; |
| void RewriteMetaDataIntoBuffer(std::string &Result) override; |
| void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, |
| std::string &Result) override; |
| |
| // Rewriting ivar |
| void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, |
| std::string &Result) override; |
| Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override; |
| }; |
| } // end anonymous namespace |
| |
| void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType, |
| NamedDecl *D) { |
| if (const FunctionProtoType *fproto |
| = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) { |
| for (const auto &I : fproto->param_types()) |
| if (isTopLevelBlockPointerType(I)) { |
| // All the args are checked/rewritten. Don't call twice! |
| RewriteBlockPointerDecl(D); |
| break; |
| } |
| } |
| } |
| |
| void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { |
| const PointerType *PT = funcType->getAs<PointerType>(); |
| if (PT && PointerTypeTakesAnyBlockArguments(funcType)) |
| RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); |
| } |
| |
| static bool IsHeaderFile(const std::string &Filename) { |
| std::string::size_type DotPos = Filename.rfind('.'); |
| |
| if (DotPos == std::string::npos) { |
| // no file extension |
| return false; |
| } |
| |
| std::string Ext = Filename.substr(DotPos + 1); |
| // C header: .h |
| // C++ header: .hh or .H; |
| return Ext == "h" || Ext == "hh" || Ext == "H"; |
| } |
| |
| RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, |
| DiagnosticsEngine &D, const LangOptions &LOpts, |
| bool silenceMacroWarn) |
| : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)), |
| SilenceRewriteMacroWarning(silenceMacroWarn) { |
| IsHeader = IsHeaderFile(inFile); |
| RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, |
| "rewriting sub-expression within a macro (may not be correct)"); |
| TryFinallyContainsReturnDiag = Diags.getCustomDiagID( |
| DiagnosticsEngine::Warning, |
| "rewriter doesn't support user-specified control flow semantics " |
| "for @try/@finally (code may not execute properly)"); |
| } |
| |
| std::unique_ptr<ASTConsumer> |
| clang::CreateObjCRewriter(const std::string &InFile, |
| std::unique_ptr<raw_ostream> OS, |
| DiagnosticsEngine &Diags, const LangOptions &LOpts, |
| bool SilenceRewriteMacroWarning) { |
| return std::make_unique<RewriteObjCFragileABI>( |
| InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning); |
| } |
| |
| void RewriteObjC::InitializeCommon(ASTContext &context) { |
| Context = &context; |
| SM = &Context->getSourceManager(); |
| TUDecl = Context->getTranslationUnitDecl(); |
| MsgSendFunctionDecl = nullptr; |
| MsgSendSuperFunctionDecl = nullptr; |
| MsgSendStretFunctionDecl = nullptr; |
| MsgSendSuperStretFunctionDecl = nullptr; |
| MsgSendFpretFunctionDecl = nullptr; |
| GetClassFunctionDecl = nullptr; |
| GetMetaClassFunctionDecl = nullptr; |
| GetSuperClassFunctionDecl = nullptr; |
| SelGetUidFunctionDecl = nullptr; |
| CFStringFunctionDecl = nullptr; |
| ConstantStringClassReference = nullptr; |
| NSStringRecord = nullptr; |
| CurMethodDef = nullptr; |
| CurFunctionDef = nullptr; |
| CurFunctionDeclToDeclareForBlock = nullptr; |
| GlobalVarDecl = nullptr; |
| SuperStructDecl = nullptr; |
| ProtocolTypeDecl = nullptr; |
| ConstantStringDecl = nullptr; |
| BcLabelCount = 0; |
| SuperConstructorFunctionDecl = nullptr; |
| NumObjCStringLiterals = 0; |
| PropParentMap = nullptr; |
| CurrentBody = nullptr; |
| DisableReplaceStmt = false; |
| objc_impl_method = false; |
| |
| // Get the ID and start/end of the main file. |
| MainFileID = SM->getMainFileID(); |
| llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID); |
| MainFileStart = MainBuf.getBufferStart(); |
| MainFileEnd = MainBuf.getBufferEnd(); |
| |
| Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // Top Level Driver Code |
| //===----------------------------------------------------------------------===// |
| |
| void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) { |
| if (Diags.hasErrorOccurred()) |
| return; |
| |
| // Two cases: either the decl could be in the main file, or it could be in a |
| // #included file. If the former, rewrite it now. If the later, check to see |
| // if we rewrote the #include/#import. |
| SourceLocation Loc = D->getLocation(); |
| Loc = SM->getExpansionLoc(Loc); |
| |
| // If this is for a builtin, ignore it. |
| if (Loc.isInvalid()) return; |
| |
| // Look for built-in declarations that we need to refer during the rewrite. |
| if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| RewriteFunctionDecl(FD); |
| } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { |
| // declared in <Foundation/NSString.h> |
| if (FVD->getName() == "_NSConstantStringClassReference") { |
| ConstantStringClassReference = FVD; |
| return; |
| } |
| } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) { |
| if (ID->isThisDeclarationADefinition()) |
| RewriteInterfaceDecl(ID); |
| } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { |
| RewriteCategoryDecl(CD); |
| } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { |
| if (PD->isThisDeclarationADefinition()) |
| RewriteProtocolDecl(PD); |
| } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { |
| // Recurse into linkage specifications |
| for (DeclContext::decl_iterator DI = LSD->decls_begin(), |
| DIEnd = LSD->decls_end(); |
| DI != DIEnd; ) { |
| if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { |
| if (!IFace->isThisDeclarationADefinition()) { |
| SmallVector<Decl *, 8> DG; |
| SourceLocation StartLoc = IFace->getBeginLoc(); |
| do { |
| if (isa<ObjCInterfaceDecl>(*DI) && |
| !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && |
| StartLoc == (*DI)->getBeginLoc()) |
| DG.push_back(*DI); |
| else |
| break; |
| |
| ++DI; |
| } while (DI != DIEnd); |
| RewriteForwardClassDecl(DG); |
| continue; |
| } |
| } |
| |
| if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { |
| if (!Proto->isThisDeclarationADefinition()) { |
| SmallVector<Decl *, 8> DG; |
| SourceLocation StartLoc = Proto->getBeginLoc(); |
| do { |
| if (isa<ObjCProtocolDecl>(*DI) && |
| !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && |
| StartLoc == (*DI)->getBeginLoc()) |
| DG.push_back(*DI); |
| else |
| break; |
| |
| ++DI; |
| } while (DI != DIEnd); |
| RewriteForwardProtocolDecl(DG); |
| continue; |
| } |
| } |
| |
| HandleTopLevelSingleDecl(*DI); |
| ++DI; |
| } |
| } |
| // If we have a decl in the main file, see if we should rewrite it. |
| if (SM->isWrittenInMainFile(Loc)) |
| return HandleDeclInMainFile(D); |
| } |
| |
| //===----------------------------------------------------------------------===// |
| // Syntactic (non-AST) Rewriting Code |
| //===----------------------------------------------------------------------===// |
| |
| void RewriteObjC::RewriteInclude() { |
| SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); |
| StringRef MainBuf = SM->getBufferData(MainFileID); |
| const char *MainBufStart = MainBuf.begin(); |
| const char *MainBufEnd = MainBuf.end(); |
| size_t ImportLen = strlen("import"); |
| |
| // Loop over the whole file, looking for includes. |
| for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { |
| if (*BufPtr == '#') { |
| if (++BufPtr == MainBufEnd) |
| return; |
| while (*BufPtr == ' ' || *BufPtr == '\t') |
| if (++BufPtr == MainBufEnd) |
| return; |
| if (!strncmp(BufPtr, "import", ImportLen)) { |
| // replace import with include |
| SourceLocation ImportLoc = |
| LocStart.getLocWithOffset(BufPtr-MainBufStart); |
| ReplaceText(ImportLoc, ImportLen, "include"); |
| BufPtr += ImportLen; |
| } |
| } |
| } |
| } |
| |
| static std::string getIvarAccessString(ObjCIvarDecl *OID) { |
| const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface(); |
| std::string S; |
| S = "((struct "; |
| S += ClassDecl->getIdentifier()->getName(); |
| S += "_IMPL *)self)->"; |
| S += OID->getName(); |
| return S; |
| } |
| |
| void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| ObjCImplementationDecl *IMD, |
| ObjCCategoryImplDecl *CID) { |
| static bool objcGetPropertyDefined = false; |
| static bool objcSetPropertyDefined = false; |
| SourceLocation startLoc = PID->getBeginLoc(); |
| InsertText(startLoc, "// "); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| assert((*startBuf == '@') && "bogus @synthesize location"); |
| const char *semiBuf = strchr(startBuf, ';'); |
| assert((*semiBuf == ';') && "@synthesize: can't find ';'"); |
| SourceLocation onePastSemiLoc = |
| startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| |
| if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| return; // FIXME: is this correct? |
| |
| // Generate the 'getter' function. |
| ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
| ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); |
| |
| if (!OID) |
| return; |
| |
| unsigned Attributes = PD->getPropertyAttributes(); |
| if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) { |
| bool GenGetProperty = |
| !(Attributes & ObjCPropertyAttribute::kind_nonatomic) && |
| (Attributes & (ObjCPropertyAttribute::kind_retain | |
| ObjCPropertyAttribute::kind_copy)); |
| std::string Getr; |
| if (GenGetProperty && !objcGetPropertyDefined) { |
| objcGetPropertyDefined = true; |
| // FIXME. Is this attribute correct in all cases? |
| Getr = "\nextern \"C\" __declspec(dllimport) " |
| "id objc_getProperty(id, SEL, long, bool);\n"; |
| } |
| RewriteObjCMethodDecl(OID->getContainingInterface(), |
| PID->getGetterMethodDecl(), Getr); |
| Getr += "{ "; |
| // Synthesize an explicit cast to gain access to the ivar. |
| // See objc-act.c:objc_synthesize_new_getter() for details. |
| if (GenGetProperty) { |
| // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) |
| Getr += "typedef "; |
| const FunctionType *FPRetType = nullptr; |
| RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr, |
| FPRetType); |
| Getr += " _TYPE"; |
| if (FPRetType) { |
| Getr += ")"; // close the precedence "scope" for "*". |
| |
| // Now, emit the argument types (if any). |
| if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ |
| Getr += "("; |
| for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
| if (i) Getr += ", "; |
| std::string ParamStr = |
| FT->getParamType(i).getAsString(Context->getPrintingPolicy()); |
| Getr += ParamStr; |
| } |
| if (FT->isVariadic()) { |
| if (FT->getNumParams()) |
| Getr += ", "; |
| Getr += "..."; |
| } |
| Getr += ")"; |
| } else |
| Getr += "()"; |
| } |
| Getr += ";\n"; |
| Getr += "return (_TYPE)"; |
| Getr += "objc_getProperty(self, _cmd, "; |
| RewriteIvarOffsetComputation(OID, Getr); |
| Getr += ", 1)"; |
| } |
| else |
| Getr += "return " + getIvarAccessString(OID); |
| Getr += "; }"; |
| InsertText(onePastSemiLoc, Getr); |
| } |
| |
| if (PD->isReadOnly() || !PID->getSetterMethodDecl() || |
| PID->getSetterMethodDecl()->isDefined()) |
| return; |
| |
| // Generate the 'setter' function. |
| std::string Setr; |
| bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain | |
| ObjCPropertyAttribute::kind_copy); |
| if (GenSetProperty && !objcSetPropertyDefined) { |
| objcSetPropertyDefined = true; |
| // FIXME. Is this attribute correct in all cases? |
| Setr = "\nextern \"C\" __declspec(dllimport) " |
| "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; |
| } |
| |
| RewriteObjCMethodDecl(OID->getContainingInterface(), |
| PID->getSetterMethodDecl(), Setr); |
| Setr += "{ "; |
| // Synthesize an explicit cast to initialize the ivar. |
| // See objc-act.c:objc_synthesize_new_setter() for details. |
| if (GenSetProperty) { |
| Setr += "objc_setProperty (self, _cmd, "; |
| RewriteIvarOffsetComputation(OID, Setr); |
| Setr += ", (id)"; |
| Setr += PD->getName(); |
| Setr += ", "; |
| if (Attributes & ObjCPropertyAttribute::kind_nonatomic) |
| Setr += "0, "; |
| else |
| Setr += "1, "; |
| if (Attributes & ObjCPropertyAttribute::kind_copy) |
| Setr += "1)"; |
| else |
| Setr += "0)"; |
| } |
| else { |
| Setr += getIvarAccessString(OID) + " = "; |
| Setr += PD->getName(); |
| } |
| Setr += "; }"; |
| InsertText(onePastSemiLoc, Setr); |
| } |
| |
| static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, |
| std::string &typedefString) { |
| typedefString += "#ifndef _REWRITER_typedef_"; |
| typedefString += ForwardDecl->getNameAsString(); |
| typedefString += "\n"; |
| typedefString += "#define _REWRITER_typedef_"; |
| typedefString += ForwardDecl->getNameAsString(); |
| typedefString += "\n"; |
| typedefString += "typedef struct objc_object "; |
| typedefString += ForwardDecl->getNameAsString(); |
| typedefString += ";\n#endif\n"; |
| } |
| |
| void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, |
| const std::string &typedefString) { |
| SourceLocation startLoc = ClassDecl->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| const char *semiPtr = strchr(startBuf, ';'); |
| // Replace the @class with typedefs corresponding to the classes. |
| ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString); |
| } |
| |
| void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) { |
| std::string typedefString; |
| for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { |
| ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I); |
| if (I == D.begin()) { |
| // Translate to typedef's that forward reference structs with the same name |
| // as the class. As a convenience, we include the original declaration |
| // as a comment. |
| typedefString += "// @class "; |
| typedefString += ForwardDecl->getNameAsString(); |
| typedefString += ";\n"; |
| } |
| RewriteOneForwardClassDecl(ForwardDecl, typedefString); |
| } |
| DeclGroupRef::iterator I = D.begin(); |
| RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString); |
| } |
| |
| void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) { |
| std::string typedefString; |
| for (unsigned i = 0; i < D.size(); i++) { |
| ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]); |
| if (i == 0) { |
| typedefString += "// @class "; |
| typedefString += ForwardDecl->getNameAsString(); |
| typedefString += ";\n"; |
| } |
| RewriteOneForwardClassDecl(ForwardDecl, typedefString); |
| } |
| RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString); |
| } |
| |
| void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { |
| // When method is a synthesized one, such as a getter/setter there is |
| // nothing to rewrite. |
| if (Method->isImplicit()) |
| return; |
| SourceLocation LocStart = Method->getBeginLoc(); |
| SourceLocation LocEnd = Method->getEndLoc(); |
| |
| if (SM->getExpansionLineNumber(LocEnd) > |
| SM->getExpansionLineNumber(LocStart)) { |
| InsertText(LocStart, "#if 0\n"); |
| ReplaceText(LocEnd, 1, ";\n#endif\n"); |
| } else { |
| InsertText(LocStart, "// "); |
| } |
| } |
| |
| void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) { |
| SourceLocation Loc = prop->getAtLoc(); |
| |
| ReplaceText(Loc, 0, "// "); |
| // FIXME: handle properties that are declared across multiple lines. |
| } |
| |
| void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { |
| SourceLocation LocStart = CatDecl->getBeginLoc(); |
| |
| // FIXME: handle category headers that are declared across multiple lines. |
| ReplaceText(LocStart, 0, "// "); |
| |
| for (auto *I : CatDecl->instance_properties()) |
| RewriteProperty(I); |
| for (auto *I : CatDecl->instance_methods()) |
| RewriteMethodDeclaration(I); |
| for (auto *I : CatDecl->class_methods()) |
| RewriteMethodDeclaration(I); |
| |
| // Lastly, comment out the @end. |
| ReplaceText(CatDecl->getAtEndRange().getBegin(), |
| strlen("@end"), "/* @end */"); |
| } |
| |
| void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { |
| SourceLocation LocStart = PDecl->getBeginLoc(); |
| assert(PDecl->isThisDeclarationADefinition()); |
| |
| // FIXME: handle protocol headers that are declared across multiple lines. |
| ReplaceText(LocStart, 0, "// "); |
| |
| for (auto *I : PDecl->instance_methods()) |
| RewriteMethodDeclaration(I); |
| for (auto *I : PDecl->class_methods()) |
| RewriteMethodDeclaration(I); |
| for (auto *I : PDecl->instance_properties()) |
| RewriteProperty(I); |
| |
| // Lastly, comment out the @end. |
| SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); |
| ReplaceText(LocEnd, strlen("@end"), "/* @end */"); |
| |
| // Must comment out @optional/@required |
| const char *startBuf = SM->getCharacterData(LocStart); |
| const char *endBuf = SM->getCharacterData(LocEnd); |
| for (const char *p = startBuf; p < endBuf; p++) { |
| if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { |
| SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); |
| ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */"); |
| |
| } |
| else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { |
| SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); |
| ReplaceText(OptionalLoc, strlen("@required"), "/* @required */"); |
| |
| } |
| } |
| } |
| |
| void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { |
| SourceLocation LocStart = (*D.begin())->getBeginLoc(); |
| if (LocStart.isInvalid()) |
| llvm_unreachable("Invalid SourceLocation"); |
| // FIXME: handle forward protocol that are declared across multiple lines. |
| ReplaceText(LocStart, 0, "// "); |
| } |
| |
| void |
| RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { |
| SourceLocation LocStart = DG[0]->getBeginLoc(); |
| if (LocStart.isInvalid()) |
| llvm_unreachable("Invalid SourceLocation"); |
| // FIXME: handle forward protocol that are declared across multiple lines. |
| ReplaceText(LocStart, 0, "// "); |
| } |
| |
| void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr, |
| const FunctionType *&FPRetType) { |
| if (T->isObjCQualifiedIdType()) |
| ResultStr += "id"; |
| else if (T->isFunctionPointerType() || |
| T->isBlockPointerType()) { |
| // needs special handling, since pointer-to-functions have special |
| // syntax (where a decaration models use). |
| QualType retType = T; |
| QualType PointeeTy; |
| if (const PointerType* PT = retType->getAs<PointerType>()) |
| PointeeTy = PT->getPointeeType(); |
| else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) |
| PointeeTy = BPT->getPointeeType(); |
| if ((FPRetType = PointeeTy->getAs<FunctionType>())) { |
| ResultStr += |
| FPRetType->getReturnType().getAsString(Context->getPrintingPolicy()); |
| ResultStr += "(*"; |
| } |
| } else |
| ResultStr += T.getAsString(Context->getPrintingPolicy()); |
| } |
| |
| void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, |
| ObjCMethodDecl *OMD, |
| std::string &ResultStr) { |
| //fprintf(stderr,"In RewriteObjCMethodDecl\n"); |
| const FunctionType *FPRetType = nullptr; |
| ResultStr += "\nstatic "; |
| RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType); |
| ResultStr += " "; |
| |
| // Unique method name |
| std::string NameStr; |
| |
| if (OMD->isInstanceMethod()) |
| NameStr += "_I_"; |
| else |
| NameStr += "_C_"; |
| |
| NameStr += IDecl->getNameAsString(); |
| NameStr += "_"; |
| |
| if (ObjCCategoryImplDecl *CID = |
| dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { |
| NameStr += CID->getNameAsString(); |
| NameStr += "_"; |
| } |
| // Append selector names, replacing ':' with '_' |
| { |
| std::string selString = OMD->getSelector().getAsString(); |
| int len = selString.size(); |
| for (int i = 0; i < len; i++) |
| if (selString[i] == ':') |
| selString[i] = '_'; |
| NameStr += selString; |
| } |
| // Remember this name for metadata emission |
| MethodInternalNames[OMD] = NameStr; |
| ResultStr += NameStr; |
| |
| // Rewrite arguments |
| ResultStr += "("; |
| |
| // invisible arguments |
| if (OMD->isInstanceMethod()) { |
| QualType selfTy = Context->getObjCInterfaceType(IDecl); |
| selfTy = Context->getPointerType(selfTy); |
| if (!LangOpts.MicrosoftExt) { |
| if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl))) |
| ResultStr += "struct "; |
| } |
| // When rewriting for Microsoft, explicitly omit the structure name. |
| ResultStr += IDecl->getNameAsString(); |
| ResultStr += " *"; |
| } |
| else |
| ResultStr += Context->getObjCClassType().getAsString( |
| Context->getPrintingPolicy()); |
| |
| ResultStr += " self, "; |
| ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy()); |
| ResultStr += " _cmd"; |
| |
| // Method arguments. |
| for (const auto *PDecl : OMD->parameters()) { |
| ResultStr += ", "; |
| if (PDecl->getType()->isObjCQualifiedIdType()) { |
| ResultStr += "id "; |
| ResultStr += PDecl->getNameAsString(); |
| } else { |
| std::string Name = PDecl->getNameAsString(); |
| QualType QT = PDecl->getType(); |
| // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| (void)convertBlockPointerToFunctionPointer(QT); |
| QT.getAsStringInternal(Name, Context->getPrintingPolicy()); |
| ResultStr += Name; |
| } |
| } |
| if (OMD->isVariadic()) |
| ResultStr += ", ..."; |
| ResultStr += ") "; |
| |
| if (FPRetType) { |
| ResultStr += ")"; // close the precedence "scope" for "*". |
| |
| // Now, emit the argument types (if any). |
| if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { |
| ResultStr += "("; |
| for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
| if (i) ResultStr += ", "; |
| std::string ParamStr = |
| FT->getParamType(i).getAsString(Context->getPrintingPolicy()); |
| ResultStr += ParamStr; |
| } |
| if (FT->isVariadic()) { |
| if (FT->getNumParams()) |
| ResultStr += ", "; |
| ResultStr += "..."; |
| } |
| ResultStr += ")"; |
| } else { |
| ResultStr += "()"; |
| } |
| } |
| } |
| |
| void RewriteObjC::RewriteImplementationDecl(Decl *OID) { |
| ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); |
| ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); |
| assert((IMD || CID) && "Unknown ImplementationDecl"); |
| |
| InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// "); |
| |
| for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { |
| if (!OMD->getBody()) |
| continue; |
| std::string ResultStr; |
| RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); |
| SourceLocation LocStart = OMD->getBeginLoc(); |
| SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); |
| |
| const char *startBuf = SM->getCharacterData(LocStart); |
| const char *endBuf = SM->getCharacterData(LocEnd); |
| ReplaceText(LocStart, endBuf-startBuf, ResultStr); |
| } |
| |
| for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { |
| if (!OMD->getBody()) |
| continue; |
| std::string ResultStr; |
| RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); |
| SourceLocation LocStart = OMD->getBeginLoc(); |
| SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); |
| |
| const char *startBuf = SM->getCharacterData(LocStart); |
| const char *endBuf = SM->getCharacterData(LocEnd); |
| ReplaceText(LocStart, endBuf-startBuf, ResultStr); |
| } |
| for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) |
| RewritePropertyImplDecl(I, IMD, CID); |
| |
| InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// "); |
| } |
| |
| void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { |
| std::string ResultStr; |
| if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) { |
| // we haven't seen a forward decl - generate a typedef. |
| ResultStr = "#ifndef _REWRITER_typedef_"; |
| ResultStr += ClassDecl->getNameAsString(); |
| ResultStr += "\n"; |
| ResultStr += "#define _REWRITER_typedef_"; |
| ResultStr += ClassDecl->getNameAsString(); |
| ResultStr += "\n"; |
| ResultStr += "typedef struct objc_object "; |
| ResultStr += ClassDecl->getNameAsString(); |
| ResultStr += ";\n#endif\n"; |
| // Mark this typedef as having been generated. |
| ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl()); |
| } |
| RewriteObjCInternalStruct(ClassDecl, ResultStr); |
| |
| for (auto *I : ClassDecl->instance_properties()) |
| RewriteProperty(I); |
| for (auto *I : ClassDecl->instance_methods()) |
| RewriteMethodDeclaration(I); |
| for (auto *I : ClassDecl->class_methods()) |
| RewriteMethodDeclaration(I); |
| |
| // Lastly, comment out the @end. |
| ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), |
| "/* @end */"); |
| } |
| |
| Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) { |
| SourceRange OldRange = PseudoOp->getSourceRange(); |
| |
| // We just magically know some things about the structure of this |
| // expression. |
| ObjCMessageExpr *OldMsg = |
| cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr( |
| PseudoOp->getNumSemanticExprs() - 1)); |
| |
| // Because the rewriter doesn't allow us to rewrite rewritten code, |
| // we need to suppress rewriting the sub-statements. |
| Expr *Base, *RHS; |
| { |
| DisableReplaceStmtScope S(*this); |
| |
| // Rebuild the base expression if we have one. |
| Base = nullptr; |
| if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { |
| Base = OldMsg->getInstanceReceiver(); |
| Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); |
| Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); |
| } |
| |
| // Rebuild the RHS. |
| RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS(); |
| RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr(); |
| RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS)); |
| } |
| |
| // TODO: avoid this copy. |
| SmallVector<SourceLocation, 1> SelLocs; |
| OldMsg->getSelectorLocs(SelLocs); |
| |
| ObjCMessageExpr *NewMsg = nullptr; |
| switch (OldMsg->getReceiverKind()) { |
| case ObjCMessageExpr::Class: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| OldMsg->getClassReceiverTypeInfo(), |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| RHS, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| |
| case ObjCMessageExpr::Instance: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| Base, |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| RHS, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| |
| case ObjCMessageExpr::SuperClass: |
| case ObjCMessageExpr::SuperInstance: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| OldMsg->getSuperLoc(), |
| OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, |
| OldMsg->getSuperType(), |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| RHS, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| } |
| |
| Stmt *Replacement = SynthMessageExpr(NewMsg); |
| ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); |
| return Replacement; |
| } |
| |
| Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) { |
| SourceRange OldRange = PseudoOp->getSourceRange(); |
| |
| // We just magically know some things about the structure of this |
| // expression. |
| ObjCMessageExpr *OldMsg = |
| cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit()); |
| |
| // Because the rewriter doesn't allow us to rewrite rewritten code, |
| // we need to suppress rewriting the sub-statements. |
| Expr *Base = nullptr; |
| { |
| DisableReplaceStmtScope S(*this); |
| |
| // Rebuild the base expression if we have one. |
| if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { |
| Base = OldMsg->getInstanceReceiver(); |
| Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); |
| Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); |
| } |
| } |
| |
| // Intentionally empty. |
| SmallVector<SourceLocation, 1> SelLocs; |
| SmallVector<Expr*, 1> Args; |
| |
| ObjCMessageExpr *NewMsg = nullptr; |
| switch (OldMsg->getReceiverKind()) { |
| case ObjCMessageExpr::Class: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| OldMsg->getClassReceiverTypeInfo(), |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| Args, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| |
| case ObjCMessageExpr::Instance: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| Base, |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| Args, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| |
| case ObjCMessageExpr::SuperClass: |
| case ObjCMessageExpr::SuperInstance: |
| NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| OldMsg->getValueKind(), |
| OldMsg->getLeftLoc(), |
| OldMsg->getSuperLoc(), |
| OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, |
| OldMsg->getSuperType(), |
| OldMsg->getSelector(), |
| SelLocs, |
| OldMsg->getMethodDecl(), |
| Args, |
| OldMsg->getRightLoc(), |
| OldMsg->isImplicit()); |
| break; |
| } |
| |
| Stmt *Replacement = SynthMessageExpr(NewMsg); |
| ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); |
| return Replacement; |
| } |
| |
| /// SynthCountByEnumWithState - To print: |
| /// ((unsigned int (*) |
| /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| /// (void *)objc_msgSend)((id)l_collection, |
| /// sel_registerName( |
| /// "countByEnumeratingWithState:objects:count:"), |
| /// &enumState, |
| /// (id *)__rw_items, (unsigned int)16) |
| /// |
| void RewriteObjC::SynthCountByEnumWithState(std::string &buf) { |
| buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, " |
| "id *, unsigned int))(void *)objc_msgSend)"; |
| buf += "\n\t\t"; |
| buf += "((id)l_collection,\n\t\t"; |
| buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; |
| buf += "\n\t\t"; |
| buf += "&enumState, " |
| "(id *)__rw_items, (unsigned int)16)"; |
| } |
| |
| /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach |
| /// statement to exit to its outer synthesized loop. |
| /// |
| Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) { |
| if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| return S; |
| // replace break with goto __break_label |
| std::string buf; |
| |
| SourceLocation startLoc = S->getBeginLoc(); |
| buf = "goto __break_label_"; |
| buf += utostr(ObjCBcLabelNo.back()); |
| ReplaceText(startLoc, strlen("break"), buf); |
| |
| return nullptr; |
| } |
| |
| /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach |
| /// statement to continue with its inner synthesized loop. |
| /// |
| Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) { |
| if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| return S; |
| // replace continue with goto __continue_label |
| std::string buf; |
| |
| SourceLocation startLoc = S->getBeginLoc(); |
| buf = "goto __continue_label_"; |
| buf += utostr(ObjCBcLabelNo.back()); |
| ReplaceText(startLoc, strlen("continue"), buf); |
| |
| return nullptr; |
| } |
| |
| /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. |
| /// It rewrites: |
| /// for ( type elem in collection) { stmts; } |
| |
| /// Into: |
| /// { |
| /// type elem; |
| /// struct __objcFastEnumerationState enumState = { 0 }; |
| /// id __rw_items[16]; |
| /// id l_collection = (id)collection; |
| /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| /// objects:__rw_items count:16]; |
| /// if (limit) { |
| /// unsigned long startMutations = *enumState.mutationsPtr; |
| /// do { |
| /// unsigned long counter = 0; |
| /// do { |
| /// if (startMutations != *enumState.mutationsPtr) |
| /// objc_enumerationMutation(l_collection); |
| /// elem = (type)enumState.itemsPtr[counter++]; |
| /// stmts; |
| /// __continue_label: ; |
| /// } while (counter < limit); |
| /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| /// objects:__rw_items count:16]); |
| /// elem = nil; |
| /// __break_label: ; |
| /// } |
| /// else |
| /// elem = nil; |
| /// } |
| /// |
| Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| SourceLocation OrigEnd) { |
| assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); |
| assert(isa<ObjCForCollectionStmt>(Stmts.back()) && |
| "ObjCForCollectionStmt Statement stack mismatch"); |
| assert(!ObjCBcLabelNo.empty() && |
| "ObjCForCollectionStmt - Label No stack empty"); |
| |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| StringRef elementName; |
| std::string elementTypeAsString; |
| std::string buf; |
| buf = "\n{\n\t"; |
| if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { |
| // type elem; |
| NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); |
| QualType ElementType = cast<ValueDecl>(D)->getType(); |
| if (ElementType->isObjCQualifiedIdType() || |
| ElementType->isObjCQualifiedInterfaceType()) |
| // Simply use 'id' for all qualified types. |
| elementTypeAsString = "id"; |
| else |
| elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy()); |
| buf += elementTypeAsString; |
| buf += " "; |
| elementName = D->getName(); |
| buf += elementName; |
| buf += ";\n\t"; |
| } |
| else { |
| DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); |
| elementName = DR->getDecl()->getName(); |
| ValueDecl *VD = DR->getDecl(); |
| if (VD->getType()->isObjCQualifiedIdType() || |
| VD->getType()->isObjCQualifiedInterfaceType()) |
| // Simply use 'id' for all qualified types. |
| elementTypeAsString = "id"; |
| else |
| elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy()); |
| } |
| |
| // struct __objcFastEnumerationState enumState = { 0 }; |
| buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; |
| // id __rw_items[16]; |
| buf += "id __rw_items[16];\n\t"; |
| // id l_collection = (id) |
| buf += "id l_collection = (id)"; |
| // Find start location of 'collection' the hard way! |
| const char *startCollectionBuf = startBuf; |
| startCollectionBuf += 3; // skip 'for' |
| startCollectionBuf = strchr(startCollectionBuf, '('); |
| startCollectionBuf++; // skip '(' |
| // find 'in' and skip it. |
| while (*startCollectionBuf != ' ' || |
| *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || |
| (*(startCollectionBuf+3) != ' ' && |
| *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) |
| startCollectionBuf++; |
| startCollectionBuf += 3; |
| |
| // Replace: "for (type element in" with string constructed thus far. |
| ReplaceText(startLoc, startCollectionBuf - startBuf, buf); |
| // Replace ')' in for '(' type elem in collection ')' with ';' |
| SourceLocation rightParenLoc = S->getRParenLoc(); |
| const char *rparenBuf = SM->getCharacterData(rightParenLoc); |
| SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf); |
| buf = ";\n\t"; |
| |
| // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| // objects:__rw_items count:16]; |
| // which is synthesized into: |
| // unsigned int limit = |
| // ((unsigned int (*) |
| // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| // (void *)objc_msgSend)((id)l_collection, |
| // sel_registerName( |
| // "countByEnumeratingWithState:objects:count:"), |
| // (struct __objcFastEnumerationState *)&state, |
| // (id *)__rw_items, (unsigned int)16); |
| buf += "unsigned long limit =\n\t\t"; |
| SynthCountByEnumWithState(buf); |
| buf += ";\n\t"; |
| /// if (limit) { |
| /// unsigned long startMutations = *enumState.mutationsPtr; |
| /// do { |
| /// unsigned long counter = 0; |
| /// do { |
| /// if (startMutations != *enumState.mutationsPtr) |
| /// objc_enumerationMutation(l_collection); |
| /// elem = (type)enumState.itemsPtr[counter++]; |
| buf += "if (limit) {\n\t"; |
| buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; |
| buf += "do {\n\t\t"; |
| buf += "unsigned long counter = 0;\n\t\t"; |
| buf += "do {\n\t\t\t"; |
| buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; |
| buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; |
| buf += elementName; |
| buf += " = ("; |
| buf += elementTypeAsString; |
| buf += ")enumState.itemsPtr[counter++];"; |
| // Replace ')' in for '(' type elem in collection ')' with all of these. |
| ReplaceText(lparenLoc, 1, buf); |
| |
| /// __continue_label: ; |
| /// } while (counter < limit); |
| /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| /// objects:__rw_items count:16]); |
| /// elem = nil; |
| /// __break_label: ; |
| /// } |
| /// else |
| /// elem = nil; |
| /// } |
| /// |
| buf = ";\n\t"; |
| buf += "__continue_label_"; |
| buf += utostr(ObjCBcLabelNo.back()); |
| buf += ": ;"; |
| buf += "\n\t\t"; |
| buf += "} while (counter < limit);\n\t"; |
| buf += "} while (limit = "; |
| SynthCountByEnumWithState(buf); |
| buf += ");\n\t"; |
| buf += elementName; |
| buf += " = (("; |
| buf += elementTypeAsString; |
| buf += ")0);\n\t"; |
| buf += "__break_label_"; |
| buf += utostr(ObjCBcLabelNo.back()); |
| buf += ": ;\n\t"; |
| buf += "}\n\t"; |
| buf += "else\n\t\t"; |
| buf += elementName; |
| buf += " = (("; |
| buf += elementTypeAsString; |
| buf += ")0);\n\t"; |
| buf += "}\n"; |
| |
| // Insert all these *after* the statement body. |
| // FIXME: If this should support Obj-C++, support CXXTryStmt |
| if (isa<CompoundStmt>(S->getBody())) { |
| SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1); |
| InsertText(endBodyLoc, buf); |
| } else { |
| /* Need to treat single statements specially. For example: |
| * |
| * for (A *a in b) if (stuff()) break; |
| * for (A *a in b) xxxyy; |
| * |
| * The following code simply scans ahead to the semi to find the actual end. |
| */ |
| const char *stmtBuf = SM->getCharacterData(OrigEnd); |
| const char *semiBuf = strchr(stmtBuf, ';'); |
| assert(semiBuf && "Can't find ';'"); |
| SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1); |
| InsertText(endBodyLoc, buf); |
| } |
| Stmts.pop_back(); |
| ObjCBcLabelNo.pop_back(); |
| return nullptr; |
| } |
| |
| /// RewriteObjCSynchronizedStmt - |
| /// This routine rewrites @synchronized(expr) stmt; |
| /// into: |
| /// objc_sync_enter(expr); |
| /// @try stmt @finally { objc_sync_exit(expr); } |
| /// |
| Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { |
| // Get the start location and compute the semi location. |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '@') && "bogus @synchronized location"); |
| |
| std::string buf; |
| buf = "objc_sync_enter((id)"; |
| const char *lparenBuf = startBuf; |
| while (*lparenBuf != '(') lparenBuf++; |
| ReplaceText(startLoc, lparenBuf-startBuf+1, buf); |
| // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since |
| // the sync expression is typically a message expression that's already |
| // been rewritten! (which implies the SourceLocation's are invalid). |
| SourceLocation endLoc = S->getSynchBody()->getBeginLoc(); |
| const char *endBuf = SM->getCharacterData(endLoc); |
| while (*endBuf != ')') endBuf--; |
| SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf); |
| buf = ");\n"; |
| // declare a new scope with two variables, _stack and _rethrow. |
| buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n"; |
| buf += "int buf[18/*32-bit i386*/];\n"; |
| buf += "char *pointers[4];} _stack;\n"; |
| buf += "id volatile _rethrow = 0;\n"; |
| buf += "objc_exception_try_enter(&_stack);\n"; |
| buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; |
| ReplaceText(rparenLoc, 1, buf); |
| startLoc = S->getSynchBody()->getEndLoc(); |
| startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '}') && "bogus @synchronized block"); |
| SourceLocation lastCurlyLoc = startLoc; |
| buf = "}\nelse {\n"; |
| buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| buf += "}\n"; |
| buf += "{ /* implicit finally clause */\n"; |
| buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| |
| std::string syncBuf; |
| syncBuf += " objc_sync_exit("; |
| |
| Expr *syncExpr = S->getSynchExpr(); |
| CastKind CK = syncExpr->getType()->isObjCObjectPointerType() |
| ? CK_BitCast : |
| syncExpr->getType()->isBlockPointerType() |
| ? CK_BlockPointerToObjCPointerCast |
| : CK_CPointerToObjCPointerCast; |
| syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| CK, syncExpr); |
| std::string syncExprBufS; |
| llvm::raw_string_ostream syncExprBuf(syncExprBufS); |
| assert(syncExpr != nullptr && "Expected non-null Expr"); |
| syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts)); |
| syncBuf += syncExprBuf.str(); |
| syncBuf += ");"; |
| |
| buf += syncBuf; |
| buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| buf += "}\n"; |
| buf += "}"; |
| |
| ReplaceText(lastCurlyLoc, 1, buf); |
| |
| bool hasReturns = false; |
| HasReturnStmts(S->getSynchBody(), hasReturns); |
| if (hasReturns) |
| RewriteSyncReturnStmts(S->getSynchBody(), syncBuf); |
| |
| return nullptr; |
| } |
| |
| void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S) |
| { |
| // Perform a bottom up traversal of all children. |
| for (Stmt *SubStmt : S->children()) |
| if (SubStmt) |
| WarnAboutReturnGotoStmts(SubStmt); |
| |
| if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { |
| Diags.Report(Context->getFullLoc(S->getBeginLoc()), |
| TryFinallyContainsReturnDiag); |
| } |
| } |
| |
| void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns) |
| { |
| // Perform a bottom up traversal of all children. |
| for (Stmt *SubStmt : S->children()) |
| if (SubStmt) |
| HasReturnStmts(SubStmt, hasReturns); |
| |
| if (isa<ReturnStmt>(S)) |
| hasReturns = true; |
| } |
| |
| void RewriteObjC::RewriteTryReturnStmts(Stmt *S) { |
| // Perform a bottom up traversal of all children. |
| for (Stmt *SubStmt : S->children()) |
| if (SubStmt) { |
| RewriteTryReturnStmts(SubStmt); |
| } |
| if (isa<ReturnStmt>(S)) { |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| const char *semiBuf = strchr(startBuf, ';'); |
| assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'"); |
| SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| |
| std::string buf; |
| buf = "{ objc_exception_try_exit(&_stack); return"; |
| |
| ReplaceText(startLoc, 6, buf); |
| InsertText(onePastSemiLoc, "}"); |
| } |
| } |
| |
| void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { |
| // Perform a bottom up traversal of all children. |
| for (Stmt *SubStmt : S->children()) |
| if (SubStmt) { |
| RewriteSyncReturnStmts(SubStmt, syncExitBuf); |
| } |
| if (isa<ReturnStmt>(S)) { |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| |
| const char *semiBuf = strchr(startBuf, ';'); |
| assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'"); |
| SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| |
| std::string buf; |
| buf = "{ objc_exception_try_exit(&_stack);"; |
| buf += syncExitBuf; |
| buf += " return"; |
| |
| ReplaceText(startLoc, 6, buf); |
| InsertText(onePastSemiLoc, "}"); |
| } |
| } |
| |
| Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { |
| // Get the start location and compute the semi location. |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '@') && "bogus @try location"); |
| |
| std::string buf; |
| // declare a new scope with two variables, _stack and _rethrow. |
| buf = "/* @try scope begin */ { struct _objc_exception_data {\n"; |
| buf += "int buf[18/*32-bit i386*/];\n"; |
| buf += "char *pointers[4];} _stack;\n"; |
| buf += "id volatile _rethrow = 0;\n"; |
| buf += "objc_exception_try_enter(&_stack);\n"; |
| buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; |
| |
| ReplaceText(startLoc, 4, buf); |
| |
| startLoc = S->getTryBody()->getEndLoc(); |
| startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '}') && "bogus @try block"); |
| |
| SourceLocation lastCurlyLoc = startLoc; |
| if (S->getNumCatchStmts()) { |
| startLoc = startLoc.getLocWithOffset(1); |
| buf = " /* @catch begin */ else {\n"; |
| buf += " id _caught = objc_exception_extract(&_stack);\n"; |
| buf += " objc_exception_try_enter (&_stack);\n"; |
| buf += " if (_setjmp(_stack.buf))\n"; |
| buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| buf += " else { /* @catch continue */"; |
| |
| InsertText(startLoc, buf); |
| } else { /* no catch list */ |
| buf = "}\nelse {\n"; |
| buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| buf += "}"; |
| ReplaceText(lastCurlyLoc, 1, buf); |
| } |
| Stmt *lastCatchBody = nullptr; |
| for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) { |
| ObjCAtCatchStmt *Catch = S->getCatchStmt(I); |
| VarDecl *catchDecl = Catch->getCatchParamDecl(); |
| |
| if (I == 0) |
| buf = "if ("; // we are generating code for the first catch clause |
| else |
| buf = "else if ("; |
| startLoc = Catch->getBeginLoc(); |
| startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '@') && "bogus @catch location"); |
| |
| const char *lParenLoc = strchr(startBuf, '('); |
| |
| if (Catch->hasEllipsis()) { |
| // Now rewrite the body... |
| lastCatchBody = Catch->getCatchBody(); |
| SourceLocation bodyLoc = lastCatchBody->getBeginLoc(); |
| const char *bodyBuf = SM->getCharacterData(bodyLoc); |
| assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' && |
| "bogus @catch paren location"); |
| assert((*bodyBuf == '{') && "bogus @catch body location"); |
| |
| buf += "1) { id _tmp = _caught;"; |
| Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf); |
| } else if (catchDecl) { |
| QualType t = catchDecl->getType(); |
| if (t == Context->getObjCIdType()) { |
| buf += "1) { "; |
| ReplaceText(startLoc, lParenLoc-startBuf+1, buf); |
| } else if (const ObjCObjectPointerType *Ptr = |
| t->getAs<ObjCObjectPointerType>()) { |
| // Should be a pointer to a class. |
| ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface(); |
| if (IDecl) { |
| buf += "objc_exception_match((struct objc_class *)objc_getClass(\""; |
| buf += IDecl->getNameAsString(); |
| buf += "\"), (struct objc_object *)_caught)) { "; |
| ReplaceText(startLoc, lParenLoc-startBuf+1, buf); |
| } |
| } |
| // Now rewrite the body... |
| lastCatchBody = Catch->getCatchBody(); |
| SourceLocation rParenLoc = Catch->getRParenLoc(); |
| SourceLocation bodyLoc = lastCatchBody->getBeginLoc(); |
| const char *bodyBuf = SM->getCharacterData(bodyLoc); |
| const char *rParenBuf = SM->getCharacterData(rParenLoc); |
| assert((*rParenBuf == ')') && "bogus @catch paren location"); |
| assert((*bodyBuf == '{') && "bogus @catch body location"); |
| |
| // Here we replace ") {" with "= _caught;" (which initializes and |
| // declares the @catch parameter). |
| ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;"); |
| } else { |
| llvm_unreachable("@catch rewrite bug"); |
| } |
| } |
| // Complete the catch list... |
| if (lastCatchBody) { |
| SourceLocation bodyLoc = lastCatchBody->getEndLoc(); |
| assert(*SM->getCharacterData(bodyLoc) == '}' && |
| "bogus @catch body location"); |
| |
| // Insert the last (implicit) else clause *before* the right curly brace. |
| bodyLoc = bodyLoc.getLocWithOffset(-1); |
| buf = "} /* last catch end */\n"; |
| buf += "else {\n"; |
| buf += " _rethrow = _caught;\n"; |
| buf += " objc_exception_try_exit(&_stack);\n"; |
| buf += "} } /* @catch end */\n"; |
| if (!S->getFinallyStmt()) |
| buf += "}\n"; |
| InsertText(bodyLoc, buf); |
| |
| // Set lastCurlyLoc |
| lastCurlyLoc = lastCatchBody->getEndLoc(); |
| } |
| if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) { |
| startLoc = finalStmt->getBeginLoc(); |
| startBuf = SM->getCharacterData(startLoc); |
| assert((*startBuf == '@') && "bogus @finally start"); |
| |
| ReplaceText(startLoc, 8, "/* @finally */"); |
| |
| Stmt *body = finalStmt->getFinallyBody(); |
| SourceLocation startLoc = body->getBeginLoc(); |
| SourceLocation endLoc = body->getEndLoc(); |
| assert(*SM->getCharacterData(startLoc) == '{' && |
| "bogus @finally body location"); |
| assert(*SM->getCharacterData(endLoc) == '}' && |
| "bogus @finally body location"); |
| |
| startLoc = startLoc.getLocWithOffset(1); |
| InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n"); |
| endLoc = endLoc.getLocWithOffset(-1); |
| InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n"); |
| |
| // Set lastCurlyLoc |
| lastCurlyLoc = body->getEndLoc(); |
| |
| // Now check for any return/continue/go statements within the @try. |
| WarnAboutReturnGotoStmts(S->getTryBody()); |
| } else { /* no finally clause - make sure we synthesize an implicit one */ |
| buf = "{ /* implicit finally clause */\n"; |
| buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| buf += " if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| buf += "}"; |
| ReplaceText(lastCurlyLoc, 1, buf); |
| |
| // Now check for any return/continue/go statements within the @try. |
| // The implicit finally clause won't called if the @try contains any |
| // jump statements. |
| bool hasReturns = false; |
| HasReturnStmts(S->getTryBody(), hasReturns); |
| if (hasReturns) |
| RewriteTryReturnStmts(S->getTryBody()); |
| } |
| // Now emit the final closing curly brace... |
| lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1); |
| InsertText(lastCurlyLoc, " } /* @try scope end */\n"); |
| return nullptr; |
| } |
| |
| // This can't be done with ReplaceStmt(S, ThrowExpr), since |
| // the throw expression is typically a message expression that's already |
| // been rewritten! (which implies the SourceLocation's are invalid). |
| Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { |
| // Get the start location and compute the semi location. |
| SourceLocation startLoc = S->getBeginLoc(); |
| const char *startBuf = SM->getCharacterData(startLoc); |
| |
| assert((*startBuf == '@') && "bogus @throw location"); |
| |
| std::string buf; |
| /* void objc_exception_throw(id) __attribute__((noreturn)); */ |
| if (S->getThrowExpr()) |
| buf = "objc_exception_throw("; |
| else // add an implicit argument |
| buf = "objc_exception_throw(_caught"; |
| |
| // handle "@ throw" correctly. |
| const char *wBuf = strchr(startBuf, 'w'); |
| assert((*wBuf == 'w') && "@throw: can't find 'w'"); |
| ReplaceText(startLoc, wBuf-startBuf+1, buf); |
| |
| const char *semiBuf = strchr(startBuf, ';'); |
| assert((*semiBuf == ';') && "@throw: can't find ';'"); |
| SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf); |
| ReplaceText(semiLoc, 1, ");"); |
| return nullptr; |
| } |
| |
| Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { |
| // Create a new string expression. |
| std::string StrEncoding; |
| Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); |
| Expr *Replacement = getStringLiteral(StrEncoding); |
| ReplaceStmt(Exp, Replacement); |
| |
| // Replace this subexpr in the parent. |
| // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| return Replacement; |
| } |
| |
| Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { |
| if (!SelGetUidFunctionDecl) |
| SynthSelGetUidFunctionDecl(); |
| assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); |
| // Create a call to sel_registerName("selName"). |
| SmallVector<Expr*, 8> SelExprs; |
| SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); |
| CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, |
| SelExprs); |
| ReplaceStmt(Exp, SelExp); |
| // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| return SelExp; |
| } |
| |
| CallExpr * |
| RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, |
| ArrayRef<Expr *> Args, |
| SourceLocation StartLoc, |
| SourceLocation EndLoc) { |
| // Get the type, we will need to reference it in a couple spots. |
| QualType msgSendType = FD->getType(); |
| |
| // Create a reference to the objc_msgSend() declaration. |
| DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType, |
| VK_LValue, SourceLocation()); |
| |
| // Now, we cast the reference to a pointer to the objc_msgSend type. |
| QualType pToFunc = Context->getPointerType(msgSendType); |
| ImplicitCastExpr *ICE = |
| ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, |
| DRE, nullptr, VK_PRValue, FPOptionsOverride()); |
| |
| const auto *FT = msgSendType->castAs<FunctionType>(); |
| |
| CallExpr *Exp = |
| CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context), |
| VK_PRValue, EndLoc, FPOptionsOverride()); |
| return Exp; |
| } |
| |
| static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, |
| const char *&startRef, const char *&endRef) { |
| while (startBuf < endBuf) { |
| if (*startBuf == '<') |
| startRef = startBuf; // mark the start. |
| if (*startBuf == '>') { |
| if (startRef && *startRef == '<') { |
| endRef = startBuf; // mark the end. |
| return true; |
| } |
| return false; |
| } |
| startBuf++; |
| } |
| return false; |
| } |
| |
| static void scanToNextArgument(const char *&argRef) { |
| int angle = 0; |
| while (*argRef != ')' && (*argRef != ',' || angle > 0)) { |
| if (*argRef == '<') |
| angle++; |
| else if (*argRef == '>') |
| angle--; |
| argRef++; |
| } |
| assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); |
| } |
| |
| bool RewriteObjC::needToScanForQualifiers(QualType T) { |
| if (T->isObjCQualifiedIdType()) |
| return true; |
| if (const PointerType *PT = T->getAs<PointerType>()) { |
| if (PT->getPointeeType()->isObjCQualifiedIdType()) |
| return true; |
| } |
| if (T->isObjCObjectPointerType()) { |
| T = T->getPointeeType(); |
| return T->isObjCQualifiedInterfaceType(); |
| } |
| if (T->isArrayType()) { |
| QualType ElemTy = Context->getBaseElementType(T); |
| return needToScanForQualifiers(ElemTy); |
| } |
| return false; |
| } |
| |
| void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { |
| QualType Type = E->getType(); |
| if (needToScanForQualifiers(Type)) { |
| SourceLocation Loc, EndLoc; |
| |
| if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { |
| Loc = ECE->getLParenLoc(); |
| EndLoc = ECE->getRParenLoc(); |
| } else { |
| Loc = E->getBeginLoc(); |
| EndLoc = E->getEndLoc(); |
| } |
| // This will defend against trying to rewrite synthesized expressions. |
| if (Loc.isInvalid() || EndLoc.isInvalid()) |
| return; |
| |
| const char *startBuf = SM->getCharacterData(Loc); |
| const char *endBuf = SM->getCharacterData(EndLoc); |
| const char *startRef = nullptr, *endRef = nullptr; |
| if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| // Get the locations of the startRef, endRef. |
| SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf); |
| SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1); |
| // Comment out the protocol references. |
| InsertText(LessLoc, "/*"); |
| InsertText(GreaterLoc, "*/"); |
| } |
| } |
| } |
| |
| void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { |
| SourceLocation Loc; |
| QualType Type; |
| const FunctionProtoType *proto = nullptr; |
| if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { |
| Loc = VD->getLocation(); |
| Type = VD->getType(); |
| } |
| else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { |
| Loc = FD->getLocation(); |
| // Check for ObjC 'id' and class types that have been adorned with protocol |
| // information (id<p>, C<p>*). The protocol references need to be rewritten! |
| const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| assert(funcType && "missing function type"); |
| proto = dyn_cast<FunctionProtoType>(funcType); |
| if (!proto) |
| return; |
| Type = proto->getReturnType(); |
| } |
| else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { |
| Loc = FD->getLocation(); |
| Type = FD->getType(); |
| } |
| else |
| return; |
| |
| if (needToScanForQualifiers(Type)) { |
| // Since types are unique, we need to scan the buffer. |
| |
| const char *endBuf = SM->getCharacterData(Loc); |
| const char *startBuf = endBuf; |
| while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) |
| startBuf--; // scan backward (from the decl location) for return type. |
| const char *startRef = nullptr, *endRef = nullptr; |
| if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| // Get the locations of the startRef, endRef. |
| SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf); |
| SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1); |
| // Comment out the protocol references. |
| InsertText(LessLoc, "/*"); |
| InsertText(GreaterLoc, "*/"); |
| } |
| } |
| if (!proto) |
| return; // most likely, was a variable |
| // Now check arguments. |
| const char *startBuf = SM->getCharacterData(Loc); |
| const char *startFuncBuf = startBuf; |
| for (unsigned i = 0; i < proto->getNumParams(); i++) { |
| if (needToScanForQualifiers(proto->getParamType(i))) { |
| // Since types are unique, we need to scan the buffer. |
| |
| const char *endBuf = startBuf; |
| // scan forward (from the decl location) for argument types. |
| scanToNextArgument(endBuf); |
| const char *startRef = nullptr, *endRef = nullptr; |
| if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| // Get the locations of the startRef, endRef. |
| SourceLocation LessLoc = |
| Loc.getLocWithOffset(startRef-startFuncBuf); |
| SourceLocation GreaterLoc = |
| Loc.getLocWithOffset(endRef-startFuncBuf+1); |
| // Comment out the protocol references. |
| InsertText(LessLoc, "/*"); |
| InsertText(GreaterLoc, "*/"); |
| } |
| startBuf = ++endBuf; |
| } |
| else { |
| // If the function name is derived from a macro expansion, then the |
| // argument buffer will not follow the name. Need to speak with Chris. |
| while (*startBuf && *startBuf != ')' && *startBuf != ',') |
| startBuf++; // scan forward (from the decl location) for argument types. |
| startBuf++; |
| } |
| } |
| } |
| |
| void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) { |
| QualType QT = ND->getType(); |
| const Type* TypePtr = QT->getAs<Type>(); |
| if (!isa<TypeOfExprType>(TypePtr)) |
| return; |
| while (isa<TypeOfExprType>(TypePtr)) { |
| const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); |
| QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); |
| TypePtr = QT->getAs<Type>(); |
| } |
| // FIXME. This will not work for multiple declarators; as in: |
| // __typeof__(a) b,c,d; |
| std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy())); |
| SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); |
| const char *startBuf = SM->getCharacterData(DeclLoc); |
| if (ND->getInit()) { |
| std::string Name(ND->getNameAsString()); |
| TypeAsString += " " + Name + " = "; |
| Expr *E = ND->getInit(); |
| SourceLocation startLoc; |
| if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) |
| startLoc = ECE->getLParenLoc(); |
| else |
| startLoc = E->getBeginLoc(); |
| startLoc = SM->getExpansionLoc(startLoc); |
| const char *endBuf = SM->getCharacterData(startLoc); |
| ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); |
| } |
| else { |
| SourceLocation X = ND->getEndLoc(); |
| X = SM->getExpansionLoc(X); |
| const char *endBuf = SM->getCharacterData(X); |
| ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); |
| } |
| } |
| |
| // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); |
| void RewriteObjC::SynthSelGetUidFunctionDecl() { |
| IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); |
| SmallVector<QualType, 16> ArgTys; |
| ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| QualType getFuncType = |
| getSimpleFunctionType(Context->getObjCSelType(), ArgTys); |
| SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| SelGetUidIdent, getFuncType, |
| nullptr, SC_Extern); |
| } |
| |
| void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) { |
| // declared in <objc/objc.h> |
| if (FD->getIdentifier() && |
| FD->getName() == "sel_registerName") { |
| SelGetUidFunctionDecl = FD; |
| return; |
| } |
| RewriteObjCQualifiedInterfaceTypes(FD); |
| } |
| |
| void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) { |
| std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); |
| const char *argPtr = TypeString.c_str(); |
| if (!strchr(argPtr, '^')) { |
| Str += TypeString; |
| return; |
| } |
| while (*argPtr) { |
| Str += (*argPtr == '^' ? '*' : *argPtr); |
| argPtr++; |
| } |
| } |
| |
| // FIXME. Consolidate this routine with RewriteBlockPointerType. |
| void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str, |
| ValueDecl *VD) { |
| QualType Type = VD->getType(); |
| std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); |
| const char *argPtr = TypeString.c_str(); |
| int paren = 0; |
| while (*argPtr) { |
| switch (*argPtr) { |
| case '(': |
| Str += *argPtr; |
| paren++; |
| break; |
| case ')': |
| Str += *argPtr; |
| paren--; |
| break; |
| case '^': |
| Str += '*'; |
| if (paren == 1) |
| Str += VD->getNameAsString(); |
| break; |
| default: |
| Str += *argPtr; |
| break; |
| } |
| argPtr++; |
| } |
| } |
| |
| void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { |
| SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
| const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType); |
| if (!proto) |
| return; |
| QualType Type = proto->getReturnType(); |
| std::string FdStr = Type.getAsString(Context->getPrintingPolicy()); |
| FdStr += " "; |
| FdStr += FD->getName(); |
| FdStr += "("; |
| unsigned numArgs = proto->getNumParams(); |
| for (unsigned i = 0; i < numArgs; i++) { |
| QualType ArgType = proto->getParamType(i); |
| RewriteBlockPointerType(FdStr, ArgType); |
| if (i+1 < numArgs) |
| FdStr += ", "; |
| } |
| FdStr += ");\n"; |
| InsertText(FunLocStart, FdStr); |
| CurFunctionDeclToDeclareForBlock = nullptr; |
| } |
| |
| // SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super); |
| void RewriteObjC::SynthSuperConstructorFunctionDecl() { |
| if (SuperConstructorFunctionDecl) |
| return; |
| IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); |
| SmallVector<QualType, 16> ArgTys; |
| QualType argT = Context->getObjCIdType(); |
| assert(!argT.isNull() && "Can't find 'id' type"); |
| ArgTys.push_back(argT); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys); |
| SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, msgSendType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); |
| void RewriteObjC::SynthMsgSendFunctionDecl() { |
| IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); |
| SmallVector<QualType, 16> ArgTys; |
| QualType argT = Context->getObjCIdType(); |
| assert(!argT.isNull() && "Can't find 'id' type"); |
| ArgTys.push_back(argT); |
| argT = Context->getObjCSelType(); |
| assert(!argT.isNull() && "Can't find 'SEL' type"); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys, /*variadic=*/true); |
| MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, msgSendType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...); |
| void RewriteObjC::SynthMsgSendSuperFunctionDecl() { |
| IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); |
| SmallVector<QualType, 16> ArgTys; |
| RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| SourceLocation(), SourceLocation(), |
| &Context->Idents.get("objc_super")); |
| QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| ArgTys.push_back(argT); |
| argT = Context->getObjCSelType(); |
| assert(!argT.isNull() && "Can't find 'SEL' type"); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys, /*variadic=*/true); |
| MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, msgSendType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); |
| void RewriteObjC::SynthMsgSendStretFunctionDecl() { |
| IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); |
| SmallVector<QualType, 16> ArgTys; |
| QualType argT = Context->getObjCIdType(); |
| assert(!argT.isNull() && "Can't find 'id' type"); |
| ArgTys.push_back(argT); |
| argT = Context->getObjCSelType(); |
| assert(!argT.isNull() && "Can't find 'SEL' type"); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys, /*variadic=*/true); |
| MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, msgSendType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthMsgSendSuperStretFunctionDecl - |
| // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...); |
| void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() { |
| IdentifierInfo *msgSendIdent = |
| &Context->Idents.get("objc_msgSendSuper_stret"); |
| SmallVector<QualType, 16> ArgTys; |
| RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| SourceLocation(), SourceLocation(), |
| &Context->Idents.get("objc_super")); |
| QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| ArgTys.push_back(argT); |
| argT = Context->getObjCSelType(); |
| assert(!argT.isNull() && "Can't find 'SEL' type"); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys, /*variadic=*/true); |
| MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, |
| msgSendType, nullptr, |
| SC_Extern); |
| } |
| |
| // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); |
| void RewriteObjC::SynthMsgSendFpretFunctionDecl() { |
| IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); |
| SmallVector<QualType, 16> ArgTys; |
| QualType argT = Context->getObjCIdType(); |
| assert(!argT.isNull() && "Can't find 'id' type"); |
| ArgTys.push_back(argT); |
| argT = Context->getObjCSelType(); |
| assert(!argT.isNull() && "Can't find 'SEL' type"); |
| ArgTys.push_back(argT); |
| QualType msgSendType = getSimpleFunctionType(Context->DoubleTy, |
| ArgTys, /*variadic=*/true); |
| MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| msgSendIdent, msgSendType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthGetClassFunctionDecl - id objc_getClass(const char *name); |
| void RewriteObjC::SynthGetClassFunctionDecl() { |
| IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); |
| SmallVector<QualType, 16> ArgTys; |
| ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys); |
| GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| getClassIdent, getClassType, |
| nullptr, SC_Extern); |
| } |
| |
| // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); |
| void RewriteObjC::SynthGetSuperClassFunctionDecl() { |
| IdentifierInfo *getSuperClassIdent = |
| &Context->Idents.get("class_getSuperclass"); |
| SmallVector<QualType, 16> ArgTys; |
| ArgTys.push_back(Context->getObjCClassType()); |
| QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), |
| ArgTys); |
| GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| getSuperClassIdent, |
| getClassType, nullptr, |
| SC_Extern); |
| } |
| |
| // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name); |
| void RewriteObjC::SynthGetMetaClassFunctionDecl() { |
| IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); |
| SmallVector<QualType, 16> ArgTys; |
| ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(), |
| ArgTys); |
| GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| SourceLocation(), |
| SourceLocation(), |
| getClassIdent, getClassType, |
| nullptr, SC_Extern); |
| } |
| |
| Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { |
| assert(Exp != nullptr && "Expected non-null ObjCStringLiteral"); |
| QualType strType = getConstantStringStructType(); |
| |
| std::string S = "__NSConstantStringImpl_"; |
| |
| std::string tmpName = InFileName; |
| unsigned i; |
| for (i=0; i < tmpName.length(); i++) { |
| char c = tmpName.at(i); |
| // replace any non-alphanumeric characters with '_'. |
| if (!isAlphanumeric(c)) |
| tmpName[i] = '_'; |
| } |
| S += tmpName; |
| S += "_"; |
| S += utostr(NumObjCStringLiterals++); |
| |
| Preamble += "static __NSConstantStringImpl " + S; |
| Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; |
| Preamble += "0x000007c8,"; // utf8_str |
| // The pretty printer for StringLiteral handles escape characters properly. |
| std::string prettyBufS; |
| llvm::raw_string_ostream prettyBuf(prettyBufS); |
| Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts)); |
| Preamble += prettyBuf.str(); |
| Preamble += ","; |
| Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; |
| |
| VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| SourceLocation(), &Context->Idents.get(S), |
| strType, nullptr, SC_Static); |
| DeclRefExpr *DRE = new (Context) |
| DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation()); |
| Expr *Unop = UnaryOperator::Create( |
| const_cast<ASTContext &>(*Context), DRE, UO_AddrOf, |
| Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary, |
| SourceLocation(), false, FPOptionsOverride()); |
| // cast to NSConstantString * |
| CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), |
| CK_CPointerToObjCPointerCast, Unop); |
| ReplaceStmt(Exp, cast); |
| // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| return cast; |
| } |
| |
| // struct objc_super { struct objc_object *receiver; struct objc_class *super; }; |
| QualType RewriteObjC::getSuperStructType() { |
| if (!SuperStructDecl) { |
| SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| SourceLocation(), SourceLocation(), |
| &Context->Idents.get("objc_super")); |
| QualType FieldTypes[2]; |
| |
| // struct objc_object *receiver; |
| FieldTypes[0] = Context->getObjCIdType(); |
| // struct objc_class *super; |
| FieldTypes[1] = Context->getObjCClassType(); |
| |
| // Create fields |
| for (unsigned i = 0; i < 2; ++i) { |
| SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, |
| SourceLocation(), |
| SourceLocation(), nullptr, |
| FieldTypes[i], nullptr, |
| /*BitWidth=*/nullptr, |
| /*Mutable=*/false, |
| ICIS_NoInit)); |
| } |
| |
| SuperStructDecl->completeDefinition(); |
| } |
| return Context->getTagDeclType(SuperStructDecl); |
| } |
| |
| QualType RewriteObjC::getConstantStringStructType() { |
| if (!ConstantStringDecl) { |
| ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| SourceLocation(), SourceLocation(), |
| &Context->Idents.get("__NSConstantStringImpl")); |
| QualType FieldTypes[4]; |
| |
| // struct objc_object *receiver; |
| FieldTypes[0] = Context->getObjCIdType(); |
| // int flags; |
| FieldTypes[1] = Context->IntTy; |
| // char *str; |
| FieldTypes[2] = Context->getPointerType(Context->CharTy); |
| // long length; |
| FieldTypes[3] = Context->LongTy; |
| |
| // Create fields |
| for (unsigned i = 0; i < 4; ++i) { |
| ConstantStringDecl->addDecl(FieldDecl::Create(*Context, |
| ConstantStringDecl, |
| SourceLocation(), |
| SourceLocation(), nullptr, |
| FieldTypes[i], nullptr, |
| /*BitWidth=*/nullptr, |
| /*Mutable=*/true, |
| ICIS_NoInit)); |
| } |
| |
| ConstantStringDecl->completeDefinition(); |
| } |
| return Context->getTagDeclType(ConstantStringDecl); |
| } |
| |
| CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, |
| QualType msgSendType, |
| QualType returnType, |
| SmallVectorImpl<QualType> &ArgTypes, |
| SmallVectorImpl<Expr*> &MsgExprs, |
| ObjCMethodDecl *Method) { |
| // Create a reference to the objc_msgSend_stret() declaration. |
| DeclRefExpr *STDRE = |
| new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false, |
| msgSendType, VK_LValue, SourceLocation()); |
| // Need to cast objc_msgSend_stret to "void *" (see above comment). |
| CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, |
| Context->getPointerType(Context->VoidTy), |
| CK_BitCast, STDRE); |
| // Now do the "normal" pointer to function cast. |
| QualType castType = getSimpleFunctionType(returnType, ArgTypes, |
| Method ? Method->isVariadic() |
| : false); |
| castType = Context->getPointerType(castType); |
| cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, |
| cast); |
| |
| // Don't forget the parens to enforce the proper binding. |
| ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); |
| |
| const auto *FT = msgSendType->castAs<FunctionType>(); |
| CallExpr *STCE = |
| CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, |
| SourceLocation(), FPOptionsOverride()); |
| return STCE; |
| } |
| |
| Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp, |
| SourceLocation StartLoc, |
| SourceLocation EndLoc) { |
| if (!SelGetUidFunctionDecl) |
| SynthSelGetUidFunctionDecl(); |
| if (!MsgSendFunctionDecl) |
| SynthMsgSendFunctionDecl(); |
| if (!MsgSendSuperFunctionDecl) |
| SynthMsgSendSuperFunctionDecl(); |
| if (!MsgSendStretFunctionDecl) |
| SynthMsgSendStretFunctionDecl(); |
| if (!MsgSendSuperStretFunctionDecl) |
| SynthMsgSendSuperStretFunctionDecl(); |
| if (!MsgSendFpretFunctionDecl) |
| SynthMsgSendFpretFunctionDecl(); |
| if (!GetClassFunctionDecl) |
| SynthGetClassFunctionDecl(); |
| if (!GetSuperClassFunctionDecl) |
| SynthGetSuperClassFunctionDecl(); |
| if (!GetMetaClassFunctionDecl) |
| SynthGetMetaClassFunctionDecl(); |
| |
| // default to objc_msgSend(). |
| FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; |
| // May need to use objc_msgSend_stret() as well. |
| FunctionDecl *MsgSendStretFlavor = nullptr; |
| if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { |
| QualType resultType = mDecl->getReturnType(); |
| if (resultType->isRecordType()) |
| MsgSendStretFlavor = MsgSendStretFunctionDecl; |
| else if (resultType->isRealFloatingType()) |
| MsgSendFlavor = MsgSendFpretFunctionDecl; |
| } |
| |
| // Synthesize a call to objc_msgSend(). |
| SmallVector<Expr*, 8> MsgExprs; |
| switch (Exp->getReceiverKind()) { |
| case ObjCMessageExpr::SuperClass: { |
| MsgSendFlavor = MsgSendSuperFunctionDecl; |
| if (MsgSendStretFlavor) |
| MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; |
| assert( |