Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1 | //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // Hacks and fun related to the code rewriter. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Rewrite/ASTConsumers.h" |
| 15 | #include "clang/Rewrite/Rewriter.h" |
| 16 | #include "clang/AST/AST.h" |
| 17 | #include "clang/AST/ASTConsumer.h" |
| 18 | #include "clang/AST/ParentMap.h" |
| 19 | #include "clang/Basic/SourceManager.h" |
| 20 | #include "clang/Basic/IdentifierTable.h" |
| 21 | #include "clang/Basic/Diagnostic.h" |
| 22 | #include "clang/Lex/Lexer.h" |
| 23 | #include "llvm/Support/MemoryBuffer.h" |
| 24 | #include "llvm/Support/raw_ostream.h" |
| 25 | #include "llvm/ADT/StringExtras.h" |
| 26 | #include "llvm/ADT/SmallPtrSet.h" |
| 27 | #include "llvm/ADT/OwningPtr.h" |
| 28 | #include "llvm/ADT/DenseSet.h" |
| 29 | |
| 30 | using namespace clang; |
| 31 | using llvm::utostr; |
| 32 | |
| 33 | namespace { |
| 34 | class RewriteModernObjC : public ASTConsumer { |
| 35 | protected: |
| 36 | |
| 37 | enum { |
| 38 | BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), |
| 39 | block, ... */ |
| 40 | BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ |
| 41 | BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the |
| 42 | __block variable */ |
| 43 | BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy |
| 44 | helpers */ |
| 45 | BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose |
| 46 | support routines */ |
| 47 | BLOCK_BYREF_CURRENT_MAX = 256 |
| 48 | }; |
| 49 | |
| 50 | enum { |
| 51 | BLOCK_NEEDS_FREE = (1 << 24), |
| 52 | BLOCK_HAS_COPY_DISPOSE = (1 << 25), |
| 53 | BLOCK_HAS_CXX_OBJ = (1 << 26), |
| 54 | BLOCK_IS_GC = (1 << 27), |
| 55 | BLOCK_IS_GLOBAL = (1 << 28), |
| 56 | BLOCK_HAS_DESCRIPTOR = (1 << 29) |
| 57 | }; |
| 58 | static const int OBJC_ABI_VERSION = 7; |
| 59 | |
| 60 | Rewriter Rewrite; |
| 61 | DiagnosticsEngine &Diags; |
| 62 | const LangOptions &LangOpts; |
| 63 | ASTContext *Context; |
| 64 | SourceManager *SM; |
| 65 | TranslationUnitDecl *TUDecl; |
| 66 | FileID MainFileID; |
| 67 | const char *MainFileStart, *MainFileEnd; |
| 68 | Stmt *CurrentBody; |
| 69 | ParentMap *PropParentMap; // created lazily. |
| 70 | std::string InFileName; |
| 71 | raw_ostream* OutFile; |
| 72 | std::string Preamble; |
| 73 | |
| 74 | TypeDecl *ProtocolTypeDecl; |
| 75 | VarDecl *GlobalVarDecl; |
| 76 | unsigned RewriteFailedDiag; |
| 77 | // ObjC string constant support. |
| 78 | unsigned NumObjCStringLiterals; |
| 79 | VarDecl *ConstantStringClassReference; |
| 80 | RecordDecl *NSStringRecord; |
| 81 | |
| 82 | // ObjC foreach break/continue generation support. |
| 83 | int BcLabelCount; |
| 84 | |
| 85 | unsigned TryFinallyContainsReturnDiag; |
| 86 | // Needed for super. |
| 87 | ObjCMethodDecl *CurMethodDef; |
| 88 | RecordDecl *SuperStructDecl; |
| 89 | RecordDecl *ConstantStringDecl; |
| 90 | |
| 91 | FunctionDecl *MsgSendFunctionDecl; |
| 92 | FunctionDecl *MsgSendSuperFunctionDecl; |
| 93 | FunctionDecl *MsgSendStretFunctionDecl; |
| 94 | FunctionDecl *MsgSendSuperStretFunctionDecl; |
| 95 | FunctionDecl *MsgSendFpretFunctionDecl; |
| 96 | FunctionDecl *GetClassFunctionDecl; |
| 97 | FunctionDecl *GetMetaClassFunctionDecl; |
| 98 | FunctionDecl *GetSuperClassFunctionDecl; |
| 99 | FunctionDecl *SelGetUidFunctionDecl; |
| 100 | FunctionDecl *CFStringFunctionDecl; |
| 101 | FunctionDecl *SuperContructorFunctionDecl; |
| 102 | FunctionDecl *CurFunctionDef; |
| 103 | FunctionDecl *CurFunctionDeclToDeclareForBlock; |
| 104 | |
| 105 | /* Misc. containers needed for meta-data rewrite. */ |
| 106 | SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; |
| 107 | SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; |
| 108 | llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; |
| 109 | llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 110 | llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces; |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 111 | llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls; |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 112 | SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 113 | SmallVector<Stmt *, 32> Stmts; |
| 114 | SmallVector<int, 8> ObjCBcLabelNo; |
| 115 | // Remember all the @protocol(<expr>) expressions. |
| 116 | llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; |
| 117 | |
| 118 | llvm::DenseSet<uint64_t> CopyDestroyCache; |
| 119 | |
| 120 | // Block expressions. |
| 121 | SmallVector<BlockExpr *, 32> Blocks; |
| 122 | SmallVector<int, 32> InnerDeclRefsCount; |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 123 | SmallVector<DeclRefExpr *, 32> InnerDeclRefs; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 124 | |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 125 | SmallVector<DeclRefExpr *, 32> BlockDeclRefs; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 126 | |
| 127 | // Block related declarations. |
| 128 | SmallVector<ValueDecl *, 8> BlockByCopyDecls; |
| 129 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet; |
| 130 | SmallVector<ValueDecl *, 8> BlockByRefDecls; |
| 131 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet; |
| 132 | llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; |
| 133 | llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; |
| 134 | llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; |
| 135 | |
| 136 | llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 137 | llvm::DenseMap<ObjCInterfaceDecl *, |
| 138 | llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars; |
| 139 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 140 | // This maps an original source AST to it's rewritten form. This allows |
| 141 | // us to avoid rewriting the same node twice (which is very uncommon). |
| 142 | // This is needed to support some of the exotic property rewriting. |
| 143 | llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes; |
| 144 | |
| 145 | // Needed for header files being rewritten |
| 146 | bool IsHeader; |
| 147 | bool SilenceRewriteMacroWarning; |
| 148 | bool objc_impl_method; |
| 149 | |
| 150 | bool DisableReplaceStmt; |
| 151 | class DisableReplaceStmtScope { |
| 152 | RewriteModernObjC &R; |
| 153 | bool SavedValue; |
| 154 | |
| 155 | public: |
| 156 | DisableReplaceStmtScope(RewriteModernObjC &R) |
| 157 | : R(R), SavedValue(R.DisableReplaceStmt) { |
| 158 | R.DisableReplaceStmt = true; |
| 159 | } |
| 160 | ~DisableReplaceStmtScope() { |
| 161 | R.DisableReplaceStmt = SavedValue; |
| 162 | } |
| 163 | }; |
| 164 | void InitializeCommon(ASTContext &context); |
| 165 | |
| 166 | public: |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 167 | llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 168 | // Top Level Driver code. |
| 169 | virtual bool HandleTopLevelDecl(DeclGroupRef D) { |
| 170 | for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { |
| 171 | if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) { |
| 172 | if (!Class->isThisDeclarationADefinition()) { |
| 173 | RewriteForwardClassDecl(D); |
| 174 | break; |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 175 | } else { |
| 176 | // Keep track of all interface declarations seen. |
Fariborz Jahanian | f329527 | 2012-02-24 21:42:38 +0000 | [diff] [blame] | 177 | ObjCInterfacesSeen.push_back(Class); |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 178 | break; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 179 | } |
| 180 | } |
| 181 | |
| 182 | if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) { |
| 183 | if (!Proto->isThisDeclarationADefinition()) { |
| 184 | RewriteForwardProtocolDecl(D); |
| 185 | break; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | HandleTopLevelSingleDecl(*I); |
| 190 | } |
| 191 | return true; |
| 192 | } |
| 193 | void HandleTopLevelSingleDecl(Decl *D); |
| 194 | void HandleDeclInMainFile(Decl *D); |
| 195 | RewriteModernObjC(std::string inFile, raw_ostream *OS, |
| 196 | DiagnosticsEngine &D, const LangOptions &LOpts, |
| 197 | bool silenceMacroWarn); |
| 198 | |
| 199 | ~RewriteModernObjC() {} |
| 200 | |
| 201 | virtual void HandleTranslationUnit(ASTContext &C); |
| 202 | |
| 203 | void ReplaceStmt(Stmt *Old, Stmt *New) { |
| 204 | Stmt *ReplacingStmt = ReplacedNodes[Old]; |
| 205 | |
| 206 | if (ReplacingStmt) |
| 207 | return; // We can't rewrite the same node twice. |
| 208 | |
| 209 | if (DisableReplaceStmt) |
| 210 | return; |
| 211 | |
| 212 | // If replacement succeeded or warning disabled return with no warning. |
| 213 | if (!Rewrite.ReplaceStmt(Old, New)) { |
| 214 | ReplacedNodes[Old] = New; |
| 215 | return; |
| 216 | } |
| 217 | if (SilenceRewriteMacroWarning) |
| 218 | return; |
| 219 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 220 | << Old->getSourceRange(); |
| 221 | } |
| 222 | |
| 223 | void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { |
| 224 | if (DisableReplaceStmt) |
| 225 | return; |
| 226 | |
| 227 | // Measure the old text. |
| 228 | int Size = Rewrite.getRangeSize(SrcRange); |
| 229 | if (Size == -1) { |
| 230 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 231 | << Old->getSourceRange(); |
| 232 | return; |
| 233 | } |
| 234 | // Get the new text. |
| 235 | std::string SStr; |
| 236 | llvm::raw_string_ostream S(SStr); |
| 237 | New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts)); |
| 238 | const std::string &Str = S.str(); |
| 239 | |
| 240 | // If replacement succeeded or warning disabled return with no warning. |
| 241 | if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { |
| 242 | ReplacedNodes[Old] = New; |
| 243 | return; |
| 244 | } |
| 245 | if (SilenceRewriteMacroWarning) |
| 246 | return; |
| 247 | Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag) |
| 248 | << Old->getSourceRange(); |
| 249 | } |
| 250 | |
| 251 | void InsertText(SourceLocation Loc, StringRef Str, |
| 252 | bool InsertAfter = true) { |
| 253 | // If insertion succeeded or warning disabled return with no warning. |
| 254 | if (!Rewrite.InsertText(Loc, Str, InsertAfter) || |
| 255 | SilenceRewriteMacroWarning) |
| 256 | return; |
| 257 | |
| 258 | Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); |
| 259 | } |
| 260 | |
| 261 | void ReplaceText(SourceLocation Start, unsigned OrigLength, |
| 262 | StringRef Str) { |
| 263 | // If removal succeeded or warning disabled return with no warning. |
| 264 | if (!Rewrite.ReplaceText(Start, OrigLength, Str) || |
| 265 | SilenceRewriteMacroWarning) |
| 266 | return; |
| 267 | |
| 268 | Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); |
| 269 | } |
| 270 | |
| 271 | // Syntactic Rewriting. |
| 272 | void RewriteRecordBody(RecordDecl *RD); |
| 273 | void RewriteInclude(); |
| 274 | void RewriteForwardClassDecl(DeclGroupRef D); |
| 275 | void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG); |
| 276 | void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, |
| 277 | const std::string &typedefString); |
| 278 | void RewriteImplementations(); |
| 279 | void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| 280 | ObjCImplementationDecl *IMD, |
| 281 | ObjCCategoryImplDecl *CID); |
| 282 | void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); |
| 283 | void RewriteImplementationDecl(Decl *Dcl); |
| 284 | void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, |
| 285 | ObjCMethodDecl *MDecl, std::string &ResultStr); |
| 286 | void RewriteTypeIntoString(QualType T, std::string &ResultStr, |
| 287 | const FunctionType *&FPRetType); |
| 288 | void RewriteByRefString(std::string &ResultStr, const std::string &Name, |
| 289 | ValueDecl *VD, bool def=false); |
| 290 | void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); |
| 291 | void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); |
| 292 | void RewriteForwardProtocolDecl(DeclGroupRef D); |
| 293 | void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG); |
| 294 | void RewriteMethodDeclaration(ObjCMethodDecl *Method); |
| 295 | void RewriteProperty(ObjCPropertyDecl *prop); |
| 296 | void RewriteFunctionDecl(FunctionDecl *FD); |
| 297 | void RewriteBlockPointerType(std::string& Str, QualType Type); |
| 298 | void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD); |
| 299 | void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); |
| 300 | void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); |
| 301 | void RewriteTypeOfDecl(VarDecl *VD); |
| 302 | void RewriteObjCQualifiedInterfaceTypes(Expr *E); |
| 303 | |
| 304 | // Expression Rewriting. |
| 305 | Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); |
| 306 | Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); |
| 307 | Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo); |
| 308 | Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo); |
| 309 | Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); |
| 310 | Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); |
| 311 | Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); |
| 312 | Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); |
| 313 | void RewriteTryReturnStmts(Stmt *S); |
| 314 | void RewriteSyncReturnStmts(Stmt *S, std::string buf); |
| 315 | Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); |
| 316 | Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); |
| 317 | Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); |
| 318 | Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| 319 | SourceLocation OrigEnd); |
| 320 | Stmt *RewriteBreakStmt(BreakStmt *S); |
| 321 | Stmt *RewriteContinueStmt(ContinueStmt *S); |
| 322 | void RewriteCastExpr(CStyleCastExpr *CE); |
| 323 | |
| 324 | // Block rewriting. |
| 325 | void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); |
| 326 | |
| 327 | // Block specific rewrite rules. |
| 328 | void RewriteBlockPointerDecl(NamedDecl *VD); |
| 329 | void RewriteByRefVar(VarDecl *VD); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 330 | Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 331 | Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); |
| 332 | void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); |
| 333 | |
| 334 | void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, |
| 335 | std::string &Result); |
| 336 | |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 337 | void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); |
| 338 | |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 339 | bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); |
| 340 | |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 341 | void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, |
| 342 | std::string &Result); |
| 343 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 344 | virtual void Initialize(ASTContext &context); |
| 345 | |
| 346 | // Misc. AST transformation routines. Somtimes they end up calling |
| 347 | // rewriting routines on the new ASTs. |
| 348 | CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, |
| 349 | Expr **args, unsigned nargs, |
| 350 | SourceLocation StartLoc=SourceLocation(), |
| 351 | SourceLocation EndLoc=SourceLocation()); |
| 352 | |
| 353 | Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, |
| 354 | SourceLocation StartLoc=SourceLocation(), |
| 355 | SourceLocation EndLoc=SourceLocation()); |
| 356 | |
| 357 | void SynthCountByEnumWithState(std::string &buf); |
| 358 | void SynthMsgSendFunctionDecl(); |
| 359 | void SynthMsgSendSuperFunctionDecl(); |
| 360 | void SynthMsgSendStretFunctionDecl(); |
| 361 | void SynthMsgSendFpretFunctionDecl(); |
| 362 | void SynthMsgSendSuperStretFunctionDecl(); |
| 363 | void SynthGetClassFunctionDecl(); |
| 364 | void SynthGetMetaClassFunctionDecl(); |
| 365 | void SynthGetSuperClassFunctionDecl(); |
| 366 | void SynthSelGetUidFunctionDecl(); |
| 367 | void SynthSuperContructorFunctionDecl(); |
| 368 | |
| 369 | // Rewriting metadata |
| 370 | template<typename MethodIterator> |
| 371 | void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, |
| 372 | MethodIterator MethodEnd, |
| 373 | bool IsInstanceMethod, |
| 374 | StringRef prefix, |
| 375 | StringRef ClassName, |
| 376 | std::string &Result); |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 377 | void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, |
| 378 | std::string &Result); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 379 | virtual void RewriteObjCProtocolListMetaData( |
| 380 | const ObjCList<ObjCProtocolDecl> &Prots, |
| 381 | StringRef prefix, StringRef ClassName, std::string &Result); |
| 382 | virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| 383 | std::string &Result); |
| 384 | virtual void RewriteMetaDataIntoBuffer(std::string &Result); |
| 385 | virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, |
| 386 | std::string &Result); |
| 387 | |
| 388 | // Rewriting ivar |
| 389 | virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, |
| 390 | std::string &Result); |
| 391 | virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); |
| 392 | |
| 393 | |
| 394 | std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); |
| 395 | std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 396 | StringRef funcName, std::string Tag); |
| 397 | std::string SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 398 | StringRef funcName, std::string Tag); |
| 399 | std::string SynthesizeBlockImpl(BlockExpr *CE, |
| 400 | std::string Tag, std::string Desc); |
| 401 | std::string SynthesizeBlockDescriptor(std::string DescTag, |
| 402 | std::string ImplTag, |
| 403 | int i, StringRef funcName, |
| 404 | unsigned hasCopy); |
| 405 | Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); |
| 406 | void SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 407 | StringRef FunName); |
| 408 | FunctionDecl *SynthBlockInitFunctionDecl(StringRef name); |
| 409 | Stmt *SynthBlockInitExpr(BlockExpr *Exp, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 410 | const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 411 | |
| 412 | // Misc. helper routines. |
| 413 | QualType getProtocolType(); |
| 414 | void WarnAboutReturnGotoStmts(Stmt *S); |
| 415 | void HasReturnStmts(Stmt *S, bool &hasReturns); |
| 416 | void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); |
| 417 | void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); |
| 418 | void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); |
| 419 | |
| 420 | bool IsDeclStmtInForeachHeader(DeclStmt *DS); |
| 421 | void CollectBlockDeclRefInfo(BlockExpr *Exp); |
| 422 | void GetBlockDeclRefExprs(Stmt *S); |
| 423 | void GetInnerBlockDeclRefExprs(Stmt *S, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 424 | SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 425 | llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts); |
| 426 | |
| 427 | // We avoid calling Type::isBlockPointerType(), since it operates on the |
| 428 | // canonical type. We only care if the top-level type is a closure pointer. |
| 429 | bool isTopLevelBlockPointerType(QualType T) { |
| 430 | return isa<BlockPointerType>(T); |
| 431 | } |
| 432 | |
| 433 | /// convertBlockPointerToFunctionPointer - Converts a block-pointer type |
| 434 | /// to a function pointer type and upon success, returns true; false |
| 435 | /// otherwise. |
| 436 | bool convertBlockPointerToFunctionPointer(QualType &T) { |
| 437 | if (isTopLevelBlockPointerType(T)) { |
| 438 | const BlockPointerType *BPT = T->getAs<BlockPointerType>(); |
| 439 | T = Context->getPointerType(BPT->getPointeeType()); |
| 440 | return true; |
| 441 | } |
| 442 | return false; |
| 443 | } |
| 444 | |
Fariborz Jahanian | 164d6f8 | 2012-02-13 18:57:49 +0000 | [diff] [blame] | 445 | bool convertObjCTypeToCStyleType(QualType &T); |
| 446 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 447 | bool needToScanForQualifiers(QualType T); |
| 448 | QualType getSuperStructType(); |
| 449 | QualType getConstantStringStructType(); |
| 450 | QualType convertFunctionTypeOfBlocks(const FunctionType *FT); |
| 451 | bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf); |
| 452 | |
| 453 | void convertToUnqualifiedObjCType(QualType &T) { |
| 454 | if (T->isObjCQualifiedIdType()) |
| 455 | T = Context->getObjCIdType(); |
| 456 | else if (T->isObjCQualifiedClassType()) |
| 457 | T = Context->getObjCClassType(); |
| 458 | else if (T->isObjCObjectPointerType() && |
| 459 | T->getPointeeType()->isObjCQualifiedInterfaceType()) { |
| 460 | if (const ObjCObjectPointerType * OBJPT = |
| 461 | T->getAsObjCInterfacePointerType()) { |
| 462 | const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType(); |
| 463 | T = QualType(IFaceT, 0); |
| 464 | T = Context->getPointerType(T); |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | // FIXME: This predicate seems like it would be useful to add to ASTContext. |
| 470 | bool isObjCType(QualType T) { |
| 471 | if (!LangOpts.ObjC1 && !LangOpts.ObjC2) |
| 472 | return false; |
| 473 | |
| 474 | QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); |
| 475 | |
| 476 | if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || |
| 477 | OCT == Context->getCanonicalType(Context->getObjCClassType())) |
| 478 | return true; |
| 479 | |
| 480 | if (const PointerType *PT = OCT->getAs<PointerType>()) { |
| 481 | if (isa<ObjCInterfaceType>(PT->getPointeeType()) || |
| 482 | PT->getPointeeType()->isObjCQualifiedIdType()) |
| 483 | return true; |
| 484 | } |
| 485 | return false; |
| 486 | } |
| 487 | bool PointerTypeTakesAnyBlockArguments(QualType QT); |
| 488 | bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); |
| 489 | void GetExtentOfArgList(const char *Name, const char *&LParen, |
| 490 | const char *&RParen); |
| 491 | |
| 492 | void QuoteDoublequotes(std::string &From, std::string &To) { |
| 493 | for (unsigned i = 0; i < From.length(); i++) { |
| 494 | if (From[i] == '"') |
| 495 | To += "\\\""; |
| 496 | else |
| 497 | To += From[i]; |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | QualType getSimpleFunctionType(QualType result, |
| 502 | const QualType *args, |
| 503 | unsigned numArgs, |
| 504 | bool variadic = false) { |
| 505 | if (result == Context->getObjCInstanceType()) |
| 506 | result = Context->getObjCIdType(); |
| 507 | FunctionProtoType::ExtProtoInfo fpi; |
| 508 | fpi.Variadic = variadic; |
| 509 | return Context->getFunctionType(result, args, numArgs, fpi); |
| 510 | } |
| 511 | |
| 512 | // Helper function: create a CStyleCastExpr with trivial type source info. |
| 513 | CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, |
| 514 | CastKind Kind, Expr *E) { |
| 515 | TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); |
| 516 | return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo, |
| 517 | SourceLocation(), SourceLocation()); |
| 518 | } |
| 519 | }; |
| 520 | |
| 521 | } |
| 522 | |
| 523 | void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType, |
| 524 | NamedDecl *D) { |
| 525 | if (const FunctionProtoType *fproto |
| 526 | = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) { |
| 527 | for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(), |
| 528 | E = fproto->arg_type_end(); I && (I != E); ++I) |
| 529 | if (isTopLevelBlockPointerType(*I)) { |
| 530 | // All the args are checked/rewritten. Don't call twice! |
| 531 | RewriteBlockPointerDecl(D); |
| 532 | break; |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { |
| 538 | const PointerType *PT = funcType->getAs<PointerType>(); |
| 539 | if (PT && PointerTypeTakesAnyBlockArguments(funcType)) |
| 540 | RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); |
| 541 | } |
| 542 | |
| 543 | static bool IsHeaderFile(const std::string &Filename) { |
| 544 | std::string::size_type DotPos = Filename.rfind('.'); |
| 545 | |
| 546 | if (DotPos == std::string::npos) { |
| 547 | // no file extension |
| 548 | return false; |
| 549 | } |
| 550 | |
| 551 | std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); |
| 552 | // C header: .h |
| 553 | // C++ header: .hh or .H; |
| 554 | return Ext == "h" || Ext == "hh" || Ext == "H"; |
| 555 | } |
| 556 | |
| 557 | RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS, |
| 558 | DiagnosticsEngine &D, const LangOptions &LOpts, |
| 559 | bool silenceMacroWarn) |
| 560 | : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS), |
| 561 | SilenceRewriteMacroWarning(silenceMacroWarn) { |
| 562 | IsHeader = IsHeaderFile(inFile); |
| 563 | RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, |
| 564 | "rewriting sub-expression within a macro (may not be correct)"); |
| 565 | TryFinallyContainsReturnDiag = Diags.getCustomDiagID( |
| 566 | DiagnosticsEngine::Warning, |
| 567 | "rewriter doesn't support user-specified control flow semantics " |
| 568 | "for @try/@finally (code may not execute properly)"); |
| 569 | } |
| 570 | |
| 571 | ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile, |
| 572 | raw_ostream* OS, |
| 573 | DiagnosticsEngine &Diags, |
| 574 | const LangOptions &LOpts, |
| 575 | bool SilenceRewriteMacroWarning) { |
| 576 | return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning); |
| 577 | } |
| 578 | |
| 579 | void RewriteModernObjC::InitializeCommon(ASTContext &context) { |
| 580 | Context = &context; |
| 581 | SM = &Context->getSourceManager(); |
| 582 | TUDecl = Context->getTranslationUnitDecl(); |
| 583 | MsgSendFunctionDecl = 0; |
| 584 | MsgSendSuperFunctionDecl = 0; |
| 585 | MsgSendStretFunctionDecl = 0; |
| 586 | MsgSendSuperStretFunctionDecl = 0; |
| 587 | MsgSendFpretFunctionDecl = 0; |
| 588 | GetClassFunctionDecl = 0; |
| 589 | GetMetaClassFunctionDecl = 0; |
| 590 | GetSuperClassFunctionDecl = 0; |
| 591 | SelGetUidFunctionDecl = 0; |
| 592 | CFStringFunctionDecl = 0; |
| 593 | ConstantStringClassReference = 0; |
| 594 | NSStringRecord = 0; |
| 595 | CurMethodDef = 0; |
| 596 | CurFunctionDef = 0; |
| 597 | CurFunctionDeclToDeclareForBlock = 0; |
| 598 | GlobalVarDecl = 0; |
| 599 | SuperStructDecl = 0; |
| 600 | ProtocolTypeDecl = 0; |
| 601 | ConstantStringDecl = 0; |
| 602 | BcLabelCount = 0; |
| 603 | SuperContructorFunctionDecl = 0; |
| 604 | NumObjCStringLiterals = 0; |
| 605 | PropParentMap = 0; |
| 606 | CurrentBody = 0; |
| 607 | DisableReplaceStmt = false; |
| 608 | objc_impl_method = false; |
| 609 | |
| 610 | // Get the ID and start/end of the main file. |
| 611 | MainFileID = SM->getMainFileID(); |
| 612 | const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); |
| 613 | MainFileStart = MainBuf->getBufferStart(); |
| 614 | MainFileEnd = MainBuf->getBufferEnd(); |
| 615 | |
David Blaikie | 4e4d084 | 2012-03-11 07:00:24 +0000 | [diff] [blame] | 616 | Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 617 | } |
| 618 | |
| 619 | //===----------------------------------------------------------------------===// |
| 620 | // Top Level Driver Code |
| 621 | //===----------------------------------------------------------------------===// |
| 622 | |
| 623 | void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { |
| 624 | if (Diags.hasErrorOccurred()) |
| 625 | return; |
| 626 | |
| 627 | // Two cases: either the decl could be in the main file, or it could be in a |
| 628 | // #included file. If the former, rewrite it now. If the later, check to see |
| 629 | // if we rewrote the #include/#import. |
| 630 | SourceLocation Loc = D->getLocation(); |
| 631 | Loc = SM->getExpansionLoc(Loc); |
| 632 | |
| 633 | // If this is for a builtin, ignore it. |
| 634 | if (Loc.isInvalid()) return; |
| 635 | |
| 636 | // Look for built-in declarations that we need to refer during the rewrite. |
| 637 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 638 | RewriteFunctionDecl(FD); |
| 639 | } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { |
| 640 | // declared in <Foundation/NSString.h> |
| 641 | if (FVD->getName() == "_NSConstantStringClassReference") { |
| 642 | ConstantStringClassReference = FVD; |
| 643 | return; |
| 644 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 645 | } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { |
| 646 | RewriteCategoryDecl(CD); |
| 647 | } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { |
| 648 | if (PD->isThisDeclarationADefinition()) |
| 649 | RewriteProtocolDecl(PD); |
| 650 | } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { |
| 651 | // Recurse into linkage specifications |
| 652 | for (DeclContext::decl_iterator DI = LSD->decls_begin(), |
| 653 | DIEnd = LSD->decls_end(); |
| 654 | DI != DIEnd; ) { |
| 655 | if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { |
| 656 | if (!IFace->isThisDeclarationADefinition()) { |
| 657 | SmallVector<Decl *, 8> DG; |
| 658 | SourceLocation StartLoc = IFace->getLocStart(); |
| 659 | do { |
| 660 | if (isa<ObjCInterfaceDecl>(*DI) && |
| 661 | !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && |
| 662 | StartLoc == (*DI)->getLocStart()) |
| 663 | DG.push_back(*DI); |
| 664 | else |
| 665 | break; |
| 666 | |
| 667 | ++DI; |
| 668 | } while (DI != DIEnd); |
| 669 | RewriteForwardClassDecl(DG); |
| 670 | continue; |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { |
| 675 | if (!Proto->isThisDeclarationADefinition()) { |
| 676 | SmallVector<Decl *, 8> DG; |
| 677 | SourceLocation StartLoc = Proto->getLocStart(); |
| 678 | do { |
| 679 | if (isa<ObjCProtocolDecl>(*DI) && |
| 680 | !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && |
| 681 | StartLoc == (*DI)->getLocStart()) |
| 682 | DG.push_back(*DI); |
| 683 | else |
| 684 | break; |
| 685 | |
| 686 | ++DI; |
| 687 | } while (DI != DIEnd); |
| 688 | RewriteForwardProtocolDecl(DG); |
| 689 | continue; |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | HandleTopLevelSingleDecl(*DI); |
| 694 | ++DI; |
| 695 | } |
| 696 | } |
| 697 | // If we have a decl in the main file, see if we should rewrite it. |
| 698 | if (SM->isFromMainFile(Loc)) |
| 699 | return HandleDeclInMainFile(D); |
| 700 | } |
| 701 | |
| 702 | //===----------------------------------------------------------------------===// |
| 703 | // Syntactic (non-AST) Rewriting Code |
| 704 | //===----------------------------------------------------------------------===// |
| 705 | |
| 706 | void RewriteModernObjC::RewriteInclude() { |
| 707 | SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); |
| 708 | StringRef MainBuf = SM->getBufferData(MainFileID); |
| 709 | const char *MainBufStart = MainBuf.begin(); |
| 710 | const char *MainBufEnd = MainBuf.end(); |
| 711 | size_t ImportLen = strlen("import"); |
| 712 | |
| 713 | // Loop over the whole file, looking for includes. |
| 714 | for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { |
| 715 | if (*BufPtr == '#') { |
| 716 | if (++BufPtr == MainBufEnd) |
| 717 | return; |
| 718 | while (*BufPtr == ' ' || *BufPtr == '\t') |
| 719 | if (++BufPtr == MainBufEnd) |
| 720 | return; |
| 721 | if (!strncmp(BufPtr, "import", ImportLen)) { |
| 722 | // replace import with include |
| 723 | SourceLocation ImportLoc = |
| 724 | LocStart.getLocWithOffset(BufPtr-MainBufStart); |
| 725 | ReplaceText(ImportLoc, ImportLen, "include"); |
| 726 | BufPtr += ImportLen; |
| 727 | } |
| 728 | } |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | static std::string getIvarAccessString(ObjCIvarDecl *OID) { |
| 733 | const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface(); |
| 734 | std::string S; |
| 735 | S = "((struct "; |
| 736 | S += ClassDecl->getIdentifier()->getName(); |
| 737 | S += "_IMPL *)self)->"; |
| 738 | S += OID->getName(); |
| 739 | return S; |
| 740 | } |
| 741 | |
| 742 | void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, |
| 743 | ObjCImplementationDecl *IMD, |
| 744 | ObjCCategoryImplDecl *CID) { |
| 745 | static bool objcGetPropertyDefined = false; |
| 746 | static bool objcSetPropertyDefined = false; |
| 747 | SourceLocation startLoc = PID->getLocStart(); |
| 748 | InsertText(startLoc, "// "); |
| 749 | const char *startBuf = SM->getCharacterData(startLoc); |
| 750 | assert((*startBuf == '@') && "bogus @synthesize location"); |
| 751 | const char *semiBuf = strchr(startBuf, ';'); |
| 752 | assert((*semiBuf == ';') && "@synthesize: can't find ';'"); |
| 753 | SourceLocation onePastSemiLoc = |
| 754 | startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| 755 | |
| 756 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 757 | return; // FIXME: is this correct? |
| 758 | |
| 759 | // Generate the 'getter' function. |
| 760 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
| 761 | ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); |
| 762 | |
| 763 | if (!OID) |
| 764 | return; |
| 765 | unsigned Attributes = PD->getPropertyAttributes(); |
| 766 | if (!PD->getGetterMethodDecl()->isDefined()) { |
| 767 | bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && |
| 768 | (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | |
| 769 | ObjCPropertyDecl::OBJC_PR_copy)); |
| 770 | std::string Getr; |
| 771 | if (GenGetProperty && !objcGetPropertyDefined) { |
| 772 | objcGetPropertyDefined = true; |
| 773 | // FIXME. Is this attribute correct in all cases? |
| 774 | Getr = "\nextern \"C\" __declspec(dllimport) " |
| 775 | "id objc_getProperty(id, SEL, long, bool);\n"; |
| 776 | } |
| 777 | RewriteObjCMethodDecl(OID->getContainingInterface(), |
| 778 | PD->getGetterMethodDecl(), Getr); |
| 779 | Getr += "{ "; |
| 780 | // Synthesize an explicit cast to gain access to the ivar. |
| 781 | // See objc-act.c:objc_synthesize_new_getter() for details. |
| 782 | if (GenGetProperty) { |
| 783 | // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) |
| 784 | Getr += "typedef "; |
| 785 | const FunctionType *FPRetType = 0; |
| 786 | RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr, |
| 787 | FPRetType); |
| 788 | Getr += " _TYPE"; |
| 789 | if (FPRetType) { |
| 790 | Getr += ")"; // close the precedence "scope" for "*". |
| 791 | |
| 792 | // Now, emit the argument types (if any). |
| 793 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ |
| 794 | Getr += "("; |
| 795 | for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { |
| 796 | if (i) Getr += ", "; |
| 797 | std::string ParamStr = FT->getArgType(i).getAsString( |
| 798 | Context->getPrintingPolicy()); |
| 799 | Getr += ParamStr; |
| 800 | } |
| 801 | if (FT->isVariadic()) { |
| 802 | if (FT->getNumArgs()) Getr += ", "; |
| 803 | Getr += "..."; |
| 804 | } |
| 805 | Getr += ")"; |
| 806 | } else |
| 807 | Getr += "()"; |
| 808 | } |
| 809 | Getr += ";\n"; |
| 810 | Getr += "return (_TYPE)"; |
| 811 | Getr += "objc_getProperty(self, _cmd, "; |
| 812 | RewriteIvarOffsetComputation(OID, Getr); |
| 813 | Getr += ", 1)"; |
| 814 | } |
| 815 | else |
| 816 | Getr += "return " + getIvarAccessString(OID); |
| 817 | Getr += "; }"; |
| 818 | InsertText(onePastSemiLoc, Getr); |
| 819 | } |
| 820 | |
| 821 | if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined()) |
| 822 | return; |
| 823 | |
| 824 | // Generate the 'setter' function. |
| 825 | std::string Setr; |
| 826 | bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain | |
| 827 | ObjCPropertyDecl::OBJC_PR_copy); |
| 828 | if (GenSetProperty && !objcSetPropertyDefined) { |
| 829 | objcSetPropertyDefined = true; |
| 830 | // FIXME. Is this attribute correct in all cases? |
| 831 | Setr = "\nextern \"C\" __declspec(dllimport) " |
| 832 | "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; |
| 833 | } |
| 834 | |
| 835 | RewriteObjCMethodDecl(OID->getContainingInterface(), |
| 836 | PD->getSetterMethodDecl(), Setr); |
| 837 | Setr += "{ "; |
| 838 | // Synthesize an explicit cast to initialize the ivar. |
| 839 | // See objc-act.c:objc_synthesize_new_setter() for details. |
| 840 | if (GenSetProperty) { |
| 841 | Setr += "objc_setProperty (self, _cmd, "; |
| 842 | RewriteIvarOffsetComputation(OID, Setr); |
| 843 | Setr += ", (id)"; |
| 844 | Setr += PD->getName(); |
| 845 | Setr += ", "; |
| 846 | if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) |
| 847 | Setr += "0, "; |
| 848 | else |
| 849 | Setr += "1, "; |
| 850 | if (Attributes & ObjCPropertyDecl::OBJC_PR_copy) |
| 851 | Setr += "1)"; |
| 852 | else |
| 853 | Setr += "0)"; |
| 854 | } |
| 855 | else { |
| 856 | Setr += getIvarAccessString(OID) + " = "; |
| 857 | Setr += PD->getName(); |
| 858 | } |
| 859 | Setr += "; }"; |
| 860 | InsertText(onePastSemiLoc, Setr); |
| 861 | } |
| 862 | |
| 863 | static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, |
| 864 | std::string &typedefString) { |
| 865 | typedefString += "#ifndef _REWRITER_typedef_"; |
| 866 | typedefString += ForwardDecl->getNameAsString(); |
| 867 | typedefString += "\n"; |
| 868 | typedefString += "#define _REWRITER_typedef_"; |
| 869 | typedefString += ForwardDecl->getNameAsString(); |
| 870 | typedefString += "\n"; |
| 871 | typedefString += "typedef struct objc_object "; |
| 872 | typedefString += ForwardDecl->getNameAsString(); |
Fariborz Jahanian | c38503b | 2012-03-12 23:58:28 +0000 | [diff] [blame] | 873 | // typedef struct { } _objc_exc_Classname; |
| 874 | typedefString += ";\ntypedef struct {} _objc_exc_"; |
| 875 | typedefString += ForwardDecl->getNameAsString(); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 876 | typedefString += ";\n#endif\n"; |
| 877 | } |
| 878 | |
| 879 | void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, |
| 880 | const std::string &typedefString) { |
| 881 | SourceLocation startLoc = ClassDecl->getLocStart(); |
| 882 | const char *startBuf = SM->getCharacterData(startLoc); |
| 883 | const char *semiPtr = strchr(startBuf, ';'); |
| 884 | // Replace the @class with typedefs corresponding to the classes. |
| 885 | ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); |
| 886 | } |
| 887 | |
| 888 | void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { |
| 889 | std::string typedefString; |
| 890 | for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { |
| 891 | ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I); |
| 892 | if (I == D.begin()) { |
| 893 | // Translate to typedef's that forward reference structs with the same name |
| 894 | // as the class. As a convenience, we include the original declaration |
| 895 | // as a comment. |
| 896 | typedefString += "// @class "; |
| 897 | typedefString += ForwardDecl->getNameAsString(); |
| 898 | typedefString += ";\n"; |
| 899 | } |
| 900 | RewriteOneForwardClassDecl(ForwardDecl, typedefString); |
| 901 | } |
| 902 | DeclGroupRef::iterator I = D.begin(); |
| 903 | RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString); |
| 904 | } |
| 905 | |
| 906 | void RewriteModernObjC::RewriteForwardClassDecl( |
| 907 | const llvm::SmallVector<Decl*, 8> &D) { |
| 908 | std::string typedefString; |
| 909 | for (unsigned i = 0; i < D.size(); i++) { |
| 910 | ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]); |
| 911 | if (i == 0) { |
| 912 | typedefString += "// @class "; |
| 913 | typedefString += ForwardDecl->getNameAsString(); |
| 914 | typedefString += ";\n"; |
| 915 | } |
| 916 | RewriteOneForwardClassDecl(ForwardDecl, typedefString); |
| 917 | } |
| 918 | RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString); |
| 919 | } |
| 920 | |
| 921 | void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { |
| 922 | // When method is a synthesized one, such as a getter/setter there is |
| 923 | // nothing to rewrite. |
| 924 | if (Method->isImplicit()) |
| 925 | return; |
| 926 | SourceLocation LocStart = Method->getLocStart(); |
| 927 | SourceLocation LocEnd = Method->getLocEnd(); |
| 928 | |
| 929 | if (SM->getExpansionLineNumber(LocEnd) > |
| 930 | SM->getExpansionLineNumber(LocStart)) { |
| 931 | InsertText(LocStart, "#if 0\n"); |
| 932 | ReplaceText(LocEnd, 1, ";\n#endif\n"); |
| 933 | } else { |
| 934 | InsertText(LocStart, "// "); |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) { |
| 939 | SourceLocation Loc = prop->getAtLoc(); |
| 940 | |
| 941 | ReplaceText(Loc, 0, "// "); |
| 942 | // FIXME: handle properties that are declared across multiple lines. |
| 943 | } |
| 944 | |
| 945 | void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { |
| 946 | SourceLocation LocStart = CatDecl->getLocStart(); |
| 947 | |
| 948 | // FIXME: handle category headers that are declared across multiple lines. |
| 949 | ReplaceText(LocStart, 0, "// "); |
Fariborz Jahanian | af30029 | 2012-02-20 20:09:20 +0000 | [diff] [blame] | 950 | if (CatDecl->getIvarLBraceLoc().isValid()) |
| 951 | InsertText(CatDecl->getIvarLBraceLoc(), "// "); |
Fariborz Jahanian | d2aea12 | 2012-02-19 19:00:05 +0000 | [diff] [blame] | 952 | for (ObjCCategoryDecl::ivar_iterator |
| 953 | I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) { |
| 954 | ObjCIvarDecl *Ivar = (*I); |
| 955 | SourceLocation LocStart = Ivar->getLocStart(); |
| 956 | ReplaceText(LocStart, 0, "// "); |
| 957 | } |
Fariborz Jahanian | af30029 | 2012-02-20 20:09:20 +0000 | [diff] [blame] | 958 | if (CatDecl->getIvarRBraceLoc().isValid()) |
| 959 | InsertText(CatDecl->getIvarRBraceLoc(), "// "); |
| 960 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 961 | for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(), |
| 962 | E = CatDecl->prop_end(); I != E; ++I) |
| 963 | RewriteProperty(*I); |
| 964 | |
| 965 | for (ObjCCategoryDecl::instmeth_iterator |
| 966 | I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end(); |
| 967 | I != E; ++I) |
| 968 | RewriteMethodDeclaration(*I); |
| 969 | for (ObjCCategoryDecl::classmeth_iterator |
| 970 | I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end(); |
| 971 | I != E; ++I) |
| 972 | RewriteMethodDeclaration(*I); |
| 973 | |
| 974 | // Lastly, comment out the @end. |
| 975 | ReplaceText(CatDecl->getAtEndRange().getBegin(), |
| 976 | strlen("@end"), "/* @end */"); |
| 977 | } |
| 978 | |
| 979 | void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { |
| 980 | SourceLocation LocStart = PDecl->getLocStart(); |
| 981 | assert(PDecl->isThisDeclarationADefinition()); |
| 982 | |
| 983 | // FIXME: handle protocol headers that are declared across multiple lines. |
| 984 | ReplaceText(LocStart, 0, "// "); |
| 985 | |
| 986 | for (ObjCProtocolDecl::instmeth_iterator |
| 987 | I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); |
| 988 | I != E; ++I) |
| 989 | RewriteMethodDeclaration(*I); |
| 990 | for (ObjCProtocolDecl::classmeth_iterator |
| 991 | I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); |
| 992 | I != E; ++I) |
| 993 | RewriteMethodDeclaration(*I); |
| 994 | |
| 995 | for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(), |
| 996 | E = PDecl->prop_end(); I != E; ++I) |
| 997 | RewriteProperty(*I); |
| 998 | |
| 999 | // Lastly, comment out the @end. |
| 1000 | SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); |
| 1001 | ReplaceText(LocEnd, strlen("@end"), "/* @end */"); |
| 1002 | |
| 1003 | // Must comment out @optional/@required |
| 1004 | const char *startBuf = SM->getCharacterData(LocStart); |
| 1005 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 1006 | for (const char *p = startBuf; p < endBuf; p++) { |
| 1007 | if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { |
| 1008 | SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); |
| 1009 | ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */"); |
| 1010 | |
| 1011 | } |
| 1012 | else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { |
| 1013 | SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); |
| 1014 | ReplaceText(OptionalLoc, strlen("@required"), "/* @required */"); |
| 1015 | |
| 1016 | } |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { |
| 1021 | SourceLocation LocStart = (*D.begin())->getLocStart(); |
| 1022 | if (LocStart.isInvalid()) |
| 1023 | llvm_unreachable("Invalid SourceLocation"); |
| 1024 | // FIXME: handle forward protocol that are declared across multiple lines. |
| 1025 | ReplaceText(LocStart, 0, "// "); |
| 1026 | } |
| 1027 | |
| 1028 | void |
| 1029 | RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) { |
| 1030 | SourceLocation LocStart = DG[0]->getLocStart(); |
| 1031 | if (LocStart.isInvalid()) |
| 1032 | llvm_unreachable("Invalid SourceLocation"); |
| 1033 | // FIXME: handle forward protocol that are declared across multiple lines. |
| 1034 | ReplaceText(LocStart, 0, "// "); |
| 1035 | } |
| 1036 | |
| 1037 | void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr, |
| 1038 | const FunctionType *&FPRetType) { |
| 1039 | if (T->isObjCQualifiedIdType()) |
| 1040 | ResultStr += "id"; |
| 1041 | else if (T->isFunctionPointerType() || |
| 1042 | T->isBlockPointerType()) { |
| 1043 | // needs special handling, since pointer-to-functions have special |
| 1044 | // syntax (where a decaration models use). |
| 1045 | QualType retType = T; |
| 1046 | QualType PointeeTy; |
| 1047 | if (const PointerType* PT = retType->getAs<PointerType>()) |
| 1048 | PointeeTy = PT->getPointeeType(); |
| 1049 | else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) |
| 1050 | PointeeTy = BPT->getPointeeType(); |
| 1051 | if ((FPRetType = PointeeTy->getAs<FunctionType>())) { |
| 1052 | ResultStr += FPRetType->getResultType().getAsString( |
| 1053 | Context->getPrintingPolicy()); |
| 1054 | ResultStr += "(*"; |
| 1055 | } |
| 1056 | } else |
| 1057 | ResultStr += T.getAsString(Context->getPrintingPolicy()); |
| 1058 | } |
| 1059 | |
| 1060 | void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, |
| 1061 | ObjCMethodDecl *OMD, |
| 1062 | std::string &ResultStr) { |
| 1063 | //fprintf(stderr,"In RewriteObjCMethodDecl\n"); |
| 1064 | const FunctionType *FPRetType = 0; |
| 1065 | ResultStr += "\nstatic "; |
| 1066 | RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType); |
| 1067 | ResultStr += " "; |
| 1068 | |
| 1069 | // Unique method name |
| 1070 | std::string NameStr; |
| 1071 | |
| 1072 | if (OMD->isInstanceMethod()) |
| 1073 | NameStr += "_I_"; |
| 1074 | else |
| 1075 | NameStr += "_C_"; |
| 1076 | |
| 1077 | NameStr += IDecl->getNameAsString(); |
| 1078 | NameStr += "_"; |
| 1079 | |
| 1080 | if (ObjCCategoryImplDecl *CID = |
| 1081 | dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { |
| 1082 | NameStr += CID->getNameAsString(); |
| 1083 | NameStr += "_"; |
| 1084 | } |
| 1085 | // Append selector names, replacing ':' with '_' |
| 1086 | { |
| 1087 | std::string selString = OMD->getSelector().getAsString(); |
| 1088 | int len = selString.size(); |
| 1089 | for (int i = 0; i < len; i++) |
| 1090 | if (selString[i] == ':') |
| 1091 | selString[i] = '_'; |
| 1092 | NameStr += selString; |
| 1093 | } |
| 1094 | // Remember this name for metadata emission |
| 1095 | MethodInternalNames[OMD] = NameStr; |
| 1096 | ResultStr += NameStr; |
| 1097 | |
| 1098 | // Rewrite arguments |
| 1099 | ResultStr += "("; |
| 1100 | |
| 1101 | // invisible arguments |
| 1102 | if (OMD->isInstanceMethod()) { |
| 1103 | QualType selfTy = Context->getObjCInterfaceType(IDecl); |
| 1104 | selfTy = Context->getPointerType(selfTy); |
| 1105 | if (!LangOpts.MicrosoftExt) { |
| 1106 | if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl))) |
| 1107 | ResultStr += "struct "; |
| 1108 | } |
| 1109 | // When rewriting for Microsoft, explicitly omit the structure name. |
| 1110 | ResultStr += IDecl->getNameAsString(); |
| 1111 | ResultStr += " *"; |
| 1112 | } |
| 1113 | else |
| 1114 | ResultStr += Context->getObjCClassType().getAsString( |
| 1115 | Context->getPrintingPolicy()); |
| 1116 | |
| 1117 | ResultStr += " self, "; |
| 1118 | ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy()); |
| 1119 | ResultStr += " _cmd"; |
| 1120 | |
| 1121 | // Method arguments. |
| 1122 | for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), |
| 1123 | E = OMD->param_end(); PI != E; ++PI) { |
| 1124 | ParmVarDecl *PDecl = *PI; |
| 1125 | ResultStr += ", "; |
| 1126 | if (PDecl->getType()->isObjCQualifiedIdType()) { |
| 1127 | ResultStr += "id "; |
| 1128 | ResultStr += PDecl->getNameAsString(); |
| 1129 | } else { |
| 1130 | std::string Name = PDecl->getNameAsString(); |
| 1131 | QualType QT = PDecl->getType(); |
| 1132 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 1133 | if (convertBlockPointerToFunctionPointer(QT)) |
| 1134 | QT.getAsStringInternal(Name, Context->getPrintingPolicy()); |
| 1135 | else |
| 1136 | PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy()); |
| 1137 | ResultStr += Name; |
| 1138 | } |
| 1139 | } |
| 1140 | if (OMD->isVariadic()) |
| 1141 | ResultStr += ", ..."; |
| 1142 | ResultStr += ") "; |
| 1143 | |
| 1144 | if (FPRetType) { |
| 1145 | ResultStr += ")"; // close the precedence "scope" for "*". |
| 1146 | |
| 1147 | // Now, emit the argument types (if any). |
| 1148 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { |
| 1149 | ResultStr += "("; |
| 1150 | for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { |
| 1151 | if (i) ResultStr += ", "; |
| 1152 | std::string ParamStr = FT->getArgType(i).getAsString( |
| 1153 | Context->getPrintingPolicy()); |
| 1154 | ResultStr += ParamStr; |
| 1155 | } |
| 1156 | if (FT->isVariadic()) { |
| 1157 | if (FT->getNumArgs()) ResultStr += ", "; |
| 1158 | ResultStr += "..."; |
| 1159 | } |
| 1160 | ResultStr += ")"; |
| 1161 | } else { |
| 1162 | ResultStr += "()"; |
| 1163 | } |
| 1164 | } |
| 1165 | } |
| 1166 | void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { |
| 1167 | ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); |
| 1168 | ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); |
| 1169 | |
Fariborz Jahanian | d2aea12 | 2012-02-19 19:00:05 +0000 | [diff] [blame] | 1170 | if (IMD) { |
| 1171 | InsertText(IMD->getLocStart(), "// "); |
Fariborz Jahanian | af30029 | 2012-02-20 20:09:20 +0000 | [diff] [blame] | 1172 | if (IMD->getIvarLBraceLoc().isValid()) |
| 1173 | InsertText(IMD->getIvarLBraceLoc(), "// "); |
| 1174 | for (ObjCImplementationDecl::ivar_iterator |
| 1175 | I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) { |
| 1176 | ObjCIvarDecl *Ivar = (*I); |
| 1177 | SourceLocation LocStart = Ivar->getLocStart(); |
| 1178 | ReplaceText(LocStart, 0, "// "); |
Fariborz Jahanian | d2aea12 | 2012-02-19 19:00:05 +0000 | [diff] [blame] | 1179 | } |
Fariborz Jahanian | af30029 | 2012-02-20 20:09:20 +0000 | [diff] [blame] | 1180 | if (IMD->getIvarRBraceLoc().isValid()) |
| 1181 | InsertText(IMD->getIvarRBraceLoc(), "// "); |
Fariborz Jahanian | d2aea12 | 2012-02-19 19:00:05 +0000 | [diff] [blame] | 1182 | } |
| 1183 | else |
| 1184 | InsertText(CID->getLocStart(), "// "); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1185 | |
| 1186 | for (ObjCCategoryImplDecl::instmeth_iterator |
| 1187 | I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(), |
| 1188 | E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); |
| 1189 | I != E; ++I) { |
| 1190 | std::string ResultStr; |
| 1191 | ObjCMethodDecl *OMD = *I; |
| 1192 | RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); |
| 1193 | SourceLocation LocStart = OMD->getLocStart(); |
| 1194 | SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); |
| 1195 | |
| 1196 | const char *startBuf = SM->getCharacterData(LocStart); |
| 1197 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 1198 | ReplaceText(LocStart, endBuf-startBuf, ResultStr); |
| 1199 | } |
| 1200 | |
| 1201 | for (ObjCCategoryImplDecl::classmeth_iterator |
| 1202 | I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(), |
| 1203 | E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); |
| 1204 | I != E; ++I) { |
| 1205 | std::string ResultStr; |
| 1206 | ObjCMethodDecl *OMD = *I; |
| 1207 | RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); |
| 1208 | SourceLocation LocStart = OMD->getLocStart(); |
| 1209 | SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart(); |
| 1210 | |
| 1211 | const char *startBuf = SM->getCharacterData(LocStart); |
| 1212 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 1213 | ReplaceText(LocStart, endBuf-startBuf, ResultStr); |
| 1214 | } |
| 1215 | for (ObjCCategoryImplDecl::propimpl_iterator |
| 1216 | I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(), |
| 1217 | E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); |
| 1218 | I != E; ++I) { |
| 1219 | RewritePropertyImplDecl(*I, IMD, CID); |
| 1220 | } |
| 1221 | |
| 1222 | InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// "); |
| 1223 | } |
| 1224 | |
| 1225 | void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { |
Fariborz Jahanian | 8f1fed0 | 2012-02-11 20:10:52 +0000 | [diff] [blame] | 1226 | // Do not synthesize more than once. |
| 1227 | if (ObjCSynthesizedStructs.count(ClassDecl)) |
| 1228 | return; |
| 1229 | // Make sure super class's are written before current class is written. |
| 1230 | ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass(); |
| 1231 | while (SuperClass) { |
| 1232 | RewriteInterfaceDecl(SuperClass); |
| 1233 | SuperClass = SuperClass->getSuperClass(); |
| 1234 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1235 | std::string ResultStr; |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 1236 | if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1237 | // we haven't seen a forward decl - generate a typedef. |
Fariborz Jahanian | c38503b | 2012-03-12 23:58:28 +0000 | [diff] [blame] | 1238 | RewriteOneForwardClassDecl(ClassDecl, ResultStr); |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 1239 | RewriteIvarOffsetSymbols(ClassDecl, ResultStr); |
| 1240 | |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1241 | RewriteObjCInternalStruct(ClassDecl, ResultStr); |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 1242 | // Mark this typedef as having been written into its c++ equivalent. |
| 1243 | ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1244 | |
| 1245 | for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(), |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1246 | E = ClassDecl->prop_end(); I != E; ++I) |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1247 | RewriteProperty(*I); |
| 1248 | for (ObjCInterfaceDecl::instmeth_iterator |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1249 | I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end(); |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1250 | I != E; ++I) |
| 1251 | RewriteMethodDeclaration(*I); |
| 1252 | for (ObjCInterfaceDecl::classmeth_iterator |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1253 | I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end(); |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1254 | I != E; ++I) |
| 1255 | RewriteMethodDeclaration(*I); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1256 | |
Fariborz Jahanian | 4339bb3 | 2012-02-15 22:01:47 +0000 | [diff] [blame] | 1257 | // Lastly, comment out the @end. |
| 1258 | ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), |
| 1259 | "/* @end */"); |
| 1260 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1261 | } |
| 1262 | |
| 1263 | Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) { |
| 1264 | SourceRange OldRange = PseudoOp->getSourceRange(); |
| 1265 | |
| 1266 | // We just magically know some things about the structure of this |
| 1267 | // expression. |
| 1268 | ObjCMessageExpr *OldMsg = |
| 1269 | cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr( |
| 1270 | PseudoOp->getNumSemanticExprs() - 1)); |
| 1271 | |
| 1272 | // Because the rewriter doesn't allow us to rewrite rewritten code, |
| 1273 | // we need to suppress rewriting the sub-statements. |
| 1274 | Expr *Base, *RHS; |
| 1275 | { |
| 1276 | DisableReplaceStmtScope S(*this); |
| 1277 | |
| 1278 | // Rebuild the base expression if we have one. |
| 1279 | Base = 0; |
| 1280 | if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { |
| 1281 | Base = OldMsg->getInstanceReceiver(); |
| 1282 | Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); |
| 1283 | Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); |
| 1284 | } |
| 1285 | |
| 1286 | // Rebuild the RHS. |
| 1287 | RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS(); |
| 1288 | RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr(); |
| 1289 | RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS)); |
| 1290 | } |
| 1291 | |
| 1292 | // TODO: avoid this copy. |
| 1293 | SmallVector<SourceLocation, 1> SelLocs; |
| 1294 | OldMsg->getSelectorLocs(SelLocs); |
| 1295 | |
| 1296 | ObjCMessageExpr *NewMsg = 0; |
| 1297 | switch (OldMsg->getReceiverKind()) { |
| 1298 | case ObjCMessageExpr::Class: |
| 1299 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1300 | OldMsg->getValueKind(), |
| 1301 | OldMsg->getLeftLoc(), |
| 1302 | OldMsg->getClassReceiverTypeInfo(), |
| 1303 | OldMsg->getSelector(), |
| 1304 | SelLocs, |
| 1305 | OldMsg->getMethodDecl(), |
| 1306 | RHS, |
| 1307 | OldMsg->getRightLoc(), |
| 1308 | OldMsg->isImplicit()); |
| 1309 | break; |
| 1310 | |
| 1311 | case ObjCMessageExpr::Instance: |
| 1312 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1313 | OldMsg->getValueKind(), |
| 1314 | OldMsg->getLeftLoc(), |
| 1315 | Base, |
| 1316 | OldMsg->getSelector(), |
| 1317 | SelLocs, |
| 1318 | OldMsg->getMethodDecl(), |
| 1319 | RHS, |
| 1320 | OldMsg->getRightLoc(), |
| 1321 | OldMsg->isImplicit()); |
| 1322 | break; |
| 1323 | |
| 1324 | case ObjCMessageExpr::SuperClass: |
| 1325 | case ObjCMessageExpr::SuperInstance: |
| 1326 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1327 | OldMsg->getValueKind(), |
| 1328 | OldMsg->getLeftLoc(), |
| 1329 | OldMsg->getSuperLoc(), |
| 1330 | OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, |
| 1331 | OldMsg->getSuperType(), |
| 1332 | OldMsg->getSelector(), |
| 1333 | SelLocs, |
| 1334 | OldMsg->getMethodDecl(), |
| 1335 | RHS, |
| 1336 | OldMsg->getRightLoc(), |
| 1337 | OldMsg->isImplicit()); |
| 1338 | break; |
| 1339 | } |
| 1340 | |
| 1341 | Stmt *Replacement = SynthMessageExpr(NewMsg); |
| 1342 | ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); |
| 1343 | return Replacement; |
| 1344 | } |
| 1345 | |
| 1346 | Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) { |
| 1347 | SourceRange OldRange = PseudoOp->getSourceRange(); |
| 1348 | |
| 1349 | // We just magically know some things about the structure of this |
| 1350 | // expression. |
| 1351 | ObjCMessageExpr *OldMsg = |
| 1352 | cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit()); |
| 1353 | |
| 1354 | // Because the rewriter doesn't allow us to rewrite rewritten code, |
| 1355 | // we need to suppress rewriting the sub-statements. |
| 1356 | Expr *Base = 0; |
| 1357 | { |
| 1358 | DisableReplaceStmtScope S(*this); |
| 1359 | |
| 1360 | // Rebuild the base expression if we have one. |
| 1361 | if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { |
| 1362 | Base = OldMsg->getInstanceReceiver(); |
| 1363 | Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); |
| 1364 | Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | // Intentionally empty. |
| 1369 | SmallVector<SourceLocation, 1> SelLocs; |
| 1370 | SmallVector<Expr*, 1> Args; |
| 1371 | |
| 1372 | ObjCMessageExpr *NewMsg = 0; |
| 1373 | switch (OldMsg->getReceiverKind()) { |
| 1374 | case ObjCMessageExpr::Class: |
| 1375 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1376 | OldMsg->getValueKind(), |
| 1377 | OldMsg->getLeftLoc(), |
| 1378 | OldMsg->getClassReceiverTypeInfo(), |
| 1379 | OldMsg->getSelector(), |
| 1380 | SelLocs, |
| 1381 | OldMsg->getMethodDecl(), |
| 1382 | Args, |
| 1383 | OldMsg->getRightLoc(), |
| 1384 | OldMsg->isImplicit()); |
| 1385 | break; |
| 1386 | |
| 1387 | case ObjCMessageExpr::Instance: |
| 1388 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1389 | OldMsg->getValueKind(), |
| 1390 | OldMsg->getLeftLoc(), |
| 1391 | Base, |
| 1392 | OldMsg->getSelector(), |
| 1393 | SelLocs, |
| 1394 | OldMsg->getMethodDecl(), |
| 1395 | Args, |
| 1396 | OldMsg->getRightLoc(), |
| 1397 | OldMsg->isImplicit()); |
| 1398 | break; |
| 1399 | |
| 1400 | case ObjCMessageExpr::SuperClass: |
| 1401 | case ObjCMessageExpr::SuperInstance: |
| 1402 | NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), |
| 1403 | OldMsg->getValueKind(), |
| 1404 | OldMsg->getLeftLoc(), |
| 1405 | OldMsg->getSuperLoc(), |
| 1406 | OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, |
| 1407 | OldMsg->getSuperType(), |
| 1408 | OldMsg->getSelector(), |
| 1409 | SelLocs, |
| 1410 | OldMsg->getMethodDecl(), |
| 1411 | Args, |
| 1412 | OldMsg->getRightLoc(), |
| 1413 | OldMsg->isImplicit()); |
| 1414 | break; |
| 1415 | } |
| 1416 | |
| 1417 | Stmt *Replacement = SynthMessageExpr(NewMsg); |
| 1418 | ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); |
| 1419 | return Replacement; |
| 1420 | } |
| 1421 | |
| 1422 | /// SynthCountByEnumWithState - To print: |
| 1423 | /// ((unsigned int (*) |
| 1424 | /// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| 1425 | /// (void *)objc_msgSend)((id)l_collection, |
| 1426 | /// sel_registerName( |
| 1427 | /// "countByEnumeratingWithState:objects:count:"), |
| 1428 | /// &enumState, |
| 1429 | /// (id *)__rw_items, (unsigned int)16) |
| 1430 | /// |
| 1431 | void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) { |
| 1432 | buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, " |
| 1433 | "id *, unsigned int))(void *)objc_msgSend)"; |
| 1434 | buf += "\n\t\t"; |
| 1435 | buf += "((id)l_collection,\n\t\t"; |
| 1436 | buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; |
| 1437 | buf += "\n\t\t"; |
| 1438 | buf += "&enumState, " |
| 1439 | "(id *)__rw_items, (unsigned int)16)"; |
| 1440 | } |
| 1441 | |
| 1442 | /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach |
| 1443 | /// statement to exit to its outer synthesized loop. |
| 1444 | /// |
| 1445 | Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) { |
| 1446 | if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| 1447 | return S; |
| 1448 | // replace break with goto __break_label |
| 1449 | std::string buf; |
| 1450 | |
| 1451 | SourceLocation startLoc = S->getLocStart(); |
| 1452 | buf = "goto __break_label_"; |
| 1453 | buf += utostr(ObjCBcLabelNo.back()); |
| 1454 | ReplaceText(startLoc, strlen("break"), buf); |
| 1455 | |
| 1456 | return 0; |
| 1457 | } |
| 1458 | |
| 1459 | /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach |
| 1460 | /// statement to continue with its inner synthesized loop. |
| 1461 | /// |
| 1462 | Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) { |
| 1463 | if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) |
| 1464 | return S; |
| 1465 | // replace continue with goto __continue_label |
| 1466 | std::string buf; |
| 1467 | |
| 1468 | SourceLocation startLoc = S->getLocStart(); |
| 1469 | buf = "goto __continue_label_"; |
| 1470 | buf += utostr(ObjCBcLabelNo.back()); |
| 1471 | ReplaceText(startLoc, strlen("continue"), buf); |
| 1472 | |
| 1473 | return 0; |
| 1474 | } |
| 1475 | |
| 1476 | /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. |
| 1477 | /// It rewrites: |
| 1478 | /// for ( type elem in collection) { stmts; } |
| 1479 | |
| 1480 | /// Into: |
| 1481 | /// { |
| 1482 | /// type elem; |
| 1483 | /// struct __objcFastEnumerationState enumState = { 0 }; |
| 1484 | /// id __rw_items[16]; |
| 1485 | /// id l_collection = (id)collection; |
| 1486 | /// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| 1487 | /// objects:__rw_items count:16]; |
| 1488 | /// if (limit) { |
| 1489 | /// unsigned long startMutations = *enumState.mutationsPtr; |
| 1490 | /// do { |
| 1491 | /// unsigned long counter = 0; |
| 1492 | /// do { |
| 1493 | /// if (startMutations != *enumState.mutationsPtr) |
| 1494 | /// objc_enumerationMutation(l_collection); |
| 1495 | /// elem = (type)enumState.itemsPtr[counter++]; |
| 1496 | /// stmts; |
| 1497 | /// __continue_label: ; |
| 1498 | /// } while (counter < limit); |
| 1499 | /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| 1500 | /// objects:__rw_items count:16]); |
| 1501 | /// elem = nil; |
| 1502 | /// __break_label: ; |
| 1503 | /// } |
| 1504 | /// else |
| 1505 | /// elem = nil; |
| 1506 | /// } |
| 1507 | /// |
| 1508 | Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, |
| 1509 | SourceLocation OrigEnd) { |
| 1510 | assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); |
| 1511 | assert(isa<ObjCForCollectionStmt>(Stmts.back()) && |
| 1512 | "ObjCForCollectionStmt Statement stack mismatch"); |
| 1513 | assert(!ObjCBcLabelNo.empty() && |
| 1514 | "ObjCForCollectionStmt - Label No stack empty"); |
| 1515 | |
| 1516 | SourceLocation startLoc = S->getLocStart(); |
| 1517 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1518 | StringRef elementName; |
| 1519 | std::string elementTypeAsString; |
| 1520 | std::string buf; |
| 1521 | buf = "\n{\n\t"; |
| 1522 | if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { |
| 1523 | // type elem; |
| 1524 | NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); |
| 1525 | QualType ElementType = cast<ValueDecl>(D)->getType(); |
| 1526 | if (ElementType->isObjCQualifiedIdType() || |
| 1527 | ElementType->isObjCQualifiedInterfaceType()) |
| 1528 | // Simply use 'id' for all qualified types. |
| 1529 | elementTypeAsString = "id"; |
| 1530 | else |
| 1531 | elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy()); |
| 1532 | buf += elementTypeAsString; |
| 1533 | buf += " "; |
| 1534 | elementName = D->getName(); |
| 1535 | buf += elementName; |
| 1536 | buf += ";\n\t"; |
| 1537 | } |
| 1538 | else { |
| 1539 | DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); |
| 1540 | elementName = DR->getDecl()->getName(); |
| 1541 | ValueDecl *VD = cast<ValueDecl>(DR->getDecl()); |
| 1542 | if (VD->getType()->isObjCQualifiedIdType() || |
| 1543 | VD->getType()->isObjCQualifiedInterfaceType()) |
| 1544 | // Simply use 'id' for all qualified types. |
| 1545 | elementTypeAsString = "id"; |
| 1546 | else |
| 1547 | elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy()); |
| 1548 | } |
| 1549 | |
| 1550 | // struct __objcFastEnumerationState enumState = { 0 }; |
| 1551 | buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; |
| 1552 | // id __rw_items[16]; |
| 1553 | buf += "id __rw_items[16];\n\t"; |
| 1554 | // id l_collection = (id) |
| 1555 | buf += "id l_collection = (id)"; |
| 1556 | // Find start location of 'collection' the hard way! |
| 1557 | const char *startCollectionBuf = startBuf; |
| 1558 | startCollectionBuf += 3; // skip 'for' |
| 1559 | startCollectionBuf = strchr(startCollectionBuf, '('); |
| 1560 | startCollectionBuf++; // skip '(' |
| 1561 | // find 'in' and skip it. |
| 1562 | while (*startCollectionBuf != ' ' || |
| 1563 | *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || |
| 1564 | (*(startCollectionBuf+3) != ' ' && |
| 1565 | *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) |
| 1566 | startCollectionBuf++; |
| 1567 | startCollectionBuf += 3; |
| 1568 | |
| 1569 | // Replace: "for (type element in" with string constructed thus far. |
| 1570 | ReplaceText(startLoc, startCollectionBuf - startBuf, buf); |
| 1571 | // Replace ')' in for '(' type elem in collection ')' with ';' |
| 1572 | SourceLocation rightParenLoc = S->getRParenLoc(); |
| 1573 | const char *rparenBuf = SM->getCharacterData(rightParenLoc); |
| 1574 | SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf); |
| 1575 | buf = ";\n\t"; |
| 1576 | |
| 1577 | // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState |
| 1578 | // objects:__rw_items count:16]; |
| 1579 | // which is synthesized into: |
| 1580 | // unsigned int limit = |
| 1581 | // ((unsigned int (*) |
| 1582 | // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int)) |
| 1583 | // (void *)objc_msgSend)((id)l_collection, |
| 1584 | // sel_registerName( |
| 1585 | // "countByEnumeratingWithState:objects:count:"), |
| 1586 | // (struct __objcFastEnumerationState *)&state, |
| 1587 | // (id *)__rw_items, (unsigned int)16); |
| 1588 | buf += "unsigned long limit =\n\t\t"; |
| 1589 | SynthCountByEnumWithState(buf); |
| 1590 | buf += ";\n\t"; |
| 1591 | /// if (limit) { |
| 1592 | /// unsigned long startMutations = *enumState.mutationsPtr; |
| 1593 | /// do { |
| 1594 | /// unsigned long counter = 0; |
| 1595 | /// do { |
| 1596 | /// if (startMutations != *enumState.mutationsPtr) |
| 1597 | /// objc_enumerationMutation(l_collection); |
| 1598 | /// elem = (type)enumState.itemsPtr[counter++]; |
| 1599 | buf += "if (limit) {\n\t"; |
| 1600 | buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; |
| 1601 | buf += "do {\n\t\t"; |
| 1602 | buf += "unsigned long counter = 0;\n\t\t"; |
| 1603 | buf += "do {\n\t\t\t"; |
| 1604 | buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; |
| 1605 | buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; |
| 1606 | buf += elementName; |
| 1607 | buf += " = ("; |
| 1608 | buf += elementTypeAsString; |
| 1609 | buf += ")enumState.itemsPtr[counter++];"; |
| 1610 | // Replace ')' in for '(' type elem in collection ')' with all of these. |
| 1611 | ReplaceText(lparenLoc, 1, buf); |
| 1612 | |
| 1613 | /// __continue_label: ; |
| 1614 | /// } while (counter < limit); |
| 1615 | /// } while (limit = [l_collection countByEnumeratingWithState:&enumState |
| 1616 | /// objects:__rw_items count:16]); |
| 1617 | /// elem = nil; |
| 1618 | /// __break_label: ; |
| 1619 | /// } |
| 1620 | /// else |
| 1621 | /// elem = nil; |
| 1622 | /// } |
| 1623 | /// |
| 1624 | buf = ";\n\t"; |
| 1625 | buf += "__continue_label_"; |
| 1626 | buf += utostr(ObjCBcLabelNo.back()); |
| 1627 | buf += ": ;"; |
| 1628 | buf += "\n\t\t"; |
| 1629 | buf += "} while (counter < limit);\n\t"; |
| 1630 | buf += "} while (limit = "; |
| 1631 | SynthCountByEnumWithState(buf); |
| 1632 | buf += ");\n\t"; |
| 1633 | buf += elementName; |
| 1634 | buf += " = (("; |
| 1635 | buf += elementTypeAsString; |
| 1636 | buf += ")0);\n\t"; |
| 1637 | buf += "__break_label_"; |
| 1638 | buf += utostr(ObjCBcLabelNo.back()); |
| 1639 | buf += ": ;\n\t"; |
| 1640 | buf += "}\n\t"; |
| 1641 | buf += "else\n\t\t"; |
| 1642 | buf += elementName; |
| 1643 | buf += " = (("; |
| 1644 | buf += elementTypeAsString; |
| 1645 | buf += ")0);\n\t"; |
| 1646 | buf += "}\n"; |
| 1647 | |
| 1648 | // Insert all these *after* the statement body. |
| 1649 | // FIXME: If this should support Obj-C++, support CXXTryStmt |
| 1650 | if (isa<CompoundStmt>(S->getBody())) { |
| 1651 | SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1); |
| 1652 | InsertText(endBodyLoc, buf); |
| 1653 | } else { |
| 1654 | /* Need to treat single statements specially. For example: |
| 1655 | * |
| 1656 | * for (A *a in b) if (stuff()) break; |
| 1657 | * for (A *a in b) xxxyy; |
| 1658 | * |
| 1659 | * The following code simply scans ahead to the semi to find the actual end. |
| 1660 | */ |
| 1661 | const char *stmtBuf = SM->getCharacterData(OrigEnd); |
| 1662 | const char *semiBuf = strchr(stmtBuf, ';'); |
| 1663 | assert(semiBuf && "Can't find ';'"); |
| 1664 | SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1); |
| 1665 | InsertText(endBodyLoc, buf); |
| 1666 | } |
| 1667 | Stmts.pop_back(); |
| 1668 | ObjCBcLabelNo.pop_back(); |
| 1669 | return 0; |
| 1670 | } |
| 1671 | |
| 1672 | /// RewriteObjCSynchronizedStmt - |
| 1673 | /// This routine rewrites @synchronized(expr) stmt; |
| 1674 | /// into: |
| 1675 | /// objc_sync_enter(expr); |
| 1676 | /// @try stmt @finally { objc_sync_exit(expr); } |
| 1677 | /// |
| 1678 | Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { |
| 1679 | // Get the start location and compute the semi location. |
| 1680 | SourceLocation startLoc = S->getLocStart(); |
| 1681 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1682 | |
| 1683 | assert((*startBuf == '@') && "bogus @synchronized location"); |
| 1684 | |
| 1685 | std::string buf; |
| 1686 | buf = "objc_sync_enter((id)"; |
| 1687 | const char *lparenBuf = startBuf; |
| 1688 | while (*lparenBuf != '(') lparenBuf++; |
| 1689 | ReplaceText(startLoc, lparenBuf-startBuf+1, buf); |
| 1690 | // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since |
| 1691 | // the sync expression is typically a message expression that's already |
| 1692 | // been rewritten! (which implies the SourceLocation's are invalid). |
| 1693 | SourceLocation endLoc = S->getSynchBody()->getLocStart(); |
| 1694 | const char *endBuf = SM->getCharacterData(endLoc); |
| 1695 | while (*endBuf != ')') endBuf--; |
| 1696 | SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf); |
| 1697 | buf = ");\n"; |
| 1698 | // declare a new scope with two variables, _stack and _rethrow. |
| 1699 | buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n"; |
| 1700 | buf += "int buf[18/*32-bit i386*/];\n"; |
| 1701 | buf += "char *pointers[4];} _stack;\n"; |
| 1702 | buf += "id volatile _rethrow = 0;\n"; |
| 1703 | buf += "objc_exception_try_enter(&_stack);\n"; |
| 1704 | buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n"; |
| 1705 | ReplaceText(rparenLoc, 1, buf); |
| 1706 | startLoc = S->getSynchBody()->getLocEnd(); |
| 1707 | startBuf = SM->getCharacterData(startLoc); |
| 1708 | |
| 1709 | assert((*startBuf == '}') && "bogus @synchronized block"); |
| 1710 | SourceLocation lastCurlyLoc = startLoc; |
| 1711 | buf = "}\nelse {\n"; |
| 1712 | buf += " _rethrow = objc_exception_extract(&_stack);\n"; |
| 1713 | buf += "}\n"; |
| 1714 | buf += "{ /* implicit finally clause */\n"; |
| 1715 | buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n"; |
| 1716 | |
| 1717 | std::string syncBuf; |
| 1718 | syncBuf += " objc_sync_exit("; |
| 1719 | |
| 1720 | Expr *syncExpr = S->getSynchExpr(); |
| 1721 | CastKind CK = syncExpr->getType()->isObjCObjectPointerType() |
| 1722 | ? CK_BitCast : |
| 1723 | syncExpr->getType()->isBlockPointerType() |
| 1724 | ? CK_BlockPointerToObjCPointerCast |
| 1725 | : CK_CPointerToObjCPointerCast; |
| 1726 | syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 1727 | CK, syncExpr); |
| 1728 | std::string syncExprBufS; |
| 1729 | llvm::raw_string_ostream syncExprBuf(syncExprBufS); |
| 1730 | syncExpr->printPretty(syncExprBuf, *Context, 0, |
| 1731 | PrintingPolicy(LangOpts)); |
| 1732 | syncBuf += syncExprBuf.str(); |
| 1733 | syncBuf += ");"; |
| 1734 | |
| 1735 | buf += syncBuf; |
| 1736 | buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n"; |
| 1737 | buf += "}\n"; |
| 1738 | buf += "}"; |
| 1739 | |
| 1740 | ReplaceText(lastCurlyLoc, 1, buf); |
| 1741 | |
| 1742 | bool hasReturns = false; |
| 1743 | HasReturnStmts(S->getSynchBody(), hasReturns); |
| 1744 | if (hasReturns) |
| 1745 | RewriteSyncReturnStmts(S->getSynchBody(), syncBuf); |
| 1746 | |
| 1747 | return 0; |
| 1748 | } |
| 1749 | |
| 1750 | void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) |
| 1751 | { |
| 1752 | // Perform a bottom up traversal of all children. |
| 1753 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 1754 | if (*CI) |
| 1755 | WarnAboutReturnGotoStmts(*CI); |
| 1756 | |
| 1757 | if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { |
| 1758 | Diags.Report(Context->getFullLoc(S->getLocStart()), |
| 1759 | TryFinallyContainsReturnDiag); |
| 1760 | } |
| 1761 | return; |
| 1762 | } |
| 1763 | |
| 1764 | void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns) |
| 1765 | { |
| 1766 | // Perform a bottom up traversal of all children. |
| 1767 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 1768 | if (*CI) |
| 1769 | HasReturnStmts(*CI, hasReturns); |
| 1770 | |
| 1771 | if (isa<ReturnStmt>(S)) |
| 1772 | hasReturns = true; |
| 1773 | return; |
| 1774 | } |
| 1775 | |
| 1776 | void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) { |
| 1777 | // Perform a bottom up traversal of all children. |
| 1778 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 1779 | if (*CI) { |
| 1780 | RewriteTryReturnStmts(*CI); |
| 1781 | } |
| 1782 | if (isa<ReturnStmt>(S)) { |
| 1783 | SourceLocation startLoc = S->getLocStart(); |
| 1784 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1785 | |
| 1786 | const char *semiBuf = strchr(startBuf, ';'); |
| 1787 | assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'"); |
| 1788 | SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| 1789 | |
| 1790 | std::string buf; |
| 1791 | buf = "{ objc_exception_try_exit(&_stack); return"; |
| 1792 | |
| 1793 | ReplaceText(startLoc, 6, buf); |
| 1794 | InsertText(onePastSemiLoc, "}"); |
| 1795 | } |
| 1796 | return; |
| 1797 | } |
| 1798 | |
| 1799 | void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) { |
| 1800 | // Perform a bottom up traversal of all children. |
| 1801 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 1802 | if (*CI) { |
| 1803 | RewriteSyncReturnStmts(*CI, syncExitBuf); |
| 1804 | } |
| 1805 | if (isa<ReturnStmt>(S)) { |
| 1806 | SourceLocation startLoc = S->getLocStart(); |
| 1807 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1808 | |
| 1809 | const char *semiBuf = strchr(startBuf, ';'); |
| 1810 | assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'"); |
| 1811 | SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); |
| 1812 | |
| 1813 | std::string buf; |
| 1814 | buf = "{ objc_exception_try_exit(&_stack);"; |
| 1815 | buf += syncExitBuf; |
| 1816 | buf += " return"; |
| 1817 | |
| 1818 | ReplaceText(startLoc, 6, buf); |
| 1819 | InsertText(onePastSemiLoc, "}"); |
| 1820 | } |
| 1821 | return; |
| 1822 | } |
| 1823 | |
| 1824 | Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { |
| 1825 | // Get the start location and compute the semi location. |
| 1826 | SourceLocation startLoc = S->getLocStart(); |
| 1827 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1828 | |
| 1829 | assert((*startBuf == '@') && "bogus @try location"); |
Fariborz Jahanian | c38503b | 2012-03-12 23:58:28 +0000 | [diff] [blame] | 1830 | // @try -> try |
| 1831 | ReplaceText(startLoc, 1, ""); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1832 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1833 | for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) { |
| 1834 | ObjCAtCatchStmt *Catch = S->getCatchStmt(I); |
Fariborz Jahanian | c38503b | 2012-03-12 23:58:28 +0000 | [diff] [blame] | 1835 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1836 | startLoc = Catch->getLocStart(); |
| 1837 | startBuf = SM->getCharacterData(startLoc); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1838 | assert((*startBuf == '@') && "bogus @catch location"); |
Fariborz Jahanian | c38503b | 2012-03-12 23:58:28 +0000 | [diff] [blame] | 1839 | // @catch -> catch |
| 1840 | ReplaceText(startLoc, 1, ""); |
| 1841 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1842 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1843 | return 0; |
| 1844 | } |
| 1845 | |
| 1846 | // This can't be done with ReplaceStmt(S, ThrowExpr), since |
| 1847 | // the throw expression is typically a message expression that's already |
| 1848 | // been rewritten! (which implies the SourceLocation's are invalid). |
| 1849 | Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { |
| 1850 | // Get the start location and compute the semi location. |
| 1851 | SourceLocation startLoc = S->getLocStart(); |
| 1852 | const char *startBuf = SM->getCharacterData(startLoc); |
| 1853 | |
| 1854 | assert((*startBuf == '@') && "bogus @throw location"); |
| 1855 | |
| 1856 | std::string buf; |
| 1857 | /* void objc_exception_throw(id) __attribute__((noreturn)); */ |
| 1858 | if (S->getThrowExpr()) |
| 1859 | buf = "objc_exception_throw("; |
| 1860 | else // add an implicit argument |
| 1861 | buf = "objc_exception_throw(_caught"; |
| 1862 | |
| 1863 | // handle "@ throw" correctly. |
| 1864 | const char *wBuf = strchr(startBuf, 'w'); |
| 1865 | assert((*wBuf == 'w') && "@throw: can't find 'w'"); |
| 1866 | ReplaceText(startLoc, wBuf-startBuf+1, buf); |
| 1867 | |
| 1868 | const char *semiBuf = strchr(startBuf, ';'); |
| 1869 | assert((*semiBuf == ';') && "@throw: can't find ';'"); |
| 1870 | SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf); |
| 1871 | ReplaceText(semiLoc, 1, ");"); |
| 1872 | return 0; |
| 1873 | } |
| 1874 | |
| 1875 | Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { |
| 1876 | // Create a new string expression. |
| 1877 | QualType StrType = Context->getPointerType(Context->CharTy); |
| 1878 | std::string StrEncoding; |
| 1879 | Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); |
| 1880 | Expr *Replacement = StringLiteral::Create(*Context, StrEncoding, |
| 1881 | StringLiteral::Ascii, false, |
| 1882 | StrType, SourceLocation()); |
| 1883 | ReplaceStmt(Exp, Replacement); |
| 1884 | |
| 1885 | // Replace this subexpr in the parent. |
| 1886 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 1887 | return Replacement; |
| 1888 | } |
| 1889 | |
| 1890 | Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { |
| 1891 | if (!SelGetUidFunctionDecl) |
| 1892 | SynthSelGetUidFunctionDecl(); |
| 1893 | assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); |
| 1894 | // Create a call to sel_registerName("selName"). |
| 1895 | SmallVector<Expr*, 8> SelExprs; |
| 1896 | QualType argType = Context->getPointerType(Context->CharTy); |
| 1897 | SelExprs.push_back(StringLiteral::Create(*Context, |
| 1898 | Exp->getSelector().getAsString(), |
| 1899 | StringLiteral::Ascii, false, |
| 1900 | argType, SourceLocation())); |
| 1901 | CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, |
| 1902 | &SelExprs[0], SelExprs.size()); |
| 1903 | ReplaceStmt(Exp, SelExp); |
| 1904 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 1905 | return SelExp; |
| 1906 | } |
| 1907 | |
| 1908 | CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl( |
| 1909 | FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc, |
| 1910 | SourceLocation EndLoc) { |
| 1911 | // Get the type, we will need to reference it in a couple spots. |
| 1912 | QualType msgSendType = FD->getType(); |
| 1913 | |
| 1914 | // Create a reference to the objc_msgSend() declaration. |
| 1915 | DeclRefExpr *DRE = |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 1916 | new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 1917 | |
| 1918 | // Now, we cast the reference to a pointer to the objc_msgSend type. |
| 1919 | QualType pToFunc = Context->getPointerType(msgSendType); |
| 1920 | ImplicitCastExpr *ICE = |
| 1921 | ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, |
| 1922 | DRE, 0, VK_RValue); |
| 1923 | |
| 1924 | const FunctionType *FT = msgSendType->getAs<FunctionType>(); |
| 1925 | |
| 1926 | CallExpr *Exp = |
| 1927 | new (Context) CallExpr(*Context, ICE, args, nargs, |
| 1928 | FT->getCallResultType(*Context), |
| 1929 | VK_RValue, EndLoc); |
| 1930 | return Exp; |
| 1931 | } |
| 1932 | |
| 1933 | static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, |
| 1934 | const char *&startRef, const char *&endRef) { |
| 1935 | while (startBuf < endBuf) { |
| 1936 | if (*startBuf == '<') |
| 1937 | startRef = startBuf; // mark the start. |
| 1938 | if (*startBuf == '>') { |
| 1939 | if (startRef && *startRef == '<') { |
| 1940 | endRef = startBuf; // mark the end. |
| 1941 | return true; |
| 1942 | } |
| 1943 | return false; |
| 1944 | } |
| 1945 | startBuf++; |
| 1946 | } |
| 1947 | return false; |
| 1948 | } |
| 1949 | |
| 1950 | static void scanToNextArgument(const char *&argRef) { |
| 1951 | int angle = 0; |
| 1952 | while (*argRef != ')' && (*argRef != ',' || angle > 0)) { |
| 1953 | if (*argRef == '<') |
| 1954 | angle++; |
| 1955 | else if (*argRef == '>') |
| 1956 | angle--; |
| 1957 | argRef++; |
| 1958 | } |
| 1959 | assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); |
| 1960 | } |
| 1961 | |
| 1962 | bool RewriteModernObjC::needToScanForQualifiers(QualType T) { |
| 1963 | if (T->isObjCQualifiedIdType()) |
| 1964 | return true; |
| 1965 | if (const PointerType *PT = T->getAs<PointerType>()) { |
| 1966 | if (PT->getPointeeType()->isObjCQualifiedIdType()) |
| 1967 | return true; |
| 1968 | } |
| 1969 | if (T->isObjCObjectPointerType()) { |
| 1970 | T = T->getPointeeType(); |
| 1971 | return T->isObjCQualifiedInterfaceType(); |
| 1972 | } |
| 1973 | if (T->isArrayType()) { |
| 1974 | QualType ElemTy = Context->getBaseElementType(T); |
| 1975 | return needToScanForQualifiers(ElemTy); |
| 1976 | } |
| 1977 | return false; |
| 1978 | } |
| 1979 | |
| 1980 | void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { |
| 1981 | QualType Type = E->getType(); |
| 1982 | if (needToScanForQualifiers(Type)) { |
| 1983 | SourceLocation Loc, EndLoc; |
| 1984 | |
| 1985 | if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { |
| 1986 | Loc = ECE->getLParenLoc(); |
| 1987 | EndLoc = ECE->getRParenLoc(); |
| 1988 | } else { |
| 1989 | Loc = E->getLocStart(); |
| 1990 | EndLoc = E->getLocEnd(); |
| 1991 | } |
| 1992 | // This will defend against trying to rewrite synthesized expressions. |
| 1993 | if (Loc.isInvalid() || EndLoc.isInvalid()) |
| 1994 | return; |
| 1995 | |
| 1996 | const char *startBuf = SM->getCharacterData(Loc); |
| 1997 | const char *endBuf = SM->getCharacterData(EndLoc); |
| 1998 | const char *startRef = 0, *endRef = 0; |
| 1999 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2000 | // Get the locations of the startRef, endRef. |
| 2001 | SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf); |
| 2002 | SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1); |
| 2003 | // Comment out the protocol references. |
| 2004 | InsertText(LessLoc, "/*"); |
| 2005 | InsertText(GreaterLoc, "*/"); |
| 2006 | } |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { |
| 2011 | SourceLocation Loc; |
| 2012 | QualType Type; |
| 2013 | const FunctionProtoType *proto = 0; |
| 2014 | if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { |
| 2015 | Loc = VD->getLocation(); |
| 2016 | Type = VD->getType(); |
| 2017 | } |
| 2018 | else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { |
| 2019 | Loc = FD->getLocation(); |
| 2020 | // Check for ObjC 'id' and class types that have been adorned with protocol |
| 2021 | // information (id<p>, C<p>*). The protocol references need to be rewritten! |
| 2022 | const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| 2023 | assert(funcType && "missing function type"); |
| 2024 | proto = dyn_cast<FunctionProtoType>(funcType); |
| 2025 | if (!proto) |
| 2026 | return; |
| 2027 | Type = proto->getResultType(); |
| 2028 | } |
| 2029 | else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { |
| 2030 | Loc = FD->getLocation(); |
| 2031 | Type = FD->getType(); |
| 2032 | } |
| 2033 | else |
| 2034 | return; |
| 2035 | |
| 2036 | if (needToScanForQualifiers(Type)) { |
| 2037 | // Since types are unique, we need to scan the buffer. |
| 2038 | |
| 2039 | const char *endBuf = SM->getCharacterData(Loc); |
| 2040 | const char *startBuf = endBuf; |
| 2041 | while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) |
| 2042 | startBuf--; // scan backward (from the decl location) for return type. |
| 2043 | const char *startRef = 0, *endRef = 0; |
| 2044 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2045 | // Get the locations of the startRef, endRef. |
| 2046 | SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf); |
| 2047 | SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1); |
| 2048 | // Comment out the protocol references. |
| 2049 | InsertText(LessLoc, "/*"); |
| 2050 | InsertText(GreaterLoc, "*/"); |
| 2051 | } |
| 2052 | } |
| 2053 | if (!proto) |
| 2054 | return; // most likely, was a variable |
| 2055 | // Now check arguments. |
| 2056 | const char *startBuf = SM->getCharacterData(Loc); |
| 2057 | const char *startFuncBuf = startBuf; |
| 2058 | for (unsigned i = 0; i < proto->getNumArgs(); i++) { |
| 2059 | if (needToScanForQualifiers(proto->getArgType(i))) { |
| 2060 | // Since types are unique, we need to scan the buffer. |
| 2061 | |
| 2062 | const char *endBuf = startBuf; |
| 2063 | // scan forward (from the decl location) for argument types. |
| 2064 | scanToNextArgument(endBuf); |
| 2065 | const char *startRef = 0, *endRef = 0; |
| 2066 | if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { |
| 2067 | // Get the locations of the startRef, endRef. |
| 2068 | SourceLocation LessLoc = |
| 2069 | Loc.getLocWithOffset(startRef-startFuncBuf); |
| 2070 | SourceLocation GreaterLoc = |
| 2071 | Loc.getLocWithOffset(endRef-startFuncBuf+1); |
| 2072 | // Comment out the protocol references. |
| 2073 | InsertText(LessLoc, "/*"); |
| 2074 | InsertText(GreaterLoc, "*/"); |
| 2075 | } |
| 2076 | startBuf = ++endBuf; |
| 2077 | } |
| 2078 | else { |
| 2079 | // If the function name is derived from a macro expansion, then the |
| 2080 | // argument buffer will not follow the name. Need to speak with Chris. |
| 2081 | while (*startBuf && *startBuf != ')' && *startBuf != ',') |
| 2082 | startBuf++; // scan forward (from the decl location) for argument types. |
| 2083 | startBuf++; |
| 2084 | } |
| 2085 | } |
| 2086 | } |
| 2087 | |
| 2088 | void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) { |
| 2089 | QualType QT = ND->getType(); |
| 2090 | const Type* TypePtr = QT->getAs<Type>(); |
| 2091 | if (!isa<TypeOfExprType>(TypePtr)) |
| 2092 | return; |
| 2093 | while (isa<TypeOfExprType>(TypePtr)) { |
| 2094 | const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); |
| 2095 | QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); |
| 2096 | TypePtr = QT->getAs<Type>(); |
| 2097 | } |
| 2098 | // FIXME. This will not work for multiple declarators; as in: |
| 2099 | // __typeof__(a) b,c,d; |
| 2100 | std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy())); |
| 2101 | SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); |
| 2102 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 2103 | if (ND->getInit()) { |
| 2104 | std::string Name(ND->getNameAsString()); |
| 2105 | TypeAsString += " " + Name + " = "; |
| 2106 | Expr *E = ND->getInit(); |
| 2107 | SourceLocation startLoc; |
| 2108 | if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) |
| 2109 | startLoc = ECE->getLParenLoc(); |
| 2110 | else |
| 2111 | startLoc = E->getLocStart(); |
| 2112 | startLoc = SM->getExpansionLoc(startLoc); |
| 2113 | const char *endBuf = SM->getCharacterData(startLoc); |
| 2114 | ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); |
| 2115 | } |
| 2116 | else { |
| 2117 | SourceLocation X = ND->getLocEnd(); |
| 2118 | X = SM->getExpansionLoc(X); |
| 2119 | const char *endBuf = SM->getCharacterData(X); |
| 2120 | ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); |
| 2121 | } |
| 2122 | } |
| 2123 | |
| 2124 | // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); |
| 2125 | void RewriteModernObjC::SynthSelGetUidFunctionDecl() { |
| 2126 | IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); |
| 2127 | SmallVector<QualType, 16> ArgTys; |
| 2128 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2129 | QualType getFuncType = |
| 2130 | getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size()); |
| 2131 | SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2132 | SourceLocation(), |
| 2133 | SourceLocation(), |
| 2134 | SelGetUidIdent, getFuncType, 0, |
| 2135 | SC_Extern, |
| 2136 | SC_None, false); |
| 2137 | } |
| 2138 | |
| 2139 | void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) { |
| 2140 | // declared in <objc/objc.h> |
| 2141 | if (FD->getIdentifier() && |
| 2142 | FD->getName() == "sel_registerName") { |
| 2143 | SelGetUidFunctionDecl = FD; |
| 2144 | return; |
| 2145 | } |
| 2146 | RewriteObjCQualifiedInterfaceTypes(FD); |
| 2147 | } |
| 2148 | |
| 2149 | void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) { |
| 2150 | std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); |
| 2151 | const char *argPtr = TypeString.c_str(); |
| 2152 | if (!strchr(argPtr, '^')) { |
| 2153 | Str += TypeString; |
| 2154 | return; |
| 2155 | } |
| 2156 | while (*argPtr) { |
| 2157 | Str += (*argPtr == '^' ? '*' : *argPtr); |
| 2158 | argPtr++; |
| 2159 | } |
| 2160 | } |
| 2161 | |
| 2162 | // FIXME. Consolidate this routine with RewriteBlockPointerType. |
| 2163 | void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str, |
| 2164 | ValueDecl *VD) { |
| 2165 | QualType Type = VD->getType(); |
| 2166 | std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); |
| 2167 | const char *argPtr = TypeString.c_str(); |
| 2168 | int paren = 0; |
| 2169 | while (*argPtr) { |
| 2170 | switch (*argPtr) { |
| 2171 | case '(': |
| 2172 | Str += *argPtr; |
| 2173 | paren++; |
| 2174 | break; |
| 2175 | case ')': |
| 2176 | Str += *argPtr; |
| 2177 | paren--; |
| 2178 | break; |
| 2179 | case '^': |
| 2180 | Str += '*'; |
| 2181 | if (paren == 1) |
| 2182 | Str += VD->getNameAsString(); |
| 2183 | break; |
| 2184 | default: |
| 2185 | Str += *argPtr; |
| 2186 | break; |
| 2187 | } |
| 2188 | argPtr++; |
| 2189 | } |
| 2190 | } |
| 2191 | |
| 2192 | |
| 2193 | void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { |
| 2194 | SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
| 2195 | const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); |
| 2196 | const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType); |
| 2197 | if (!proto) |
| 2198 | return; |
| 2199 | QualType Type = proto->getResultType(); |
| 2200 | std::string FdStr = Type.getAsString(Context->getPrintingPolicy()); |
| 2201 | FdStr += " "; |
| 2202 | FdStr += FD->getName(); |
| 2203 | FdStr += "("; |
| 2204 | unsigned numArgs = proto->getNumArgs(); |
| 2205 | for (unsigned i = 0; i < numArgs; i++) { |
| 2206 | QualType ArgType = proto->getArgType(i); |
| 2207 | RewriteBlockPointerType(FdStr, ArgType); |
| 2208 | if (i+1 < numArgs) |
| 2209 | FdStr += ", "; |
| 2210 | } |
| 2211 | FdStr += ");\n"; |
| 2212 | InsertText(FunLocStart, FdStr); |
| 2213 | CurFunctionDeclToDeclareForBlock = 0; |
| 2214 | } |
| 2215 | |
| 2216 | // SynthSuperContructorFunctionDecl - id objc_super(id obj, id super); |
| 2217 | void RewriteModernObjC::SynthSuperContructorFunctionDecl() { |
| 2218 | if (SuperContructorFunctionDecl) |
| 2219 | return; |
| 2220 | IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); |
| 2221 | SmallVector<QualType, 16> ArgTys; |
| 2222 | QualType argT = Context->getObjCIdType(); |
| 2223 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2224 | ArgTys.push_back(argT); |
| 2225 | ArgTys.push_back(argT); |
| 2226 | QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2227 | &ArgTys[0], ArgTys.size()); |
| 2228 | SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2229 | SourceLocation(), |
| 2230 | SourceLocation(), |
| 2231 | msgSendIdent, msgSendType, 0, |
| 2232 | SC_Extern, |
| 2233 | SC_None, false); |
| 2234 | } |
| 2235 | |
| 2236 | // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); |
| 2237 | void RewriteModernObjC::SynthMsgSendFunctionDecl() { |
| 2238 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); |
| 2239 | SmallVector<QualType, 16> ArgTys; |
| 2240 | QualType argT = Context->getObjCIdType(); |
| 2241 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2242 | ArgTys.push_back(argT); |
| 2243 | argT = Context->getObjCSelType(); |
| 2244 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2245 | ArgTys.push_back(argT); |
| 2246 | QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2247 | &ArgTys[0], ArgTys.size(), |
| 2248 | true /*isVariadic*/); |
| 2249 | MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2250 | SourceLocation(), |
| 2251 | SourceLocation(), |
| 2252 | msgSendIdent, msgSendType, 0, |
| 2253 | SC_Extern, |
| 2254 | SC_None, false); |
| 2255 | } |
| 2256 | |
| 2257 | // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...); |
| 2258 | void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() { |
| 2259 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); |
| 2260 | SmallVector<QualType, 16> ArgTys; |
| 2261 | RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 2262 | SourceLocation(), SourceLocation(), |
| 2263 | &Context->Idents.get("objc_super")); |
| 2264 | QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 2265 | assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| 2266 | ArgTys.push_back(argT); |
| 2267 | argT = Context->getObjCSelType(); |
| 2268 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2269 | ArgTys.push_back(argT); |
| 2270 | QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2271 | &ArgTys[0], ArgTys.size(), |
| 2272 | true /*isVariadic*/); |
| 2273 | MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2274 | SourceLocation(), |
| 2275 | SourceLocation(), |
| 2276 | msgSendIdent, msgSendType, 0, |
| 2277 | SC_Extern, |
| 2278 | SC_None, false); |
| 2279 | } |
| 2280 | |
| 2281 | // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); |
| 2282 | void RewriteModernObjC::SynthMsgSendStretFunctionDecl() { |
| 2283 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); |
| 2284 | SmallVector<QualType, 16> ArgTys; |
| 2285 | QualType argT = Context->getObjCIdType(); |
| 2286 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2287 | ArgTys.push_back(argT); |
| 2288 | argT = Context->getObjCSelType(); |
| 2289 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2290 | ArgTys.push_back(argT); |
| 2291 | QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2292 | &ArgTys[0], ArgTys.size(), |
| 2293 | true /*isVariadic*/); |
| 2294 | MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2295 | SourceLocation(), |
| 2296 | SourceLocation(), |
| 2297 | msgSendIdent, msgSendType, 0, |
| 2298 | SC_Extern, |
| 2299 | SC_None, false); |
| 2300 | } |
| 2301 | |
| 2302 | // SynthMsgSendSuperStretFunctionDecl - |
| 2303 | // id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...); |
| 2304 | void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() { |
| 2305 | IdentifierInfo *msgSendIdent = |
| 2306 | &Context->Idents.get("objc_msgSendSuper_stret"); |
| 2307 | SmallVector<QualType, 16> ArgTys; |
| 2308 | RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 2309 | SourceLocation(), SourceLocation(), |
| 2310 | &Context->Idents.get("objc_super")); |
| 2311 | QualType argT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 2312 | assert(!argT.isNull() && "Can't build 'struct objc_super *' type"); |
| 2313 | ArgTys.push_back(argT); |
| 2314 | argT = Context->getObjCSelType(); |
| 2315 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2316 | ArgTys.push_back(argT); |
| 2317 | QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2318 | &ArgTys[0], ArgTys.size(), |
| 2319 | true /*isVariadic*/); |
| 2320 | MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2321 | SourceLocation(), |
| 2322 | SourceLocation(), |
| 2323 | msgSendIdent, msgSendType, 0, |
| 2324 | SC_Extern, |
| 2325 | SC_None, false); |
| 2326 | } |
| 2327 | |
| 2328 | // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); |
| 2329 | void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() { |
| 2330 | IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); |
| 2331 | SmallVector<QualType, 16> ArgTys; |
| 2332 | QualType argT = Context->getObjCIdType(); |
| 2333 | assert(!argT.isNull() && "Can't find 'id' type"); |
| 2334 | ArgTys.push_back(argT); |
| 2335 | argT = Context->getObjCSelType(); |
| 2336 | assert(!argT.isNull() && "Can't find 'SEL' type"); |
| 2337 | ArgTys.push_back(argT); |
| 2338 | QualType msgSendType = getSimpleFunctionType(Context->DoubleTy, |
| 2339 | &ArgTys[0], ArgTys.size(), |
| 2340 | true /*isVariadic*/); |
| 2341 | MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2342 | SourceLocation(), |
| 2343 | SourceLocation(), |
| 2344 | msgSendIdent, msgSendType, 0, |
| 2345 | SC_Extern, |
| 2346 | SC_None, false); |
| 2347 | } |
| 2348 | |
| 2349 | // SynthGetClassFunctionDecl - id objc_getClass(const char *name); |
| 2350 | void RewriteModernObjC::SynthGetClassFunctionDecl() { |
| 2351 | IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); |
| 2352 | SmallVector<QualType, 16> ArgTys; |
| 2353 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2354 | QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2355 | &ArgTys[0], ArgTys.size()); |
| 2356 | GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2357 | SourceLocation(), |
| 2358 | SourceLocation(), |
| 2359 | getClassIdent, getClassType, 0, |
| 2360 | SC_Extern, |
| 2361 | SC_None, false); |
| 2362 | } |
| 2363 | |
| 2364 | // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); |
| 2365 | void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { |
| 2366 | IdentifierInfo *getSuperClassIdent = |
| 2367 | &Context->Idents.get("class_getSuperclass"); |
| 2368 | SmallVector<QualType, 16> ArgTys; |
| 2369 | ArgTys.push_back(Context->getObjCClassType()); |
| 2370 | QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), |
| 2371 | &ArgTys[0], ArgTys.size()); |
| 2372 | GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2373 | SourceLocation(), |
| 2374 | SourceLocation(), |
| 2375 | getSuperClassIdent, |
| 2376 | getClassType, 0, |
| 2377 | SC_Extern, |
| 2378 | SC_None, |
| 2379 | false); |
| 2380 | } |
| 2381 | |
| 2382 | // SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name); |
| 2383 | void RewriteModernObjC::SynthGetMetaClassFunctionDecl() { |
| 2384 | IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); |
| 2385 | SmallVector<QualType, 16> ArgTys; |
| 2386 | ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); |
| 2387 | QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(), |
| 2388 | &ArgTys[0], ArgTys.size()); |
| 2389 | GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, |
| 2390 | SourceLocation(), |
| 2391 | SourceLocation(), |
| 2392 | getClassIdent, getClassType, 0, |
| 2393 | SC_Extern, |
| 2394 | SC_None, false); |
| 2395 | } |
| 2396 | |
| 2397 | Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { |
| 2398 | QualType strType = getConstantStringStructType(); |
| 2399 | |
| 2400 | std::string S = "__NSConstantStringImpl_"; |
| 2401 | |
| 2402 | std::string tmpName = InFileName; |
| 2403 | unsigned i; |
| 2404 | for (i=0; i < tmpName.length(); i++) { |
| 2405 | char c = tmpName.at(i); |
| 2406 | // replace any non alphanumeric characters with '_'. |
| 2407 | if (!isalpha(c) && (c < '0' || c > '9')) |
| 2408 | tmpName[i] = '_'; |
| 2409 | } |
| 2410 | S += tmpName; |
| 2411 | S += "_"; |
| 2412 | S += utostr(NumObjCStringLiterals++); |
| 2413 | |
| 2414 | Preamble += "static __NSConstantStringImpl " + S; |
| 2415 | Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; |
| 2416 | Preamble += "0x000007c8,"; // utf8_str |
| 2417 | // The pretty printer for StringLiteral handles escape characters properly. |
| 2418 | std::string prettyBufS; |
| 2419 | llvm::raw_string_ostream prettyBuf(prettyBufS); |
| 2420 | Exp->getString()->printPretty(prettyBuf, *Context, 0, |
| 2421 | PrintingPolicy(LangOpts)); |
| 2422 | Preamble += prettyBuf.str(); |
| 2423 | Preamble += ","; |
| 2424 | Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; |
| 2425 | |
| 2426 | VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 2427 | SourceLocation(), &Context->Idents.get(S), |
| 2428 | strType, 0, SC_Static, SC_None); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2429 | DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2430 | SourceLocation()); |
| 2431 | Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf, |
| 2432 | Context->getPointerType(DRE->getType()), |
| 2433 | VK_RValue, OK_Ordinary, |
| 2434 | SourceLocation()); |
| 2435 | // cast to NSConstantString * |
| 2436 | CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), |
| 2437 | CK_CPointerToObjCPointerCast, Unop); |
| 2438 | ReplaceStmt(Exp, cast); |
| 2439 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 2440 | return cast; |
| 2441 | } |
| 2442 | |
| 2443 | // struct objc_super { struct objc_object *receiver; struct objc_class *super; }; |
| 2444 | QualType RewriteModernObjC::getSuperStructType() { |
| 2445 | if (!SuperStructDecl) { |
| 2446 | SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 2447 | SourceLocation(), SourceLocation(), |
| 2448 | &Context->Idents.get("objc_super")); |
| 2449 | QualType FieldTypes[2]; |
| 2450 | |
| 2451 | // struct objc_object *receiver; |
| 2452 | FieldTypes[0] = Context->getObjCIdType(); |
| 2453 | // struct objc_class *super; |
| 2454 | FieldTypes[1] = Context->getObjCClassType(); |
| 2455 | |
| 2456 | // Create fields |
| 2457 | for (unsigned i = 0; i < 2; ++i) { |
| 2458 | SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, |
| 2459 | SourceLocation(), |
| 2460 | SourceLocation(), 0, |
| 2461 | FieldTypes[i], 0, |
| 2462 | /*BitWidth=*/0, |
| 2463 | /*Mutable=*/false, |
| 2464 | /*HasInit=*/false)); |
| 2465 | } |
| 2466 | |
| 2467 | SuperStructDecl->completeDefinition(); |
| 2468 | } |
| 2469 | return Context->getTagDeclType(SuperStructDecl); |
| 2470 | } |
| 2471 | |
| 2472 | QualType RewriteModernObjC::getConstantStringStructType() { |
| 2473 | if (!ConstantStringDecl) { |
| 2474 | ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 2475 | SourceLocation(), SourceLocation(), |
| 2476 | &Context->Idents.get("__NSConstantStringImpl")); |
| 2477 | QualType FieldTypes[4]; |
| 2478 | |
| 2479 | // struct objc_object *receiver; |
| 2480 | FieldTypes[0] = Context->getObjCIdType(); |
| 2481 | // int flags; |
| 2482 | FieldTypes[1] = Context->IntTy; |
| 2483 | // char *str; |
| 2484 | FieldTypes[2] = Context->getPointerType(Context->CharTy); |
| 2485 | // long length; |
| 2486 | FieldTypes[3] = Context->LongTy; |
| 2487 | |
| 2488 | // Create fields |
| 2489 | for (unsigned i = 0; i < 4; ++i) { |
| 2490 | ConstantStringDecl->addDecl(FieldDecl::Create(*Context, |
| 2491 | ConstantStringDecl, |
| 2492 | SourceLocation(), |
| 2493 | SourceLocation(), 0, |
| 2494 | FieldTypes[i], 0, |
| 2495 | /*BitWidth=*/0, |
| 2496 | /*Mutable=*/true, |
| 2497 | /*HasInit=*/false)); |
| 2498 | } |
| 2499 | |
| 2500 | ConstantStringDecl->completeDefinition(); |
| 2501 | } |
| 2502 | return Context->getTagDeclType(ConstantStringDecl); |
| 2503 | } |
| 2504 | |
| 2505 | Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, |
| 2506 | SourceLocation StartLoc, |
| 2507 | SourceLocation EndLoc) { |
| 2508 | if (!SelGetUidFunctionDecl) |
| 2509 | SynthSelGetUidFunctionDecl(); |
| 2510 | if (!MsgSendFunctionDecl) |
| 2511 | SynthMsgSendFunctionDecl(); |
| 2512 | if (!MsgSendSuperFunctionDecl) |
| 2513 | SynthMsgSendSuperFunctionDecl(); |
| 2514 | if (!MsgSendStretFunctionDecl) |
| 2515 | SynthMsgSendStretFunctionDecl(); |
| 2516 | if (!MsgSendSuperStretFunctionDecl) |
| 2517 | SynthMsgSendSuperStretFunctionDecl(); |
| 2518 | if (!MsgSendFpretFunctionDecl) |
| 2519 | SynthMsgSendFpretFunctionDecl(); |
| 2520 | if (!GetClassFunctionDecl) |
| 2521 | SynthGetClassFunctionDecl(); |
| 2522 | if (!GetSuperClassFunctionDecl) |
| 2523 | SynthGetSuperClassFunctionDecl(); |
| 2524 | if (!GetMetaClassFunctionDecl) |
| 2525 | SynthGetMetaClassFunctionDecl(); |
| 2526 | |
| 2527 | // default to objc_msgSend(). |
| 2528 | FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; |
| 2529 | // May need to use objc_msgSend_stret() as well. |
| 2530 | FunctionDecl *MsgSendStretFlavor = 0; |
| 2531 | if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { |
| 2532 | QualType resultType = mDecl->getResultType(); |
| 2533 | if (resultType->isRecordType()) |
| 2534 | MsgSendStretFlavor = MsgSendStretFunctionDecl; |
| 2535 | else if (resultType->isRealFloatingType()) |
| 2536 | MsgSendFlavor = MsgSendFpretFunctionDecl; |
| 2537 | } |
| 2538 | |
| 2539 | // Synthesize a call to objc_msgSend(). |
| 2540 | SmallVector<Expr*, 8> MsgExprs; |
| 2541 | switch (Exp->getReceiverKind()) { |
| 2542 | case ObjCMessageExpr::SuperClass: { |
| 2543 | MsgSendFlavor = MsgSendSuperFunctionDecl; |
| 2544 | if (MsgSendStretFlavor) |
| 2545 | MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; |
| 2546 | assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); |
| 2547 | |
| 2548 | ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); |
| 2549 | |
| 2550 | SmallVector<Expr*, 4> InitExprs; |
| 2551 | |
| 2552 | // set the receiver to self, the first argument to all methods. |
| 2553 | InitExprs.push_back( |
| 2554 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2555 | CK_BitCast, |
| 2556 | new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2557 | false, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2558 | Context->getObjCIdType(), |
| 2559 | VK_RValue, |
| 2560 | SourceLocation())) |
| 2561 | ); // set the 'receiver'. |
| 2562 | |
| 2563 | // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) |
| 2564 | SmallVector<Expr*, 8> ClsExprs; |
| 2565 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2566 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2567 | ClassDecl->getIdentifier()->getName(), |
| 2568 | StringLiteral::Ascii, false, |
| 2569 | argType, SourceLocation())); |
| 2570 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, |
| 2571 | &ClsExprs[0], |
| 2572 | ClsExprs.size(), |
| 2573 | StartLoc, |
| 2574 | EndLoc); |
| 2575 | // (Class)objc_getClass("CurrentClass") |
| 2576 | CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context, |
| 2577 | Context->getObjCClassType(), |
| 2578 | CK_BitCast, Cls); |
| 2579 | ClsExprs.clear(); |
| 2580 | ClsExprs.push_back(ArgExpr); |
| 2581 | Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, |
| 2582 | &ClsExprs[0], ClsExprs.size(), |
| 2583 | StartLoc, EndLoc); |
| 2584 | |
| 2585 | // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) |
| 2586 | // To turn off a warning, type-cast to 'id' |
| 2587 | InitExprs.push_back( // set 'super class', using class_getSuperclass(). |
| 2588 | NoTypeInfoCStyleCastExpr(Context, |
| 2589 | Context->getObjCIdType(), |
| 2590 | CK_BitCast, Cls)); |
| 2591 | // struct objc_super |
| 2592 | QualType superType = getSuperStructType(); |
| 2593 | Expr *SuperRep; |
| 2594 | |
| 2595 | if (LangOpts.MicrosoftExt) { |
| 2596 | SynthSuperContructorFunctionDecl(); |
| 2597 | // Simulate a contructor call... |
| 2598 | DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2599 | false, superType, VK_LValue, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2600 | SourceLocation()); |
| 2601 | SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], |
| 2602 | InitExprs.size(), |
| 2603 | superType, VK_LValue, |
| 2604 | SourceLocation()); |
| 2605 | // The code for super is a little tricky to prevent collision with |
| 2606 | // the structure definition in the header. The rewriter has it's own |
| 2607 | // internal definition (__rw_objc_super) that is uses. This is why |
| 2608 | // we need the cast below. For example: |
| 2609 | // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) |
| 2610 | // |
| 2611 | SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, |
| 2612 | Context->getPointerType(SuperRep->getType()), |
| 2613 | VK_RValue, OK_Ordinary, |
| 2614 | SourceLocation()); |
| 2615 | SuperRep = NoTypeInfoCStyleCastExpr(Context, |
| 2616 | Context->getPointerType(superType), |
| 2617 | CK_BitCast, SuperRep); |
| 2618 | } else { |
| 2619 | // (struct objc_super) { <exprs from above> } |
| 2620 | InitListExpr *ILE = |
| 2621 | new (Context) InitListExpr(*Context, SourceLocation(), |
| 2622 | &InitExprs[0], InitExprs.size(), |
| 2623 | SourceLocation()); |
| 2624 | TypeSourceInfo *superTInfo |
| 2625 | = Context->getTrivialTypeSourceInfo(superType); |
| 2626 | SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, |
| 2627 | superType, VK_LValue, |
| 2628 | ILE, false); |
| 2629 | // struct objc_super * |
| 2630 | SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, |
| 2631 | Context->getPointerType(SuperRep->getType()), |
| 2632 | VK_RValue, OK_Ordinary, |
| 2633 | SourceLocation()); |
| 2634 | } |
| 2635 | MsgExprs.push_back(SuperRep); |
| 2636 | break; |
| 2637 | } |
| 2638 | |
| 2639 | case ObjCMessageExpr::Class: { |
| 2640 | SmallVector<Expr*, 8> ClsExprs; |
| 2641 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2642 | ObjCInterfaceDecl *Class |
| 2643 | = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface(); |
| 2644 | IdentifierInfo *clsName = Class->getIdentifier(); |
| 2645 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2646 | clsName->getName(), |
| 2647 | StringLiteral::Ascii, false, |
| 2648 | argType, SourceLocation())); |
| 2649 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, |
| 2650 | &ClsExprs[0], |
| 2651 | ClsExprs.size(), |
| 2652 | StartLoc, EndLoc); |
| 2653 | MsgExprs.push_back(Cls); |
| 2654 | break; |
| 2655 | } |
| 2656 | |
| 2657 | case ObjCMessageExpr::SuperInstance:{ |
| 2658 | MsgSendFlavor = MsgSendSuperFunctionDecl; |
| 2659 | if (MsgSendStretFlavor) |
| 2660 | MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; |
| 2661 | assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); |
| 2662 | ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); |
| 2663 | SmallVector<Expr*, 4> InitExprs; |
| 2664 | |
| 2665 | InitExprs.push_back( |
| 2666 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2667 | CK_BitCast, |
| 2668 | new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(), |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2669 | false, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2670 | Context->getObjCIdType(), |
| 2671 | VK_RValue, SourceLocation())) |
| 2672 | ); // set the 'receiver'. |
| 2673 | |
| 2674 | // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) |
| 2675 | SmallVector<Expr*, 8> ClsExprs; |
| 2676 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2677 | ClsExprs.push_back(StringLiteral::Create(*Context, |
| 2678 | ClassDecl->getIdentifier()->getName(), |
| 2679 | StringLiteral::Ascii, false, argType, |
| 2680 | SourceLocation())); |
| 2681 | CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, |
| 2682 | &ClsExprs[0], |
| 2683 | ClsExprs.size(), |
| 2684 | StartLoc, EndLoc); |
| 2685 | // (Class)objc_getClass("CurrentClass") |
| 2686 | CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context, |
| 2687 | Context->getObjCClassType(), |
| 2688 | CK_BitCast, Cls); |
| 2689 | ClsExprs.clear(); |
| 2690 | ClsExprs.push_back(ArgExpr); |
| 2691 | Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, |
| 2692 | &ClsExprs[0], ClsExprs.size(), |
| 2693 | StartLoc, EndLoc); |
| 2694 | |
| 2695 | // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) |
| 2696 | // To turn off a warning, type-cast to 'id' |
| 2697 | InitExprs.push_back( |
| 2698 | // set 'super class', using class_getSuperclass(). |
| 2699 | NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2700 | CK_BitCast, Cls)); |
| 2701 | // struct objc_super |
| 2702 | QualType superType = getSuperStructType(); |
| 2703 | Expr *SuperRep; |
| 2704 | |
| 2705 | if (LangOpts.MicrosoftExt) { |
| 2706 | SynthSuperContructorFunctionDecl(); |
| 2707 | // Simulate a contructor call... |
| 2708 | DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2709 | false, superType, VK_LValue, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2710 | SourceLocation()); |
| 2711 | SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], |
| 2712 | InitExprs.size(), |
| 2713 | superType, VK_LValue, SourceLocation()); |
| 2714 | // The code for super is a little tricky to prevent collision with |
| 2715 | // the structure definition in the header. The rewriter has it's own |
| 2716 | // internal definition (__rw_objc_super) that is uses. This is why |
| 2717 | // we need the cast below. For example: |
| 2718 | // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) |
| 2719 | // |
| 2720 | SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf, |
| 2721 | Context->getPointerType(SuperRep->getType()), |
| 2722 | VK_RValue, OK_Ordinary, |
| 2723 | SourceLocation()); |
| 2724 | SuperRep = NoTypeInfoCStyleCastExpr(Context, |
| 2725 | Context->getPointerType(superType), |
| 2726 | CK_BitCast, SuperRep); |
| 2727 | } else { |
| 2728 | // (struct objc_super) { <exprs from above> } |
| 2729 | InitListExpr *ILE = |
| 2730 | new (Context) InitListExpr(*Context, SourceLocation(), |
| 2731 | &InitExprs[0], InitExprs.size(), |
| 2732 | SourceLocation()); |
| 2733 | TypeSourceInfo *superTInfo |
| 2734 | = Context->getTrivialTypeSourceInfo(superType); |
| 2735 | SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, |
| 2736 | superType, VK_RValue, ILE, |
| 2737 | false); |
| 2738 | } |
| 2739 | MsgExprs.push_back(SuperRep); |
| 2740 | break; |
| 2741 | } |
| 2742 | |
| 2743 | case ObjCMessageExpr::Instance: { |
| 2744 | // Remove all type-casts because it may contain objc-style types; e.g. |
| 2745 | // Foo<Proto> *. |
| 2746 | Expr *recExpr = Exp->getInstanceReceiver(); |
| 2747 | while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr)) |
| 2748 | recExpr = CE->getSubExpr(); |
| 2749 | CastKind CK = recExpr->getType()->isObjCObjectPointerType() |
| 2750 | ? CK_BitCast : recExpr->getType()->isBlockPointerType() |
| 2751 | ? CK_BlockPointerToObjCPointerCast |
| 2752 | : CK_CPointerToObjCPointerCast; |
| 2753 | |
| 2754 | recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2755 | CK, recExpr); |
| 2756 | MsgExprs.push_back(recExpr); |
| 2757 | break; |
| 2758 | } |
| 2759 | } |
| 2760 | |
| 2761 | // Create a call to sel_registerName("selName"), it will be the 2nd argument. |
| 2762 | SmallVector<Expr*, 8> SelExprs; |
| 2763 | QualType argType = Context->getPointerType(Context->CharTy); |
| 2764 | SelExprs.push_back(StringLiteral::Create(*Context, |
| 2765 | Exp->getSelector().getAsString(), |
| 2766 | StringLiteral::Ascii, false, |
| 2767 | argType, SourceLocation())); |
| 2768 | CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, |
| 2769 | &SelExprs[0], SelExprs.size(), |
| 2770 | StartLoc, |
| 2771 | EndLoc); |
| 2772 | MsgExprs.push_back(SelExp); |
| 2773 | |
| 2774 | // Now push any user supplied arguments. |
| 2775 | for (unsigned i = 0; i < Exp->getNumArgs(); i++) { |
| 2776 | Expr *userExpr = Exp->getArg(i); |
| 2777 | // Make all implicit casts explicit...ICE comes in handy:-) |
| 2778 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) { |
| 2779 | // Reuse the ICE type, it is exactly what the doctor ordered. |
| 2780 | QualType type = ICE->getType(); |
| 2781 | if (needToScanForQualifiers(type)) |
| 2782 | type = Context->getObjCIdType(); |
| 2783 | // Make sure we convert "type (^)(...)" to "type (*)(...)". |
| 2784 | (void)convertBlockPointerToFunctionPointer(type); |
| 2785 | const Expr *SubExpr = ICE->IgnoreParenImpCasts(); |
| 2786 | CastKind CK; |
| 2787 | if (SubExpr->getType()->isIntegralType(*Context) && |
| 2788 | type->isBooleanType()) { |
| 2789 | CK = CK_IntegralToBoolean; |
| 2790 | } else if (type->isObjCObjectPointerType()) { |
| 2791 | if (SubExpr->getType()->isBlockPointerType()) { |
| 2792 | CK = CK_BlockPointerToObjCPointerCast; |
| 2793 | } else if (SubExpr->getType()->isPointerType()) { |
| 2794 | CK = CK_CPointerToObjCPointerCast; |
| 2795 | } else { |
| 2796 | CK = CK_BitCast; |
| 2797 | } |
| 2798 | } else { |
| 2799 | CK = CK_BitCast; |
| 2800 | } |
| 2801 | |
| 2802 | userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr); |
| 2803 | } |
| 2804 | // Make id<P...> cast into an 'id' cast. |
| 2805 | else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) { |
| 2806 | if (CE->getType()->isObjCQualifiedIdType()) { |
| 2807 | while ((CE = dyn_cast<CStyleCastExpr>(userExpr))) |
| 2808 | userExpr = CE->getSubExpr(); |
| 2809 | CastKind CK; |
| 2810 | if (userExpr->getType()->isIntegralType(*Context)) { |
| 2811 | CK = CK_IntegralToPointer; |
| 2812 | } else if (userExpr->getType()->isBlockPointerType()) { |
| 2813 | CK = CK_BlockPointerToObjCPointerCast; |
| 2814 | } else if (userExpr->getType()->isPointerType()) { |
| 2815 | CK = CK_CPointerToObjCPointerCast; |
| 2816 | } else { |
| 2817 | CK = CK_BitCast; |
| 2818 | } |
| 2819 | userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), |
| 2820 | CK, userExpr); |
| 2821 | } |
| 2822 | } |
| 2823 | MsgExprs.push_back(userExpr); |
| 2824 | // We've transferred the ownership to MsgExprs. For now, we *don't* null |
| 2825 | // out the argument in the original expression (since we aren't deleting |
| 2826 | // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info. |
| 2827 | //Exp->setArg(i, 0); |
| 2828 | } |
| 2829 | // Generate the funky cast. |
| 2830 | CastExpr *cast; |
| 2831 | SmallVector<QualType, 8> ArgTypes; |
| 2832 | QualType returnType; |
| 2833 | |
| 2834 | // Push 'id' and 'SEL', the 2 implicit arguments. |
| 2835 | if (MsgSendFlavor == MsgSendSuperFunctionDecl) |
| 2836 | ArgTypes.push_back(Context->getPointerType(getSuperStructType())); |
| 2837 | else |
| 2838 | ArgTypes.push_back(Context->getObjCIdType()); |
| 2839 | ArgTypes.push_back(Context->getObjCSelType()); |
| 2840 | if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) { |
| 2841 | // Push any user argument types. |
| 2842 | for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), |
| 2843 | E = OMD->param_end(); PI != E; ++PI) { |
| 2844 | QualType t = (*PI)->getType()->isObjCQualifiedIdType() |
| 2845 | ? Context->getObjCIdType() |
| 2846 | : (*PI)->getType(); |
| 2847 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 2848 | (void)convertBlockPointerToFunctionPointer(t); |
| 2849 | ArgTypes.push_back(t); |
| 2850 | } |
| 2851 | returnType = Exp->getType(); |
| 2852 | convertToUnqualifiedObjCType(returnType); |
| 2853 | (void)convertBlockPointerToFunctionPointer(returnType); |
| 2854 | } else { |
| 2855 | returnType = Context->getObjCIdType(); |
| 2856 | } |
| 2857 | // Get the type, we will need to reference it in a couple spots. |
| 2858 | QualType msgSendType = MsgSendFlavor->getType(); |
| 2859 | |
| 2860 | // Create a reference to the objc_msgSend() declaration. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2861 | DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2862 | VK_LValue, SourceLocation()); |
| 2863 | |
| 2864 | // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). |
| 2865 | // If we don't do this cast, we get the following bizarre warning/note: |
| 2866 | // xx.m:13: warning: function called through a non-compatible type |
| 2867 | // xx.m:13: note: if this code is reached, the program will abort |
| 2868 | cast = NoTypeInfoCStyleCastExpr(Context, |
| 2869 | Context->getPointerType(Context->VoidTy), |
| 2870 | CK_BitCast, DRE); |
| 2871 | |
| 2872 | // Now do the "normal" pointer to function cast. |
| 2873 | QualType castType = |
| 2874 | getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(), |
| 2875 | // If we don't have a method decl, force a variadic cast. |
| 2876 | Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true); |
| 2877 | castType = Context->getPointerType(castType); |
| 2878 | cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, |
| 2879 | cast); |
| 2880 | |
| 2881 | // Don't forget the parens to enforce the proper binding. |
| 2882 | ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); |
| 2883 | |
| 2884 | const FunctionType *FT = msgSendType->getAs<FunctionType>(); |
| 2885 | CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], |
| 2886 | MsgExprs.size(), |
| 2887 | FT->getResultType(), VK_RValue, |
| 2888 | EndLoc); |
| 2889 | Stmt *ReplacingStmt = CE; |
| 2890 | if (MsgSendStretFlavor) { |
| 2891 | // We have the method which returns a struct/union. Must also generate |
| 2892 | // call to objc_msgSend_stret and hang both varieties on a conditional |
| 2893 | // expression which dictate which one to envoke depending on size of |
| 2894 | // method's return type. |
| 2895 | |
| 2896 | // Create a reference to the objc_msgSend_stret() declaration. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2897 | DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, |
| 2898 | false, msgSendType, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2899 | VK_LValue, SourceLocation()); |
| 2900 | // Need to cast objc_msgSend_stret to "void *" (see above comment). |
| 2901 | cast = NoTypeInfoCStyleCastExpr(Context, |
| 2902 | Context->getPointerType(Context->VoidTy), |
| 2903 | CK_BitCast, STDRE); |
| 2904 | // Now do the "normal" pointer to function cast. |
| 2905 | castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(), |
| 2906 | Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false); |
| 2907 | castType = Context->getPointerType(castType); |
| 2908 | cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, |
| 2909 | cast); |
| 2910 | |
| 2911 | // Don't forget the parens to enforce the proper binding. |
| 2912 | PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast); |
| 2913 | |
| 2914 | FT = msgSendType->getAs<FunctionType>(); |
| 2915 | CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0], |
| 2916 | MsgExprs.size(), |
| 2917 | FT->getResultType(), VK_RValue, |
| 2918 | SourceLocation()); |
| 2919 | |
| 2920 | // Build sizeof(returnType) |
| 2921 | UnaryExprOrTypeTraitExpr *sizeofExpr = |
| 2922 | new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf, |
| 2923 | Context->getTrivialTypeSourceInfo(returnType), |
| 2924 | Context->getSizeType(), SourceLocation(), |
| 2925 | SourceLocation()); |
| 2926 | // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...)) |
| 2927 | // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases. |
| 2928 | // For X86 it is more complicated and some kind of target specific routine |
| 2929 | // is needed to decide what to do. |
| 2930 | unsigned IntSize = |
| 2931 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 2932 | IntegerLiteral *limit = IntegerLiteral::Create(*Context, |
| 2933 | llvm::APInt(IntSize, 8), |
| 2934 | Context->IntTy, |
| 2935 | SourceLocation()); |
| 2936 | BinaryOperator *lessThanExpr = |
| 2937 | new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy, |
| 2938 | VK_RValue, OK_Ordinary, SourceLocation()); |
| 2939 | // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...)) |
| 2940 | ConditionalOperator *CondExpr = |
| 2941 | new (Context) ConditionalOperator(lessThanExpr, |
| 2942 | SourceLocation(), CE, |
| 2943 | SourceLocation(), STCE, |
| 2944 | returnType, VK_RValue, OK_Ordinary); |
| 2945 | ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), |
| 2946 | CondExpr); |
| 2947 | } |
| 2948 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 2949 | return ReplacingStmt; |
| 2950 | } |
| 2951 | |
| 2952 | Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { |
| 2953 | Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(), |
| 2954 | Exp->getLocEnd()); |
| 2955 | |
| 2956 | // Now do the actual rewrite. |
| 2957 | ReplaceStmt(Exp, ReplacingStmt); |
| 2958 | |
| 2959 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 2960 | return ReplacingStmt; |
| 2961 | } |
| 2962 | |
| 2963 | // typedef struct objc_object Protocol; |
| 2964 | QualType RewriteModernObjC::getProtocolType() { |
| 2965 | if (!ProtocolTypeDecl) { |
| 2966 | TypeSourceInfo *TInfo |
| 2967 | = Context->getTrivialTypeSourceInfo(Context->getObjCIdType()); |
| 2968 | ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, |
| 2969 | SourceLocation(), SourceLocation(), |
| 2970 | &Context->Idents.get("Protocol"), |
| 2971 | TInfo); |
| 2972 | } |
| 2973 | return Context->getTypeDeclType(ProtocolTypeDecl); |
| 2974 | } |
| 2975 | |
| 2976 | /// RewriteObjCProtocolExpr - Rewrite a protocol expression into |
| 2977 | /// a synthesized/forward data reference (to the protocol's metadata). |
| 2978 | /// The forward references (and metadata) are generated in |
| 2979 | /// RewriteModernObjC::HandleTranslationUnit(). |
| 2980 | Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { |
| 2981 | std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString(); |
| 2982 | IdentifierInfo *ID = &Context->Idents.get(Name); |
| 2983 | VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 2984 | SourceLocation(), ID, getProtocolType(), 0, |
| 2985 | SC_Extern, SC_None); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 2986 | DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(), |
| 2987 | VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 2988 | Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf, |
| 2989 | Context->getPointerType(DRE->getType()), |
| 2990 | VK_RValue, OK_Ordinary, SourceLocation()); |
| 2991 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(), |
| 2992 | CK_BitCast, |
| 2993 | DerefExpr); |
| 2994 | ReplaceStmt(Exp, castExpr); |
| 2995 | ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl()); |
| 2996 | // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. |
| 2997 | return castExpr; |
| 2998 | |
| 2999 | } |
| 3000 | |
| 3001 | bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf, |
| 3002 | const char *endBuf) { |
| 3003 | while (startBuf < endBuf) { |
| 3004 | if (*startBuf == '#') { |
| 3005 | // Skip whitespace. |
| 3006 | for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf) |
| 3007 | ; |
| 3008 | if (!strncmp(startBuf, "if", strlen("if")) || |
| 3009 | !strncmp(startBuf, "ifdef", strlen("ifdef")) || |
| 3010 | !strncmp(startBuf, "ifndef", strlen("ifndef")) || |
| 3011 | !strncmp(startBuf, "define", strlen("define")) || |
| 3012 | !strncmp(startBuf, "undef", strlen("undef")) || |
| 3013 | !strncmp(startBuf, "else", strlen("else")) || |
| 3014 | !strncmp(startBuf, "elif", strlen("elif")) || |
| 3015 | !strncmp(startBuf, "endif", strlen("endif")) || |
| 3016 | !strncmp(startBuf, "pragma", strlen("pragma")) || |
| 3017 | !strncmp(startBuf, "include", strlen("include")) || |
| 3018 | !strncmp(startBuf, "import", strlen("import")) || |
| 3019 | !strncmp(startBuf, "include_next", strlen("include_next"))) |
| 3020 | return true; |
| 3021 | } |
| 3022 | startBuf++; |
| 3023 | } |
| 3024 | return false; |
| 3025 | } |
| 3026 | |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3027 | /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3028 | /// It handles elaborated types, as well as enum types in the process. |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3029 | bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, |
| 3030 | std::string &Result) { |
| 3031 | if (Type->isArrayType()) { |
| 3032 | QualType ElemTy = Context->getBaseElementType(Type); |
| 3033 | return RewriteObjCFieldDeclType(ElemTy, Result); |
| 3034 | } |
| 3035 | else if (Type->isRecordType()) { |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3036 | RecordDecl *RD = Type->getAs<RecordType>()->getDecl(); |
| 3037 | if (RD->isCompleteDefinition()) { |
| 3038 | if (RD->isStruct()) |
| 3039 | Result += "\n\tstruct "; |
| 3040 | else if (RD->isUnion()) |
| 3041 | Result += "\n\tunion "; |
| 3042 | else |
| 3043 | assert(false && "class not allowed as an ivar type"); |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3044 | |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3045 | Result += RD->getName(); |
| 3046 | if (TagsDefinedInIvarDecls.count(RD)) { |
| 3047 | // This struct is already defined. Do not write its definition again. |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3048 | Result += " "; |
| 3049 | return true; |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3050 | } |
| 3051 | TagsDefinedInIvarDecls.insert(RD); |
| 3052 | Result += " {\n"; |
| 3053 | for (RecordDecl::field_iterator i = RD->field_begin(), |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3054 | e = RD->field_end(); i != e; ++i) { |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3055 | FieldDecl *FD = *i; |
| 3056 | RewriteObjCFieldDecl(FD, Result); |
| 3057 | } |
| 3058 | Result += "\t} "; |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3059 | return true; |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3060 | } |
| 3061 | } |
| 3062 | else if (Type->isEnumeralType()) { |
| 3063 | EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); |
| 3064 | if (ED->isCompleteDefinition()) { |
| 3065 | Result += "\n\tenum "; |
| 3066 | Result += ED->getName(); |
| 3067 | if (TagsDefinedInIvarDecls.count(ED)) { |
| 3068 | // This enum is already defined. Do not write its definition again. |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3069 | Result += " "; |
| 3070 | return true; |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3071 | } |
| 3072 | TagsDefinedInIvarDecls.insert(ED); |
| 3073 | |
| 3074 | Result += " {\n"; |
| 3075 | for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(), |
| 3076 | ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) { |
| 3077 | Result += "\t"; Result += EC->getName(); Result += " = "; |
| 3078 | llvm::APSInt Val = EC->getInitVal(); |
| 3079 | Result += Val.toString(10); |
| 3080 | Result += ",\n"; |
| 3081 | } |
| 3082 | Result += "\t} "; |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3083 | return true; |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3084 | } |
| 3085 | } |
| 3086 | |
| 3087 | Result += "\t"; |
| 3088 | convertObjCTypeToCStyleType(Type); |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3089 | return false; |
| 3090 | } |
| 3091 | |
| 3092 | |
| 3093 | /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. |
| 3094 | /// It handles elaborated types, as well as enum types in the process. |
| 3095 | void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, |
| 3096 | std::string &Result) { |
| 3097 | QualType Type = fieldDecl->getType(); |
| 3098 | std::string Name = fieldDecl->getNameAsString(); |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3099 | |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3100 | bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); |
| 3101 | if (!EleboratedType) |
| 3102 | Type.getAsStringInternal(Name, Context->getPrintingPolicy()); |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3103 | Result += Name; |
| 3104 | if (fieldDecl->isBitField()) { |
| 3105 | Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context)); |
| 3106 | } |
Fariborz Jahanian | 97c1fd6 | 2012-03-09 23:46:23 +0000 | [diff] [blame] | 3107 | else if (EleboratedType && Type->isArrayType()) { |
| 3108 | CanQualType CType = Context->getCanonicalType(Type); |
| 3109 | while (isa<ArrayType>(CType)) { |
| 3110 | if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) { |
| 3111 | Result += "["; |
| 3112 | llvm::APInt Dim = CAT->getSize(); |
| 3113 | Result += utostr(Dim.getZExtValue()); |
| 3114 | Result += "]"; |
| 3115 | } |
| 3116 | CType = CType->getAs<ArrayType>()->getElementType(); |
| 3117 | } |
| 3118 | } |
| 3119 | |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3120 | Result += ";\n"; |
| 3121 | } |
| 3122 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3123 | /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to |
| 3124 | /// an objective-c class with ivars. |
| 3125 | void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, |
| 3126 | std::string &Result) { |
| 3127 | assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); |
| 3128 | assert(CDecl->getName() != "" && |
| 3129 | "Name missing in SynthesizeObjCInternalStruct"); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3130 | ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3131 | SmallVector<ObjCIvarDecl *, 8> IVars; |
| 3132 | for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); |
Fariborz Jahanian | 9a2105b | 2012-03-06 17:16:27 +0000 | [diff] [blame] | 3133 | IVD; IVD = IVD->getNextIvar()) |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3134 | IVars.push_back(IVD); |
Fariborz Jahanian | 9a2105b | 2012-03-06 17:16:27 +0000 | [diff] [blame] | 3135 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3136 | SourceLocation LocStart = CDecl->getLocStart(); |
| 3137 | SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3138 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3139 | const char *startBuf = SM->getCharacterData(LocStart); |
| 3140 | const char *endBuf = SM->getCharacterData(LocEnd); |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3141 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3142 | // If no ivars and no root or if its root, directly or indirectly, |
| 3143 | // have no ivars (thus not synthesized) then no need to synthesize this class. |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3144 | if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3145 | (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) { |
| 3146 | endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); |
| 3147 | ReplaceText(LocStart, endBuf-startBuf, Result); |
| 3148 | return; |
| 3149 | } |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3150 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3151 | Result += "\nstruct "; |
| 3152 | Result += CDecl->getNameAsString(); |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3153 | Result += "_IMPL {\n"; |
| 3154 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 3155 | if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3156 | Result += "\tstruct "; Result += RCDecl->getNameAsString(); |
| 3157 | Result += "_IMPL "; Result += RCDecl->getNameAsString(); |
| 3158 | Result += "_IVARS;\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3159 | } |
Fariborz Jahanian | 15f8777 | 2012-02-28 22:45:07 +0000 | [diff] [blame] | 3160 | TagsDefinedInIvarDecls.clear(); |
| 3161 | for (unsigned i = 0, e = IVars.size(); i < e; i++) |
| 3162 | RewriteObjCFieldDecl(IVars[i], Result); |
Fariborz Jahanian | 0b17b9a | 2012-02-12 21:36:23 +0000 | [diff] [blame] | 3163 | |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 3164 | Result += "};\n"; |
| 3165 | endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); |
| 3166 | ReplaceText(LocStart, endBuf-startBuf, Result); |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 3167 | // Mark this struct as having been generated. |
| 3168 | if (!ObjCSynthesizedStructs.insert(CDecl)) |
| 3169 | llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct"); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3170 | } |
| 3171 | |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 3172 | /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which |
| 3173 | /// have been referenced in an ivar access expression. |
| 3174 | void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, |
| 3175 | std::string &Result) { |
| 3176 | // write out ivar offset symbols which have been referenced in an ivar |
| 3177 | // access expression. |
| 3178 | llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl]; |
| 3179 | if (Ivars.empty()) |
| 3180 | return; |
| 3181 | for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(), |
| 3182 | e = Ivars.end(); i != e; i++) { |
| 3183 | ObjCIvarDecl *IvarDecl = (*i); |
Fariborz Jahanian | 40a777a | 2012-03-12 16:46:58 +0000 | [diff] [blame] | 3184 | Result += "\n"; |
| 3185 | if (LangOpts.MicrosoftExt) |
| 3186 | Result += "__declspec(allocate(\".objc_ivar$B\")) "; |
| 3187 | if (LangOpts.MicrosoftExt && |
| 3188 | IvarDecl->getAccessControl() != ObjCIvarDecl::Private && |
| 3189 | IvarDecl->getAccessControl() != ObjCIvarDecl::Package) { |
| 3190 | const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface(); |
| 3191 | if (CDecl->getImplementation()) |
| 3192 | Result += "__declspec(dllexport) "; |
| 3193 | } |
| 3194 | Result += "extern unsigned long OBJC_IVAR_$_"; |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 3195 | Result += CDecl->getName(); Result += "_"; |
| 3196 | Result += IvarDecl->getName(); Result += ";"; |
| 3197 | } |
| 3198 | } |
| 3199 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3200 | //===----------------------------------------------------------------------===// |
| 3201 | // Meta Data Emission |
| 3202 | //===----------------------------------------------------------------------===// |
| 3203 | |
| 3204 | |
| 3205 | /// RewriteImplementations - This routine rewrites all method implementations |
| 3206 | /// and emits meta-data. |
| 3207 | |
| 3208 | void RewriteModernObjC::RewriteImplementations() { |
| 3209 | int ClsDefCount = ClassImplementation.size(); |
| 3210 | int CatDefCount = CategoryImplementation.size(); |
| 3211 | |
| 3212 | // Rewrite implemented methods |
Fariborz Jahanian | 8f1fed0 | 2012-02-11 20:10:52 +0000 | [diff] [blame] | 3213 | for (int i = 0; i < ClsDefCount; i++) { |
| 3214 | ObjCImplementationDecl *OIMP = ClassImplementation[i]; |
| 3215 | ObjCInterfaceDecl *CDecl = OIMP->getClassInterface(); |
| 3216 | if (CDecl->isImplicitInterfaceDecl()) |
Fariborz Jahanian | cf4c60f | 2012-02-17 22:20:12 +0000 | [diff] [blame] | 3217 | assert(false && |
| 3218 | "Legacy implicit interface rewriting not supported in moder abi"); |
Fariborz Jahanian | 8f1fed0 | 2012-02-11 20:10:52 +0000 | [diff] [blame] | 3219 | RewriteImplementationDecl(OIMP); |
| 3220 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3221 | |
Fariborz Jahanian | 8c00a1b | 2012-02-17 20:33:00 +0000 | [diff] [blame] | 3222 | for (int i = 0; i < CatDefCount; i++) { |
| 3223 | ObjCCategoryImplDecl *CIMP = CategoryImplementation[i]; |
| 3224 | ObjCInterfaceDecl *CDecl = CIMP->getClassInterface(); |
| 3225 | if (CDecl->isImplicitInterfaceDecl()) |
| 3226 | assert(false && |
| 3227 | "Legacy implicit interface rewriting not supported in moder abi"); |
Fariborz Jahanian | 8c00a1b | 2012-02-17 20:33:00 +0000 | [diff] [blame] | 3228 | RewriteImplementationDecl(CIMP); |
| 3229 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3230 | } |
| 3231 | |
| 3232 | void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, |
| 3233 | const std::string &Name, |
| 3234 | ValueDecl *VD, bool def) { |
| 3235 | assert(BlockByRefDeclNo.count(VD) && |
| 3236 | "RewriteByRefString: ByRef decl missing"); |
| 3237 | if (def) |
| 3238 | ResultStr += "struct "; |
| 3239 | ResultStr += "__Block_byref_" + Name + |
| 3240 | "_" + utostr(BlockByRefDeclNo[VD]) ; |
| 3241 | } |
| 3242 | |
| 3243 | static bool HasLocalVariableExternalStorage(ValueDecl *VD) { |
| 3244 | if (VarDecl *Var = dyn_cast<VarDecl>(VD)) |
| 3245 | return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage()); |
| 3246 | return false; |
| 3247 | } |
| 3248 | |
| 3249 | std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 3250 | StringRef funcName, |
| 3251 | std::string Tag) { |
| 3252 | const FunctionType *AFT = CE->getFunctionType(); |
| 3253 | QualType RT = AFT->getResultType(); |
| 3254 | std::string StructRef = "struct " + Tag; |
| 3255 | std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + |
| 3256 | funcName.str() + "_" + "block_func_" + utostr(i); |
| 3257 | |
| 3258 | BlockDecl *BD = CE->getBlockDecl(); |
| 3259 | |
| 3260 | if (isa<FunctionNoProtoType>(AFT)) { |
| 3261 | // No user-supplied arguments. Still need to pass in a pointer to the |
| 3262 | // block (to reference imported block decl refs). |
| 3263 | S += "(" + StructRef + " *__cself)"; |
| 3264 | } else if (BD->param_empty()) { |
| 3265 | S += "(" + StructRef + " *__cself)"; |
| 3266 | } else { |
| 3267 | const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); |
| 3268 | assert(FT && "SynthesizeBlockFunc: No function proto"); |
| 3269 | S += '('; |
| 3270 | // first add the implicit argument. |
| 3271 | S += StructRef + " *__cself, "; |
| 3272 | std::string ParamStr; |
| 3273 | for (BlockDecl::param_iterator AI = BD->param_begin(), |
| 3274 | E = BD->param_end(); AI != E; ++AI) { |
| 3275 | if (AI != BD->param_begin()) S += ", "; |
| 3276 | ParamStr = (*AI)->getNameAsString(); |
| 3277 | QualType QT = (*AI)->getType(); |
| 3278 | if (convertBlockPointerToFunctionPointer(QT)) |
| 3279 | QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy()); |
| 3280 | else |
| 3281 | QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy()); |
| 3282 | S += ParamStr; |
| 3283 | } |
| 3284 | if (FT->isVariadic()) { |
| 3285 | if (!BD->param_empty()) S += ", "; |
| 3286 | S += "..."; |
| 3287 | } |
| 3288 | S += ')'; |
| 3289 | } |
| 3290 | S += " {\n"; |
| 3291 | |
| 3292 | // Create local declarations to avoid rewriting all closure decl ref exprs. |
| 3293 | // First, emit a declaration for all "by ref" decls. |
| 3294 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 3295 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 3296 | S += " "; |
| 3297 | std::string Name = (*I)->getNameAsString(); |
| 3298 | std::string TypeString; |
| 3299 | RewriteByRefString(TypeString, Name, (*I)); |
| 3300 | TypeString += " *"; |
| 3301 | Name = TypeString + Name; |
| 3302 | S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; |
| 3303 | } |
| 3304 | // Next, emit a declaration for all "by copy" declarations. |
| 3305 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 3306 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 3307 | S += " "; |
| 3308 | // Handle nested closure invocation. For example: |
| 3309 | // |
| 3310 | // void (^myImportedClosure)(void); |
| 3311 | // myImportedClosure = ^(void) { setGlobalInt(x + y); }; |
| 3312 | // |
| 3313 | // void (^anotherClosure)(void); |
| 3314 | // anotherClosure = ^(void) { |
| 3315 | // myImportedClosure(); // import and invoke the closure |
| 3316 | // }; |
| 3317 | // |
| 3318 | if (isTopLevelBlockPointerType((*I)->getType())) { |
| 3319 | RewriteBlockPointerTypeVariable(S, (*I)); |
| 3320 | S += " = ("; |
| 3321 | RewriteBlockPointerType(S, (*I)->getType()); |
| 3322 | S += ")"; |
| 3323 | S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; |
| 3324 | } |
| 3325 | else { |
| 3326 | std::string Name = (*I)->getNameAsString(); |
| 3327 | QualType QT = (*I)->getType(); |
| 3328 | if (HasLocalVariableExternalStorage(*I)) |
| 3329 | QT = Context->getPointerType(QT); |
| 3330 | QT.getAsStringInternal(Name, Context->getPrintingPolicy()); |
| 3331 | S += Name + " = __cself->" + |
| 3332 | (*I)->getNameAsString() + "; // bound by copy\n"; |
| 3333 | } |
| 3334 | } |
| 3335 | std::string RewrittenStr = RewrittenBlockExprs[CE]; |
| 3336 | const char *cstr = RewrittenStr.c_str(); |
| 3337 | while (*cstr++ != '{') ; |
| 3338 | S += cstr; |
| 3339 | S += "\n"; |
| 3340 | return S; |
| 3341 | } |
| 3342 | |
| 3343 | std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 3344 | StringRef funcName, |
| 3345 | std::string Tag) { |
| 3346 | std::string StructRef = "struct " + Tag; |
| 3347 | std::string S = "static void __"; |
| 3348 | |
| 3349 | S += funcName; |
| 3350 | S += "_block_copy_" + utostr(i); |
| 3351 | S += "(" + StructRef; |
| 3352 | S += "*dst, " + StructRef; |
| 3353 | S += "*src) {"; |
| 3354 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 3355 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 3356 | ValueDecl *VD = (*I); |
| 3357 | S += "_Block_object_assign((void*)&dst->"; |
| 3358 | S += (*I)->getNameAsString(); |
| 3359 | S += ", (void*)src->"; |
| 3360 | S += (*I)->getNameAsString(); |
| 3361 | if (BlockByRefDeclsPtrSet.count((*I))) |
| 3362 | S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; |
| 3363 | else if (VD->getType()->isBlockPointerType()) |
| 3364 | S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; |
| 3365 | else |
| 3366 | S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; |
| 3367 | } |
| 3368 | S += "}\n"; |
| 3369 | |
| 3370 | S += "\nstatic void __"; |
| 3371 | S += funcName; |
| 3372 | S += "_block_dispose_" + utostr(i); |
| 3373 | S += "(" + StructRef; |
| 3374 | S += "*src) {"; |
| 3375 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 3376 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 3377 | ValueDecl *VD = (*I); |
| 3378 | S += "_Block_object_dispose((void*)src->"; |
| 3379 | S += (*I)->getNameAsString(); |
| 3380 | if (BlockByRefDeclsPtrSet.count((*I))) |
| 3381 | S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; |
| 3382 | else if (VD->getType()->isBlockPointerType()) |
| 3383 | S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; |
| 3384 | else |
| 3385 | S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; |
| 3386 | } |
| 3387 | S += "}\n"; |
| 3388 | return S; |
| 3389 | } |
| 3390 | |
| 3391 | std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, |
| 3392 | std::string Desc) { |
| 3393 | std::string S = "\nstruct " + Tag; |
| 3394 | std::string Constructor = " " + Tag; |
| 3395 | |
| 3396 | S += " {\n struct __block_impl impl;\n"; |
| 3397 | S += " struct " + Desc; |
| 3398 | S += "* Desc;\n"; |
| 3399 | |
| 3400 | Constructor += "(void *fp, "; // Invoke function pointer. |
| 3401 | Constructor += "struct " + Desc; // Descriptor pointer. |
| 3402 | Constructor += " *desc"; |
| 3403 | |
| 3404 | if (BlockDeclRefs.size()) { |
| 3405 | // Output all "by copy" declarations. |
| 3406 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 3407 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 3408 | S += " "; |
| 3409 | std::string FieldName = (*I)->getNameAsString(); |
| 3410 | std::string ArgName = "_" + FieldName; |
| 3411 | // Handle nested closure invocation. For example: |
| 3412 | // |
| 3413 | // void (^myImportedBlock)(void); |
| 3414 | // myImportedBlock = ^(void) { setGlobalInt(x + y); }; |
| 3415 | // |
| 3416 | // void (^anotherBlock)(void); |
| 3417 | // anotherBlock = ^(void) { |
| 3418 | // myImportedBlock(); // import and invoke the closure |
| 3419 | // }; |
| 3420 | // |
| 3421 | if (isTopLevelBlockPointerType((*I)->getType())) { |
| 3422 | S += "struct __block_impl *"; |
| 3423 | Constructor += ", void *" + ArgName; |
| 3424 | } else { |
| 3425 | QualType QT = (*I)->getType(); |
| 3426 | if (HasLocalVariableExternalStorage(*I)) |
| 3427 | QT = Context->getPointerType(QT); |
| 3428 | QT.getAsStringInternal(FieldName, Context->getPrintingPolicy()); |
| 3429 | QT.getAsStringInternal(ArgName, Context->getPrintingPolicy()); |
| 3430 | Constructor += ", " + ArgName; |
| 3431 | } |
| 3432 | S += FieldName + ";\n"; |
| 3433 | } |
| 3434 | // Output all "by ref" declarations. |
| 3435 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 3436 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 3437 | S += " "; |
| 3438 | std::string FieldName = (*I)->getNameAsString(); |
| 3439 | std::string ArgName = "_" + FieldName; |
| 3440 | { |
| 3441 | std::string TypeString; |
| 3442 | RewriteByRefString(TypeString, FieldName, (*I)); |
| 3443 | TypeString += " *"; |
| 3444 | FieldName = TypeString + FieldName; |
| 3445 | ArgName = TypeString + ArgName; |
| 3446 | Constructor += ", " + ArgName; |
| 3447 | } |
| 3448 | S += FieldName + "; // by ref\n"; |
| 3449 | } |
| 3450 | // Finish writing the constructor. |
| 3451 | Constructor += ", int flags=0)"; |
| 3452 | // Initialize all "by copy" arguments. |
| 3453 | bool firsTime = true; |
| 3454 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 3455 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 3456 | std::string Name = (*I)->getNameAsString(); |
| 3457 | if (firsTime) { |
| 3458 | Constructor += " : "; |
| 3459 | firsTime = false; |
| 3460 | } |
| 3461 | else |
| 3462 | Constructor += ", "; |
| 3463 | if (isTopLevelBlockPointerType((*I)->getType())) |
| 3464 | Constructor += Name + "((struct __block_impl *)_" + Name + ")"; |
| 3465 | else |
| 3466 | Constructor += Name + "(_" + Name + ")"; |
| 3467 | } |
| 3468 | // Initialize all "by ref" arguments. |
| 3469 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 3470 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 3471 | std::string Name = (*I)->getNameAsString(); |
| 3472 | if (firsTime) { |
| 3473 | Constructor += " : "; |
| 3474 | firsTime = false; |
| 3475 | } |
| 3476 | else |
| 3477 | Constructor += ", "; |
| 3478 | Constructor += Name + "(_" + Name + "->__forwarding)"; |
| 3479 | } |
| 3480 | |
| 3481 | Constructor += " {\n"; |
| 3482 | if (GlobalVarDecl) |
| 3483 | Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; |
| 3484 | else |
| 3485 | Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; |
| 3486 | Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
| 3487 | |
| 3488 | Constructor += " Desc = desc;\n"; |
| 3489 | } else { |
| 3490 | // Finish writing the constructor. |
| 3491 | Constructor += ", int flags=0) {\n"; |
| 3492 | if (GlobalVarDecl) |
| 3493 | Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; |
| 3494 | else |
| 3495 | Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; |
| 3496 | Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
| 3497 | Constructor += " Desc = desc;\n"; |
| 3498 | } |
| 3499 | Constructor += " "; |
| 3500 | Constructor += "}\n"; |
| 3501 | S += Constructor; |
| 3502 | S += "};\n"; |
| 3503 | return S; |
| 3504 | } |
| 3505 | |
| 3506 | std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, |
| 3507 | std::string ImplTag, int i, |
| 3508 | StringRef FunName, |
| 3509 | unsigned hasCopy) { |
| 3510 | std::string S = "\nstatic struct " + DescTag; |
| 3511 | |
| 3512 | S += " {\n unsigned long reserved;\n"; |
| 3513 | S += " unsigned long Block_size;\n"; |
| 3514 | if (hasCopy) { |
| 3515 | S += " void (*copy)(struct "; |
| 3516 | S += ImplTag; S += "*, struct "; |
| 3517 | S += ImplTag; S += "*);\n"; |
| 3518 | |
| 3519 | S += " void (*dispose)(struct "; |
| 3520 | S += ImplTag; S += "*);\n"; |
| 3521 | } |
| 3522 | S += "} "; |
| 3523 | |
| 3524 | S += DescTag + "_DATA = { 0, sizeof(struct "; |
| 3525 | S += ImplTag + ")"; |
| 3526 | if (hasCopy) { |
| 3527 | S += ", __" + FunName.str() + "_block_copy_" + utostr(i); |
| 3528 | S += ", __" + FunName.str() + "_block_dispose_" + utostr(i); |
| 3529 | } |
| 3530 | S += "};\n"; |
| 3531 | return S; |
| 3532 | } |
| 3533 | |
| 3534 | void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 3535 | StringRef FunName) { |
| 3536 | // Insert declaration for the function in which block literal is used. |
| 3537 | if (CurFunctionDeclToDeclareForBlock && !Blocks.empty()) |
| 3538 | RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock); |
| 3539 | bool RewriteSC = (GlobalVarDecl && |
| 3540 | !Blocks.empty() && |
| 3541 | GlobalVarDecl->getStorageClass() == SC_Static && |
| 3542 | GlobalVarDecl->getType().getCVRQualifiers()); |
| 3543 | if (RewriteSC) { |
| 3544 | std::string SC(" void __"); |
| 3545 | SC += GlobalVarDecl->getNameAsString(); |
| 3546 | SC += "() {}"; |
| 3547 | InsertText(FunLocStart, SC); |
| 3548 | } |
| 3549 | |
| 3550 | // Insert closures that were part of the function. |
| 3551 | for (unsigned i = 0, count=0; i < Blocks.size(); i++) { |
| 3552 | CollectBlockDeclRefInfo(Blocks[i]); |
| 3553 | // Need to copy-in the inner copied-in variables not actually used in this |
| 3554 | // block. |
| 3555 | for (int j = 0; j < InnerDeclRefsCount[i]; j++) { |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3556 | DeclRefExpr *Exp = InnerDeclRefs[count++]; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3557 | ValueDecl *VD = Exp->getDecl(); |
| 3558 | BlockDeclRefs.push_back(Exp); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3559 | if (!VD->hasAttr<BlocksAttr>()) { |
| 3560 | if (!BlockByCopyDeclsPtrSet.count(VD)) { |
| 3561 | BlockByCopyDeclsPtrSet.insert(VD); |
| 3562 | BlockByCopyDecls.push_back(VD); |
| 3563 | } |
| 3564 | continue; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3565 | } |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3566 | |
| 3567 | if (!BlockByRefDeclsPtrSet.count(VD)) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3568 | BlockByRefDeclsPtrSet.insert(VD); |
| 3569 | BlockByRefDecls.push_back(VD); |
| 3570 | } |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3571 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3572 | // imported objects in the inner blocks not used in the outer |
| 3573 | // blocks must be copied/disposed in the outer block as well. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3574 | if (VD->getType()->isObjCObjectPointerType() || |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3575 | VD->getType()->isBlockPointerType()) |
| 3576 | ImportedBlockDecls.insert(VD); |
| 3577 | } |
| 3578 | |
| 3579 | std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i); |
| 3580 | std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i); |
| 3581 | |
| 3582 | std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag); |
| 3583 | |
| 3584 | InsertText(FunLocStart, CI); |
| 3585 | |
| 3586 | std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag); |
| 3587 | |
| 3588 | InsertText(FunLocStart, CF); |
| 3589 | |
| 3590 | if (ImportedBlockDecls.size()) { |
| 3591 | std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag); |
| 3592 | InsertText(FunLocStart, HF); |
| 3593 | } |
| 3594 | std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName, |
| 3595 | ImportedBlockDecls.size() > 0); |
| 3596 | InsertText(FunLocStart, BD); |
| 3597 | |
| 3598 | BlockDeclRefs.clear(); |
| 3599 | BlockByRefDecls.clear(); |
| 3600 | BlockByRefDeclsPtrSet.clear(); |
| 3601 | BlockByCopyDecls.clear(); |
| 3602 | BlockByCopyDeclsPtrSet.clear(); |
| 3603 | ImportedBlockDecls.clear(); |
| 3604 | } |
| 3605 | if (RewriteSC) { |
| 3606 | // Must insert any 'const/volatile/static here. Since it has been |
| 3607 | // removed as result of rewriting of block literals. |
| 3608 | std::string SC; |
| 3609 | if (GlobalVarDecl->getStorageClass() == SC_Static) |
| 3610 | SC = "static "; |
| 3611 | if (GlobalVarDecl->getType().isConstQualified()) |
| 3612 | SC += "const "; |
| 3613 | if (GlobalVarDecl->getType().isVolatileQualified()) |
| 3614 | SC += "volatile "; |
| 3615 | if (GlobalVarDecl->getType().isRestrictQualified()) |
| 3616 | SC += "restrict "; |
| 3617 | InsertText(FunLocStart, SC); |
| 3618 | } |
| 3619 | |
| 3620 | Blocks.clear(); |
| 3621 | InnerDeclRefsCount.clear(); |
| 3622 | InnerDeclRefs.clear(); |
| 3623 | RewrittenBlockExprs.clear(); |
| 3624 | } |
| 3625 | |
| 3626 | void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { |
| 3627 | SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
| 3628 | StringRef FuncName = FD->getName(); |
| 3629 | |
| 3630 | SynthesizeBlockLiterals(FunLocStart, FuncName); |
| 3631 | } |
| 3632 | |
| 3633 | static void BuildUniqueMethodName(std::string &Name, |
| 3634 | ObjCMethodDecl *MD) { |
| 3635 | ObjCInterfaceDecl *IFace = MD->getClassInterface(); |
| 3636 | Name = IFace->getName(); |
| 3637 | Name += "__" + MD->getSelector().getAsString(); |
| 3638 | // Convert colons to underscores. |
| 3639 | std::string::size_type loc = 0; |
| 3640 | while ((loc = Name.find(":", loc)) != std::string::npos) |
| 3641 | Name.replace(loc, 1, "_"); |
| 3642 | } |
| 3643 | |
| 3644 | void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { |
| 3645 | //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); |
| 3646 | //SourceLocation FunLocStart = MD->getLocStart(); |
| 3647 | SourceLocation FunLocStart = MD->getLocStart(); |
| 3648 | std::string FuncName; |
| 3649 | BuildUniqueMethodName(FuncName, MD); |
| 3650 | SynthesizeBlockLiterals(FunLocStart, FuncName); |
| 3651 | } |
| 3652 | |
| 3653 | void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) { |
| 3654 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 3655 | if (*CI) { |
| 3656 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) |
| 3657 | GetBlockDeclRefExprs(CBE->getBody()); |
| 3658 | else |
| 3659 | GetBlockDeclRefExprs(*CI); |
| 3660 | } |
| 3661 | // Handle specific things. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3662 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) |
| 3663 | if (DRE->refersToEnclosingLocal() && |
| 3664 | HasLocalVariableExternalStorage(DRE->getDecl())) { |
| 3665 | BlockDeclRefs.push_back(DRE); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3666 | } |
| 3667 | |
| 3668 | return; |
| 3669 | } |
| 3670 | |
| 3671 | void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3672 | SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3673 | llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) { |
| 3674 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 3675 | if (*CI) { |
| 3676 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) { |
| 3677 | InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl())); |
| 3678 | GetInnerBlockDeclRefExprs(CBE->getBody(), |
| 3679 | InnerBlockDeclRefs, |
| 3680 | InnerContexts); |
| 3681 | } |
| 3682 | else |
| 3683 | GetInnerBlockDeclRefExprs(*CI, |
| 3684 | InnerBlockDeclRefs, |
| 3685 | InnerContexts); |
| 3686 | |
| 3687 | } |
| 3688 | // Handle specific things. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3689 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { |
| 3690 | if (DRE->refersToEnclosingLocal()) { |
| 3691 | if (!isa<FunctionDecl>(DRE->getDecl()) && |
| 3692 | !InnerContexts.count(DRE->getDecl()->getDeclContext())) |
| 3693 | InnerBlockDeclRefs.push_back(DRE); |
| 3694 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) |
| 3695 | if (Var->isFunctionOrMethodVarDecl()) |
| 3696 | ImportedLocalExternalDecls.insert(Var); |
| 3697 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3698 | } |
| 3699 | |
| 3700 | return; |
| 3701 | } |
| 3702 | |
Fariborz Jahanian | 164d6f8 | 2012-02-13 18:57:49 +0000 | [diff] [blame] | 3703 | /// convertObjCTypeToCStyleType - This routine converts such objc types |
| 3704 | /// as qualified objects, and blocks to their closest c/c++ types that |
| 3705 | /// it can. It returns true if input type was modified. |
| 3706 | bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { |
| 3707 | QualType oldT = T; |
| 3708 | convertBlockPointerToFunctionPointer(T); |
| 3709 | if (T->isFunctionPointerType()) { |
| 3710 | QualType PointeeTy; |
| 3711 | if (const PointerType* PT = T->getAs<PointerType>()) { |
| 3712 | PointeeTy = PT->getPointeeType(); |
| 3713 | if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) { |
| 3714 | T = convertFunctionTypeOfBlocks(FT); |
| 3715 | T = Context->getPointerType(T); |
| 3716 | } |
| 3717 | } |
| 3718 | } |
| 3719 | |
| 3720 | convertToUnqualifiedObjCType(T); |
| 3721 | return T != oldT; |
| 3722 | } |
| 3723 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3724 | /// convertFunctionTypeOfBlocks - This routine converts a function type |
| 3725 | /// whose result type may be a block pointer or whose argument type(s) |
| 3726 | /// might be block pointers to an equivalent function type replacing |
| 3727 | /// all block pointers to function pointers. |
| 3728 | QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { |
| 3729 | const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); |
| 3730 | // FTP will be null for closures that don't take arguments. |
| 3731 | // Generate a funky cast. |
| 3732 | SmallVector<QualType, 8> ArgTypes; |
| 3733 | QualType Res = FT->getResultType(); |
Fariborz Jahanian | 164d6f8 | 2012-02-13 18:57:49 +0000 | [diff] [blame] | 3734 | bool modified = convertObjCTypeToCStyleType(Res); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3735 | |
| 3736 | if (FTP) { |
| 3737 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 3738 | E = FTP->arg_type_end(); I && (I != E); ++I) { |
| 3739 | QualType t = *I; |
| 3740 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
Fariborz Jahanian | 164d6f8 | 2012-02-13 18:57:49 +0000 | [diff] [blame] | 3741 | if (convertObjCTypeToCStyleType(t)) |
| 3742 | modified = true; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3743 | ArgTypes.push_back(t); |
| 3744 | } |
| 3745 | } |
| 3746 | QualType FuncType; |
Fariborz Jahanian | 164d6f8 | 2012-02-13 18:57:49 +0000 | [diff] [blame] | 3747 | if (modified) |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3748 | FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size()); |
| 3749 | else FuncType = QualType(FT, 0); |
| 3750 | return FuncType; |
| 3751 | } |
| 3752 | |
| 3753 | Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { |
| 3754 | // Navigate to relevant type information. |
| 3755 | const BlockPointerType *CPT = 0; |
| 3756 | |
| 3757 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) { |
| 3758 | CPT = DRE->getType()->getAs<BlockPointerType>(); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3759 | } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { |
| 3760 | CPT = MExpr->getType()->getAs<BlockPointerType>(); |
| 3761 | } |
| 3762 | else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { |
| 3763 | return SynthesizeBlockCall(Exp, PRE->getSubExpr()); |
| 3764 | } |
| 3765 | else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) |
| 3766 | CPT = IEXPR->getType()->getAs<BlockPointerType>(); |
| 3767 | else if (const ConditionalOperator *CEXPR = |
| 3768 | dyn_cast<ConditionalOperator>(BlockExp)) { |
| 3769 | Expr *LHSExp = CEXPR->getLHS(); |
| 3770 | Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); |
| 3771 | Expr *RHSExp = CEXPR->getRHS(); |
| 3772 | Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp); |
| 3773 | Expr *CONDExp = CEXPR->getCond(); |
| 3774 | ConditionalOperator *CondExpr = |
| 3775 | new (Context) ConditionalOperator(CONDExp, |
| 3776 | SourceLocation(), cast<Expr>(LHSStmt), |
| 3777 | SourceLocation(), cast<Expr>(RHSStmt), |
| 3778 | Exp->getType(), VK_RValue, OK_Ordinary); |
| 3779 | return CondExpr; |
| 3780 | } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) { |
| 3781 | CPT = IRE->getType()->getAs<BlockPointerType>(); |
| 3782 | } else if (const PseudoObjectExpr *POE |
| 3783 | = dyn_cast<PseudoObjectExpr>(BlockExp)) { |
| 3784 | CPT = POE->getType()->castAs<BlockPointerType>(); |
| 3785 | } else { |
| 3786 | assert(1 && "RewriteBlockClass: Bad type"); |
| 3787 | } |
| 3788 | assert(CPT && "RewriteBlockClass: Bad type"); |
| 3789 | const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>(); |
| 3790 | assert(FT && "RewriteBlockClass: Bad type"); |
| 3791 | const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); |
| 3792 | // FTP will be null for closures that don't take arguments. |
| 3793 | |
| 3794 | RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 3795 | SourceLocation(), SourceLocation(), |
| 3796 | &Context->Idents.get("__block_impl")); |
| 3797 | QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD)); |
| 3798 | |
| 3799 | // Generate a funky cast. |
| 3800 | SmallVector<QualType, 8> ArgTypes; |
| 3801 | |
| 3802 | // Push the block argument type. |
| 3803 | ArgTypes.push_back(PtrBlock); |
| 3804 | if (FTP) { |
| 3805 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 3806 | E = FTP->arg_type_end(); I && (I != E); ++I) { |
| 3807 | QualType t = *I; |
| 3808 | // Make sure we convert "t (^)(...)" to "t (*)(...)". |
| 3809 | if (!convertBlockPointerToFunctionPointer(t)) |
| 3810 | convertToUnqualifiedObjCType(t); |
| 3811 | ArgTypes.push_back(t); |
| 3812 | } |
| 3813 | } |
| 3814 | // Now do the pointer to function cast. |
| 3815 | QualType PtrToFuncCastType |
| 3816 | = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size()); |
| 3817 | |
| 3818 | PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); |
| 3819 | |
| 3820 | CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock, |
| 3821 | CK_BitCast, |
| 3822 | const_cast<Expr*>(BlockExp)); |
| 3823 | // Don't forget the parens to enforce the proper binding. |
| 3824 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), |
| 3825 | BlkCast); |
| 3826 | //PE->dump(); |
| 3827 | |
| 3828 | FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(), |
| 3829 | SourceLocation(), |
| 3830 | &Context->Idents.get("FuncPtr"), |
| 3831 | Context->VoidPtrTy, 0, |
| 3832 | /*BitWidth=*/0, /*Mutable=*/true, |
| 3833 | /*HasInit=*/false); |
| 3834 | MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(), |
| 3835 | FD->getType(), VK_LValue, |
| 3836 | OK_Ordinary); |
| 3837 | |
| 3838 | |
| 3839 | CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, |
| 3840 | CK_BitCast, ME); |
| 3841 | PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); |
| 3842 | |
| 3843 | SmallVector<Expr*, 8> BlkExprs; |
| 3844 | // Add the implicit argument. |
| 3845 | BlkExprs.push_back(BlkCast); |
| 3846 | // Add the user arguments. |
| 3847 | for (CallExpr::arg_iterator I = Exp->arg_begin(), |
| 3848 | E = Exp->arg_end(); I != E; ++I) { |
| 3849 | BlkExprs.push_back(*I); |
| 3850 | } |
| 3851 | CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0], |
| 3852 | BlkExprs.size(), |
| 3853 | Exp->getType(), VK_RValue, |
| 3854 | SourceLocation()); |
| 3855 | return CE; |
| 3856 | } |
| 3857 | |
| 3858 | // We need to return the rewritten expression to handle cases where the |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3859 | // DeclRefExpr is embedded in another expression being rewritten. |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3860 | // For example: |
| 3861 | // |
| 3862 | // int main() { |
| 3863 | // __block Foo *f; |
| 3864 | // __block int i; |
| 3865 | // |
| 3866 | // void (^myblock)() = ^() { |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3867 | // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten). |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3868 | // i = 77; |
| 3869 | // }; |
| 3870 | //} |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3871 | Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3872 | // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR |
| 3873 | // for each DeclRefExp where BYREFVAR is name of the variable. |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 3874 | ValueDecl *VD = DeclRefExp->getDecl(); |
| 3875 | bool isArrow = DeclRefExp->refersToEnclosingLocal(); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 3876 | |
| 3877 | FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(), |
| 3878 | SourceLocation(), |
| 3879 | &Context->Idents.get("__forwarding"), |
| 3880 | Context->VoidPtrTy, 0, |
| 3881 | /*BitWidth=*/0, /*Mutable=*/true, |
| 3882 | /*HasInit=*/false); |
| 3883 | MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow, |
| 3884 | FD, SourceLocation(), |
| 3885 | FD->getType(), VK_LValue, |
| 3886 | OK_Ordinary); |
| 3887 | |
| 3888 | StringRef Name = VD->getName(); |
| 3889 | FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(), |
| 3890 | &Context->Idents.get(Name), |
| 3891 | Context->VoidPtrTy, 0, |
| 3892 | /*BitWidth=*/0, /*Mutable=*/true, |
| 3893 | /*HasInit=*/false); |
| 3894 | ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(), |
| 3895 | DeclRefExp->getType(), VK_LValue, OK_Ordinary); |
| 3896 | |
| 3897 | |
| 3898 | |
| 3899 | // Need parens to enforce precedence. |
| 3900 | ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), |
| 3901 | DeclRefExp->getExprLoc(), |
| 3902 | ME); |
| 3903 | ReplaceStmt(DeclRefExp, PE); |
| 3904 | return PE; |
| 3905 | } |
| 3906 | |
| 3907 | // Rewrites the imported local variable V with external storage |
| 3908 | // (static, extern, etc.) as *V |
| 3909 | // |
| 3910 | Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { |
| 3911 | ValueDecl *VD = DRE->getDecl(); |
| 3912 | if (VarDecl *Var = dyn_cast<VarDecl>(VD)) |
| 3913 | if (!ImportedLocalExternalDecls.count(Var)) |
| 3914 | return DRE; |
| 3915 | Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(), |
| 3916 | VK_LValue, OK_Ordinary, |
| 3917 | DRE->getLocation()); |
| 3918 | // Need parens to enforce precedence. |
| 3919 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), |
| 3920 | Exp); |
| 3921 | ReplaceStmt(DRE, PE); |
| 3922 | return PE; |
| 3923 | } |
| 3924 | |
| 3925 | void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) { |
| 3926 | SourceLocation LocStart = CE->getLParenLoc(); |
| 3927 | SourceLocation LocEnd = CE->getRParenLoc(); |
| 3928 | |
| 3929 | // Need to avoid trying to rewrite synthesized casts. |
| 3930 | if (LocStart.isInvalid()) |
| 3931 | return; |
| 3932 | // Need to avoid trying to rewrite casts contained in macros. |
| 3933 | if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) |
| 3934 | return; |
| 3935 | |
| 3936 | const char *startBuf = SM->getCharacterData(LocStart); |
| 3937 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 3938 | QualType QT = CE->getType(); |
| 3939 | const Type* TypePtr = QT->getAs<Type>(); |
| 3940 | if (isa<TypeOfExprType>(TypePtr)) { |
| 3941 | const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); |
| 3942 | QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); |
| 3943 | std::string TypeAsString = "("; |
| 3944 | RewriteBlockPointerType(TypeAsString, QT); |
| 3945 | TypeAsString += ")"; |
| 3946 | ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString); |
| 3947 | return; |
| 3948 | } |
| 3949 | // advance the location to startArgList. |
| 3950 | const char *argPtr = startBuf; |
| 3951 | |
| 3952 | while (*argPtr++ && (argPtr < endBuf)) { |
| 3953 | switch (*argPtr) { |
| 3954 | case '^': |
| 3955 | // Replace the '^' with '*'. |
| 3956 | LocStart = LocStart.getLocWithOffset(argPtr-startBuf); |
| 3957 | ReplaceText(LocStart, 1, "*"); |
| 3958 | break; |
| 3959 | } |
| 3960 | } |
| 3961 | return; |
| 3962 | } |
| 3963 | |
| 3964 | void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { |
| 3965 | SourceLocation DeclLoc = FD->getLocation(); |
| 3966 | unsigned parenCount = 0; |
| 3967 | |
| 3968 | // We have 1 or more arguments that have closure pointers. |
| 3969 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 3970 | const char *startArgList = strchr(startBuf, '('); |
| 3971 | |
| 3972 | assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); |
| 3973 | |
| 3974 | parenCount++; |
| 3975 | // advance the location to startArgList. |
| 3976 | DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf); |
| 3977 | assert((DeclLoc.isValid()) && "Invalid DeclLoc"); |
| 3978 | |
| 3979 | const char *argPtr = startArgList; |
| 3980 | |
| 3981 | while (*argPtr++ && parenCount) { |
| 3982 | switch (*argPtr) { |
| 3983 | case '^': |
| 3984 | // Replace the '^' with '*'. |
| 3985 | DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList); |
| 3986 | ReplaceText(DeclLoc, 1, "*"); |
| 3987 | break; |
| 3988 | case '(': |
| 3989 | parenCount++; |
| 3990 | break; |
| 3991 | case ')': |
| 3992 | parenCount--; |
| 3993 | break; |
| 3994 | } |
| 3995 | } |
| 3996 | return; |
| 3997 | } |
| 3998 | |
| 3999 | bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { |
| 4000 | const FunctionProtoType *FTP; |
| 4001 | const PointerType *PT = QT->getAs<PointerType>(); |
| 4002 | if (PT) { |
| 4003 | FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4004 | } else { |
| 4005 | const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); |
| 4006 | assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); |
| 4007 | FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4008 | } |
| 4009 | if (FTP) { |
| 4010 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 4011 | E = FTP->arg_type_end(); I != E; ++I) |
| 4012 | if (isTopLevelBlockPointerType(*I)) |
| 4013 | return true; |
| 4014 | } |
| 4015 | return false; |
| 4016 | } |
| 4017 | |
| 4018 | bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { |
| 4019 | const FunctionProtoType *FTP; |
| 4020 | const PointerType *PT = QT->getAs<PointerType>(); |
| 4021 | if (PT) { |
| 4022 | FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4023 | } else { |
| 4024 | const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); |
| 4025 | assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); |
| 4026 | FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); |
| 4027 | } |
| 4028 | if (FTP) { |
| 4029 | for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(), |
| 4030 | E = FTP->arg_type_end(); I != E; ++I) { |
| 4031 | if ((*I)->isObjCQualifiedIdType()) |
| 4032 | return true; |
| 4033 | if ((*I)->isObjCObjectPointerType() && |
| 4034 | (*I)->getPointeeType()->isObjCQualifiedInterfaceType()) |
| 4035 | return true; |
| 4036 | } |
| 4037 | |
| 4038 | } |
| 4039 | return false; |
| 4040 | } |
| 4041 | |
| 4042 | void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen, |
| 4043 | const char *&RParen) { |
| 4044 | const char *argPtr = strchr(Name, '('); |
| 4045 | assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); |
| 4046 | |
| 4047 | LParen = argPtr; // output the start. |
| 4048 | argPtr++; // skip past the left paren. |
| 4049 | unsigned parenCount = 1; |
| 4050 | |
| 4051 | while (*argPtr && parenCount) { |
| 4052 | switch (*argPtr) { |
| 4053 | case '(': parenCount++; break; |
| 4054 | case ')': parenCount--; break; |
| 4055 | default: break; |
| 4056 | } |
| 4057 | if (parenCount) argPtr++; |
| 4058 | } |
| 4059 | assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); |
| 4060 | RParen = argPtr; // output the end |
| 4061 | } |
| 4062 | |
| 4063 | void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { |
| 4064 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { |
| 4065 | RewriteBlockPointerFunctionArgs(FD); |
| 4066 | return; |
| 4067 | } |
| 4068 | // Handle Variables and Typedefs. |
| 4069 | SourceLocation DeclLoc = ND->getLocation(); |
| 4070 | QualType DeclT; |
| 4071 | if (VarDecl *VD = dyn_cast<VarDecl>(ND)) |
| 4072 | DeclT = VD->getType(); |
| 4073 | else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND)) |
| 4074 | DeclT = TDD->getUnderlyingType(); |
| 4075 | else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) |
| 4076 | DeclT = FD->getType(); |
| 4077 | else |
| 4078 | llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled"); |
| 4079 | |
| 4080 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 4081 | const char *endBuf = startBuf; |
| 4082 | // scan backward (from the decl location) for the end of the previous decl. |
| 4083 | while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) |
| 4084 | startBuf--; |
| 4085 | SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf); |
| 4086 | std::string buf; |
| 4087 | unsigned OrigLength=0; |
| 4088 | // *startBuf != '^' if we are dealing with a pointer to function that |
| 4089 | // may take block argument types (which will be handled below). |
| 4090 | if (*startBuf == '^') { |
| 4091 | // Replace the '^' with '*', computing a negative offset. |
| 4092 | buf = '*'; |
| 4093 | startBuf++; |
| 4094 | OrigLength++; |
| 4095 | } |
| 4096 | while (*startBuf != ')') { |
| 4097 | buf += *startBuf; |
| 4098 | startBuf++; |
| 4099 | OrigLength++; |
| 4100 | } |
| 4101 | buf += ')'; |
| 4102 | OrigLength++; |
| 4103 | |
| 4104 | if (PointerTypeTakesAnyBlockArguments(DeclT) || |
| 4105 | PointerTypeTakesAnyObjCQualifiedType(DeclT)) { |
| 4106 | // Replace the '^' with '*' for arguments. |
| 4107 | // Replace id<P> with id/*<>*/ |
| 4108 | DeclLoc = ND->getLocation(); |
| 4109 | startBuf = SM->getCharacterData(DeclLoc); |
| 4110 | const char *argListBegin, *argListEnd; |
| 4111 | GetExtentOfArgList(startBuf, argListBegin, argListEnd); |
| 4112 | while (argListBegin < argListEnd) { |
| 4113 | if (*argListBegin == '^') |
| 4114 | buf += '*'; |
| 4115 | else if (*argListBegin == '<') { |
| 4116 | buf += "/*"; |
| 4117 | buf += *argListBegin++; |
| 4118 | OrigLength++;; |
| 4119 | while (*argListBegin != '>') { |
| 4120 | buf += *argListBegin++; |
| 4121 | OrigLength++; |
| 4122 | } |
| 4123 | buf += *argListBegin; |
| 4124 | buf += "*/"; |
| 4125 | } |
| 4126 | else |
| 4127 | buf += *argListBegin; |
| 4128 | argListBegin++; |
| 4129 | OrigLength++; |
| 4130 | } |
| 4131 | buf += ')'; |
| 4132 | OrigLength++; |
| 4133 | } |
| 4134 | ReplaceText(Start, OrigLength, buf); |
| 4135 | |
| 4136 | return; |
| 4137 | } |
| 4138 | |
| 4139 | |
| 4140 | /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: |
| 4141 | /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, |
| 4142 | /// struct Block_byref_id_object *src) { |
| 4143 | /// _Block_object_assign (&_dest->object, _src->object, |
| 4144 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT |
| 4145 | /// [|BLOCK_FIELD_IS_WEAK]) // object |
| 4146 | /// _Block_object_assign(&_dest->object, _src->object, |
| 4147 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK |
| 4148 | /// [|BLOCK_FIELD_IS_WEAK]) // block |
| 4149 | /// } |
| 4150 | /// And: |
| 4151 | /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { |
| 4152 | /// _Block_object_dispose(_src->object, |
| 4153 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT |
| 4154 | /// [|BLOCK_FIELD_IS_WEAK]) // object |
| 4155 | /// _Block_object_dispose(_src->object, |
| 4156 | /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK |
| 4157 | /// [|BLOCK_FIELD_IS_WEAK]) // block |
| 4158 | /// } |
| 4159 | |
| 4160 | std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, |
| 4161 | int flag) { |
| 4162 | std::string S; |
| 4163 | if (CopyDestroyCache.count(flag)) |
| 4164 | return S; |
| 4165 | CopyDestroyCache.insert(flag); |
| 4166 | S = "static void __Block_byref_id_object_copy_"; |
| 4167 | S += utostr(flag); |
| 4168 | S += "(void *dst, void *src) {\n"; |
| 4169 | |
| 4170 | // offset into the object pointer is computed as: |
| 4171 | // void * + void* + int + int + void* + void * |
| 4172 | unsigned IntSize = |
| 4173 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 4174 | unsigned VoidPtrSize = |
| 4175 | static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); |
| 4176 | |
| 4177 | unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); |
| 4178 | S += " _Block_object_assign((char*)dst + "; |
| 4179 | S += utostr(offset); |
| 4180 | S += ", *(void * *) ((char*)src + "; |
| 4181 | S += utostr(offset); |
| 4182 | S += "), "; |
| 4183 | S += utostr(flag); |
| 4184 | S += ");\n}\n"; |
| 4185 | |
| 4186 | S += "static void __Block_byref_id_object_dispose_"; |
| 4187 | S += utostr(flag); |
| 4188 | S += "(void *src) {\n"; |
| 4189 | S += " _Block_object_dispose(*(void * *) ((char*)src + "; |
| 4190 | S += utostr(offset); |
| 4191 | S += "), "; |
| 4192 | S += utostr(flag); |
| 4193 | S += ");\n}\n"; |
| 4194 | return S; |
| 4195 | } |
| 4196 | |
| 4197 | /// RewriteByRefVar - For each __block typex ND variable this routine transforms |
| 4198 | /// the declaration into: |
| 4199 | /// struct __Block_byref_ND { |
| 4200 | /// void *__isa; // NULL for everything except __weak pointers |
| 4201 | /// struct __Block_byref_ND *__forwarding; |
| 4202 | /// int32_t __flags; |
| 4203 | /// int32_t __size; |
| 4204 | /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object |
| 4205 | /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object |
| 4206 | /// typex ND; |
| 4207 | /// }; |
| 4208 | /// |
| 4209 | /// It then replaces declaration of ND variable with: |
| 4210 | /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, |
| 4211 | /// __size=sizeof(struct __Block_byref_ND), |
| 4212 | /// ND=initializer-if-any}; |
| 4213 | /// |
| 4214 | /// |
| 4215 | void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) { |
| 4216 | // Insert declaration for the function in which block literal is |
| 4217 | // used. |
| 4218 | if (CurFunctionDeclToDeclareForBlock) |
| 4219 | RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock); |
| 4220 | int flag = 0; |
| 4221 | int isa = 0; |
| 4222 | SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); |
| 4223 | if (DeclLoc.isInvalid()) |
| 4224 | // If type location is missing, it is because of missing type (a warning). |
| 4225 | // Use variable's location which is good for this case. |
| 4226 | DeclLoc = ND->getLocation(); |
| 4227 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 4228 | SourceLocation X = ND->getLocEnd(); |
| 4229 | X = SM->getExpansionLoc(X); |
| 4230 | const char *endBuf = SM->getCharacterData(X); |
| 4231 | std::string Name(ND->getNameAsString()); |
| 4232 | std::string ByrefType; |
| 4233 | RewriteByRefString(ByrefType, Name, ND, true); |
| 4234 | ByrefType += " {\n"; |
| 4235 | ByrefType += " void *__isa;\n"; |
| 4236 | RewriteByRefString(ByrefType, Name, ND); |
| 4237 | ByrefType += " *__forwarding;\n"; |
| 4238 | ByrefType += " int __flags;\n"; |
| 4239 | ByrefType += " int __size;\n"; |
| 4240 | // Add void *__Block_byref_id_object_copy; |
| 4241 | // void *__Block_byref_id_object_dispose; if needed. |
| 4242 | QualType Ty = ND->getType(); |
| 4243 | bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty); |
| 4244 | if (HasCopyAndDispose) { |
| 4245 | ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n"; |
| 4246 | ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n"; |
| 4247 | } |
| 4248 | |
| 4249 | QualType T = Ty; |
| 4250 | (void)convertBlockPointerToFunctionPointer(T); |
| 4251 | T.getAsStringInternal(Name, Context->getPrintingPolicy()); |
| 4252 | |
| 4253 | ByrefType += " " + Name + ";\n"; |
| 4254 | ByrefType += "};\n"; |
| 4255 | // Insert this type in global scope. It is needed by helper function. |
| 4256 | SourceLocation FunLocStart; |
| 4257 | if (CurFunctionDef) |
| 4258 | FunLocStart = CurFunctionDef->getTypeSpecStartLoc(); |
| 4259 | else { |
| 4260 | assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); |
| 4261 | FunLocStart = CurMethodDef->getLocStart(); |
| 4262 | } |
| 4263 | InsertText(FunLocStart, ByrefType); |
| 4264 | if (Ty.isObjCGCWeak()) { |
| 4265 | flag |= BLOCK_FIELD_IS_WEAK; |
| 4266 | isa = 1; |
| 4267 | } |
| 4268 | |
| 4269 | if (HasCopyAndDispose) { |
| 4270 | flag = BLOCK_BYREF_CALLER; |
| 4271 | QualType Ty = ND->getType(); |
| 4272 | // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well. |
| 4273 | if (Ty->isBlockPointerType()) |
| 4274 | flag |= BLOCK_FIELD_IS_BLOCK; |
| 4275 | else |
| 4276 | flag |= BLOCK_FIELD_IS_OBJECT; |
| 4277 | std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag); |
| 4278 | if (!HF.empty()) |
| 4279 | InsertText(FunLocStart, HF); |
| 4280 | } |
| 4281 | |
| 4282 | // struct __Block_byref_ND ND = |
| 4283 | // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), |
| 4284 | // initializer-if-any}; |
| 4285 | bool hasInit = (ND->getInit() != 0); |
| 4286 | unsigned flags = 0; |
| 4287 | if (HasCopyAndDispose) |
| 4288 | flags |= BLOCK_HAS_COPY_DISPOSE; |
| 4289 | Name = ND->getNameAsString(); |
| 4290 | ByrefType.clear(); |
| 4291 | RewriteByRefString(ByrefType, Name, ND); |
| 4292 | std::string ForwardingCastType("("); |
| 4293 | ForwardingCastType += ByrefType + " *)"; |
| 4294 | if (!hasInit) { |
| 4295 | ByrefType += " " + Name + " = {(void*)"; |
| 4296 | ByrefType += utostr(isa); |
| 4297 | ByrefType += "," + ForwardingCastType + "&" + Name + ", "; |
| 4298 | ByrefType += utostr(flags); |
| 4299 | ByrefType += ", "; |
| 4300 | ByrefType += "sizeof("; |
| 4301 | RewriteByRefString(ByrefType, Name, ND); |
| 4302 | ByrefType += ")"; |
| 4303 | if (HasCopyAndDispose) { |
| 4304 | ByrefType += ", __Block_byref_id_object_copy_"; |
| 4305 | ByrefType += utostr(flag); |
| 4306 | ByrefType += ", __Block_byref_id_object_dispose_"; |
| 4307 | ByrefType += utostr(flag); |
| 4308 | } |
| 4309 | ByrefType += "};\n"; |
| 4310 | unsigned nameSize = Name.size(); |
| 4311 | // for block or function pointer declaration. Name is aleady |
| 4312 | // part of the declaration. |
| 4313 | if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) |
| 4314 | nameSize = 1; |
| 4315 | ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType); |
| 4316 | } |
| 4317 | else { |
| 4318 | SourceLocation startLoc; |
| 4319 | Expr *E = ND->getInit(); |
| 4320 | if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) |
| 4321 | startLoc = ECE->getLParenLoc(); |
| 4322 | else |
| 4323 | startLoc = E->getLocStart(); |
| 4324 | startLoc = SM->getExpansionLoc(startLoc); |
| 4325 | endBuf = SM->getCharacterData(startLoc); |
| 4326 | ByrefType += " " + Name; |
| 4327 | ByrefType += " = {(void*)"; |
| 4328 | ByrefType += utostr(isa); |
| 4329 | ByrefType += "," + ForwardingCastType + "&" + Name + ", "; |
| 4330 | ByrefType += utostr(flags); |
| 4331 | ByrefType += ", "; |
| 4332 | ByrefType += "sizeof("; |
| 4333 | RewriteByRefString(ByrefType, Name, ND); |
| 4334 | ByrefType += "), "; |
| 4335 | if (HasCopyAndDispose) { |
| 4336 | ByrefType += "__Block_byref_id_object_copy_"; |
| 4337 | ByrefType += utostr(flag); |
| 4338 | ByrefType += ", __Block_byref_id_object_dispose_"; |
| 4339 | ByrefType += utostr(flag); |
| 4340 | ByrefType += ", "; |
| 4341 | } |
| 4342 | ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); |
| 4343 | |
| 4344 | // Complete the newly synthesized compound expression by inserting a right |
| 4345 | // curly brace before the end of the declaration. |
| 4346 | // FIXME: This approach avoids rewriting the initializer expression. It |
| 4347 | // also assumes there is only one declarator. For example, the following |
| 4348 | // isn't currently supported by this routine (in general): |
| 4349 | // |
| 4350 | // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37; |
| 4351 | // |
| 4352 | const char *startInitializerBuf = SM->getCharacterData(startLoc); |
| 4353 | const char *semiBuf = strchr(startInitializerBuf, ';'); |
| 4354 | assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'"); |
| 4355 | SourceLocation semiLoc = |
| 4356 | startLoc.getLocWithOffset(semiBuf-startInitializerBuf); |
| 4357 | |
| 4358 | InsertText(semiLoc, "}"); |
| 4359 | } |
| 4360 | return; |
| 4361 | } |
| 4362 | |
| 4363 | void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { |
| 4364 | // Add initializers for any closure decl refs. |
| 4365 | GetBlockDeclRefExprs(Exp->getBody()); |
| 4366 | if (BlockDeclRefs.size()) { |
| 4367 | // Unique all "by copy" declarations. |
| 4368 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4369 | if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4370 | if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { |
| 4371 | BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); |
| 4372 | BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl()); |
| 4373 | } |
| 4374 | } |
| 4375 | // Unique all "by ref" declarations. |
| 4376 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4377 | if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4378 | if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { |
| 4379 | BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); |
| 4380 | BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl()); |
| 4381 | } |
| 4382 | } |
| 4383 | // Find any imported blocks...they will need special attention. |
| 4384 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4385 | if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4386 | BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || |
| 4387 | BlockDeclRefs[i]->getType()->isBlockPointerType()) |
| 4388 | ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 4389 | } |
| 4390 | } |
| 4391 | |
| 4392 | FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { |
| 4393 | IdentifierInfo *ID = &Context->Idents.get(name); |
| 4394 | QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); |
| 4395 | return FunctionDecl::Create(*Context, TUDecl, SourceLocation(), |
| 4396 | SourceLocation(), ID, FType, 0, SC_Extern, |
| 4397 | SC_None, false, false); |
| 4398 | } |
| 4399 | |
| 4400 | Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4401 | const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4402 | const BlockDecl *block = Exp->getBlockDecl(); |
| 4403 | Blocks.push_back(Exp); |
| 4404 | |
| 4405 | CollectBlockDeclRefInfo(Exp); |
| 4406 | |
| 4407 | // Add inner imported variables now used in current block. |
| 4408 | int countOfInnerDecls = 0; |
| 4409 | if (!InnerBlockDeclRefs.empty()) { |
| 4410 | for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) { |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4411 | DeclRefExpr *Exp = InnerBlockDeclRefs[i]; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4412 | ValueDecl *VD = Exp->getDecl(); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4413 | if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4414 | // We need to save the copied-in variables in nested |
| 4415 | // blocks because it is needed at the end for some of the API generations. |
| 4416 | // See SynthesizeBlockLiterals routine. |
| 4417 | InnerDeclRefs.push_back(Exp); countOfInnerDecls++; |
| 4418 | BlockDeclRefs.push_back(Exp); |
| 4419 | BlockByCopyDeclsPtrSet.insert(VD); |
| 4420 | BlockByCopyDecls.push_back(VD); |
| 4421 | } |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4422 | if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4423 | InnerDeclRefs.push_back(Exp); countOfInnerDecls++; |
| 4424 | BlockDeclRefs.push_back(Exp); |
| 4425 | BlockByRefDeclsPtrSet.insert(VD); |
| 4426 | BlockByRefDecls.push_back(VD); |
| 4427 | } |
| 4428 | } |
| 4429 | // Find any imported blocks...they will need special attention. |
| 4430 | for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4431 | if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4432 | InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || |
| 4433 | InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) |
| 4434 | ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); |
| 4435 | } |
| 4436 | InnerDeclRefsCount.push_back(countOfInnerDecls); |
| 4437 | |
| 4438 | std::string FuncName; |
| 4439 | |
| 4440 | if (CurFunctionDef) |
| 4441 | FuncName = CurFunctionDef->getNameAsString(); |
| 4442 | else if (CurMethodDef) |
| 4443 | BuildUniqueMethodName(FuncName, CurMethodDef); |
| 4444 | else if (GlobalVarDecl) |
| 4445 | FuncName = std::string(GlobalVarDecl->getNameAsString()); |
| 4446 | |
| 4447 | std::string BlockNumber = utostr(Blocks.size()-1); |
| 4448 | |
| 4449 | std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; |
| 4450 | std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; |
| 4451 | |
| 4452 | // Get a pointer to the function type so we can cast appropriately. |
| 4453 | QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType()); |
| 4454 | QualType FType = Context->getPointerType(BFT); |
| 4455 | |
| 4456 | FunctionDecl *FD; |
| 4457 | Expr *NewRep; |
| 4458 | |
| 4459 | // Simulate a contructor call... |
| 4460 | FD = SynthBlockInitFunctionDecl(Tag); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4461 | DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4462 | SourceLocation()); |
| 4463 | |
| 4464 | SmallVector<Expr*, 4> InitExprs; |
| 4465 | |
| 4466 | // Initialize the block function. |
| 4467 | FD = SynthBlockInitFunctionDecl(Func); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4468 | DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), |
| 4469 | VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4470 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, |
| 4471 | CK_BitCast, Arg); |
| 4472 | InitExprs.push_back(castExpr); |
| 4473 | |
| 4474 | // Initialize the block descriptor. |
| 4475 | std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; |
| 4476 | |
| 4477 | VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, |
| 4478 | SourceLocation(), SourceLocation(), |
| 4479 | &Context->Idents.get(DescData.c_str()), |
| 4480 | Context->VoidPtrTy, 0, |
| 4481 | SC_Static, SC_None); |
| 4482 | UnaryOperator *DescRefExpr = |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4483 | new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4484 | Context->VoidPtrTy, |
| 4485 | VK_LValue, |
| 4486 | SourceLocation()), |
| 4487 | UO_AddrOf, |
| 4488 | Context->getPointerType(Context->VoidPtrTy), |
| 4489 | VK_RValue, OK_Ordinary, |
| 4490 | SourceLocation()); |
| 4491 | InitExprs.push_back(DescRefExpr); |
| 4492 | |
| 4493 | // Add initializers for any closure decl refs. |
| 4494 | if (BlockDeclRefs.size()) { |
| 4495 | Expr *Exp; |
| 4496 | // Output all "by copy" declarations. |
| 4497 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 4498 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 4499 | if (isObjCType((*I)->getType())) { |
| 4500 | // FIXME: Conform to ABI ([[obj retain] autorelease]). |
| 4501 | FD = SynthBlockInitFunctionDecl((*I)->getName()); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4502 | Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), |
| 4503 | VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4504 | if (HasLocalVariableExternalStorage(*I)) { |
| 4505 | QualType QT = (*I)->getType(); |
| 4506 | QT = Context->getPointerType(QT); |
| 4507 | Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue, |
| 4508 | OK_Ordinary, SourceLocation()); |
| 4509 | } |
| 4510 | } else if (isTopLevelBlockPointerType((*I)->getType())) { |
| 4511 | FD = SynthBlockInitFunctionDecl((*I)->getName()); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4512 | Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), |
| 4513 | VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4514 | Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, |
| 4515 | CK_BitCast, Arg); |
| 4516 | } else { |
| 4517 | FD = SynthBlockInitFunctionDecl((*I)->getName()); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4518 | Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), |
| 4519 | VK_LValue, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4520 | if (HasLocalVariableExternalStorage(*I)) { |
| 4521 | QualType QT = (*I)->getType(); |
| 4522 | QT = Context->getPointerType(QT); |
| 4523 | Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue, |
| 4524 | OK_Ordinary, SourceLocation()); |
| 4525 | } |
| 4526 | |
| 4527 | } |
| 4528 | InitExprs.push_back(Exp); |
| 4529 | } |
| 4530 | // Output all "by ref" declarations. |
| 4531 | for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 4532 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 4533 | ValueDecl *ND = (*I); |
| 4534 | std::string Name(ND->getNameAsString()); |
| 4535 | std::string RecName; |
| 4536 | RewriteByRefString(RecName, Name, ND, true); |
| 4537 | IdentifierInfo *II = &Context->Idents.get(RecName.c_str() |
| 4538 | + sizeof("struct")); |
| 4539 | RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, |
| 4540 | SourceLocation(), SourceLocation(), |
| 4541 | II); |
| 4542 | assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); |
| 4543 | QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); |
| 4544 | |
| 4545 | FD = SynthBlockInitFunctionDecl((*I)->getName()); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4546 | Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue, |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4547 | SourceLocation()); |
| 4548 | bool isNestedCapturedVar = false; |
| 4549 | if (block) |
| 4550 | for (BlockDecl::capture_const_iterator ci = block->capture_begin(), |
| 4551 | ce = block->capture_end(); ci != ce; ++ci) { |
| 4552 | const VarDecl *variable = ci->getVariable(); |
| 4553 | if (variable == ND && ci->isNested()) { |
| 4554 | assert (ci->isByRef() && |
| 4555 | "SynthBlockInitExpr - captured block variable is not byref"); |
| 4556 | isNestedCapturedVar = true; |
| 4557 | break; |
| 4558 | } |
| 4559 | } |
| 4560 | // captured nested byref variable has its address passed. Do not take |
| 4561 | // its address again. |
| 4562 | if (!isNestedCapturedVar) |
| 4563 | Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, |
| 4564 | Context->getPointerType(Exp->getType()), |
| 4565 | VK_RValue, OK_Ordinary, SourceLocation()); |
| 4566 | Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp); |
| 4567 | InitExprs.push_back(Exp); |
| 4568 | } |
| 4569 | } |
| 4570 | if (ImportedBlockDecls.size()) { |
| 4571 | // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR |
| 4572 | int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); |
| 4573 | unsigned IntSize = |
| 4574 | static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); |
| 4575 | Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), |
| 4576 | Context->IntTy, SourceLocation()); |
| 4577 | InitExprs.push_back(FlagExp); |
| 4578 | } |
| 4579 | NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(), |
| 4580 | FType, VK_LValue, SourceLocation()); |
| 4581 | NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf, |
| 4582 | Context->getPointerType(NewRep->getType()), |
| 4583 | VK_RValue, OK_Ordinary, SourceLocation()); |
| 4584 | NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast, |
| 4585 | NewRep); |
| 4586 | BlockDeclRefs.clear(); |
| 4587 | BlockByRefDecls.clear(); |
| 4588 | BlockByRefDeclsPtrSet.clear(); |
| 4589 | BlockByCopyDecls.clear(); |
| 4590 | BlockByCopyDeclsPtrSet.clear(); |
| 4591 | ImportedBlockDecls.clear(); |
| 4592 | return NewRep; |
| 4593 | } |
| 4594 | |
| 4595 | bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { |
| 4596 | if (const ObjCForCollectionStmt * CS = |
| 4597 | dyn_cast<ObjCForCollectionStmt>(Stmts.back())) |
| 4598 | return CS->getElement() == DS; |
| 4599 | return false; |
| 4600 | } |
| 4601 | |
| 4602 | //===----------------------------------------------------------------------===// |
| 4603 | // Function Body / Expression rewriting |
| 4604 | //===----------------------------------------------------------------------===// |
| 4605 | |
| 4606 | Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { |
| 4607 | if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || |
| 4608 | isa<DoStmt>(S) || isa<ForStmt>(S)) |
| 4609 | Stmts.push_back(S); |
| 4610 | else if (isa<ObjCForCollectionStmt>(S)) { |
| 4611 | Stmts.push_back(S); |
| 4612 | ObjCBcLabelNo.push_back(++BcLabelCount); |
| 4613 | } |
| 4614 | |
| 4615 | // Pseudo-object operations and ivar references need special |
| 4616 | // treatment because we're going to recursively rewrite them. |
| 4617 | if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) { |
| 4618 | if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) { |
| 4619 | return RewritePropertyOrImplicitSetter(PseudoOp); |
| 4620 | } else { |
| 4621 | return RewritePropertyOrImplicitGetter(PseudoOp); |
| 4622 | } |
| 4623 | } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { |
| 4624 | return RewriteObjCIvarRefExpr(IvarRefExpr); |
| 4625 | } |
| 4626 | |
| 4627 | SourceRange OrigStmtRange = S->getSourceRange(); |
| 4628 | |
| 4629 | // Perform a bottom up rewrite of all children. |
| 4630 | for (Stmt::child_range CI = S->children(); CI; ++CI) |
| 4631 | if (*CI) { |
| 4632 | Stmt *childStmt = (*CI); |
| 4633 | Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt); |
| 4634 | if (newStmt) { |
| 4635 | *CI = newStmt; |
| 4636 | } |
| 4637 | } |
| 4638 | |
| 4639 | if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) { |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 4640 | SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4641 | llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts; |
| 4642 | InnerContexts.insert(BE->getBlockDecl()); |
| 4643 | ImportedLocalExternalDecls.clear(); |
| 4644 | GetInnerBlockDeclRefExprs(BE->getBody(), |
| 4645 | InnerBlockDeclRefs, InnerContexts); |
| 4646 | // Rewrite the block body in place. |
| 4647 | Stmt *SaveCurrentBody = CurrentBody; |
| 4648 | CurrentBody = BE->getBody(); |
| 4649 | PropParentMap = 0; |
| 4650 | // block literal on rhs of a property-dot-sytax assignment |
| 4651 | // must be replaced by its synthesize ast so getRewrittenText |
| 4652 | // works as expected. In this case, what actually ends up on RHS |
| 4653 | // is the blockTranscribed which is the helper function for the |
| 4654 | // block literal; as in: self.c = ^() {[ace ARR];}; |
| 4655 | bool saveDisableReplaceStmt = DisableReplaceStmt; |
| 4656 | DisableReplaceStmt = false; |
| 4657 | RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); |
| 4658 | DisableReplaceStmt = saveDisableReplaceStmt; |
| 4659 | CurrentBody = SaveCurrentBody; |
| 4660 | PropParentMap = 0; |
| 4661 | ImportedLocalExternalDecls.clear(); |
| 4662 | // Now we snarf the rewritten text and stash it away for later use. |
| 4663 | std::string Str = Rewrite.getRewrittenText(BE->getSourceRange()); |
| 4664 | RewrittenBlockExprs[BE] = Str; |
| 4665 | |
| 4666 | Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); |
| 4667 | |
| 4668 | //blockTranscribed->dump(); |
| 4669 | ReplaceStmt(S, blockTranscribed); |
| 4670 | return blockTranscribed; |
| 4671 | } |
| 4672 | // Handle specific things. |
| 4673 | if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S)) |
| 4674 | return RewriteAtEncode(AtEncode); |
| 4675 | |
| 4676 | if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S)) |
| 4677 | return RewriteAtSelector(AtSelector); |
| 4678 | |
| 4679 | if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) |
| 4680 | return RewriteObjCStringLiteral(AtString); |
| 4681 | |
| 4682 | if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { |
| 4683 | #if 0 |
| 4684 | // Before we rewrite it, put the original message expression in a comment. |
| 4685 | SourceLocation startLoc = MessExpr->getLocStart(); |
| 4686 | SourceLocation endLoc = MessExpr->getLocEnd(); |
| 4687 | |
| 4688 | const char *startBuf = SM->getCharacterData(startLoc); |
| 4689 | const char *endBuf = SM->getCharacterData(endLoc); |
| 4690 | |
| 4691 | std::string messString; |
| 4692 | messString += "// "; |
| 4693 | messString.append(startBuf, endBuf-startBuf+1); |
| 4694 | messString += "\n"; |
| 4695 | |
| 4696 | // FIXME: Missing definition of |
| 4697 | // InsertText(clang::SourceLocation, char const*, unsigned int). |
| 4698 | // InsertText(startLoc, messString.c_str(), messString.size()); |
| 4699 | // Tried this, but it didn't work either... |
| 4700 | // ReplaceText(startLoc, 0, messString.c_str(), messString.size()); |
| 4701 | #endif |
| 4702 | return RewriteMessageExpr(MessExpr); |
| 4703 | } |
| 4704 | |
| 4705 | if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) |
| 4706 | return RewriteObjCTryStmt(StmtTry); |
| 4707 | |
| 4708 | if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S)) |
| 4709 | return RewriteObjCSynchronizedStmt(StmtTry); |
| 4710 | |
| 4711 | if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S)) |
| 4712 | return RewriteObjCThrowStmt(StmtThrow); |
| 4713 | |
| 4714 | if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S)) |
| 4715 | return RewriteObjCProtocolExpr(ProtocolExp); |
| 4716 | |
| 4717 | if (ObjCForCollectionStmt *StmtForCollection = |
| 4718 | dyn_cast<ObjCForCollectionStmt>(S)) |
| 4719 | return RewriteObjCForCollectionStmt(StmtForCollection, |
| 4720 | OrigStmtRange.getEnd()); |
| 4721 | if (BreakStmt *StmtBreakStmt = |
| 4722 | dyn_cast<BreakStmt>(S)) |
| 4723 | return RewriteBreakStmt(StmtBreakStmt); |
| 4724 | if (ContinueStmt *StmtContinueStmt = |
| 4725 | dyn_cast<ContinueStmt>(S)) |
| 4726 | return RewriteContinueStmt(StmtContinueStmt); |
| 4727 | |
| 4728 | // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls |
| 4729 | // and cast exprs. |
| 4730 | if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { |
| 4731 | // FIXME: What we're doing here is modifying the type-specifier that |
| 4732 | // precedes the first Decl. In the future the DeclGroup should have |
| 4733 | // a separate type-specifier that we can rewrite. |
| 4734 | // NOTE: We need to avoid rewriting the DeclStmt if it is within |
| 4735 | // the context of an ObjCForCollectionStmt. For example: |
| 4736 | // NSArray *someArray; |
| 4737 | // for (id <FooProtocol> index in someArray) ; |
| 4738 | // This is because RewriteObjCForCollectionStmt() does textual rewriting |
| 4739 | // and it depends on the original text locations/positions. |
| 4740 | if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) |
| 4741 | RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); |
| 4742 | |
| 4743 | // Blocks rewrite rules. |
| 4744 | for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); |
| 4745 | DI != DE; ++DI) { |
| 4746 | Decl *SD = *DI; |
| 4747 | if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { |
| 4748 | if (isTopLevelBlockPointerType(ND->getType())) |
| 4749 | RewriteBlockPointerDecl(ND); |
| 4750 | else if (ND->getType()->isFunctionPointerType()) |
| 4751 | CheckFunctionPointerDecl(ND->getType(), ND); |
| 4752 | if (VarDecl *VD = dyn_cast<VarDecl>(SD)) { |
| 4753 | if (VD->hasAttr<BlocksAttr>()) { |
| 4754 | static unsigned uniqueByrefDeclCount = 0; |
| 4755 | assert(!BlockByRefDeclNo.count(ND) && |
| 4756 | "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"); |
| 4757 | BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; |
| 4758 | RewriteByRefVar(VD); |
| 4759 | } |
| 4760 | else |
| 4761 | RewriteTypeOfDecl(VD); |
| 4762 | } |
| 4763 | } |
| 4764 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) { |
| 4765 | if (isTopLevelBlockPointerType(TD->getUnderlyingType())) |
| 4766 | RewriteBlockPointerDecl(TD); |
| 4767 | else if (TD->getUnderlyingType()->isFunctionPointerType()) |
| 4768 | CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); |
| 4769 | } |
| 4770 | } |
| 4771 | } |
| 4772 | |
| 4773 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) |
| 4774 | RewriteObjCQualifiedInterfaceTypes(CE); |
| 4775 | |
| 4776 | if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || |
| 4777 | isa<DoStmt>(S) || isa<ForStmt>(S)) { |
| 4778 | assert(!Stmts.empty() && "Statement stack is empty"); |
| 4779 | assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || |
| 4780 | isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) |
| 4781 | && "Statement stack mismatch"); |
| 4782 | Stmts.pop_back(); |
| 4783 | } |
| 4784 | // Handle blocks rewriting. |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4785 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { |
| 4786 | ValueDecl *VD = DRE->getDecl(); |
| 4787 | if (VD->hasAttr<BlocksAttr>()) |
| 4788 | return RewriteBlockDeclRefExpr(DRE); |
| 4789 | if (HasLocalVariableExternalStorage(VD)) |
| 4790 | return RewriteLocalVariableExternalStorage(DRE); |
| 4791 | } |
| 4792 | |
| 4793 | if (CallExpr *CE = dyn_cast<CallExpr>(S)) { |
| 4794 | if (CE->getCallee()->getType()->isBlockPointerType()) { |
| 4795 | Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); |
| 4796 | ReplaceStmt(S, BlockCall); |
| 4797 | return BlockCall; |
| 4798 | } |
| 4799 | } |
| 4800 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) { |
| 4801 | RewriteCastExpr(CE); |
| 4802 | } |
| 4803 | #if 0 |
| 4804 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { |
| 4805 | CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), |
| 4806 | ICE->getSubExpr(), |
| 4807 | SourceLocation()); |
| 4808 | // Get the new text. |
| 4809 | std::string SStr; |
| 4810 | llvm::raw_string_ostream Buf(SStr); |
| 4811 | Replacement->printPretty(Buf, *Context); |
| 4812 | const std::string &Str = Buf.str(); |
| 4813 | |
| 4814 | printf("CAST = %s\n", &Str[0]); |
| 4815 | InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size()); |
| 4816 | delete S; |
| 4817 | return Replacement; |
| 4818 | } |
| 4819 | #endif |
| 4820 | // Return this stmt unmodified. |
| 4821 | return S; |
| 4822 | } |
| 4823 | |
| 4824 | void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) { |
| 4825 | for (RecordDecl::field_iterator i = RD->field_begin(), |
| 4826 | e = RD->field_end(); i != e; ++i) { |
| 4827 | FieldDecl *FD = *i; |
| 4828 | if (isTopLevelBlockPointerType(FD->getType())) |
| 4829 | RewriteBlockPointerDecl(FD); |
| 4830 | if (FD->getType()->isObjCQualifiedIdType() || |
| 4831 | FD->getType()->isObjCQualifiedInterfaceType()) |
| 4832 | RewriteObjCQualifiedInterfaceTypes(FD); |
| 4833 | } |
| 4834 | } |
| 4835 | |
| 4836 | /// HandleDeclInMainFile - This is called for each top-level decl defined in the |
| 4837 | /// main file of the input. |
| 4838 | void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { |
| 4839 | switch (D->getKind()) { |
| 4840 | case Decl::Function: { |
| 4841 | FunctionDecl *FD = cast<FunctionDecl>(D); |
| 4842 | if (FD->isOverloadedOperator()) |
| 4843 | return; |
| 4844 | |
| 4845 | // Since function prototypes don't have ParmDecl's, we check the function |
| 4846 | // prototype. This enables us to rewrite function declarations and |
| 4847 | // definitions using the same code. |
| 4848 | RewriteBlocksInFunctionProtoType(FD->getType(), FD); |
| 4849 | |
Argyrios Kyrtzidis | 9335df3 | 2012-02-12 04:48:45 +0000 | [diff] [blame] | 4850 | if (!FD->isThisDeclarationADefinition()) |
| 4851 | break; |
| 4852 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4853 | // FIXME: If this should support Obj-C++, support CXXTryStmt |
| 4854 | if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) { |
| 4855 | CurFunctionDef = FD; |
| 4856 | CurFunctionDeclToDeclareForBlock = FD; |
| 4857 | CurrentBody = Body; |
| 4858 | Body = |
| 4859 | cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); |
| 4860 | FD->setBody(Body); |
| 4861 | CurrentBody = 0; |
| 4862 | if (PropParentMap) { |
| 4863 | delete PropParentMap; |
| 4864 | PropParentMap = 0; |
| 4865 | } |
| 4866 | // This synthesizes and inserts the block "impl" struct, invoke function, |
| 4867 | // and any copy/dispose helper functions. |
| 4868 | InsertBlockLiteralsWithinFunction(FD); |
| 4869 | CurFunctionDef = 0; |
| 4870 | CurFunctionDeclToDeclareForBlock = 0; |
| 4871 | } |
| 4872 | break; |
| 4873 | } |
| 4874 | case Decl::ObjCMethod: { |
| 4875 | ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D); |
| 4876 | if (CompoundStmt *Body = MD->getCompoundBody()) { |
| 4877 | CurMethodDef = MD; |
| 4878 | CurrentBody = Body; |
| 4879 | Body = |
| 4880 | cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); |
| 4881 | MD->setBody(Body); |
| 4882 | CurrentBody = 0; |
| 4883 | if (PropParentMap) { |
| 4884 | delete PropParentMap; |
| 4885 | PropParentMap = 0; |
| 4886 | } |
| 4887 | InsertBlockLiteralsWithinMethod(MD); |
| 4888 | CurMethodDef = 0; |
| 4889 | } |
| 4890 | break; |
| 4891 | } |
| 4892 | case Decl::ObjCImplementation: { |
| 4893 | ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D); |
| 4894 | ClassImplementation.push_back(CI); |
| 4895 | break; |
| 4896 | } |
| 4897 | case Decl::ObjCCategoryImpl: { |
| 4898 | ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D); |
| 4899 | CategoryImplementation.push_back(CI); |
| 4900 | break; |
| 4901 | } |
| 4902 | case Decl::Var: { |
| 4903 | VarDecl *VD = cast<VarDecl>(D); |
| 4904 | RewriteObjCQualifiedInterfaceTypes(VD); |
| 4905 | if (isTopLevelBlockPointerType(VD->getType())) |
| 4906 | RewriteBlockPointerDecl(VD); |
| 4907 | else if (VD->getType()->isFunctionPointerType()) { |
| 4908 | CheckFunctionPointerDecl(VD->getType(), VD); |
| 4909 | if (VD->getInit()) { |
| 4910 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { |
| 4911 | RewriteCastExpr(CE); |
| 4912 | } |
| 4913 | } |
| 4914 | } else if (VD->getType()->isRecordType()) { |
| 4915 | RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl(); |
| 4916 | if (RD->isCompleteDefinition()) |
| 4917 | RewriteRecordBody(RD); |
| 4918 | } |
| 4919 | if (VD->getInit()) { |
| 4920 | GlobalVarDecl = VD; |
| 4921 | CurrentBody = VD->getInit(); |
| 4922 | RewriteFunctionBodyOrGlobalInitializer(VD->getInit()); |
| 4923 | CurrentBody = 0; |
| 4924 | if (PropParentMap) { |
| 4925 | delete PropParentMap; |
| 4926 | PropParentMap = 0; |
| 4927 | } |
| 4928 | SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName()); |
| 4929 | GlobalVarDecl = 0; |
| 4930 | |
| 4931 | // This is needed for blocks. |
| 4932 | if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { |
| 4933 | RewriteCastExpr(CE); |
| 4934 | } |
| 4935 | } |
| 4936 | break; |
| 4937 | } |
| 4938 | case Decl::TypeAlias: |
| 4939 | case Decl::Typedef: { |
| 4940 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { |
| 4941 | if (isTopLevelBlockPointerType(TD->getUnderlyingType())) |
| 4942 | RewriteBlockPointerDecl(TD); |
| 4943 | else if (TD->getUnderlyingType()->isFunctionPointerType()) |
| 4944 | CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); |
| 4945 | } |
| 4946 | break; |
| 4947 | } |
| 4948 | case Decl::CXXRecord: |
| 4949 | case Decl::Record: { |
| 4950 | RecordDecl *RD = cast<RecordDecl>(D); |
| 4951 | if (RD->isCompleteDefinition()) |
| 4952 | RewriteRecordBody(RD); |
| 4953 | break; |
| 4954 | } |
| 4955 | default: |
| 4956 | break; |
| 4957 | } |
| 4958 | // Nothing yet. |
| 4959 | } |
| 4960 | |
| 4961 | void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { |
| 4962 | if (Diags.hasErrorOccurred()) |
| 4963 | return; |
| 4964 | |
| 4965 | RewriteInclude(); |
| 4966 | |
| 4967 | // Here's a great place to add any extra declarations that may be needed. |
| 4968 | // Write out meta data for each @protocol(<expr>). |
| 4969 | for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(), |
| 4970 | E = ProtocolExprDecls.end(); I != E; ++I) |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 4971 | RewriteObjCProtocolMetaData(*I, Preamble); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4972 | |
| 4973 | InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); |
Fariborz Jahanian | 5731778 | 2012-02-21 23:58:41 +0000 | [diff] [blame] | 4974 | for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { |
| 4975 | ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; |
| 4976 | // Write struct declaration for the class matching its ivar declarations. |
| 4977 | // Note that for modern abi, this is postponed until the end of TU |
| 4978 | // because class extensions and the implementation might declare their own |
| 4979 | // private ivars. |
| 4980 | RewriteInterfaceDecl(CDecl); |
| 4981 | } |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 4982 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 4983 | if (ClassImplementation.size() || CategoryImplementation.size()) |
| 4984 | RewriteImplementations(); |
| 4985 | |
| 4986 | // Get the buffer corresponding to MainFileID. If we haven't changed it, then |
| 4987 | // we are done. |
| 4988 | if (const RewriteBuffer *RewriteBuf = |
| 4989 | Rewrite.getRewriteBufferFor(MainFileID)) { |
| 4990 | //printf("Changed:\n"); |
| 4991 | *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); |
| 4992 | } else { |
| 4993 | llvm::errs() << "No changes\n"; |
| 4994 | } |
| 4995 | |
| 4996 | if (ClassImplementation.size() || CategoryImplementation.size() || |
| 4997 | ProtocolExprDecls.size()) { |
| 4998 | // Rewrite Objective-c meta data* |
| 4999 | std::string ResultStr; |
| 5000 | RewriteMetaDataIntoBuffer(ResultStr); |
| 5001 | // Emit metadata. |
| 5002 | *OutFile << ResultStr; |
| 5003 | } |
| 5004 | OutFile->flush(); |
| 5005 | } |
| 5006 | |
| 5007 | void RewriteModernObjC::Initialize(ASTContext &context) { |
| 5008 | InitializeCommon(context); |
| 5009 | |
Fariborz Jahanian | 6991bc5 | 2012-03-10 17:45:38 +0000 | [diff] [blame] | 5010 | Preamble += "#ifndef __OBJC2__\n"; |
| 5011 | Preamble += "#define __OBJC2__\n"; |
| 5012 | Preamble += "#endif\n"; |
| 5013 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5014 | // declaring objc_selector outside the parameter list removes a silly |
| 5015 | // scope related warning... |
| 5016 | if (IsHeader) |
| 5017 | Preamble = "#pragma once\n"; |
| 5018 | Preamble += "struct objc_selector; struct objc_class;\n"; |
| 5019 | Preamble += "struct __rw_objc_super { struct objc_object *object; "; |
| 5020 | Preamble += "struct objc_object *superClass; "; |
| 5021 | if (LangOpts.MicrosoftExt) { |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 5022 | // Define all sections using syntax that makes sense. |
| 5023 | Preamble += "\n#pragma section(\".datacoal_nt$B\", long, read, write)\n"; |
| 5024 | Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n"; |
| 5025 | Preamble += "#pragma section(\".objc_classlist$B\", long, read, write)\n"; |
| 5026 | Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n"; |
| 5027 | Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; |
| 5028 | Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; |
Fariborz Jahanian | 40a777a | 2012-03-12 16:46:58 +0000 | [diff] [blame] | 5029 | Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 5030 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5031 | // Add a constructor for creating temporary objects. |
| 5032 | Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) " |
| 5033 | ": "; |
| 5034 | Preamble += "object(o), superClass(s) {} "; |
| 5035 | } |
| 5036 | Preamble += "};\n"; |
| 5037 | Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; |
| 5038 | Preamble += "typedef struct objc_object Protocol;\n"; |
| 5039 | Preamble += "#define _REWRITER_typedef_Protocol\n"; |
| 5040 | Preamble += "#endif\n"; |
| 5041 | if (LangOpts.MicrosoftExt) { |
| 5042 | Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; |
| 5043 | Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; |
| 5044 | } else |
| 5045 | Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; |
| 5046 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend"; |
| 5047 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 5048 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper"; |
| 5049 | Preamble += "(struct objc_super *, struct objc_selector *, ...);\n"; |
| 5050 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret"; |
| 5051 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 5052 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret"; |
| 5053 | Preamble += "(struct objc_super *, struct objc_selector *, ...);\n"; |
| 5054 | Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret"; |
| 5055 | Preamble += "(struct objc_object *, struct objc_selector *, ...);\n"; |
| 5056 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass"; |
| 5057 | Preamble += "(const char *);\n"; |
| 5058 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass"; |
| 5059 | Preamble += "(struct objc_class *);\n"; |
| 5060 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass"; |
| 5061 | Preamble += "(const char *);\n"; |
| 5062 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n"; |
| 5063 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n"; |
| 5064 | Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n"; |
| 5065 | Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n"; |
| 5066 | Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match"; |
| 5067 | Preamble += "(struct objc_class *, struct objc_object *);\n"; |
| 5068 | // @synchronized hooks. |
| 5069 | Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n"; |
| 5070 | Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n"; |
| 5071 | Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n"; |
| 5072 | Preamble += "#ifndef __FASTENUMERATIONSTATE\n"; |
| 5073 | Preamble += "struct __objcFastEnumerationState {\n\t"; |
| 5074 | Preamble += "unsigned long state;\n\t"; |
| 5075 | Preamble += "void **itemsPtr;\n\t"; |
| 5076 | Preamble += "unsigned long *mutationsPtr;\n\t"; |
| 5077 | Preamble += "unsigned long extra[5];\n};\n"; |
| 5078 | Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n"; |
| 5079 | Preamble += "#define __FASTENUMERATIONSTATE\n"; |
| 5080 | Preamble += "#endif\n"; |
| 5081 | Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n"; |
| 5082 | Preamble += "struct __NSConstantStringImpl {\n"; |
| 5083 | Preamble += " int *isa;\n"; |
| 5084 | Preamble += " int flags;\n"; |
| 5085 | Preamble += " char *str;\n"; |
| 5086 | Preamble += " long length;\n"; |
| 5087 | Preamble += "};\n"; |
| 5088 | Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n"; |
| 5089 | Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n"; |
| 5090 | Preamble += "#else\n"; |
| 5091 | Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n"; |
| 5092 | Preamble += "#endif\n"; |
| 5093 | Preamble += "#define __NSCONSTANTSTRINGIMPL\n"; |
| 5094 | Preamble += "#endif\n"; |
| 5095 | // Blocks preamble. |
| 5096 | Preamble += "#ifndef BLOCK_IMPL\n"; |
| 5097 | Preamble += "#define BLOCK_IMPL\n"; |
| 5098 | Preamble += "struct __block_impl {\n"; |
| 5099 | Preamble += " void *isa;\n"; |
| 5100 | Preamble += " int Flags;\n"; |
| 5101 | Preamble += " int Reserved;\n"; |
| 5102 | Preamble += " void *FuncPtr;\n"; |
| 5103 | Preamble += "};\n"; |
| 5104 | Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n"; |
| 5105 | Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n"; |
| 5106 | Preamble += "extern \"C\" __declspec(dllexport) " |
| 5107 | "void _Block_object_assign(void *, const void *, const int);\n"; |
| 5108 | Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n"; |
| 5109 | Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n"; |
| 5110 | Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n"; |
| 5111 | Preamble += "#else\n"; |
| 5112 | Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n"; |
| 5113 | Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n"; |
| 5114 | Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n"; |
| 5115 | Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n"; |
| 5116 | Preamble += "#endif\n"; |
| 5117 | Preamble += "#endif\n"; |
| 5118 | if (LangOpts.MicrosoftExt) { |
| 5119 | Preamble += "#undef __OBJC_RW_DLLIMPORT\n"; |
| 5120 | Preamble += "#undef __OBJC_RW_STATICIMPORT\n"; |
| 5121 | Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests. |
| 5122 | Preamble += "#define __attribute__(X)\n"; |
| 5123 | Preamble += "#endif\n"; |
| 5124 | Preamble += "#define __weak\n"; |
| 5125 | } |
| 5126 | else { |
| 5127 | Preamble += "#define __block\n"; |
| 5128 | Preamble += "#define __weak\n"; |
| 5129 | } |
| 5130 | // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long |
| 5131 | // as this avoids warning in any 64bit/32bit compilation model. |
| 5132 | Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; |
| 5133 | } |
| 5134 | |
| 5135 | /// RewriteIvarOffsetComputation - This rutine synthesizes computation of |
| 5136 | /// ivar offset. |
| 5137 | void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, |
| 5138 | std::string &Result) { |
| 5139 | if (ivar->isBitField()) { |
| 5140 | // FIXME: The hack below doesn't work for bitfields. For now, we simply |
| 5141 | // place all bitfields at offset 0. |
| 5142 | Result += "0"; |
| 5143 | } else { |
| 5144 | Result += "__OFFSETOFIVAR__(struct "; |
| 5145 | Result += ivar->getContainingInterface()->getNameAsString(); |
| 5146 | if (LangOpts.MicrosoftExt) |
| 5147 | Result += "_IMPL"; |
| 5148 | Result += ", "; |
| 5149 | Result += ivar->getNameAsString(); |
| 5150 | Result += ")"; |
| 5151 | } |
| 5152 | } |
| 5153 | |
| 5154 | /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI. |
| 5155 | /// struct _prop_t { |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5156 | /// const char *name; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5157 | /// char *attributes; |
| 5158 | /// } |
| 5159 | |
| 5160 | /// struct _prop_list_t { |
| 5161 | /// uint32_t entsize; // sizeof(struct _prop_t) |
| 5162 | /// uint32_t count_of_properties; |
| 5163 | /// struct _prop_t prop_list[count_of_properties]; |
| 5164 | /// } |
| 5165 | |
| 5166 | /// struct _protocol_t; |
| 5167 | |
| 5168 | /// struct _protocol_list_t { |
| 5169 | /// long protocol_count; // Note, this is 32/64 bit |
| 5170 | /// struct _protocol_t * protocol_list[protocol_count]; |
| 5171 | /// } |
| 5172 | |
| 5173 | /// struct _objc_method { |
| 5174 | /// SEL _cmd; |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5175 | /// const char *method_type; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5176 | /// char *_imp; |
| 5177 | /// } |
| 5178 | |
| 5179 | /// struct _method_list_t { |
| 5180 | /// uint32_t entsize; // sizeof(struct _objc_method) |
| 5181 | /// uint32_t method_count; |
| 5182 | /// struct _objc_method method_list[method_count]; |
| 5183 | /// } |
| 5184 | |
| 5185 | /// struct _protocol_t { |
| 5186 | /// id isa; // NULL |
| 5187 | /// const char * const protocol_name; |
| 5188 | /// const struct _protocol_list_t * protocol_list; // super protocols |
| 5189 | /// const struct method_list_t * const instance_methods; |
| 5190 | /// const struct method_list_t * const class_methods; |
| 5191 | /// const struct method_list_t *optionalInstanceMethods; |
| 5192 | /// const struct method_list_t *optionalClassMethods; |
| 5193 | /// const struct _prop_list_t * properties; |
| 5194 | /// const uint32_t size; // sizeof(struct _protocol_t) |
| 5195 | /// const uint32_t flags; // = 0 |
| 5196 | /// const char ** extendedMethodTypes; |
| 5197 | /// } |
| 5198 | |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5199 | /// struct _ivar_t { |
| 5200 | /// unsigned long int *offset; // pointer to ivar offset location |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5201 | /// const char *name; |
| 5202 | /// const char *type; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5203 | /// uint32_t alignment; |
| 5204 | /// uint32_t size; |
| 5205 | /// } |
| 5206 | |
| 5207 | /// struct _ivar_list_t { |
| 5208 | /// uint32 entsize; // sizeof(struct _ivar_t) |
| 5209 | /// uint32 count; |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5210 | /// struct _ivar_t list[count]; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5211 | /// } |
| 5212 | |
| 5213 | /// struct _class_ro_t { |
| 5214 | /// uint32_t const flags; |
| 5215 | /// uint32_t const instanceStart; |
| 5216 | /// uint32_t const instanceSize; |
| 5217 | /// uint32_t const reserved; // only when building for 64bit targets |
| 5218 | /// const uint8_t * const ivarLayout; |
| 5219 | /// const char *const name; |
| 5220 | /// const struct _method_list_t * const baseMethods; |
Fariborz Jahanian | 0a52534 | 2012-02-14 19:31:35 +0000 | [diff] [blame] | 5221 | /// const struct _protocol_list_t *const baseProtocols; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5222 | /// const struct _ivar_list_t *const ivars; |
| 5223 | /// const uint8_t * const weakIvarLayout; |
| 5224 | /// const struct _prop_list_t * const properties; |
| 5225 | /// } |
| 5226 | |
| 5227 | /// struct _class_t { |
| 5228 | /// struct _class_t *isa; |
| 5229 | /// struct _class_t * const superclass; |
| 5230 | /// void *cache; |
| 5231 | /// IMP *vtable; |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5232 | /// struct _class_ro_t *ro; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5233 | /// } |
| 5234 | |
| 5235 | /// struct _category_t { |
| 5236 | /// const char * const name; |
| 5237 | /// struct _class_t *const cls; |
| 5238 | /// const struct _method_list_t * const instance_methods; |
| 5239 | /// const struct _method_list_t * const class_methods; |
| 5240 | /// const struct _protocol_list_t * const protocols; |
| 5241 | /// const struct _prop_list_t * const properties; |
| 5242 | /// } |
| 5243 | |
| 5244 | /// MessageRefTy - LLVM for: |
| 5245 | /// struct _message_ref_t { |
| 5246 | /// IMP messenger; |
| 5247 | /// SEL name; |
| 5248 | /// }; |
| 5249 | |
| 5250 | /// SuperMessageRefTy - LLVM for: |
| 5251 | /// struct _super_message_ref_t { |
| 5252 | /// SUPER_IMP messenger; |
| 5253 | /// SEL name; |
| 5254 | /// }; |
| 5255 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5256 | static void WriteModernMetadataDeclarations(std::string &Result) { |
| 5257 | static bool meta_data_declared = false; |
| 5258 | if (meta_data_declared) |
| 5259 | return; |
| 5260 | |
| 5261 | Result += "\nstruct _prop_t {\n"; |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5262 | Result += "\tconst char *name;\n"; |
| 5263 | Result += "\tconst char *attributes;\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5264 | Result += "};\n"; |
| 5265 | |
| 5266 | Result += "\nstruct _protocol_t;\n"; |
| 5267 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5268 | Result += "\nstruct _objc_method {\n"; |
| 5269 | Result += "\tstruct objc_selector * _cmd;\n"; |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5270 | Result += "\tconst char *method_type;\n"; |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5271 | Result += "\tvoid *_imp;\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5272 | Result += "};\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5273 | |
| 5274 | Result += "\nstruct _protocol_t {\n"; |
| 5275 | Result += "\tvoid * isa; // NULL\n"; |
| 5276 | Result += "\tconst char * const protocol_name;\n"; |
| 5277 | Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n"; |
| 5278 | Result += "\tconst struct method_list_t * const instance_methods;\n"; |
| 5279 | Result += "\tconst struct method_list_t * const class_methods;\n"; |
| 5280 | Result += "\tconst struct method_list_t *optionalInstanceMethods;\n"; |
| 5281 | Result += "\tconst struct method_list_t *optionalClassMethods;\n"; |
| 5282 | Result += "\tconst struct _prop_list_t * properties;\n"; |
| 5283 | Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n"; |
| 5284 | Result += "\tconst unsigned int flags; // = 0\n"; |
| 5285 | Result += "\tconst char ** extendedMethodTypes;\n"; |
| 5286 | Result += "};\n"; |
| 5287 | |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5288 | Result += "\nstruct _ivar_t {\n"; |
| 5289 | Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5290 | Result += "\tconst char *name;\n"; |
| 5291 | Result += "\tconst char *type;\n"; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5292 | Result += "\tunsigned int alignment;\n"; |
| 5293 | Result += "\tunsigned int size;\n"; |
| 5294 | Result += "};\n"; |
| 5295 | |
| 5296 | Result += "\nstruct _class_ro_t {\n"; |
| 5297 | Result += "\tunsigned int const flags;\n"; |
| 5298 | Result += "\tunsigned int instanceStart;\n"; |
| 5299 | Result += "\tunsigned int const instanceSize;\n"; |
| 5300 | Result += "\tunsigned int const reserved; // only when building for 64bit targets\n"; |
| 5301 | Result += "\tconst unsigned char * const ivarLayout;\n"; |
| 5302 | Result += "\tconst char *const name;\n"; |
| 5303 | Result += "\tconst struct _method_list_t * const baseMethods;\n"; |
| 5304 | Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n"; |
| 5305 | Result += "\tconst struct _ivar_list_t *const ivars;\n"; |
| 5306 | Result += "\tconst unsigned char *const weakIvarLayout;\n"; |
| 5307 | Result += "\tconst struct _prop_list_t *const properties;\n"; |
| 5308 | Result += "};\n"; |
| 5309 | |
| 5310 | Result += "\nstruct _class_t {\n"; |
| 5311 | Result += "\tstruct _class_t *isa;\n"; |
| 5312 | Result += "\tstruct _class_t *const superclass;\n"; |
| 5313 | Result += "\tvoid *cache;\n"; |
| 5314 | Result += "\tvoid *vtable;\n"; |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5315 | Result += "\tstruct _class_ro_t *ro;\n"; |
Fariborz Jahanian | 42e9a35 | 2012-02-10 00:04:22 +0000 | [diff] [blame] | 5316 | Result += "};\n"; |
| 5317 | |
| 5318 | Result += "\nstruct _category_t {\n"; |
| 5319 | Result += "\tconst char * const name;\n"; |
| 5320 | Result += "\tstruct _class_t *const cls;\n"; |
| 5321 | Result += "\tconst struct _method_list_t *const instance_methods;\n"; |
| 5322 | Result += "\tconst struct _method_list_t *const class_methods;\n"; |
| 5323 | Result += "\tconst struct _protocol_list_t *const protocols;\n"; |
| 5324 | Result += "\tconst struct _prop_list_t *const properties;\n"; |
| 5325 | Result += "};\n"; |
| 5326 | |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5327 | Result += "extern void *_objc_empty_cache;\n"; |
| 5328 | Result += "extern void *_objc_empty_vtable;\n"; |
| 5329 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5330 | meta_data_declared = true; |
| 5331 | } |
| 5332 | |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5333 | static void Write_protocol_list_t_TypeDecl(std::string &Result, |
| 5334 | long super_protocol_count) { |
| 5335 | Result += "struct /*_protocol_list_t*/"; Result += " {\n"; |
| 5336 | Result += "\tlong protocol_count; // Note, this is 32/64 bit\n"; |
| 5337 | Result += "\tstruct _protocol_t *super_protocols["; |
| 5338 | Result += utostr(super_protocol_count); Result += "];\n"; |
| 5339 | Result += "}"; |
| 5340 | } |
| 5341 | |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5342 | static void Write_method_list_t_TypeDecl(std::string &Result, |
| 5343 | unsigned int method_count) { |
| 5344 | Result += "struct /*_method_list_t*/"; Result += " {\n"; |
| 5345 | Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n"; |
| 5346 | Result += "\tunsigned int method_count;\n"; |
| 5347 | Result += "\tstruct _objc_method method_list["; |
| 5348 | Result += utostr(method_count); Result += "];\n"; |
| 5349 | Result += "}"; |
| 5350 | } |
| 5351 | |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5352 | static void Write__prop_list_t_TypeDecl(std::string &Result, |
| 5353 | unsigned int property_count) { |
| 5354 | Result += "struct /*_prop_list_t*/"; Result += " {\n"; |
| 5355 | Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; |
| 5356 | Result += "\tunsigned int count_of_properties;\n"; |
| 5357 | Result += "\tstruct _prop_t prop_list["; |
| 5358 | Result += utostr(property_count); Result += "];\n"; |
| 5359 | Result += "}"; |
| 5360 | } |
| 5361 | |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5362 | static void Write__ivar_list_t_TypeDecl(std::string &Result, |
| 5363 | unsigned int ivar_count) { |
| 5364 | Result += "struct /*_ivar_list_t*/"; Result += " {\n"; |
| 5365 | Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; |
| 5366 | Result += "\tunsigned int count;\n"; |
| 5367 | Result += "\tstruct _ivar_t ivar_list["; |
| 5368 | Result += utostr(ivar_count); Result += "];\n"; |
| 5369 | Result += "}"; |
| 5370 | } |
| 5371 | |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5372 | static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result, |
| 5373 | ArrayRef<ObjCProtocolDecl *> SuperProtocols, |
| 5374 | StringRef VarName, |
| 5375 | StringRef ProtocolName) { |
| 5376 | if (SuperProtocols.size() > 0) { |
| 5377 | Result += "\nstatic "; |
| 5378 | Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); |
| 5379 | Result += " "; Result += VarName; |
| 5380 | Result += ProtocolName; |
| 5381 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; |
| 5382 | Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; |
| 5383 | for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { |
| 5384 | ObjCProtocolDecl *SuperPD = SuperProtocols[i]; |
| 5385 | Result += "\t&"; Result += "_OBJC_PROTOCOL_"; |
| 5386 | Result += SuperPD->getNameAsString(); |
| 5387 | if (i == e-1) |
| 5388 | Result += "\n};\n"; |
| 5389 | else |
| 5390 | Result += ",\n"; |
| 5391 | } |
| 5392 | } |
| 5393 | } |
| 5394 | |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5395 | static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, |
| 5396 | ASTContext *Context, std::string &Result, |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5397 | ArrayRef<ObjCMethodDecl *> Methods, |
| 5398 | StringRef VarName, |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5399 | StringRef TopLevelDeclName, |
| 5400 | bool MethodImpl) { |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5401 | if (Methods.size() > 0) { |
| 5402 | Result += "\nstatic "; |
| 5403 | Write_method_list_t_TypeDecl(Result, Methods.size()); |
| 5404 | Result += " "; Result += VarName; |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5405 | Result += TopLevelDeclName; |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5406 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; |
| 5407 | Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; |
| 5408 | Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; |
| 5409 | for (unsigned i = 0, e = Methods.size(); i < e; i++) { |
| 5410 | ObjCMethodDecl *MD = Methods[i]; |
| 5411 | if (i == 0) |
| 5412 | Result += "\t{{(struct objc_selector *)\""; |
| 5413 | else |
| 5414 | Result += "\t{(struct objc_selector *)\""; |
| 5415 | Result += (MD)->getSelector().getAsString(); Result += "\""; |
| 5416 | Result += ", "; |
| 5417 | std::string MethodTypeString; |
| 5418 | Context->getObjCEncodingForMethodDecl(MD, MethodTypeString); |
| 5419 | Result += "\""; Result += MethodTypeString; Result += "\""; |
| 5420 | Result += ", "; |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5421 | if (!MethodImpl) |
| 5422 | Result += "0"; |
| 5423 | else { |
| 5424 | Result += "(void *)"; |
| 5425 | Result += RewriteObj.MethodInternalNames[MD]; |
| 5426 | } |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5427 | if (i == e-1) |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5428 | Result += "}}\n"; |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5429 | else |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5430 | Result += "},\n"; |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5431 | } |
| 5432 | Result += "};\n"; |
| 5433 | } |
| 5434 | } |
| 5435 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5436 | static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5437 | ASTContext *Context, std::string &Result, |
| 5438 | ArrayRef<ObjCPropertyDecl *> Properties, |
| 5439 | const Decl *Container, |
| 5440 | StringRef VarName, |
| 5441 | StringRef ProtocolName) { |
| 5442 | if (Properties.size() > 0) { |
| 5443 | Result += "\nstatic "; |
| 5444 | Write__prop_list_t_TypeDecl(Result, Properties.size()); |
| 5445 | Result += " "; Result += VarName; |
| 5446 | Result += ProtocolName; |
| 5447 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; |
| 5448 | Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; |
| 5449 | Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; |
| 5450 | for (unsigned i = 0, e = Properties.size(); i < e; i++) { |
| 5451 | ObjCPropertyDecl *PropDecl = Properties[i]; |
| 5452 | if (i == 0) |
| 5453 | Result += "\t{{\""; |
| 5454 | else |
| 5455 | Result += "\t{\""; |
| 5456 | Result += PropDecl->getName(); Result += "\","; |
| 5457 | std::string PropertyTypeString, QuotePropertyTypeString; |
| 5458 | Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString); |
| 5459 | RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString); |
| 5460 | Result += "\""; Result += QuotePropertyTypeString; Result += "\""; |
| 5461 | if (i == e-1) |
| 5462 | Result += "}}\n"; |
| 5463 | else |
| 5464 | Result += "},\n"; |
| 5465 | } |
| 5466 | Result += "};\n"; |
| 5467 | } |
| 5468 | } |
| 5469 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5470 | // Metadata flags |
| 5471 | enum MetaDataDlags { |
| 5472 | CLS = 0x0, |
| 5473 | CLS_META = 0x1, |
| 5474 | CLS_ROOT = 0x2, |
| 5475 | OBJC2_CLS_HIDDEN = 0x10, |
| 5476 | CLS_EXCEPTION = 0x20, |
| 5477 | |
| 5478 | /// (Obsolete) ARC-specific: this class has a .release_ivars method |
| 5479 | CLS_HAS_IVAR_RELEASER = 0x40, |
| 5480 | /// class was compiled with -fobjc-arr |
| 5481 | CLS_COMPILED_BY_ARC = 0x80 // (1<<7) |
| 5482 | }; |
| 5483 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5484 | static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, |
| 5485 | unsigned int flags, |
| 5486 | const std::string &InstanceStart, |
| 5487 | const std::string &InstanceSize, |
| 5488 | ArrayRef<ObjCMethodDecl *>baseMethods, |
| 5489 | ArrayRef<ObjCProtocolDecl *>baseProtocols, |
| 5490 | ArrayRef<ObjCIvarDecl *>ivars, |
| 5491 | ArrayRef<ObjCPropertyDecl *>Properties, |
| 5492 | StringRef VarName, |
| 5493 | StringRef ClassName) { |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5494 | Result += "\nstatic struct _class_ro_t "; |
| 5495 | Result += VarName; Result += ClassName; |
| 5496 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; |
| 5497 | Result += "\t"; |
| 5498 | Result += llvm::utostr(flags); Result += ", "; |
| 5499 | Result += InstanceStart; Result += ", "; |
| 5500 | Result += InstanceSize; Result += ", \n"; |
| 5501 | Result += "\t"; |
| 5502 | // uint32_t const reserved; // only when building for 64bit targets |
| 5503 | Result += "(unsigned int)0, \n\t"; |
| 5504 | // const uint8_t * const ivarLayout; |
| 5505 | Result += "0, \n\t"; |
| 5506 | Result += "\""; Result += ClassName; Result += "\",\n\t"; |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5507 | bool metaclass = ((flags & CLS_META) != 0); |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5508 | if (baseMethods.size() > 0) { |
| 5509 | Result += "(const struct _method_list_t *)&"; |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5510 | if (metaclass) |
| 5511 | Result += "_OBJC_$_CLASS_METHODS_"; |
| 5512 | else |
| 5513 | Result += "_OBJC_$_INSTANCE_METHODS_"; |
| 5514 | Result += ClassName; |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5515 | Result += ",\n\t"; |
| 5516 | } |
| 5517 | else |
| 5518 | Result += "0, \n\t"; |
| 5519 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5520 | if (!metaclass && baseProtocols.size() > 0) { |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5521 | Result += "(const struct _objc_protocol_list *)&"; |
| 5522 | Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName; |
| 5523 | Result += ",\n\t"; |
| 5524 | } |
| 5525 | else |
| 5526 | Result += "0, \n\t"; |
| 5527 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5528 | if (!metaclass && ivars.size() > 0) { |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5529 | Result += "(const struct _ivar_list_t *)&"; |
| 5530 | Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName; |
| 5531 | Result += ",\n\t"; |
| 5532 | } |
| 5533 | else |
| 5534 | Result += "0, \n\t"; |
| 5535 | |
| 5536 | // weakIvarLayout |
| 5537 | Result += "0, \n\t"; |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 5538 | if (!metaclass && Properties.size() > 0) { |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5539 | Result += "(const struct _prop_list_t *)&"; |
Fariborz Jahanian | eeabf38 | 2012-02-16 21:57:59 +0000 | [diff] [blame] | 5540 | Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5541 | Result += ",\n"; |
| 5542 | } |
| 5543 | else |
| 5544 | Result += "0, \n"; |
| 5545 | |
| 5546 | Result += "};\n"; |
| 5547 | } |
| 5548 | |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5549 | static void Write_class_t(ASTContext *Context, std::string &Result, |
| 5550 | StringRef VarName, |
| 5551 | const ObjCInterfaceDecl *CDecl, bool metadata) { |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5552 | |
| 5553 | if (metadata && !CDecl->getSuperClass()) { |
| 5554 | // Need to handle a case of use of forward declaration. |
Fariborz Jahanian | ce0d897 | 2012-03-10 18:25:06 +0000 | [diff] [blame] | 5555 | Result += "\n"; |
| 5556 | if (CDecl->getImplementation()) |
| 5557 | Result += "__declspec(dllexport) "; |
| 5558 | Result += "extern struct _class_t OBJC_CLASS_$_"; |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5559 | Result += CDecl->getNameAsString(); |
| 5560 | Result += ";\n"; |
| 5561 | } |
| 5562 | // Also, for possibility of 'super' metadata class not having been defined yet. |
| 5563 | if (CDecl->getSuperClass()) { |
Fariborz Jahanian | ce0d897 | 2012-03-10 18:25:06 +0000 | [diff] [blame] | 5564 | Result += "\n"; |
| 5565 | if (CDecl->getSuperClass()->getImplementation()) |
| 5566 | Result += "__declspec(dllexport) "; |
| 5567 | Result += "extern struct _class_t "; |
| 5568 | Result += VarName; |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5569 | Result += CDecl->getSuperClass()->getNameAsString(); |
| 5570 | Result += ";\n"; |
| 5571 | } |
| 5572 | |
Fariborz Jahanian | e57303c | 2012-03-10 00:39:34 +0000 | [diff] [blame] | 5573 | Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString(); |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 5574 | Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; |
| 5575 | Result += "\t"; |
| 5576 | if (metadata) { |
| 5577 | if (CDecl->getSuperClass()) { |
| 5578 | Result += "&"; Result += VarName; |
| 5579 | Result += CDecl->getSuperClass()->getNameAsString(); |
| 5580 | Result += ",\n\t"; |
| 5581 | Result += "&"; Result += VarName; |
| 5582 | Result += CDecl->getSuperClass()->getNameAsString(); |
| 5583 | Result += ",\n\t"; |
| 5584 | } |
| 5585 | else { |
| 5586 | Result += "&"; Result += VarName; |
| 5587 | Result += CDecl->getNameAsString(); |
| 5588 | Result += ",\n\t"; |
| 5589 | Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); |
| 5590 | Result += ",\n\t"; |
| 5591 | } |
| 5592 | } |
| 5593 | else { |
| 5594 | Result += "&OBJC_METACLASS_$_"; |
| 5595 | Result += CDecl->getNameAsString(); |
| 5596 | Result += ",\n\t"; |
| 5597 | if (CDecl->getSuperClass()) { |
| 5598 | Result += "&"; Result += VarName; |
| 5599 | Result += CDecl->getSuperClass()->getNameAsString(); |
| 5600 | Result += ",\n\t"; |
| 5601 | } |
| 5602 | else |
| 5603 | Result += "0,\n\t"; |
| 5604 | } |
| 5605 | Result += "(void *)&_objc_empty_cache,\n\t"; |
| 5606 | Result += "(void *)&_objc_empty_vtable,\n\t"; |
| 5607 | if (metadata) |
| 5608 | Result += "&_OBJC_METACLASS_RO_$_"; |
| 5609 | else |
| 5610 | Result += "&_OBJC_CLASS_RO_$_"; |
| 5611 | Result += CDecl->getNameAsString(); |
| 5612 | Result += ",\n};\n"; |
| 5613 | } |
| 5614 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 5615 | static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, |
| 5616 | std::string &Result, |
| 5617 | StringRef CatName, |
| 5618 | StringRef ClassName, |
| 5619 | ArrayRef<ObjCMethodDecl *> InstanceMethods, |
| 5620 | ArrayRef<ObjCMethodDecl *> ClassMethods, |
| 5621 | ArrayRef<ObjCProtocolDecl *> RefedProtocols, |
| 5622 | ArrayRef<ObjCPropertyDecl *> ClassProperties) { |
Fariborz Jahanian | 8c00a1b | 2012-02-17 20:33:00 +0000 | [diff] [blame] | 5623 | // must declare an extern class object in case this class is not implemented |
| 5624 | // in this TU. |
| 5625 | Result += "\nextern struct _class_t "; |
| 5626 | Result += "OBJC_CLASS_$_"; Result += ClassName; |
| 5627 | Result += ";\n"; |
| 5628 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 5629 | Result += "\nstatic struct _category_t "; |
| 5630 | Result += "_OBJC_$_CATEGORY_"; |
| 5631 | Result += ClassName; Result += "_$_"; Result += CatName; |
| 5632 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; |
| 5633 | Result += "{\n"; |
| 5634 | Result += "\t\""; Result += ClassName; Result += "\",\n"; |
| 5635 | Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName; |
| 5636 | Result += ",\n"; |
| 5637 | if (InstanceMethods.size() > 0) { |
| 5638 | Result += "\t(const struct _method_list_t *)&"; |
| 5639 | Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; |
| 5640 | Result += ClassName; Result += "_$_"; Result += CatName; |
| 5641 | Result += ",\n"; |
| 5642 | } |
| 5643 | else |
| 5644 | Result += "\t0,\n"; |
| 5645 | |
| 5646 | if (ClassMethods.size() > 0) { |
| 5647 | Result += "\t(const struct _method_list_t *)&"; |
| 5648 | Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; |
| 5649 | Result += ClassName; Result += "_$_"; Result += CatName; |
| 5650 | Result += ",\n"; |
| 5651 | } |
| 5652 | else |
| 5653 | Result += "\t0,\n"; |
| 5654 | |
| 5655 | if (RefedProtocols.size() > 0) { |
| 5656 | Result += "\t(const struct _protocol_list_t *)&"; |
| 5657 | Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; |
| 5658 | Result += ClassName; Result += "_$_"; Result += CatName; |
| 5659 | Result += ",\n"; |
| 5660 | } |
| 5661 | else |
| 5662 | Result += "\t0,\n"; |
| 5663 | |
| 5664 | if (ClassProperties.size() > 0) { |
| 5665 | Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; |
| 5666 | Result += ClassName; Result += "_$_"; Result += CatName; |
| 5667 | Result += ",\n"; |
| 5668 | } |
| 5669 | else |
| 5670 | Result += "\t0,\n"; |
| 5671 | |
| 5672 | Result += "};\n"; |
| 5673 | } |
| 5674 | |
Fariborz Jahanian | e0adbd8 | 2012-02-08 22:23:26 +0000 | [diff] [blame] | 5675 | static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj, |
| 5676 | ASTContext *Context, std::string &Result, |
| 5677 | ArrayRef<ObjCMethodDecl *> Methods, |
| 5678 | StringRef VarName, |
| 5679 | StringRef ProtocolName) { |
| 5680 | if (Methods.size() == 0) |
| 5681 | return; |
| 5682 | |
| 5683 | Result += "\nstatic const char *"; |
| 5684 | Result += VarName; Result += ProtocolName; |
| 5685 | Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; |
| 5686 | Result += "{\n"; |
| 5687 | for (unsigned i = 0, e = Methods.size(); i < e; i++) { |
| 5688 | ObjCMethodDecl *MD = Methods[i]; |
| 5689 | std::string MethodTypeString, QuoteMethodTypeString; |
| 5690 | Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true); |
| 5691 | RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString); |
| 5692 | Result += "\t\""; Result += QuoteMethodTypeString; Result += "\""; |
| 5693 | if (i == e-1) |
| 5694 | Result += "\n};\n"; |
| 5695 | else { |
| 5696 | Result += ",\n"; |
| 5697 | } |
| 5698 | } |
| 5699 | } |
| 5700 | |
Fariborz Jahanian | 40a777a | 2012-03-12 16:46:58 +0000 | [diff] [blame] | 5701 | static void Write_IvarOffsetVar(ASTContext *Context, |
| 5702 | std::string &Result, |
Fariborz Jahanian | db64923 | 2012-02-13 20:59:02 +0000 | [diff] [blame] | 5703 | ArrayRef<ObjCIvarDecl *> Ivars, |
| 5704 | StringRef VarName, |
| 5705 | StringRef ClassName) { |
| 5706 | // FIXME. visibilty of offset symbols may have to be set; for Darwin |
| 5707 | // this is what happens: |
| 5708 | /** |
| 5709 | if (Ivar->getAccessControl() == ObjCIvarDecl::Private || |
| 5710 | Ivar->getAccessControl() == ObjCIvarDecl::Package || |
| 5711 | Class->getVisibility() == HiddenVisibility) |
| 5712 | Visibility shoud be: HiddenVisibility; |
| 5713 | else |
| 5714 | Visibility shoud be: DefaultVisibility; |
| 5715 | */ |
| 5716 | |
Fariborz Jahanian | 07e5288 | 2012-02-13 21:34:45 +0000 | [diff] [blame] | 5717 | Result += "\n"; |
| 5718 | for (unsigned i =0, e = Ivars.size(); i < e; i++) { |
| 5719 | ObjCIvarDecl *IvarDecl = Ivars[i]; |
Fariborz Jahanian | 40a777a | 2012-03-12 16:46:58 +0000 | [diff] [blame] | 5720 | if (Context->getLangOpts().MicrosoftExt) |
| 5721 | Result += "__declspec(allocate(\".objc_ivar$B\")) "; |
| 5722 | |
| 5723 | if (!Context->getLangOpts().MicrosoftExt || |
| 5724 | IvarDecl->getAccessControl() == ObjCIvarDecl::Private || |
Fariborz Jahanian | 117591f | 2012-03-10 01:34:42 +0000 | [diff] [blame] | 5725 | IvarDecl->getAccessControl() == ObjCIvarDecl::Package) |
Fariborz Jahanian | d1c84d3 | 2012-03-10 00:53:02 +0000 | [diff] [blame] | 5726 | Result += "unsigned long int "; |
| 5727 | else |
| 5728 | Result += "__declspec(dllexport) unsigned long int "; |
| 5729 | |
| 5730 | Result += VarName; |
Fariborz Jahanian | 07e5288 | 2012-02-13 21:34:45 +0000 | [diff] [blame] | 5731 | Result += ClassName; Result += "_"; |
| 5732 | Result += IvarDecl->getName(); |
| 5733 | Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))"; |
| 5734 | Result += " = "; |
| 5735 | if (IvarDecl->isBitField()) { |
| 5736 | // FIXME: The hack below doesn't work for bitfields. For now, we simply |
| 5737 | // place all bitfields at offset 0. |
| 5738 | Result += "0;\n"; |
| 5739 | } |
| 5740 | else { |
Fariborz Jahanian | db64923 | 2012-02-13 20:59:02 +0000 | [diff] [blame] | 5741 | Result += "__OFFSETOFIVAR__(struct "; |
| 5742 | Result += ClassName; |
| 5743 | Result += "_IMPL, "; |
| 5744 | Result += IvarDecl->getName(); Result += ");\n"; |
| 5745 | } |
| 5746 | } |
| 5747 | } |
| 5748 | |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5749 | static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, |
| 5750 | ASTContext *Context, std::string &Result, |
| 5751 | ArrayRef<ObjCIvarDecl *> Ivars, |
| 5752 | StringRef VarName, |
| 5753 | StringRef ClassName) { |
| 5754 | if (Ivars.size() > 0) { |
Fariborz Jahanian | 40a777a | 2012-03-12 16:46:58 +0000 | [diff] [blame] | 5755 | Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName); |
Fariborz Jahanian | 07e5288 | 2012-02-13 21:34:45 +0000 | [diff] [blame] | 5756 | |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5757 | Result += "\nstatic "; |
| 5758 | Write__ivar_list_t_TypeDecl(Result, Ivars.size()); |
| 5759 | Result += " "; Result += VarName; |
| 5760 | Result += ClassName; |
| 5761 | Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; |
| 5762 | Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n"; |
| 5763 | Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n"; |
| 5764 | for (unsigned i =0, e = Ivars.size(); i < e; i++) { |
| 5765 | ObjCIvarDecl *IvarDecl = Ivars[i]; |
| 5766 | if (i == 0) |
| 5767 | Result += "\t{{"; |
| 5768 | else |
| 5769 | Result += "\t {"; |
Fariborz Jahanian | db64923 | 2012-02-13 20:59:02 +0000 | [diff] [blame] | 5770 | |
| 5771 | Result += "(unsigned long int *)&OBJC_IVAR_$_"; |
| 5772 | Result += ClassName; Result += "_"; Result += IvarDecl->getName(); |
| 5773 | Result += ", "; |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5774 | |
| 5775 | Result += "\""; Result += IvarDecl->getName(); Result += "\", "; |
| 5776 | std::string IvarTypeString, QuoteIvarTypeString; |
| 5777 | Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString, |
| 5778 | IvarDecl); |
| 5779 | RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); |
| 5780 | Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; |
| 5781 | |
Fariborz Jahanian | 8f1fed0 | 2012-02-11 20:10:52 +0000 | [diff] [blame] | 5782 | // FIXME. this alignment represents the host alignment and need be changed to |
| 5783 | // represent the target alignment. |
| 5784 | unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8; |
| 5785 | Align = llvm::Log2_32(Align); |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5786 | Result += llvm::utostr(Align); Result += ", "; |
Fariborz Jahanian | a63b422 | 2012-02-10 23:18:24 +0000 | [diff] [blame] | 5787 | CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType()); |
| 5788 | Result += llvm::utostr(Size.getQuantity()); |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 5789 | if (i == e-1) |
| 5790 | Result += "}}\n"; |
| 5791 | else |
| 5792 | Result += "},\n"; |
| 5793 | } |
| 5794 | Result += "};\n"; |
| 5795 | } |
| 5796 | } |
| 5797 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5798 | /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5799 | void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, |
| 5800 | std::string &Result) { |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5801 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5802 | // Do not synthesize the protocol more than once. |
| 5803 | if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) |
| 5804 | return; |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5805 | WriteModernMetadataDeclarations(Result); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5806 | |
| 5807 | if (ObjCProtocolDecl *Def = PDecl->getDefinition()) |
| 5808 | PDecl = Def; |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5809 | // Must write out all protocol definitions in current qualifier list, |
| 5810 | // and in their nested qualifiers before writing out current definition. |
| 5811 | for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), |
| 5812 | E = PDecl->protocol_end(); I != E; ++I) |
| 5813 | RewriteObjCProtocolMetaData(*I, Result); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5814 | |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5815 | // Construct method lists. |
| 5816 | std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; |
| 5817 | std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; |
| 5818 | for (ObjCProtocolDecl::instmeth_iterator |
| 5819 | I = PDecl->instmeth_begin(), E = PDecl->instmeth_end(); |
| 5820 | I != E; ++I) { |
| 5821 | ObjCMethodDecl *MD = *I; |
| 5822 | if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { |
| 5823 | OptInstanceMethods.push_back(MD); |
| 5824 | } else { |
| 5825 | InstanceMethods.push_back(MD); |
| 5826 | } |
| 5827 | } |
| 5828 | |
| 5829 | for (ObjCProtocolDecl::classmeth_iterator |
| 5830 | I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); |
| 5831 | I != E; ++I) { |
| 5832 | ObjCMethodDecl *MD = *I; |
| 5833 | if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { |
| 5834 | OptClassMethods.push_back(MD); |
| 5835 | } else { |
| 5836 | ClassMethods.push_back(MD); |
| 5837 | } |
| 5838 | } |
Fariborz Jahanian | e0adbd8 | 2012-02-08 22:23:26 +0000 | [diff] [blame] | 5839 | std::vector<ObjCMethodDecl *> AllMethods; |
| 5840 | for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++) |
| 5841 | AllMethods.push_back(InstanceMethods[i]); |
| 5842 | for (unsigned i = 0, e = ClassMethods.size(); i < e; i++) |
| 5843 | AllMethods.push_back(ClassMethods[i]); |
| 5844 | for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++) |
| 5845 | AllMethods.push_back(OptInstanceMethods[i]); |
| 5846 | for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++) |
| 5847 | AllMethods.push_back(OptClassMethods[i]); |
| 5848 | |
| 5849 | Write__extendedMethodTypes_initializer(*this, Context, Result, |
| 5850 | AllMethods, |
| 5851 | "_OBJC_PROTOCOL_METHOD_TYPES_", |
| 5852 | PDecl->getNameAsString()); |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5853 | // Protocol's super protocol list |
| 5854 | std::vector<ObjCProtocolDecl *> SuperProtocols; |
| 5855 | for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), |
| 5856 | E = PDecl->protocol_end(); I != E; ++I) |
| 5857 | SuperProtocols.push_back(*I); |
| 5858 | |
| 5859 | Write_protocol_list_initializer(Context, Result, SuperProtocols, |
| 5860 | "_OBJC_PROTOCOL_REFS_", |
| 5861 | PDecl->getNameAsString()); |
| 5862 | |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5863 | Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5864 | "_OBJC_PROTOCOL_INSTANCE_METHODS_", |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5865 | PDecl->getNameAsString(), false); |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5866 | |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5867 | Write_method_list_t_initializer(*this, Context, Result, ClassMethods, |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5868 | "_OBJC_PROTOCOL_CLASS_METHODS_", |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5869 | PDecl->getNameAsString(), false); |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5870 | |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5871 | Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5872 | "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5873 | PDecl->getNameAsString(), false); |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5874 | |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5875 | Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5876 | "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 5877 | PDecl->getNameAsString(), false); |
Fariborz Jahanian | 77e4bca | 2012-02-07 20:15:08 +0000 | [diff] [blame] | 5878 | |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5879 | // Protocol's property metadata. |
| 5880 | std::vector<ObjCPropertyDecl *> ProtocolProperties; |
| 5881 | for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(), |
| 5882 | E = PDecl->prop_end(); I != E; ++I) |
| 5883 | ProtocolProperties.push_back(*I); |
| 5884 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 5885 | Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties, |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5886 | /* Container */0, |
| 5887 | "_OBJC_PROTOCOL_PROPERTIES_", |
| 5888 | PDecl->getNameAsString()); |
Fariborz Jahanian | da35eac | 2012-02-07 23:31:52 +0000 | [diff] [blame] | 5889 | |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5890 | // Writer out root metadata for current protocol: struct _protocol_t |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 5891 | Result += "\n"; |
| 5892 | if (LangOpts.MicrosoftExt) |
| 5893 | Result += "__declspec(allocate(\".datacoal_nt$B\")) "; |
| 5894 | Result += "static struct _protocol_t _OBJC_PROTOCOL_"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5895 | Result += PDecl->getNameAsString(); |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5896 | Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n"; |
| 5897 | Result += "\t0,\n"; // id is; is null |
| 5898 | Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n"; |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5899 | if (SuperProtocols.size() > 0) { |
| 5900 | Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_"; |
| 5901 | Result += PDecl->getNameAsString(); Result += ",\n"; |
| 5902 | } |
| 5903 | else |
| 5904 | Result += "\t0,\n"; |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5905 | if (InstanceMethods.size() > 0) { |
| 5906 | Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; |
| 5907 | Result += PDecl->getNameAsString(); Result += ",\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5908 | } |
| 5909 | else |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5910 | Result += "\t0,\n"; |
| 5911 | |
| 5912 | if (ClassMethods.size() > 0) { |
| 5913 | Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; |
| 5914 | Result += PDecl->getNameAsString(); Result += ",\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5915 | } |
| 5916 | else |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5917 | Result += "\t0,\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5918 | |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5919 | if (OptInstanceMethods.size() > 0) { |
| 5920 | Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; |
| 5921 | Result += PDecl->getNameAsString(); Result += ",\n"; |
| 5922 | } |
| 5923 | else |
| 5924 | Result += "\t0,\n"; |
| 5925 | |
| 5926 | if (OptClassMethods.size() > 0) { |
| 5927 | Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; |
| 5928 | Result += PDecl->getNameAsString(); Result += ",\n"; |
| 5929 | } |
| 5930 | else |
| 5931 | Result += "\t0,\n"; |
| 5932 | |
| 5933 | if (ProtocolProperties.size() > 0) { |
| 5934 | Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; |
| 5935 | Result += PDecl->getNameAsString(); Result += ",\n"; |
| 5936 | } |
| 5937 | else |
| 5938 | Result += "\t0,\n"; |
| 5939 | |
| 5940 | Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; |
| 5941 | Result += "\t0,\n"; |
| 5942 | |
Fariborz Jahanian | e0adbd8 | 2012-02-08 22:23:26 +0000 | [diff] [blame] | 5943 | if (AllMethods.size() > 0) { |
| 5944 | Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; |
| 5945 | Result += PDecl->getNameAsString(); |
| 5946 | Result += "\n};\n"; |
| 5947 | } |
| 5948 | else |
| 5949 | Result += "\t0\n};\n"; |
Fariborz Jahanian | 82848c2 | 2012-02-08 00:50:52 +0000 | [diff] [blame] | 5950 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5951 | // Mark this protocol as having been generated. |
| 5952 | if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl())) |
| 5953 | llvm_unreachable("protocol already synthesized"); |
| 5954 | |
| 5955 | } |
| 5956 | |
| 5957 | void RewriteModernObjC::RewriteObjCProtocolListMetaData( |
| 5958 | const ObjCList<ObjCProtocolDecl> &Protocols, |
| 5959 | StringRef prefix, StringRef ClassName, |
| 5960 | std::string &Result) { |
| 5961 | if (Protocols.empty()) return; |
| 5962 | |
| 5963 | for (unsigned i = 0; i != Protocols.size(); i++) |
Fariborz Jahanian | da9624a | 2012-02-08 19:53:58 +0000 | [diff] [blame] | 5964 | RewriteObjCProtocolMetaData(Protocols[i], Result); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5965 | |
| 5966 | // Output the top lovel protocol meta-data for the class. |
| 5967 | /* struct _objc_protocol_list { |
| 5968 | struct _objc_protocol_list *next; |
| 5969 | int protocol_count; |
| 5970 | struct _objc_protocol *class_protocols[]; |
| 5971 | } |
| 5972 | */ |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 5973 | Result += "\n"; |
| 5974 | if (LangOpts.MicrosoftExt) |
| 5975 | Result += "__declspec(allocate(\".cat_cls_meth$B\")) "; |
| 5976 | Result += "static struct {\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 5977 | Result += "\tstruct _objc_protocol_list *next;\n"; |
| 5978 | Result += "\tint protocol_count;\n"; |
| 5979 | Result += "\tstruct _objc_protocol *class_protocols["; |
| 5980 | Result += utostr(Protocols.size()); |
| 5981 | Result += "];\n} _OBJC_"; |
| 5982 | Result += prefix; |
| 5983 | Result += "_PROTOCOLS_"; |
| 5984 | Result += ClassName; |
| 5985 | Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= " |
| 5986 | "{\n\t0, "; |
| 5987 | Result += utostr(Protocols.size()); |
| 5988 | Result += "\n"; |
| 5989 | |
| 5990 | Result += "\t,{&_OBJC_PROTOCOL_"; |
| 5991 | Result += Protocols[0]->getNameAsString(); |
| 5992 | Result += " \n"; |
| 5993 | |
| 5994 | for (unsigned i = 1; i != Protocols.size(); i++) { |
| 5995 | Result += "\t ,&_OBJC_PROTOCOL_"; |
| 5996 | Result += Protocols[i]->getNameAsString(); |
| 5997 | Result += "\n"; |
| 5998 | } |
| 5999 | Result += "\t }\n};\n"; |
| 6000 | } |
| 6001 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 6002 | /// hasObjCExceptionAttribute - Return true if this class or any super |
| 6003 | /// class has the __objc_exception__ attribute. |
| 6004 | /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen. |
| 6005 | static bool hasObjCExceptionAttribute(ASTContext &Context, |
| 6006 | const ObjCInterfaceDecl *OID) { |
| 6007 | if (OID->hasAttr<ObjCExceptionAttr>()) |
| 6008 | return true; |
| 6009 | if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) |
| 6010 | return hasObjCExceptionAttribute(Context, Super); |
| 6011 | return false; |
| 6012 | } |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6013 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6014 | void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, |
| 6015 | std::string &Result) { |
| 6016 | ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); |
| 6017 | |
| 6018 | // Explicitly declared @interface's are already synthesized. |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 6019 | if (CDecl->isImplicitInterfaceDecl()) |
| 6020 | assert(false && |
| 6021 | "Legacy implicit interface rewriting not supported in moder abi"); |
Fariborz Jahanian | 8f1fed0 | 2012-02-11 20:10:52 +0000 | [diff] [blame] | 6022 | |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 6023 | WriteModernMetadataDeclarations(Result); |
| 6024 | SmallVector<ObjCIvarDecl *, 8> IVars; |
| 6025 | |
| 6026 | for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); |
| 6027 | IVD; IVD = IVD->getNextIvar()) { |
| 6028 | // Ignore unnamed bit-fields. |
| 6029 | if (!IVD->getDeclName()) |
| 6030 | continue; |
| 6031 | IVars.push_back(IVD); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6032 | } |
| 6033 | |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 6034 | Write__ivar_list_t_initializer(*this, Context, Result, IVars, |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6035 | "_OBJC_$_INSTANCE_VARIABLES_", |
Fariborz Jahanian | ae93295 | 2012-02-10 20:47:10 +0000 | [diff] [blame] | 6036 | CDecl->getNameAsString()); |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 6037 | |
| 6038 | // Build _objc_method_list for class's instance methods if needed |
| 6039 | SmallVector<ObjCMethodDecl *, 32> |
| 6040 | InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); |
| 6041 | |
| 6042 | // If any of our property implementations have associated getters or |
| 6043 | // setters, produce metadata for them as well. |
| 6044 | for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(), |
| 6045 | PropEnd = IDecl->propimpl_end(); |
| 6046 | Prop != PropEnd; ++Prop) { |
| 6047 | if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 6048 | continue; |
| 6049 | if (!(*Prop)->getPropertyIvarDecl()) |
| 6050 | continue; |
| 6051 | ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl(); |
| 6052 | if (!PD) |
| 6053 | continue; |
| 6054 | if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) |
| 6055 | if (!Getter->isDefined()) |
| 6056 | InstanceMethods.push_back(Getter); |
| 6057 | if (PD->isReadOnly()) |
| 6058 | continue; |
| 6059 | if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) |
| 6060 | if (!Setter->isDefined()) |
| 6061 | InstanceMethods.push_back(Setter); |
| 6062 | } |
| 6063 | |
| 6064 | Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, |
| 6065 | "_OBJC_$_INSTANCE_METHODS_", |
| 6066 | IDecl->getNameAsString(), true); |
| 6067 | |
| 6068 | SmallVector<ObjCMethodDecl *, 32> |
| 6069 | ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end()); |
| 6070 | |
| 6071 | Write_method_list_t_initializer(*this, Context, Result, ClassMethods, |
| 6072 | "_OBJC_$_CLASS_METHODS_", |
| 6073 | IDecl->getNameAsString(), true); |
Fariborz Jahanian | 0a52534 | 2012-02-14 19:31:35 +0000 | [diff] [blame] | 6074 | |
| 6075 | // Protocols referenced in class declaration? |
| 6076 | // Protocol's super protocol list |
| 6077 | std::vector<ObjCProtocolDecl *> RefedProtocols; |
| 6078 | const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols(); |
| 6079 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
| 6080 | E = Protocols.end(); |
| 6081 | I != E; ++I) { |
| 6082 | RefedProtocols.push_back(*I); |
| 6083 | // Must write out all protocol definitions in current qualifier list, |
| 6084 | // and in their nested qualifiers before writing out current definition. |
| 6085 | RewriteObjCProtocolMetaData(*I, Result); |
| 6086 | } |
| 6087 | |
| 6088 | Write_protocol_list_initializer(Context, Result, |
| 6089 | RefedProtocols, |
| 6090 | "_OBJC_CLASS_PROTOCOLS_$_", |
| 6091 | IDecl->getNameAsString()); |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6092 | |
| 6093 | // Protocol's property metadata. |
| 6094 | std::vector<ObjCPropertyDecl *> ClassProperties; |
| 6095 | for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), |
| 6096 | E = CDecl->prop_end(); I != E; ++I) |
| 6097 | ClassProperties.push_back(*I); |
| 6098 | |
| 6099 | Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, |
| 6100 | /* Container */0, |
Fariborz Jahanian | eeabf38 | 2012-02-16 21:57:59 +0000 | [diff] [blame] | 6101 | "_OBJC_$_PROP_LIST_", |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6102 | CDecl->getNameAsString()); |
Fariborz Jahanian | 90af4e2 | 2012-02-14 17:19:02 +0000 | [diff] [blame] | 6103 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6104 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 6105 | // Data for initializing _class_ro_t metaclass meta-data |
| 6106 | uint32_t flags = CLS_META; |
| 6107 | std::string InstanceSize; |
| 6108 | std::string InstanceStart; |
| 6109 | |
| 6110 | |
| 6111 | bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; |
| 6112 | if (classIsHidden) |
| 6113 | flags |= OBJC2_CLS_HIDDEN; |
| 6114 | |
| 6115 | if (!CDecl->getSuperClass()) |
| 6116 | // class is root |
| 6117 | flags |= CLS_ROOT; |
| 6118 | InstanceSize = "sizeof(struct _class_t)"; |
| 6119 | InstanceStart = InstanceSize; |
| 6120 | Write__class_ro_t_initializer(Context, Result, flags, |
| 6121 | InstanceStart, InstanceSize, |
| 6122 | ClassMethods, |
| 6123 | 0, |
| 6124 | 0, |
| 6125 | 0, |
| 6126 | "_OBJC_METACLASS_RO_$_", |
| 6127 | CDecl->getNameAsString()); |
| 6128 | |
| 6129 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6130 | // Data for initializing _class_ro_t meta-data |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 6131 | flags = CLS; |
| 6132 | if (classIsHidden) |
| 6133 | flags |= OBJC2_CLS_HIDDEN; |
| 6134 | |
| 6135 | if (hasObjCExceptionAttribute(*Context, CDecl)) |
| 6136 | flags |= CLS_EXCEPTION; |
| 6137 | |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6138 | if (!CDecl->getSuperClass()) |
| 6139 | // class is root |
| 6140 | flags |= CLS_ROOT; |
| 6141 | |
Fariborz Jahanian | 6ade343 | 2012-02-16 18:54:09 +0000 | [diff] [blame] | 6142 | InstanceSize.clear(); |
| 6143 | InstanceStart.clear(); |
Fariborz Jahanian | f1c1d9a | 2012-02-15 00:50:11 +0000 | [diff] [blame] | 6144 | if (!ObjCSynthesizedStructs.count(CDecl)) { |
| 6145 | InstanceSize = "0"; |
| 6146 | InstanceStart = "0"; |
| 6147 | } |
| 6148 | else { |
| 6149 | InstanceSize = "sizeof(struct "; |
| 6150 | InstanceSize += CDecl->getNameAsString(); |
| 6151 | InstanceSize += "_IMPL)"; |
| 6152 | |
| 6153 | ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); |
| 6154 | if (IVD) { |
| 6155 | InstanceStart += "__OFFSETOFIVAR__(struct "; |
| 6156 | InstanceStart += CDecl->getNameAsString(); |
| 6157 | InstanceStart += "_IMPL, "; |
| 6158 | InstanceStart += IVD->getNameAsString(); |
| 6159 | InstanceStart += ")"; |
| 6160 | } |
| 6161 | else |
| 6162 | InstanceStart = InstanceSize; |
| 6163 | } |
| 6164 | Write__class_ro_t_initializer(Context, Result, flags, |
| 6165 | InstanceStart, InstanceSize, |
| 6166 | InstanceMethods, |
| 6167 | RefedProtocols, |
| 6168 | IVars, |
| 6169 | ClassProperties, |
| 6170 | "_OBJC_CLASS_RO_$_", |
| 6171 | CDecl->getNameAsString()); |
Fariborz Jahanian | 3f77c7b | 2012-02-16 21:37:05 +0000 | [diff] [blame] | 6172 | |
| 6173 | Write_class_t(Context, Result, |
| 6174 | "OBJC_METACLASS_$_", |
| 6175 | CDecl, /*metaclass*/true); |
| 6176 | |
| 6177 | Write_class_t(Context, Result, |
| 6178 | "OBJC_CLASS_$_", |
| 6179 | CDecl, /*metaclass*/false); |
| 6180 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6181 | } |
| 6182 | |
| 6183 | void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { |
| 6184 | int ClsDefCount = ClassImplementation.size(); |
| 6185 | int CatDefCount = CategoryImplementation.size(); |
| 6186 | |
| 6187 | // For each implemented class, write out all its meta data. |
| 6188 | for (int i = 0; i < ClsDefCount; i++) |
| 6189 | RewriteObjCClassMetaData(ClassImplementation[i], Result); |
| 6190 | |
| 6191 | // For each implemented category, write out all its meta data. |
| 6192 | for (int i = 0; i < CatDefCount; i++) |
| 6193 | RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); |
| 6194 | |
Fariborz Jahanian | df79567 | 2012-02-17 00:06:14 +0000 | [diff] [blame] | 6195 | if (ClsDefCount > 0) { |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 6196 | if (LangOpts.MicrosoftExt) |
| 6197 | Result += "__declspec(allocate(\".objc_classlist$B\")) "; |
Fariborz Jahanian | df79567 | 2012-02-17 00:06:14 +0000 | [diff] [blame] | 6198 | Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; |
| 6199 | Result += llvm::utostr(ClsDefCount); Result += "]"; |
| 6200 | Result += |
| 6201 | " __attribute__((used, section (\"__DATA, __objc_classlist," |
| 6202 | "regular,no_dead_strip\")))= {\n"; |
| 6203 | for (int i = 0; i < ClsDefCount; i++) { |
| 6204 | Result += "\t&OBJC_CLASS_$_"; |
| 6205 | Result += ClassImplementation[i]->getNameAsString(); |
| 6206 | Result += ",\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6207 | } |
Fariborz Jahanian | df79567 | 2012-02-17 00:06:14 +0000 | [diff] [blame] | 6208 | Result += "};\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6209 | } |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6210 | |
| 6211 | if (CatDefCount > 0) { |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 6212 | if (LangOpts.MicrosoftExt) |
| 6213 | Result += "__declspec(allocate(\".objc_catlist$B\")) "; |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6214 | Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; |
| 6215 | Result += llvm::utostr(CatDefCount); Result += "]"; |
| 6216 | Result += |
| 6217 | " __attribute__((used, section (\"__DATA, __objc_catlist," |
| 6218 | "regular,no_dead_strip\")))= {\n"; |
| 6219 | for (int i = 0; i < CatDefCount; i++) { |
| 6220 | Result += "\t&_OBJC_$_CATEGORY_"; |
| 6221 | Result += |
| 6222 | CategoryImplementation[i]->getClassInterface()->getNameAsString(); |
| 6223 | Result += "_$_"; |
| 6224 | Result += CategoryImplementation[i]->getNameAsString(); |
| 6225 | Result += ",\n"; |
| 6226 | } |
| 6227 | Result += "};\n"; |
| 6228 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6229 | } |
| 6230 | |
| 6231 | /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category |
| 6232 | /// implementation. |
| 6233 | void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, |
| 6234 | std::string &Result) { |
Fariborz Jahanian | 8c00a1b | 2012-02-17 20:33:00 +0000 | [diff] [blame] | 6235 | WriteModernMetadataDeclarations(Result); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6236 | ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); |
| 6237 | // Find category declaration for this implementation. |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6238 | ObjCCategoryDecl *CDecl=0; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6239 | for (CDecl = ClassDecl->getCategoryList(); CDecl; |
| 6240 | CDecl = CDecl->getNextClassCategory()) |
| 6241 | if (CDecl->getIdentifier() == IDecl->getIdentifier()) |
| 6242 | break; |
| 6243 | |
| 6244 | std::string FullCategoryName = ClassDecl->getNameAsString(); |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6245 | FullCategoryName += "_$_"; |
| 6246 | FullCategoryName += CDecl->getNameAsString(); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6247 | |
| 6248 | // Build _objc_method_list for class's instance methods if needed |
| 6249 | SmallVector<ObjCMethodDecl *, 32> |
| 6250 | InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end()); |
| 6251 | |
| 6252 | // If any of our property implementations have associated getters or |
| 6253 | // setters, produce metadata for them as well. |
| 6254 | for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(), |
| 6255 | PropEnd = IDecl->propimpl_end(); |
| 6256 | Prop != PropEnd; ++Prop) { |
| 6257 | if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) |
| 6258 | continue; |
| 6259 | if (!(*Prop)->getPropertyIvarDecl()) |
| 6260 | continue; |
| 6261 | ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl(); |
| 6262 | if (!PD) |
| 6263 | continue; |
| 6264 | if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) |
| 6265 | InstanceMethods.push_back(Getter); |
| 6266 | if (PD->isReadOnly()) |
| 6267 | continue; |
| 6268 | if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) |
| 6269 | InstanceMethods.push_back(Setter); |
| 6270 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6271 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6272 | Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, |
| 6273 | "_OBJC_$_CATEGORY_INSTANCE_METHODS_", |
| 6274 | FullCategoryName, true); |
| 6275 | |
| 6276 | SmallVector<ObjCMethodDecl *, 32> |
| 6277 | ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end()); |
| 6278 | |
| 6279 | Write_method_list_t_initializer(*this, Context, Result, ClassMethods, |
| 6280 | "_OBJC_$_CATEGORY_CLASS_METHODS_", |
| 6281 | FullCategoryName, true); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6282 | |
| 6283 | // Protocols referenced in class declaration? |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6284 | // Protocol's super protocol list |
| 6285 | std::vector<ObjCProtocolDecl *> RefedProtocols; |
Argyrios Kyrtzidis | a5f4441 | 2012-03-13 01:09:41 +0000 | [diff] [blame^] | 6286 | for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(), |
| 6287 | E = CDecl->protocol_end(); |
| 6288 | |
| 6289 | I != E; ++I) { |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6290 | RefedProtocols.push_back(*I); |
| 6291 | // Must write out all protocol definitions in current qualifier list, |
| 6292 | // and in their nested qualifiers before writing out current definition. |
| 6293 | RewriteObjCProtocolMetaData(*I, Result); |
| 6294 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6295 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6296 | Write_protocol_list_initializer(Context, Result, |
| 6297 | RefedProtocols, |
| 6298 | "_OBJC_CATEGORY_PROTOCOLS_$_", |
| 6299 | FullCategoryName); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6300 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6301 | // Protocol's property metadata. |
| 6302 | std::vector<ObjCPropertyDecl *> ClassProperties; |
| 6303 | for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), |
| 6304 | E = CDecl->prop_end(); I != E; ++I) |
| 6305 | ClassProperties.push_back(*I); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6306 | |
Fariborz Jahanian | 6118612 | 2012-02-17 18:40:41 +0000 | [diff] [blame] | 6307 | Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, |
| 6308 | /* Container */0, |
| 6309 | "_OBJC_$_PROP_LIST_", |
| 6310 | FullCategoryName); |
| 6311 | |
| 6312 | Write_category_t(*this, Context, Result, |
| 6313 | CDecl->getNameAsString(), |
| 6314 | ClassDecl->getNameAsString(), |
| 6315 | InstanceMethods, |
| 6316 | ClassMethods, |
| 6317 | RefedProtocols, |
| 6318 | ClassProperties); |
| 6319 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6320 | } |
| 6321 | |
| 6322 | // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or |
| 6323 | /// class methods. |
| 6324 | template<typename MethodIterator> |
| 6325 | void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, |
| 6326 | MethodIterator MethodEnd, |
| 6327 | bool IsInstanceMethod, |
| 6328 | StringRef prefix, |
| 6329 | StringRef ClassName, |
| 6330 | std::string &Result) { |
| 6331 | if (MethodBegin == MethodEnd) return; |
| 6332 | |
| 6333 | if (!objc_impl_method) { |
| 6334 | /* struct _objc_method { |
| 6335 | SEL _cmd; |
| 6336 | char *method_types; |
| 6337 | void *_imp; |
| 6338 | } |
| 6339 | */ |
| 6340 | Result += "\nstruct _objc_method {\n"; |
| 6341 | Result += "\tSEL _cmd;\n"; |
| 6342 | Result += "\tchar *method_types;\n"; |
| 6343 | Result += "\tvoid *_imp;\n"; |
| 6344 | Result += "};\n"; |
| 6345 | |
| 6346 | objc_impl_method = true; |
| 6347 | } |
| 6348 | |
| 6349 | // Build _objc_method_list for class's methods if needed |
| 6350 | |
| 6351 | /* struct { |
| 6352 | struct _objc_method_list *next_method; |
| 6353 | int method_count; |
| 6354 | struct _objc_method method_list[]; |
| 6355 | } |
| 6356 | */ |
| 6357 | unsigned NumMethods = std::distance(MethodBegin, MethodEnd); |
Fariborz Jahanian | 1ca052c | 2012-03-11 19:41:56 +0000 | [diff] [blame] | 6358 | Result += "\n"; |
| 6359 | if (LangOpts.MicrosoftExt) { |
| 6360 | if (IsInstanceMethod) |
| 6361 | Result += "__declspec(allocate(\".inst_meth$B\")) "; |
| 6362 | else |
| 6363 | Result += "__declspec(allocate(\".cls_meth$B\")) "; |
| 6364 | } |
| 6365 | Result += "static struct {\n"; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6366 | Result += "\tstruct _objc_method_list *next_method;\n"; |
| 6367 | Result += "\tint method_count;\n"; |
| 6368 | Result += "\tstruct _objc_method method_list["; |
| 6369 | Result += utostr(NumMethods); |
| 6370 | Result += "];\n} _OBJC_"; |
| 6371 | Result += prefix; |
| 6372 | Result += IsInstanceMethod ? "INSTANCE" : "CLASS"; |
| 6373 | Result += "_METHODS_"; |
| 6374 | Result += ClassName; |
| 6375 | Result += " __attribute__ ((used, section (\"__OBJC, __"; |
| 6376 | Result += IsInstanceMethod ? "inst" : "cls"; |
| 6377 | Result += "_meth\")))= "; |
| 6378 | Result += "{\n\t0, " + utostr(NumMethods) + "\n"; |
| 6379 | |
| 6380 | Result += "\t,{{(SEL)\""; |
| 6381 | Result += (*MethodBegin)->getSelector().getAsString().c_str(); |
| 6382 | std::string MethodTypeString; |
| 6383 | Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); |
| 6384 | Result += "\", \""; |
| 6385 | Result += MethodTypeString; |
| 6386 | Result += "\", (void *)"; |
| 6387 | Result += MethodInternalNames[*MethodBegin]; |
| 6388 | Result += "}\n"; |
| 6389 | for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) { |
| 6390 | Result += "\t ,{(SEL)\""; |
| 6391 | Result += (*MethodBegin)->getSelector().getAsString().c_str(); |
| 6392 | std::string MethodTypeString; |
| 6393 | Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); |
| 6394 | Result += "\", \""; |
| 6395 | Result += MethodTypeString; |
| 6396 | Result += "\", (void *)"; |
| 6397 | Result += MethodInternalNames[*MethodBegin]; |
| 6398 | Result += "}\n"; |
| 6399 | } |
| 6400 | Result += "\t }\n};\n"; |
| 6401 | } |
| 6402 | |
| 6403 | Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { |
| 6404 | SourceRange OldRange = IV->getSourceRange(); |
| 6405 | Expr *BaseExpr = IV->getBase(); |
| 6406 | |
| 6407 | // Rewrite the base, but without actually doing replaces. |
| 6408 | { |
| 6409 | DisableReplaceStmtScope S(*this); |
| 6410 | BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); |
| 6411 | IV->setBase(BaseExpr); |
| 6412 | } |
| 6413 | |
| 6414 | ObjCIvarDecl *D = IV->getDecl(); |
| 6415 | |
| 6416 | Expr *Replacement = IV; |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6417 | |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6418 | if (BaseExpr->getType()->isObjCObjectPointerType()) { |
| 6419 | const ObjCInterfaceType *iFaceDecl = |
| 6420 | dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); |
| 6421 | assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"); |
| 6422 | // lookup which class implements the instance variable. |
| 6423 | ObjCInterfaceDecl *clsDeclared = 0; |
| 6424 | iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), |
| 6425 | clsDeclared); |
| 6426 | assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); |
| 6427 | |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6428 | // Build name of symbol holding ivar offset. |
| 6429 | std::string IvarOffsetName = "OBJC_IVAR_$_"; |
| 6430 | IvarOffsetName += clsDeclared->getIdentifier()->getName(); |
| 6431 | IvarOffsetName += "_"; |
| 6432 | IvarOffsetName += D->getName(); |
Fariborz Jahanian | 72c88f1 | 2012-02-22 18:13:25 +0000 | [diff] [blame] | 6433 | ReferencedIvars[clsDeclared].insert(D); |
| 6434 | |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6435 | // cast offset to "char *". |
| 6436 | CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, |
| 6437 | Context->getPointerType(Context->CharTy), |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6438 | CK_BitCast, |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6439 | BaseExpr); |
| 6440 | VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), |
| 6441 | SourceLocation(), &Context->Idents.get(IvarOffsetName), |
| 6442 | Context->UnsignedLongTy, 0, SC_Extern, SC_None); |
John McCall | f4b88a4 | 2012-03-10 09:33:50 +0000 | [diff] [blame] | 6443 | DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, |
| 6444 | Context->UnsignedLongTy, VK_LValue, |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6445 | SourceLocation()); |
| 6446 | BinaryOperator *addExpr = |
| 6447 | new (Context) BinaryOperator(castExpr, DRE, BO_Add, |
| 6448 | Context->getPointerType(Context->CharTy), |
| 6449 | VK_RValue, OK_Ordinary, SourceLocation()); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6450 | // Don't forget the parens to enforce the proper binding. |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6451 | ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), |
| 6452 | SourceLocation(), |
| 6453 | addExpr); |
Fariborz Jahanian | 0d6e22a | 2012-02-24 17:35:35 +0000 | [diff] [blame] | 6454 | QualType IvarT = D->getType(); |
Fariborz Jahanian | 8e0913d | 2012-02-29 00:26:20 +0000 | [diff] [blame] | 6455 | convertObjCTypeToCStyleType(IvarT); |
Fariborz Jahanian | 0d6e22a | 2012-02-24 17:35:35 +0000 | [diff] [blame] | 6456 | QualType castT = Context->getPointerType(IvarT); |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6457 | |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6458 | castExpr = NoTypeInfoCStyleCastExpr(Context, |
| 6459 | castT, |
| 6460 | CK_BitCast, |
| 6461 | PE); |
Fariborz Jahanian | 8e0913d | 2012-02-29 00:26:20 +0000 | [diff] [blame] | 6462 | Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT, |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6463 | VK_LValue, OK_Ordinary, |
| 6464 | SourceLocation()); |
| 6465 | PE = new (Context) ParenExpr(OldRange.getBegin(), |
| 6466 | OldRange.getEnd(), |
| 6467 | Exp); |
| 6468 | |
| 6469 | Replacement = PE; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6470 | } |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6471 | |
Fariborz Jahanian | e7b3fa7 | 2012-02-21 23:46:48 +0000 | [diff] [blame] | 6472 | ReplaceStmtWithRange(IV, Replacement, OldRange); |
| 6473 | return Replacement; |
Fariborz Jahanian | 64cb63a | 2012-02-07 17:11:38 +0000 | [diff] [blame] | 6474 | } |
| 6475 | |