PageRenderTime 100ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 2ms

/contrib/llvm/tools/clang/lib/Rewrite/RewriteModernObjC.cpp

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