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