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