blob: 9f777d616e1116e140fd5fdc3347b7844a0060d5 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroff4588d0f2008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000139
Steve Naroff22216db2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000144
Steve Naroff677ab3a2008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000152 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattner3c799d72007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnercf169832009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattner2e0d2602008-01-31 19:37:57 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000172
Steve Naroff22216db2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000175
Steve Naroff08628db2008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff22216db2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceStmt(Old, New)) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000188 }
Steve Naroff08628db2008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroff00a31762008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattner1780a852008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner9cc55f52008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Chris Lattner9cc55f52008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000233
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner3c799d72007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Steve Naroff1042ff32008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattner69534692007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000282 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000283 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000284 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000285 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000286 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000287 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000288 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000289 void WarnAboutReturnGotoStmts(Stmt *S);
290 void HasReturnStmts(Stmt *S, bool &hasReturns);
291 void RewriteTryReturnStmts(Stmt *S);
292 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000293 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000294 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
296 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000301 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000302 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000303 Stmt *RewriteBreakStmt(BreakStmt *S);
304 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000305 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000306
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000307 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000308 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000309 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000310 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000311 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000312 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000313 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000314 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000315 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000316
Chris Lattner3c799d72007-10-24 17:06:59 +0000317 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000318 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000319 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000321 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000324 template<typename MethodIterator>
325 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
326 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000327 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000328 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000329 const char *ClassName,
330 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000331
Steve Naroffd9803712009-04-29 16:37:50 +0000332 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
333 const char *prefix,
334 const char *ClassName,
335 std::string &Result);
336 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000337 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000338 const char *ClassName,
339 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000340 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000341 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000342 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
343 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000344 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000345 void RewriteImplementations();
346 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Steve Naroff677ab3a2008-10-27 17:20:55 +0000348 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000349 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Steve Naroff677ab3a2008-10-27 17:20:55 +0000352 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
353 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000354
355 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void RewriteBlockCall(CallExpr *Exp);
357 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000358 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000359 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000360 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000362
363 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000365 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000367 std::string SynthesizeBlockImpl(BlockExpr *CE,
368 std::string Tag, std::string Desc);
369 std::string SynthesizeBlockDescriptor(std::string DescTag,
370 std::string ImplTag,
371 int i, const char *funcName,
372 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000373 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000374 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000375 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000376 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000377
Steve Naroff677ab3a2008-10-27 17:20:55 +0000378 void CollectBlockDeclRefInfo(BlockExpr *Exp);
379 void GetBlockCallExprs(Stmt *S);
380 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Steve Naroff677ab3a2008-10-27 17:20:55 +0000382 // We avoid calling Type::isBlockPointerType(), since it operates on the
383 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000384 bool isTopLevelBlockPointerType(QualType T) {
385 return isa<BlockPointerType>(T);
386 }
Mike Stump11289f42009-09-09 15:08:12 +0000387
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 // FIXME: This predicate seems like it would be useful to add to ASTContext.
389 bool isObjCType(QualType T) {
390 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
391 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Steve Naroff677ab3a2008-10-27 17:20:55 +0000393 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
396 OCT == Context->getCanonicalType(Context->getObjCClassType()))
397 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000398
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000399 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000400 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000401 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000402 return true;
403 }
404 return false;
405 }
406 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000407 void GetExtentOfArgList(const char *Name, const char *&LParen,
408 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000409 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Steve Narofff4b992a2008-10-28 20:29:00 +0000411 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000412 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Steve Naroffd9803712009-04-29 16:37:50 +0000414 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000415 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000416 if (From[i] == '"')
417 To += "\\\"";
418 else
419 To += From[i];
420 }
421 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000422 };
John McCall97513962010-01-15 18:39:57 +0000423
424 // Helper function: create a CStyleCastExpr with trivial type source info.
425 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
426 CastExpr::CastKind Kind, Expr *E) {
427 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
428 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
429 SourceLocation(), SourceLocation());
430 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000431}
432
Mike Stump11289f42009-09-09 15:08:12 +0000433void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
434 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000435 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000437 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000438 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000439 // All the args are checked/rewritten. Don't call twice!
440 RewriteBlockPointerDecl(D);
441 break;
442 }
443 }
444}
445
446void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000447 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000448 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000449 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000450}
451
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000452static bool IsHeaderFile(const std::string &Filename) {
453 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000454
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000455 if (DotPos == std::string::npos) {
456 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000457 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000458 }
Mike Stump11289f42009-09-09 15:08:12 +0000459
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000460 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
461 // C header: .h
462 // C++ header: .hh or .H;
463 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000464}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000465
Eli Friedman94cf21e2009-05-18 22:20:00 +0000466RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000467 Diagnostic &D, const LangOptions &LOpts,
468 bool silenceMacroWarn)
469 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
470 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000471 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000472 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000473 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000474 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000475 "rewriter doesn't support user-specified control flow semantics "
476 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000477}
478
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000479ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
480 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000481 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000482 const LangOptions &LOpts,
483 bool SilenceRewriteMacroWarning) {
484 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000485}
Chris Lattnere99c8322007-10-11 00:43:27 +0000486
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000487void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000488 Context = &context;
489 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000490 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000491 MsgSendFunctionDecl = 0;
492 MsgSendSuperFunctionDecl = 0;
493 MsgSendStretFunctionDecl = 0;
494 MsgSendSuperStretFunctionDecl = 0;
495 MsgSendFpretFunctionDecl = 0;
496 GetClassFunctionDecl = 0;
497 GetMetaClassFunctionDecl = 0;
498 SelGetUidFunctionDecl = 0;
499 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000500 ConstantStringClassReference = 0;
501 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000502 CurMethodDef = 0;
503 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000504 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000505 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000506 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000507 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000508 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000509 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000510 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000511 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000512 PropParentMap = 0;
513 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000514 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000515 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattner187f6262008-01-31 19:38:44 +0000517 // Get the ID and start/end of the main file.
518 MainFileID = SM->getMainFileID();
519 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
520 MainFileStart = MainBuf->getBufferStart();
521 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000522
Chris Lattner184e65d2009-04-14 23:22:57 +0000523 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattner187f6262008-01-31 19:38:44 +0000525 // declaring objc_selector outside the parameter list removes a silly
526 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000527 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000528 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000529 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000530 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000531 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000532 if (LangOpts.Microsoft) {
533 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000534 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
535 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000536 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000537 }
Steve Naroff00a31762008-03-27 22:29:16 +0000538 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
540 Preamble += "typedef struct objc_object Protocol;\n";
541 Preamble += "#define _REWRITER_typedef_Protocol\n";
542 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000543 if (LangOpts.Microsoft) {
544 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
545 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
546 } else
547 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
548 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000549 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000553 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000555 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000557 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000559 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
563 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000567 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000568 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000572 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
573 Preamble += "struct __objcFastEnumerationState {\n\t";
574 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000575 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000576 Preamble += "unsigned long *mutationsPtr;\n\t";
577 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "#define __FASTENUMERATIONSTATE\n";
580 Preamble += "#endif\n";
581 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
582 Preamble += "struct __NSConstantStringImpl {\n";
583 Preamble += " int *isa;\n";
584 Preamble += " int flags;\n";
585 Preamble += " char *str;\n";
586 Preamble += " long length;\n";
587 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000588 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
589 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
590 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000592 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000593 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
594 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000595 // Blocks preamble.
596 Preamble += "#ifndef BLOCK_IMPL\n";
597 Preamble += "#define BLOCK_IMPL\n";
598 Preamble += "struct __block_impl {\n";
599 Preamble += " void *isa;\n";
600 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000601 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000602 Preamble += " void *FuncPtr;\n";
603 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000604 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000605 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000606 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
607 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
608 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
610 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000611 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
612 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
615 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000616 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000617 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000618 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
619 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000620 Preamble += "#define __attribute__(X)\n";
621 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000622 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000623 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000624 Preamble += "#define __weak\n";
625 }
Chris Lattner187f6262008-01-31 19:38:44 +0000626}
627
628
Chris Lattner3c799d72007-10-24 17:06:59 +0000629//===----------------------------------------------------------------------===//
630// Top Level Driver Code
631//===----------------------------------------------------------------------===//
632
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000633void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000634 // Two cases: either the decl could be in the main file, or it could be in a
635 // #included file. If the former, rewrite it now. If the later, check to see
636 // if we rewrote the #include/#import.
637 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000638 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000639
Chris Lattner0bd1c972007-10-16 21:07:07 +0000640 // If this is for a builtin, ignore it.
641 if (Loc.isInvalid()) return;
642
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000643 // Look for built-in declarations that we need to refer during the rewrite.
644 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000645 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000646 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000647 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000648 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000649 ConstantStringClassReference = FVD;
650 return;
651 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000652 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000653 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000654 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000655 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000656 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000657 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000658 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000659 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000660 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000661 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
662 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000663 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
664 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000665 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000666 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000667 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000668 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000669 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000670 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000671}
672
Chris Lattner3c799d72007-10-24 17:06:59 +0000673//===----------------------------------------------------------------------===//
674// Syntactic (non-AST) Rewriting Code
675//===----------------------------------------------------------------------===//
676
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000677void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000678 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000679 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
680 const char *MainBufStart = MainBuf.first;
681 const char *MainBufEnd = MainBuf.second;
682 size_t ImportLen = strlen("import");
683 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000684
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000685 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000686 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
687 if (*BufPtr == '#') {
688 if (++BufPtr == MainBufEnd)
689 return;
690 while (*BufPtr == ' ' || *BufPtr == '\t')
691 if (++BufPtr == MainBufEnd)
692 return;
693 if (!strncmp(BufPtr, "import", ImportLen)) {
694 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000695 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000696 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000697 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000698 BufPtr += ImportLen;
699 }
700 }
701 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000702}
703
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000704void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000705 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
706 const char *MainBufStart = MainBuf.first;
707 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattner3c799d72007-10-24 17:06:59 +0000709 // Loop over the whole file, looking for tabs.
710 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
711 if (*BufPtr != '\t')
712 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattner3c799d72007-10-24 17:06:59 +0000714 // Okay, we found a tab. This tab will turn into at least one character,
715 // but it depends on which 'virtual column' it is in. Compute that now.
716 unsigned VCol = 0;
717 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
718 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
719 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner3c799d72007-10-24 17:06:59 +0000721 // Okay, now that we know the virtual column, we know how many spaces to
722 // insert. We assume 8-character tab-stops.
723 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattner3c799d72007-10-24 17:06:59 +0000725 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000726 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
727 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000728
Chris Lattner3c799d72007-10-24 17:06:59 +0000729 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000730 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000732}
733
Steve Naroff9af94912008-12-02 15:48:25 +0000734static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
735 ObjCIvarDecl *OID) {
736 std::string S;
737 S = "((struct ";
738 S += ClassDecl->getIdentifier()->getName();
739 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000740 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000741 return S;
742}
743
Steve Naroffc038b3a2008-12-02 17:36:43 +0000744void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
745 ObjCImplementationDecl *IMD,
746 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000747 SourceLocation startLoc = PID->getLocStart();
748 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000749 const char *startBuf = SM->getCharacterData(startLoc);
750 assert((*startBuf == '@') && "bogus @synthesize location");
751 const char *semiBuf = strchr(startBuf, ';');
752 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000753 SourceLocation onePastSemiLoc =
754 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000755
756 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
757 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000758
Steve Naroff9af94912008-12-02 15:48:25 +0000759 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000760 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000761 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000762 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000763
Steve Naroff003d00e2008-12-02 16:05:55 +0000764 if (!OID)
765 return;
Mike Stump11289f42009-09-09 15:08:12 +0000766
Steve Naroff003d00e2008-12-02 16:05:55 +0000767 std::string Getr;
768 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
769 Getr += "{ ";
770 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000771 // FIXME: deal with code generation implications for various property
772 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000773 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 Getr += "return " + getIvarAccessString(ClassDecl, OID);
775 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000776 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000777 if (PD->isReadOnly())
778 return;
Mike Stump11289f42009-09-09 15:08:12 +0000779
Steve Naroff9af94912008-12-02 15:48:25 +0000780 // Generate the 'setter' function.
781 std::string Setr;
782 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000783 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000784 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000785 // FIXME: deal with code generation implications for various property
786 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000787 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000788 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000789 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000790 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000791 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000792}
Chris Lattner16a0de42007-10-11 18:38:32 +0000793
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000794void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000795 // Get the start location and compute the semi location.
796 SourceLocation startLoc = ClassDecl->getLocation();
797 const char *startBuf = SM->getCharacterData(startLoc);
798 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner3c799d72007-10-24 17:06:59 +0000800 // Translate to typedef's that forward reference structs with the same name
801 // as the class. As a convenience, we include the original declaration
802 // as a comment.
803 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000804 typedefString += "// @class ";
805 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
806 I != E; ++I) {
807 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
808 typedefString += ForwardDecl->getNameAsString();
809 if (I+1 != E)
810 typedefString += ", ";
811 else
812 typedefString += ";\n";
813 }
814
Chris Lattner9ee23b72009-02-20 18:04:31 +0000815 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
816 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000817 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000818 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000819 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000820 typedefString += "\n";
821 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000822 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000823 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000824 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000825 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000826 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000827 }
Mike Stump11289f42009-09-09 15:08:12 +0000828
Steve Naroff574440f2007-10-24 22:48:43 +0000829 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000830 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000831 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000832}
833
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000834void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000835 SourceLocation LocStart = Method->getLocStart();
836 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattner88ea93e2009-02-04 01:06:56 +0000838 if (SM->getInstantiationLineNumber(LocEnd) >
839 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000840 InsertText(LocStart, "#if 0\n", 6);
841 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000842 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000843 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000844 }
845}
846
Mike Stump11289f42009-09-09 15:08:12 +0000847void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000848 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000850 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000852 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000853}
854
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000855void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000856 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000857
Steve Naroff5448cf62007-10-30 13:30:57 +0000858 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000859 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000860
861 for (ObjCCategoryDecl::instmeth_iterator
862 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000863 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000864 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000865 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000866 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000867 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000868 RewriteMethodDeclaration(*I);
869
Steve Naroff5448cf62007-10-30 13:30:57 +0000870 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000871 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000872}
873
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000874void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000875 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000876
Steve Narofff921385f2007-10-30 16:42:30 +0000877 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000878
Steve Narofff921385f2007-10-30 16:42:30 +0000879 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000880 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000881
882 for (ObjCProtocolDecl::instmeth_iterator
883 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000884 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000885 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000886 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000887 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000888 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000889 RewriteMethodDeclaration(*I);
890
Steve Narofff921385f2007-10-30 16:42:30 +0000891 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000892 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000893 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000894
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000895 // Must comment out @optional/@required
896 const char *startBuf = SM->getCharacterData(LocStart);
897 const char *endBuf = SM->getCharacterData(LocEnd);
898 for (const char *p = startBuf; p < endBuf; p++) {
899 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
900 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000901 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000902 ReplaceText(OptionalLoc, strlen("@optional"),
903 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000904
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000905 }
906 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
907 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000908 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000909 ReplaceText(OptionalLoc, strlen("@required"),
910 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000911
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000912 }
913 }
Steve Narofff921385f2007-10-30 16:42:30 +0000914}
915
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000916void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000917 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000918 if (LocStart.isInvalid())
919 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000920 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000921 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000922}
923
Mike Stump11289f42009-09-09 15:08:12 +0000924void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000925 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000926 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000927 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000928 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000929 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000930 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000931 else if (OMD->getResultType()->isFunctionPointerType() ||
932 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000933 // needs special handling, since pointer-to-functions have special
934 // syntax (where a decaration models use).
935 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000936 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000937 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000938 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000939 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000940 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000941 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000942 ResultStr += FPRetType->getResultType().getAsString();
943 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000944 }
945 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000946 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000947 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000948
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000949 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000950 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregorffca3a22009-01-09 17:18:27 +0000952 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000953 NameStr += "_I_";
954 else
955 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000956
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000957 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000958 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000959
960 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000961 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000962 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000963 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000964 }
Mike Stump11289f42009-09-09 15:08:12 +0000965 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000966 {
967 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000968 int len = selString.size();
969 for (int i = 0; i < len; i++)
970 if (selString[i] == ':')
971 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000972 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000973 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000974 // Remember this name for metadata emission
975 MethodInternalNames[OMD] = NameStr;
976 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000977
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 // Rewrite arguments
979 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000981 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000982 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000983 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000984 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000985 if (!LangOpts.Microsoft) {
986 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
987 ResultStr += "struct ";
988 }
989 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000990 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000991 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 }
993 else
Steve Naroffd9803712009-04-29 16:37:50 +0000994 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000995
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000996 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000997 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000998 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000999
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001000 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001001 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1002 E = OMD->param_end(); PI != E; ++PI) {
1003 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001005 if (PDecl->getType()->isObjCQualifiedIdType()) {
1006 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001007 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001008 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001009 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001010 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001011 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001012 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001013 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1014 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001015 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001016 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001017 ResultStr += Name;
1018 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001019 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001020 if (OMD->isVariadic())
1021 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001022 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001023
Steve Naroffb067bbd2008-07-16 14:40:40 +00001024 if (FPRetType) {
1025 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001026
Steve Naroffb067bbd2008-07-16 14:40:40 +00001027 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001028 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001029 ResultStr += "(";
1030 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1031 if (i) ResultStr += ", ";
1032 std::string ParamStr = FT->getArgType(i).getAsString();
1033 ResultStr += ParamStr;
1034 }
1035 if (FT->isVariadic()) {
1036 if (FT->getNumArgs()) ResultStr += ", ";
1037 ResultStr += "...";
1038 }
1039 ResultStr += ")";
1040 } else {
1041 ResultStr += "()";
1042 }
1043 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001045void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1047 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001048
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001049 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001050 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001051 else
Chris Lattner1780a852008-01-31 19:42:41 +00001052 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001053
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001054 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001055 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1056 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001057 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 ObjCMethodDecl *OMD = *I;
1060 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001061 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001062 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001063
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001064 const char *startBuf = SM->getCharacterData(LocStart);
1065 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001066 ReplaceText(LocStart, endBuf-startBuf,
1067 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001068 }
Mike Stump11289f42009-09-09 15:08:12 +00001069
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001070 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001071 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1072 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001073 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001075 ObjCMethodDecl *OMD = *I;
1076 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001078 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001079
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001080 const char *startBuf = SM->getCharacterData(LocStart);
1081 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001082 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001083 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001085 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001086 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001087 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001088 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001089 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001090 }
1091
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001092 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001093 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001094 else
Mike Stump11289f42009-09-09 15:08:12 +00001095 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001096}
1097
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001098void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001099 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001100 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001101 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001102 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001103 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001104 ResultStr += "\n";
1105 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001107 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001108 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001109 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001110 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001111 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001112 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001113 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001114 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001115
1116 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001117 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001118 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001119 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001120 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001121 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001122 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::classmeth_iterator
1124 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
1127
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001128 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001129 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001130}
1131
Steve Naroff08628db2008-12-09 12:56:34 +00001132Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1133 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001134 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1135 // This allows us to reuse all the fun and games in SynthMessageExpr().
1136 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1137 ObjCMessageExpr *MsgExpr;
1138 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1139 llvm::SmallVector<Expr *, 1> ExprVec;
1140 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroff1042ff32008-12-08 16:43:47 +00001142 Stmt *Receiver = PropRefExpr->getBase();
1143 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1144 if (PRE && PropGetters[PRE]) {
1145 // This allows us to handle chain/nested property getters.
1146 Receiver = PropGetters[PRE];
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1149 PDecl->getSetterName(), PDecl->getType(),
1150 PDecl->getSetterMethodDecl(),
1151 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001152 &ExprVec[0], 1);
1153 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Steve Naroff4588d0f2008-12-04 16:24:46 +00001155 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001156 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001157 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001158 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1159 // to things that stay around.
1160 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001161 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001162}
1163
Steve Naroff4588d0f2008-12-04 16:24:46 +00001164Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001165 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1166 // This allows us to reuse all the fun and games in SynthMessageExpr().
1167 ObjCMessageExpr *MsgExpr;
1168 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Steve Naroff1042ff32008-12-08 16:43:47 +00001170 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001171
Steve Naroff1042ff32008-12-08 16:43:47 +00001172 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1173 if (PRE && PropGetters[PRE]) {
1174 // This allows us to handle chain/nested property getters.
1175 Receiver = PropGetters[PRE];
1176 }
Mike Stump11289f42009-09-09 15:08:12 +00001177 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1178 PDecl->getGetterName(), PDecl->getType(),
1179 PDecl->getGetterMethodDecl(),
1180 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001181 0, 0);
1182
Steve Naroff22216db2008-12-04 23:50:32 +00001183 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001184
1185 if (!PropParentMap)
1186 PropParentMap = new ParentMap(CurrentBody);
1187
1188 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1189 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1190 // We stash away the ReplacingStmt since actually doing the
1191 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1192 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001193 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1194 // to things that stay around.
1195 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001196 return PropRefExpr; // return the original...
1197 } else {
1198 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001199 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001200 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1201 // to things that stay around.
1202 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001203 return ReplacingStmt;
1204 }
Steve Narofff326f402008-12-03 00:56:33 +00001205}
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001208 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001209 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001210 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001211 if (CurMethodDef) {
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001212 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1213 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001214 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001215 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001216 // lookup which class implements the instance variable.
1217 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001218 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001219 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001220 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001221
Steve Naroffb1c02372008-05-08 17:52:16 +00001222 // Synthesize an explicit cast to gain access to the ivar.
1223 std::string RecName = clsDeclared->getIdentifier()->getName();
1224 RecName += "_IMPL";
1225 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001226 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001227 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001228 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1229 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001230 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1231 CastExpr::CK_Unknown,
1232 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001233 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001234 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1235 IV->getBase()->getLocEnd(),
1236 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001237 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001238 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001239 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1240 IV->getLocation(),
1241 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001242 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001243 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001244 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001245 }
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001247 ReplaceStmt(IV->getBase(), PE);
1248 // Cannot delete IV->getBase(), since PE points to it.
1249 // Replace the old base with the cast. This is important when doing
1250 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001251 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001252 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001253 }
Steve Naroff24840f62008-04-18 21:55:08 +00001254 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001255 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001256
Steve Naroff29ce4e52008-05-06 23:20:07 +00001257 // Explicit ivar refs need to have a cast inserted.
1258 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001259 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001260 ObjCInterfaceType *iFaceDecl =
1261 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 // lookup which class implements the instance variable.
1263 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001264 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001265 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001266 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001267
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 // Synthesize an explicit cast to gain access to the ivar.
1269 std::string RecName = clsDeclared->getIdentifier()->getName();
1270 RecName += "_IMPL";
1271 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001272 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001273 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001274 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1275 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001276 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1277 CastExpr::CK_Unknown,
1278 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001279 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001280 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001281 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001282 ReplaceStmt(IV->getBase(), PE);
1283 // Cannot delete IV->getBase(), since PE points to it.
1284 // Replace the old base with the cast. This is important when doing
1285 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001286 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 return IV;
1288 }
Steve Naroff05caa482007-11-15 11:33:00 +00001289 }
Steve Naroff24840f62008-04-18 21:55:08 +00001290 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001291}
1292
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001293/// SynthCountByEnumWithState - To print:
1294/// ((unsigned int (*)
1295/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001296/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001297/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001298/// "countByEnumeratingWithState:objects:count:"),
1299/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001300/// (id *)items, (unsigned int)16)
1301///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001302void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001303 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1304 "id *, unsigned int))(void *)objc_msgSend)";
1305 buf += "\n\t\t";
1306 buf += "((id)l_collection,\n\t\t";
1307 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1308 buf += "\n\t\t";
1309 buf += "&enumState, "
1310 "(id *)items, (unsigned int)16)";
1311}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001312
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001313/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1314/// statement to exit to its outer synthesized loop.
1315///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001316Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001317 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1318 return S;
1319 // replace break with goto __break_label
1320 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001322 SourceLocation startLoc = S->getLocStart();
1323 buf = "goto __break_label_";
1324 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001325 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001326
1327 return 0;
1328}
1329
1330/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1331/// statement to continue with its inner synthesized loop.
1332///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001333Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001334 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1335 return S;
1336 // replace continue with goto __continue_label
1337 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001338
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001339 SourceLocation startLoc = S->getLocStart();
1340 buf = "goto __continue_label_";
1341 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001342 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001344 return 0;
1345}
1346
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001347/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001348/// It rewrites:
1349/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001350
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001351/// Into:
1352/// {
Mike Stump11289f42009-09-09 15:08:12 +00001353/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001354/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001355/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001356/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001357/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001358/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001359/// if (limit) {
1360/// unsigned long startMutations = *enumState.mutationsPtr;
1361/// do {
1362/// unsigned long counter = 0;
1363/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001364/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001365/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001366/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001367/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001368/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001369/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001370/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001371/// objects:items count:16]);
1372/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001373/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001374/// }
1375/// else
1376/// elem = nil;
1377/// }
1378///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001379Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001380 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001381 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001382 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001383 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001384 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001385 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001386
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001388 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001389 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001390 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001391 std::string buf;
1392 buf = "\n{\n\t";
1393 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1394 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001395 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001396 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001397 if (ElementType->isObjCQualifiedIdType() ||
1398 ElementType->isObjCQualifiedInterfaceType())
1399 // Simply use 'id' for all qualified types.
1400 elementTypeAsString = "id";
1401 else
1402 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001403 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001404 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001405 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001406 buf += elementName;
1407 buf += ";\n\t";
1408 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001409 else {
1410 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001411 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001412 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1413 if (VD->getType()->isObjCQualifiedIdType() ||
1414 VD->getType()->isObjCQualifiedInterfaceType())
1415 // Simply use 'id' for all qualified types.
1416 elementTypeAsString = "id";
1417 else
1418 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001419 }
Mike Stump11289f42009-09-09 15:08:12 +00001420
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001421 // struct __objcFastEnumerationState enumState = { 0 };
1422 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1423 // id items[16];
1424 buf += "id items[16];\n\t";
1425 // id l_collection = (id)
1426 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001427 // Find start location of 'collection' the hard way!
1428 const char *startCollectionBuf = startBuf;
1429 startCollectionBuf += 3; // skip 'for'
1430 startCollectionBuf = strchr(startCollectionBuf, '(');
1431 startCollectionBuf++; // skip '('
1432 // find 'in' and skip it.
1433 while (*startCollectionBuf != ' ' ||
1434 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1435 (*(startCollectionBuf+3) != ' ' &&
1436 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1437 startCollectionBuf++;
1438 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001439
1440 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001441 ReplaceText(startLoc, startCollectionBuf - startBuf,
1442 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001444 SourceLocation rightParenLoc = S->getRParenLoc();
1445 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1446 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001448
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1450 // objects:items count:16];
1451 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001452 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001453 // ((unsigned int (*)
1454 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001455 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001457 // "countByEnumeratingWithState:objects:count:"),
1458 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001459 // (id *)items, (unsigned int)16);
1460 buf += "unsigned long limit =\n\t\t";
1461 SynthCountByEnumWithState(buf);
1462 buf += ";\n\t";
1463 /// if (limit) {
1464 /// unsigned long startMutations = *enumState.mutationsPtr;
1465 /// do {
1466 /// unsigned long counter = 0;
1467 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001468 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001469 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001470 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001471 buf += "if (limit) {\n\t";
1472 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1473 buf += "do {\n\t\t";
1474 buf += "unsigned long counter = 0;\n\t\t";
1475 buf += "do {\n\t\t\t";
1476 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1477 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1478 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001479 buf += " = (";
1480 buf += elementTypeAsString;
1481 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001483 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001484
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001485 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001486 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001487 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001488 /// objects:items count:16]);
1489 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001490 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001491 /// }
1492 /// else
1493 /// elem = nil;
1494 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001495 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001496 buf = ";\n\t";
1497 buf += "__continue_label_";
1498 buf += utostr(ObjCBcLabelNo.back());
1499 buf += ": ;";
1500 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001501 buf += "} while (counter < limit);\n\t";
1502 buf += "} while (limit = ";
1503 SynthCountByEnumWithState(buf);
1504 buf += ");\n\t";
1505 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001506 buf += " = ((";
1507 buf += elementTypeAsString;
1508 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001509 buf += "__break_label_";
1510 buf += utostr(ObjCBcLabelNo.back());
1511 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 buf += "}\n\t";
1513 buf += "else\n\t\t";
1514 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001515 buf += " = ((";
1516 buf += elementTypeAsString;
1517 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001518 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001520 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001521 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001522 if (isa<CompoundStmt>(S->getBody())) {
1523 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1524 InsertText(endBodyLoc, buf.c_str(), buf.size());
1525 } else {
1526 /* Need to treat single statements specially. For example:
1527 *
1528 * for (A *a in b) if (stuff()) break;
1529 * for (A *a in b) xxxyy;
1530 *
1531 * The following code simply scans ahead to the semi to find the actual end.
1532 */
1533 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1534 const char *semiBuf = strchr(stmtBuf, ';');
1535 assert(semiBuf && "Can't find ';'");
1536 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1537 InsertText(endBodyLoc, buf.c_str(), buf.size());
1538 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001539 Stmts.pop_back();
1540 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001541 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001542}
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001545/// This routine rewrites @synchronized(expr) stmt;
1546/// into:
1547/// objc_sync_enter(expr);
1548/// @try stmt @finally { objc_sync_exit(expr); }
1549///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001550Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001551 // Get the start location and compute the semi location.
1552 SourceLocation startLoc = S->getLocStart();
1553 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001554
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001555 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001556
1557 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001558 buf = "objc_sync_enter((id)";
1559 const char *lparenBuf = startBuf;
1560 while (*lparenBuf != '(') lparenBuf++;
1561 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001562 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1563 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001564 // been rewritten! (which implies the SourceLocation's are invalid).
1565 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001566 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001567 while (*endBuf != ')') endBuf--;
1568 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001569 buf = ");\n";
1570 // declare a new scope with two variables, _stack and _rethrow.
1571 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1572 buf += "int buf[18/*32-bit i386*/];\n";
1573 buf += "char *pointers[4];} _stack;\n";
1574 buf += "id volatile _rethrow = 0;\n";
1575 buf += "objc_exception_try_enter(&_stack);\n";
1576 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001577 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001578 startLoc = S->getSynchBody()->getLocEnd();
1579 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001580
Steve Naroffad7013b2008-08-19 13:04:19 +00001581 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001582 SourceLocation lastCurlyLoc = startLoc;
1583 buf = "}\nelse {\n";
1584 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001585 buf += "}\n";
1586 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001587 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001588
1589 std::string syncBuf;
1590 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001591 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1592 CastExpr::CK_Unknown,
1593 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001594 std::string syncExprBufS;
1595 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001596 syncExpr->printPretty(syncExprBuf, *Context, 0,
1597 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001598 syncBuf += syncExprBuf.str();
1599 syncBuf += ");";
1600
1601 buf += syncBuf;
1602 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001603 buf += "}\n";
1604 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001605
Chris Lattner9cc55f52008-01-31 19:51:04 +00001606 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001607
1608 bool hasReturns = false;
1609 HasReturnStmts(S->getSynchBody(), hasReturns);
1610 if (hasReturns)
1611 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1612
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001613 return 0;
1614}
1615
Steve Naroffec60b432009-12-05 21:43:12 +00001616void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1617{
Steve Naroff6d6da252008-12-05 17:03:39 +00001618 // Perform a bottom up traversal of all children.
1619 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1620 CI != E; ++CI)
1621 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001622 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001623
Steve Naroffec60b432009-12-05 21:43:12 +00001624 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001625 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001626 TryFinallyContainsReturnDiag);
1627 }
1628 return;
1629}
1630
Steve Naroffec60b432009-12-05 21:43:12 +00001631void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1632{
1633 // Perform a bottom up traversal of all children.
1634 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1635 CI != E; ++CI)
1636 if (*CI)
1637 HasReturnStmts(*CI, hasReturns);
1638
1639 if (isa<ReturnStmt>(S))
1640 hasReturns = true;
1641 return;
1642}
1643
1644void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1645 // Perform a bottom up traversal of all children.
1646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1647 CI != E; ++CI)
1648 if (*CI) {
1649 RewriteTryReturnStmts(*CI);
1650 }
1651 if (isa<ReturnStmt>(S)) {
1652 SourceLocation startLoc = S->getLocStart();
1653 const char *startBuf = SM->getCharacterData(startLoc);
1654
1655 const char *semiBuf = strchr(startBuf, ';');
1656 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1657 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1658
1659 std::string buf;
1660 buf = "{ objc_exception_try_exit(&_stack); return";
1661
1662 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1663 InsertText(onePastSemiLoc, "}", 1);
1664 }
1665 return;
1666}
1667
1668void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1669 // Perform a bottom up traversal of all children.
1670 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1671 CI != E; ++CI)
1672 if (*CI) {
1673 RewriteSyncReturnStmts(*CI, syncExitBuf);
1674 }
1675 if (isa<ReturnStmt>(S)) {
1676 SourceLocation startLoc = S->getLocStart();
1677 const char *startBuf = SM->getCharacterData(startLoc);
1678
1679 const char *semiBuf = strchr(startBuf, ';');
1680 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1681 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1682
1683 std::string buf;
1684 buf = "{ objc_exception_try_exit(&_stack);";
1685 buf += syncExitBuf;
1686 buf += " return";
1687
1688 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1689 InsertText(onePastSemiLoc, "}", 1);
1690 }
1691 return;
1692}
1693
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001694Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001695 // Get the start location and compute the semi location.
1696 SourceLocation startLoc = S->getLocStart();
1697 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001698
Steve Naroffbf478ec2007-11-07 04:08:17 +00001699 assert((*startBuf == '@') && "bogus @try location");
1700
1701 std::string buf;
1702 // declare a new scope with two variables, _stack and _rethrow.
1703 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1704 buf += "int buf[18/*32-bit i386*/];\n";
1705 buf += "char *pointers[4];} _stack;\n";
1706 buf += "id volatile _rethrow = 0;\n";
1707 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001708 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001709
Chris Lattner9cc55f52008-01-31 19:51:04 +00001710 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001711
Steve Naroffbf478ec2007-11-07 04:08:17 +00001712 startLoc = S->getTryBody()->getLocEnd();
1713 startBuf = SM->getCharacterData(startLoc);
1714
1715 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001716
Steve Naroffbf478ec2007-11-07 04:08:17 +00001717 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001718 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1719 if (catchList) {
1720 startLoc = startLoc.getFileLocWithOffset(1);
1721 buf = " /* @catch begin */ else {\n";
1722 buf += " id _caught = objc_exception_extract(&_stack);\n";
1723 buf += " objc_exception_try_enter (&_stack);\n";
1724 buf += " if (_setjmp(_stack.buf))\n";
1725 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1726 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001727
Steve Naroffce2dca12008-07-16 15:31:30 +00001728 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001729 } else { /* no catch list */
1730 buf = "}\nelse {\n";
1731 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1732 buf += "}";
1733 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001734 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001735 bool sawIdTypedCatch = false;
1736 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001737 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001738 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001739
Mike Stump11289f42009-09-09 15:08:12 +00001740 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001741 buf = "if ("; // we are generating code for the first catch clause
1742 else
1743 buf = "else if (";
1744 startLoc = catchList->getLocStart();
1745 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroffbf478ec2007-11-07 04:08:17 +00001747 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001748
Steve Naroffbf478ec2007-11-07 04:08:17 +00001749 const char *lParenLoc = strchr(startBuf, '(');
1750
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001751 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001752 // Now rewrite the body...
1753 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001754 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1755 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001756 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1757 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001758 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001759
Steve Naroffedb5bc62008-02-01 20:02:07 +00001760 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001761 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001762 } else if (catchDecl) {
1763 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001764 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001765 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001766 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001767 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001768 } else if (t->isObjCObjectPointerType()) {
1769 QualType InterfaceTy = t->getPointeeType();
1770 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1771 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001773 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001774 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001775 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001776 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001777 }
1778 }
1779 // Now rewrite the body...
1780 lastCatchBody = catchList->getCatchBody();
1781 SourceLocation rParenLoc = catchList->getRParenLoc();
1782 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1783 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1784 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1785 assert((*rParenBuf == ')') && "bogus @catch paren location");
1786 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001787
Steve Naroffbf478ec2007-11-07 04:08:17 +00001788 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001789 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001790 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001791 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001792 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001793 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001794 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001795 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001796 catchList = catchList->getNextCatchStmt();
1797 }
1798 // Complete the catch list...
1799 if (lastCatchBody) {
1800 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001801 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1802 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001803
Steve Naroff4adbe312008-09-11 15:29:03 +00001804 // Insert the last (implicit) else clause *before* the right curly brace.
1805 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1806 buf = "} /* last catch end */\n";
1807 buf += "else {\n";
1808 buf += " _rethrow = _caught;\n";
1809 buf += " objc_exception_try_exit(&_stack);\n";
1810 buf += "} } /* @catch end */\n";
1811 if (!S->getFinallyStmt())
1812 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001813 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001814
Steve Naroffbf478ec2007-11-07 04:08:17 +00001815 // Set lastCurlyLoc
1816 lastCurlyLoc = lastCatchBody->getLocEnd();
1817 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001818 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001819 startLoc = finalStmt->getLocStart();
1820 startBuf = SM->getCharacterData(startLoc);
1821 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001822
Steve Naroffbf478ec2007-11-07 04:08:17 +00001823 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001824 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001825
Steve Naroffbf478ec2007-11-07 04:08:17 +00001826 Stmt *body = finalStmt->getFinallyBody();
1827 SourceLocation startLoc = body->getLocStart();
1828 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001829 assert(*SM->getCharacterData(startLoc) == '{' &&
1830 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001831 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001832 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001833
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834 startLoc = startLoc.getFileLocWithOffset(1);
1835 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001836 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001837 endLoc = endLoc.getFileLocWithOffset(-1);
1838 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001839 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001840
Steve Naroffbf478ec2007-11-07 04:08:17 +00001841 // Set lastCurlyLoc
1842 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001843
Steve Naroff6d6da252008-12-05 17:03:39 +00001844 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001845 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001846 } else { /* no finally clause - make sure we synthesize an implicit one */
1847 buf = "{ /* implicit finally clause */\n";
1848 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1849 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1850 buf += "}";
1851 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001852
1853 // Now check for any return/continue/go statements within the @try.
1854 // The implicit finally clause won't called if the @try contains any
1855 // jump statements.
1856 bool hasReturns = false;
1857 HasReturnStmts(S->getTryBody(), hasReturns);
1858 if (hasReturns)
1859 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001860 }
1861 // Now emit the final closing curly brace...
1862 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1863 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001864 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001865 return 0;
1866}
1867
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001868Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001869 return 0;
1870}
1871
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001872Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001873 return 0;
1874}
1875
Mike Stump11289f42009-09-09 15:08:12 +00001876// This can't be done with ReplaceStmt(S, ThrowExpr), since
1877// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001878// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001879Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001880 // Get the start location and compute the semi location.
1881 SourceLocation startLoc = S->getLocStart();
1882 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001883
Steve Naroffa733c7f2007-11-07 15:32:26 +00001884 assert((*startBuf == '@') && "bogus @throw location");
1885
1886 std::string buf;
1887 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001888 if (S->getThrowExpr())
1889 buf = "objc_exception_throw(";
1890 else // add an implicit argument
1891 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001892
Steve Naroff29788342008-07-25 15:41:30 +00001893 // handle "@ throw" correctly.
1894 const char *wBuf = strchr(startBuf, 'w');
1895 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1896 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001897
Steve Naroffa733c7f2007-11-07 15:32:26 +00001898 const char *semiBuf = strchr(startBuf, ';');
1899 assert((*semiBuf == ';') && "@throw: can't find ';'");
1900 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1901 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001902 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001903 return 0;
1904}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001905
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001906Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001907 // Create a new string expression.
1908 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001909 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001910 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001911 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1912 StrEncoding.length(), false,StrType,
1913 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001914 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001915
Chris Lattner4431a1b2007-11-30 22:53:43 +00001916 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001917 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001918 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001919}
1920
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001921Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001922 if (!SelGetUidFunctionDecl)
1923 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001924 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1925 // Create a call to sel_registerName("selName").
1926 llvm::SmallVector<Expr*, 8> SelExprs;
1927 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001928 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001929 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001930 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001931 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001932 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1933 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001934 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001935 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001936 return SelExp;
1937}
1938
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001939CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001940 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001941 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001942 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001943
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001944 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001945 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001946
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001947 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001948 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001949 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001950 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001951 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001952 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001953
John McCall9dd450b2009-09-21 23:43:11 +00001954 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001955
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001956 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1957 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001958}
1959
Steve Naroff50d42052007-11-01 13:24:47 +00001960static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1961 const char *&startRef, const char *&endRef) {
1962 while (startBuf < endBuf) {
1963 if (*startBuf == '<')
1964 startRef = startBuf; // mark the start.
1965 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001966 if (startRef && *startRef == '<') {
1967 endRef = startBuf; // mark the end.
1968 return true;
1969 }
1970 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001971 }
1972 startBuf++;
1973 }
1974 return false;
1975}
1976
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001977static void scanToNextArgument(const char *&argRef) {
1978 int angle = 0;
1979 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1980 if (*argRef == '<')
1981 angle++;
1982 else if (*argRef == '>')
1983 angle--;
1984 argRef++;
1985 }
1986 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1987}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001988
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001989bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001990 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001991}
1992
Steve Naroff873bd842008-07-29 18:15:38 +00001993void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1994 QualType Type = E->getType();
1995 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001996 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001997
Steve Naroffdbfc6932008-11-19 21:15:47 +00001998 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1999 Loc = ECE->getLParenLoc();
2000 EndLoc = ECE->getRParenLoc();
2001 } else {
2002 Loc = E->getLocStart();
2003 EndLoc = E->getLocEnd();
2004 }
2005 // This will defend against trying to rewrite synthesized expressions.
2006 if (Loc.isInvalid() || EndLoc.isInvalid())
2007 return;
2008
Steve Naroff873bd842008-07-29 18:15:38 +00002009 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002010 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002011 const char *startRef = 0, *endRef = 0;
2012 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2013 // Get the locations of the startRef, endRef.
2014 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2015 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2016 // Comment out the protocol references.
2017 InsertText(LessLoc, "/*", 2);
2018 InsertText(GreaterLoc, "*/", 2);
2019 }
2020 }
2021}
2022
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002023void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002024 SourceLocation Loc;
2025 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002026 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002027 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2028 Loc = VD->getLocation();
2029 Type = VD->getType();
2030 }
2031 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2032 Loc = FD->getLocation();
2033 // Check for ObjC 'id' and class types that have been adorned with protocol
2034 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002035 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002036 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002037 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002038 if (!proto)
2039 return;
2040 Type = proto->getResultType();
2041 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002042 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2043 Loc = FD->getLocation();
2044 Type = FD->getType();
2045 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002046 else
2047 return;
Mike Stump11289f42009-09-09 15:08:12 +00002048
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002049 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002050 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002051
Steve Naroff50d42052007-11-01 13:24:47 +00002052 const char *endBuf = SM->getCharacterData(Loc);
2053 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002054 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002055 startBuf--; // scan backward (from the decl location) for return type.
2056 const char *startRef = 0, *endRef = 0;
2057 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2058 // Get the locations of the startRef, endRef.
2059 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2060 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2061 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002062 InsertText(LessLoc, "/*", 2);
2063 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002064 }
2065 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002066 if (!proto)
2067 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002068 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002069 const char *startBuf = SM->getCharacterData(Loc);
2070 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002071 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2072 if (needToScanForQualifiers(proto->getArgType(i))) {
2073 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002074
Steve Naroff50d42052007-11-01 13:24:47 +00002075 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002076 // scan forward (from the decl location) for argument types.
2077 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002078 const char *startRef = 0, *endRef = 0;
2079 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2080 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002081 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002082 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002083 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002084 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002085 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002086 InsertText(LessLoc, "/*", 2);
2087 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002088 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002089 startBuf = ++endBuf;
2090 }
2091 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002092 // If the function name is derived from a macro expansion, then the
2093 // argument buffer will not follow the name. Need to speak with Chris.
2094 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002095 startBuf++; // scan forward (from the decl location) for argument types.
2096 startBuf++;
2097 }
Steve Naroff50d42052007-11-01 13:24:47 +00002098 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002099}
2100
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002101// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002102void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002103 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2104 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002105 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002106 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002107 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002108 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002109 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002110 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002111 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002112 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002113}
2114
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002115void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002116 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002117 if (FD->getIdentifier() &&
2118 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002119 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002120 return;
2121 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002122 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002123}
2124
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002125void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2126 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2127 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2128 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2129 if (!proto)
2130 return;
2131 QualType Type = proto->getResultType();
2132 std::string FdStr = Type.getAsString();
2133 FdStr += " ";
2134 FdStr += FD->getNameAsCString();
2135 FdStr += "(";
2136 unsigned numArgs = proto->getNumArgs();
2137 for (unsigned i = 0; i < numArgs; i++) {
2138 QualType ArgType = proto->getArgType(i);
2139 FdStr += ArgType.getAsString();
2140
2141 if (i+1 < numArgs)
2142 FdStr += ", ";
2143 }
2144 FdStr += ");\n";
2145 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2146 CurFunctionDeclToDeclareForBlock = 0;
2147}
2148
Steve Naroff17978c42008-03-11 17:37:02 +00002149// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002150void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002151 if (SuperContructorFunctionDecl)
2152 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002153 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002154 llvm::SmallVector<QualType, 16> ArgTys;
2155 QualType argT = Context->getObjCIdType();
2156 assert(!argT.isNull() && "Can't find 'id' type");
2157 ArgTys.push_back(argT);
2158 ArgTys.push_back(argT);
2159 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2160 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002161 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002162 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002163 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002164 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002165 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002166}
2167
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002168// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002169void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002170 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2171 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002172 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002173 assert(!argT.isNull() && "Can't find 'id' type");
2174 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002175 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002176 assert(!argT.isNull() && "Can't find 'SEL' type");
2177 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002178 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002179 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002180 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002181 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002182 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002183 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002184 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002185}
2186
Steve Naroff7fa2f042007-11-15 10:28:18 +00002187// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002188void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002189 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2190 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002191 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002192 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002193 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002194 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2195 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2196 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002197 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002198 assert(!argT.isNull() && "Can't find 'SEL' type");
2199 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002200 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002201 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002202 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002203 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002204 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002205 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002206 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002207}
2208
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002209// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002210void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002211 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2212 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002213 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002214 assert(!argT.isNull() && "Can't find 'id' type");
2215 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002216 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002217 assert(!argT.isNull() && "Can't find 'SEL' type");
2218 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002219 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002220 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002221 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002222 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002223 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002224 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002225 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002226}
2227
Mike Stump11289f42009-09-09 15:08:12 +00002228// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002229// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002230void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002231 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002232 &Context->Idents.get("objc_msgSendSuper_stret");
2233 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002234 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002235 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002236 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002237 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2238 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2239 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002240 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002241 assert(!argT.isNull() && "Can't find 'SEL' type");
2242 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002243 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002244 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002245 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002246 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002247 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002248 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002249 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002250}
2251
Steve Naroff2e4e3852008-05-08 22:02:18 +00002252// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002253void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002254 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2255 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002256 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002257 assert(!argT.isNull() && "Can't find 'id' type");
2258 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002259 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002260 assert(!argT.isNull() && "Can't find 'SEL' type");
2261 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002262 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002263 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002264 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002265 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002266 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002267 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002268 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002269}
2270
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002271// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002272void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002273 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2274 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002275 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002276 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002277 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002278 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002279 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002280 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002281 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002282 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002283}
2284
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002285// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002286void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002287 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2288 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002289 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002290 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002291 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002292 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002293 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002294 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002295 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002296 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002297}
2298
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002299Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002300 QualType strType = getConstantStringStructType();
2301
2302 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002303
2304 std::string tmpName = InFileName;
2305 unsigned i;
2306 for (i=0; i < tmpName.length(); i++) {
2307 char c = tmpName.at(i);
2308 // replace any non alphanumeric characters with '_'.
2309 if (!isalpha(c) && (c < '0' || c > '9'))
2310 tmpName[i] = '_';
2311 }
2312 S += tmpName;
2313 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002314 S += utostr(NumObjCStringLiterals++);
2315
Steve Naroff00a31762008-03-27 22:29:16 +00002316 Preamble += "static __NSConstantStringImpl " + S;
2317 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2318 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002319 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002320 std::string prettyBufS;
2321 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002322 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2323 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002324 Preamble += prettyBuf.str();
2325 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002326 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002327
2328 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2329 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002330 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002331 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2332 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002333 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002334 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002335 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002336 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2337 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002338 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002339 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002340 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002341}
2342
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002343ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002344 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002345 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002347 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002348 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002349 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002350 assert(OPT);
2351 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002352 return IT->getDecl();
2353 }
2354 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002355}
2356
2357// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002358QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002359 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002360 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002361 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002362 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002363 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002364
Steve Naroff7fa2f042007-11-15 10:28:18 +00002365 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002366 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002367 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002368 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002369
Steve Naroff7fa2f042007-11-15 10:28:18 +00002370 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002371 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002372 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2373 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002374 FieldTypes[i], 0,
2375 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002376 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregor91f84212008-12-11 16:49:14 +00002379 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002380 }
2381 return Context->getTagDeclType(SuperStructDecl);
2382}
2383
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002384QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002385 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002386 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002387 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002388 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002389 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002390
Steve Naroffce8e8862008-03-15 00:55:56 +00002391 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002392 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002393 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002394 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002395 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002396 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002397 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002398 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002399
Steve Naroffce8e8862008-03-15 00:55:56 +00002400 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002401 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002402 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2403 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002404 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002405 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002406 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002407 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002408 }
2409
2410 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002411 }
2412 return Context->getTagDeclType(ConstantStringDecl);
2413}
2414
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002415Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002416 if (!SelGetUidFunctionDecl)
2417 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002418 if (!MsgSendFunctionDecl)
2419 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002420 if (!MsgSendSuperFunctionDecl)
2421 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002422 if (!MsgSendStretFunctionDecl)
2423 SynthMsgSendStretFunctionDecl();
2424 if (!MsgSendSuperStretFunctionDecl)
2425 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002426 if (!MsgSendFpretFunctionDecl)
2427 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002428 if (!GetClassFunctionDecl)
2429 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002430 if (!GetMetaClassFunctionDecl)
2431 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002432
Steve Naroff7fa2f042007-11-15 10:28:18 +00002433 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002434 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2435 // May need to use objc_msgSend_stret() as well.
2436 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002437 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2438 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002439 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002440 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002441 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002442 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002443 }
Mike Stump11289f42009-09-09 15:08:12 +00002444
Steve Naroff574440f2007-10-24 22:48:43 +00002445 // Synthesize a call to objc_msgSend().
2446 llvm::SmallVector<Expr*, 8> MsgExprs;
2447 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002448
Steve Naroff574440f2007-10-24 22:48:43 +00002449 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2450 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002451 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2452 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002453 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002454 MsgSendFlavor = MsgSendSuperFunctionDecl;
2455 if (MsgSendStretFlavor)
2456 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2457 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002458
2459 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002460 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002461
2462 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002463
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002464 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002465 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002466 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2467 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002468 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002469 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002470 SourceLocation()))
2471 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002472
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002473 llvm::SmallVector<Expr*, 8> ClsExprs;
2474 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002475 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002476 SuperDecl->getIdentifier()->getNameStart(),
2477 SuperDecl->getIdentifier()->getLength(),
2478 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002479 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002480 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002481 ClsExprs.size());
2482 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002483 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002484 NoTypeInfoCStyleCastExpr(Context,
2485 Context->getObjCIdType(),
2486 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002487 // struct objc_super
2488 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002489 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Steve Naroff0b844f02008-03-11 18:14:26 +00002491 if (LangOpts.Microsoft) {
2492 SynthSuperContructorFunctionDecl();
2493 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002494 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002495 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002496 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002497 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002498 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002499 // The code for super is a little tricky to prevent collision with
2500 // the structure definition in the header. The rewriter has it's own
2501 // internal definition (__rw_objc_super) that is uses. This is why
2502 // we need the cast below. For example:
2503 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2504 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002505 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002506 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002507 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002508 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2509 Context->getPointerType(superType),
2510 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002511 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002512 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002513 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2514 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002515 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002516 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002517 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002518 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002519 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002520 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002521 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002522 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002523 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002524 } else {
2525 llvm::SmallVector<Expr*, 8> ClsExprs;
2526 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002527 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002528 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002529 clsName->getLength(),
2530 false, argType,
2531 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002532 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002533 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002534 ClsExprs.size());
2535 MsgExprs.push_back(Cls);
2536 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002537 } else { // instance message.
2538 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002539
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002540 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002541 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002542 if (MsgSendStretFlavor)
2543 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002544 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002545
Steve Naroff7fa2f042007-11-15 10:28:18 +00002546 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002548 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002549 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2550 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002551 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002552 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002553 SourceLocation()))
2554 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002555
Steve Naroff7fa2f042007-11-15 10:28:18 +00002556 llvm::SmallVector<Expr*, 8> ClsExprs;
2557 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002558 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002559 SuperDecl->getIdentifier()->getNameStart(),
2560 SuperDecl->getIdentifier()->getLength(),
2561 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002562 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002563 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002564 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002565 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002566 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002567 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002568 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2569 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002570 // struct objc_super
2571 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002572 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002573
Steve Naroff17978c42008-03-11 17:37:02 +00002574 if (LangOpts.Microsoft) {
2575 SynthSuperContructorFunctionDecl();
2576 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002577 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002578 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002579 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002580 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002581 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002582 // The code for super is a little tricky to prevent collision with
2583 // the structure definition in the header. The rewriter has it's own
2584 // internal definition (__rw_objc_super) that is uses. This is why
2585 // we need the cast below. For example:
2586 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2587 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002588 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002589 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002590 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002591 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2592 Context->getPointerType(superType),
2593 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002594 } else {
2595 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002596 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2597 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002598 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002599 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002600 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002601 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002602 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002603 // Remove all type-casts because it may contain objc-style types; e.g.
2604 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002605 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002606 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002607 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2608 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002609 MsgExprs.push_back(recExpr);
2610 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002611 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002612 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002613 llvm::SmallVector<Expr*, 8> SelExprs;
2614 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002615 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002616 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002617 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002618 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002619 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2620 &SelExprs[0], SelExprs.size());
2621 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002622
Steve Naroff574440f2007-10-24 22:48:43 +00002623 // Now push any user supplied arguments.
2624 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002625 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002626 // Make all implicit casts explicit...ICE comes in handy:-)
2627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2628 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002629 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002630 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002631 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002632 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2633 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002634 }
2635 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002636 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002637 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002638 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002639 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002640 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2641 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002644 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002645 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2646 // out the argument in the original expression (since we aren't deleting
2647 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2648 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002649 }
Steve Narofff36987c2007-11-04 22:37:50 +00002650 // Generate the funky cast.
2651 CastExpr *cast;
2652 llvm::SmallVector<QualType, 8> ArgTypes;
2653 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002654
Steve Narofff36987c2007-11-04 22:37:50 +00002655 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002656 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2657 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2658 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002659 ArgTypes.push_back(Context->getObjCIdType());
2660 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002661 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002662 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002663 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2664 E = OMD->param_end(); PI != E; ++PI) {
2665 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002666 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002667 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002668 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002669 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002670 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002671 t = Context->getPointerType(BPT->getPointeeType());
2672 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002673 ArgTypes.push_back(t);
2674 }
Chris Lattnera4997152009-02-20 18:43:26 +00002675 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2676 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002677 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002678 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002679 }
2680 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002681 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002682
Steve Narofff36987c2007-11-04 22:37:50 +00002683 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002684 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002685 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002686
Mike Stump11289f42009-09-09 15:08:12 +00002687 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002688 // If we don't do this cast, we get the following bizarre warning/note:
2689 // xx.m:13: warning: function called through a non-compatible type
2690 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002691 cast = NoTypeInfoCStyleCastExpr(Context,
2692 Context->getPointerType(Context->VoidTy),
2693 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002694
Steve Narofff36987c2007-11-04 22:37:50 +00002695 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002696 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002697 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002698 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002699 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002700 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002701 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2702 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002703
2704 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002705 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall9dd450b2009-09-21 23:43:11 +00002707 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002708 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002709 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002710 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002711 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002712 if (MsgSendStretFlavor) {
2713 // We have the method which returns a struct/union. Must also generate
2714 // call to objc_msgSend_stret and hang both varieties on a conditional
2715 // expression which dictate which one to envoke depending on size of
2716 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002717
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002718 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002719 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002720 SourceLocation());
2721 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002722 cast = NoTypeInfoCStyleCastExpr(Context,
2723 Context->getPointerType(Context->VoidTy),
2724 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002725 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002726 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002727 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002728 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002729 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002730 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2731 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002732
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002733 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002734 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002735
John McCall9dd450b2009-09-21 23:43:11 +00002736 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002737 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002738 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002739 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002740
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002741 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002742 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002743 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002744 Context->getSizeType(),
2745 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002746 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2747 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2748 // For X86 it is more complicated and some kind of target specific routine
2749 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002750 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002751 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002752 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002753 Context->IntTy,
2754 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002755 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2756 BinaryOperator::LE,
2757 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002758 SourceLocation());
2759 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002760 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002761 new (Context) ConditionalOperator(lessThanExpr,
2762 SourceLocation(), CE,
2763 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002764 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002767 return ReplacingStmt;
2768}
2769
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002770Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002771 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Naroff574440f2007-10-24 22:48:43 +00002773 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002774 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002775
2776 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002777 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002778}
2779
Steve Naroffd9803712009-04-29 16:37:50 +00002780// typedef struct objc_object Protocol;
2781QualType RewriteObjC::getProtocolType() {
2782 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002783 TypeSourceInfo *TInfo
2784 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002785 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002786 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002787 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002788 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002789 }
2790 return Context->getTypeDeclType(ProtocolTypeDecl);
2791}
2792
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002793/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002794/// a synthesized/forward data reference (to the protocol's metadata).
2795/// The forward references (and metadata) are generated in
2796/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002797Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002798 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2799 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002800 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002801 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002802 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2803 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2804 Context->getPointerType(DRE->getType()),
2805 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002806 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2807 CastExpr::CK_Unknown,
2808 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002809 ReplaceStmt(Exp, castExpr);
2810 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002811 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002812 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002813
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002814}
2815
Mike Stump11289f42009-09-09 15:08:12 +00002816bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002817 const char *endBuf) {
2818 while (startBuf < endBuf) {
2819 if (*startBuf == '#') {
2820 // Skip whitespace.
2821 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2822 ;
2823 if (!strncmp(startBuf, "if", strlen("if")) ||
2824 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2825 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2826 !strncmp(startBuf, "define", strlen("define")) ||
2827 !strncmp(startBuf, "undef", strlen("undef")) ||
2828 !strncmp(startBuf, "else", strlen("else")) ||
2829 !strncmp(startBuf, "elif", strlen("elif")) ||
2830 !strncmp(startBuf, "endif", strlen("endif")) ||
2831 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2832 !strncmp(startBuf, "include", strlen("include")) ||
2833 !strncmp(startBuf, "import", strlen("import")) ||
2834 !strncmp(startBuf, "include_next", strlen("include_next")))
2835 return true;
2836 }
2837 startBuf++;
2838 }
2839 return false;
2840}
2841
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002842/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002843/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002844void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002845 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002846 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002847 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002848 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002849 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002850 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002851 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002852 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002853 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002854 SourceLocation LocStart = CDecl->getLocStart();
2855 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002856
Steve Naroffdde78982007-11-14 19:25:57 +00002857 const char *startBuf = SM->getCharacterData(LocStart);
2858 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002859
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002860 // If no ivars and no root or if its root, directly or indirectly,
2861 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002862 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2863 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002864 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002865 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002866 return;
2867 }
Mike Stump11289f42009-09-09 15:08:12 +00002868
2869 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002870 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002871 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002872 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002873 if (LangOpts.Microsoft)
2874 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002875
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002876 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002877 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002878 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002879 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002880 // If the buffer contains preprocessor directives, we do more fine-grained
2881 // rewrites. This is intended to fix code that looks like (which occurs in
2882 // NSURL.h, for example):
2883 //
2884 // #ifdef XYZ
2885 // @interface Foo : NSObject
2886 // #else
2887 // @interface FooBar : NSObject
2888 // #endif
2889 // {
2890 // int i;
2891 // }
2892 // @end
2893 //
2894 // This clause is segregated to avoid breaking the common case.
2895 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002896 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002897 CDecl->getClassLoc();
2898 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002899 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002900
Chris Lattnerf5b77512009-02-20 18:18:36 +00002901 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002902 // advance to the end of the referenced protocols.
2903 while (endHeader < cursor && *endHeader != '>') endHeader++;
2904 endHeader++;
2905 }
2906 // rewrite the original header
2907 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2908 } else {
2909 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002910 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002911 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002912 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002913 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002914 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002915 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002916 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002917 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002918
Steve Naroffdde78982007-11-14 19:25:57 +00002919 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002920 SourceLocation OnePastCurly =
2921 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2922 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002923 }
2924 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002925
Steve Naroffdde78982007-11-14 19:25:57 +00002926 // Now comment out any visibility specifiers.
2927 while (cursor < endBuf) {
2928 if (*cursor == '@') {
2929 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002930 // Skip whitespace.
2931 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2932 /*scan*/;
2933
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002934 // FIXME: presence of @public, etc. inside comment results in
2935 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002936 if (!strncmp(cursor, "public", strlen("public")) ||
2937 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002938 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002939 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002940 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002941 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002942 // FIXME: If there are cases where '<' is used in ivar declaration part
2943 // of user code, then scan the ivar list and use needToScanForQualifiers
2944 // for type checking.
2945 else if (*cursor == '<') {
2946 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002947 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002948 cursor = strchr(cursor, '>');
2949 cursor++;
2950 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002951 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002952 } else if (*cursor == '^') { // rewrite block specifier.
2953 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2954 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002955 }
Steve Naroffdde78982007-11-14 19:25:57 +00002956 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002957 }
Steve Naroffdde78982007-11-14 19:25:57 +00002958 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002959 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002960 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002961 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002962 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002963 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002964 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002965 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002966 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002967 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002968 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002969 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002970 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002971 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002972}
2973
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002974// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002975/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002976template<typename MethodIterator>
2977void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2978 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002979 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002980 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002981 const char *ClassName,
2982 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002983 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002984
Chris Lattner31bc07e2007-12-12 07:46:12 +00002985 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002986 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002987 SEL _cmd;
2988 char *method_types;
2989 void *_imp;
2990 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002991 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002992 Result += "\nstruct _objc_method {\n";
2993 Result += "\tSEL _cmd;\n";
2994 Result += "\tchar *method_types;\n";
2995 Result += "\tvoid *_imp;\n";
2996 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002997
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002998 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002999 }
Mike Stump11289f42009-09-09 15:08:12 +00003000
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003001 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003002
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003003 /* struct {
3004 struct _objc_method_list *next_method;
3005 int method_count;
3006 struct _objc_method method_list[];
3007 }
3008 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003009 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003010 Result += "\nstatic struct {\n";
3011 Result += "\tstruct _objc_method_list *next_method;\n";
3012 Result += "\tint method_count;\n";
3013 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003014 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003015 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003016 Result += prefix;
3017 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3018 Result += "_METHODS_";
3019 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003020 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003021 Result += IsInstanceMethod ? "inst" : "cls";
3022 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003023 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003024
Chris Lattner31bc07e2007-12-12 07:46:12 +00003025 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003026 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003027 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003028 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003029 Result += "\", \"";
3030 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003031 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003032 Result += MethodInternalNames[*MethodBegin];
3033 Result += "}\n";
3034 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3035 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003036 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003037 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003038 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003039 Result += "\", \"";
3040 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003041 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003042 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003043 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003044 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003045 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003046}
3047
Steve Naroffd9803712009-04-29 16:37:50 +00003048/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003049void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003050RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3051 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003052 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003053
3054 // Output struct protocol_methods holder of method selector and type.
3055 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3056 /* struct protocol_methods {
3057 SEL _cmd;
3058 char *method_types;
3059 }
3060 */
3061 Result += "\nstruct _protocol_methods {\n";
3062 Result += "\tstruct objc_selector *_cmd;\n";
3063 Result += "\tchar *method_types;\n";
3064 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003065
Steve Naroffd9803712009-04-29 16:37:50 +00003066 objc_protocol_methods = true;
3067 }
3068 // Do not synthesize the protocol more than once.
3069 if (ObjCSynthesizedProtocols.count(PDecl))
3070 return;
Mike Stump11289f42009-09-09 15:08:12 +00003071
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3073 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3074 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003075 /* struct _objc_protocol_method_list {
3076 int protocol_method_count;
3077 struct protocol_methods protocols[];
3078 }
Steve Naroff251084d2008-03-12 01:06:30 +00003079 */
Steve Naroffd9803712009-04-29 16:37:50 +00003080 Result += "\nstatic struct {\n";
3081 Result += "\tint protocol_method_count;\n";
3082 Result += "\tstruct _protocol_methods protocol_methods[";
3083 Result += utostr(NumMethods);
3084 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3085 Result += PDecl->getNameAsString();
3086 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3087 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003088
Steve Naroffd9803712009-04-29 16:37:50 +00003089 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003090 for (ObjCProtocolDecl::instmeth_iterator
3091 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003092 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003093 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003094 Result += "\t ,{{(struct objc_selector *)\"";
3095 else
3096 Result += "\t ,{(struct objc_selector *)\"";
3097 Result += (*I)->getSelector().getAsString().c_str();
3098 std::string MethodTypeString;
3099 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3100 Result += "\", \"";
3101 Result += MethodTypeString;
3102 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003103 }
Steve Naroffd9803712009-04-29 16:37:50 +00003104 Result += "\t }\n};\n";
3105 }
Mike Stump11289f42009-09-09 15:08:12 +00003106
Steve Naroffd9803712009-04-29 16:37:50 +00003107 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003108 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3109 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003110 if (NumMethods > 0) {
3111 /* struct _objc_protocol_method_list {
3112 int protocol_method_count;
3113 struct protocol_methods protocols[];
3114 }
3115 */
3116 Result += "\nstatic struct {\n";
3117 Result += "\tint protocol_method_count;\n";
3118 Result += "\tstruct _protocol_methods protocol_methods[";
3119 Result += utostr(NumMethods);
3120 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3121 Result += PDecl->getNameAsString();
3122 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3123 "{\n\t";
3124 Result += utostr(NumMethods);
3125 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003126
Steve Naroffd9803712009-04-29 16:37:50 +00003127 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003128 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003129 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003130 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003131 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003132 Result += "\t ,{{(struct objc_selector *)\"";
3133 else
3134 Result += "\t ,{(struct objc_selector *)\"";
3135 Result += (*I)->getSelector().getAsString().c_str();
3136 std::string MethodTypeString;
3137 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3138 Result += "\", \"";
3139 Result += MethodTypeString;
3140 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003141 }
Steve Naroffd9803712009-04-29 16:37:50 +00003142 Result += "\t }\n};\n";
3143 }
3144
3145 // Output:
3146 /* struct _objc_protocol {
3147 // Objective-C 1.0 extensions
3148 struct _objc_protocol_extension *isa;
3149 char *protocol_name;
3150 struct _objc_protocol **protocol_list;
3151 struct _objc_protocol_method_list *instance_methods;
3152 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003153 };
Steve Naroffd9803712009-04-29 16:37:50 +00003154 */
3155 static bool objc_protocol = false;
3156 if (!objc_protocol) {
3157 Result += "\nstruct _objc_protocol {\n";
3158 Result += "\tstruct _objc_protocol_extension *isa;\n";
3159 Result += "\tchar *protocol_name;\n";
3160 Result += "\tstruct _objc_protocol **protocol_list;\n";
3161 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3162 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003163 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003164
Steve Naroffd9803712009-04-29 16:37:50 +00003165 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003166 }
Mike Stump11289f42009-09-09 15:08:12 +00003167
Steve Naroffd9803712009-04-29 16:37:50 +00003168 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3169 Result += PDecl->getNameAsString();
3170 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3171 "{\n\t0, \"";
3172 Result += PDecl->getNameAsString();
3173 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003174 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003175 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3176 Result += PDecl->getNameAsString();
3177 Result += ", ";
3178 }
3179 else
3180 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003181 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003182 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3183 Result += PDecl->getNameAsString();
3184 Result += "\n";
3185 }
3186 else
3187 Result += "0\n";
3188 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003189
Steve Naroffd9803712009-04-29 16:37:50 +00003190 // Mark this protocol as having been generated.
3191 if (!ObjCSynthesizedProtocols.insert(PDecl))
3192 assert(false && "protocol already synthesized");
3193
3194}
3195
3196void RewriteObjC::
3197RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3198 const char *prefix, const char *ClassName,
3199 std::string &Result) {
3200 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Steve Naroffd9803712009-04-29 16:37:50 +00003202 for (unsigned i = 0; i != Protocols.size(); i++)
3203 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3204
Chris Lattner388f6e92008-07-21 21:33:21 +00003205 // Output the top lovel protocol meta-data for the class.
3206 /* struct _objc_protocol_list {
3207 struct _objc_protocol_list *next;
3208 int protocol_count;
3209 struct _objc_protocol *class_protocols[];
3210 }
3211 */
3212 Result += "\nstatic struct {\n";
3213 Result += "\tstruct _objc_protocol_list *next;\n";
3214 Result += "\tint protocol_count;\n";
3215 Result += "\tstruct _objc_protocol *class_protocols[";
3216 Result += utostr(Protocols.size());
3217 Result += "];\n} _OBJC_";
3218 Result += prefix;
3219 Result += "_PROTOCOLS_";
3220 Result += ClassName;
3221 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3222 "{\n\t0, ";
3223 Result += utostr(Protocols.size());
3224 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003225
Chris Lattner388f6e92008-07-21 21:33:21 +00003226 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003227 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003228 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chris Lattner388f6e92008-07-21 21:33:21 +00003230 for (unsigned i = 1; i != Protocols.size(); i++) {
3231 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003232 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003233 Result += "\n";
3234 }
3235 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003236}
3237
Steve Naroffd9803712009-04-29 16:37:50 +00003238
Mike Stump11289f42009-09-09 15:08:12 +00003239/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003240/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003241void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003242 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003243 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003244 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003245 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003246 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003247 CDecl = CDecl->getNextClassCategory())
3248 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3249 break;
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003251 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003252 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003253 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003254
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003255 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003256 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003257 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003258
3259 // If any of our property implementations have associated getters or
3260 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003261 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3262 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003263 Prop != PropEnd; ++Prop) {
3264 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3265 continue;
3266 if (!(*Prop)->getPropertyIvarDecl())
3267 continue;
3268 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3269 if (!PD)
3270 continue;
3271 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3272 InstanceMethods.push_back(Getter);
3273 if (PD->isReadOnly())
3274 continue;
3275 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3276 InstanceMethods.push_back(Setter);
3277 }
3278 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003279 true, "CATEGORY_", FullCategoryName.c_str(),
3280 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003281
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003282 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003283 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003284 false, "CATEGORY_", FullCategoryName.c_str(),
3285 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003286
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003287 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003288 // Null CDecl is case of a category implementation with no category interface
3289 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003290 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3291 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003292 /* struct _objc_category {
3293 char *category_name;
3294 char *class_name;
3295 struct _objc_method_list *instance_methods;
3296 struct _objc_method_list *class_methods;
3297 struct _objc_protocol_list *protocols;
3298 // Objective-C 1.0 extensions
3299 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003300 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003301 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003302 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003303 */
Mike Stump11289f42009-09-09 15:08:12 +00003304
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003305 static bool objc_category = false;
3306 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003307 Result += "\nstruct _objc_category {\n";
3308 Result += "\tchar *category_name;\n";
3309 Result += "\tchar *class_name;\n";
3310 Result += "\tstruct _objc_method_list *instance_methods;\n";
3311 Result += "\tstruct _objc_method_list *class_methods;\n";
3312 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003313 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003314 Result += "\tstruct _objc_property_list *instance_properties;\n";
3315 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003316 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003317 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003318 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3319 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003320 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003321 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003322 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003323 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003324 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003325
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003326 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003327 Result += "\t, (struct _objc_method_list *)"
3328 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3329 Result += FullCategoryName;
3330 Result += "\n";
3331 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003332 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003333 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003334 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003335 Result += "\t, (struct _objc_method_list *)"
3336 "&_OBJC_CATEGORY_CLASS_METHODS_";
3337 Result += FullCategoryName;
3338 Result += "\n";
3339 }
3340 else
3341 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003342
Chris Lattnerf5b77512009-02-20 18:18:36 +00003343 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003344 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003345 Result += FullCategoryName;
3346 Result += "\n";
3347 }
3348 else
3349 Result += "\t, 0\n";
3350 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003351}
3352
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003353/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3354/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003355void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3356 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003357 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003358 if (ivar->isBitField()) {
3359 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3360 // place all bitfields at offset 0.
3361 Result += "0";
3362 } else {
3363 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003364 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003365 if (LangOpts.Microsoft)
3366 Result += "_IMPL";
3367 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003368 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003369 Result += ")";
3370 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003371}
3372
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003373//===----------------------------------------------------------------------===//
3374// Meta Data Emission
3375//===----------------------------------------------------------------------===//
3376
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003377void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003378 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003379 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003380
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003381 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003382 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003383 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003384 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003385 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Chris Lattner30d23e82007-12-12 07:56:42 +00003388 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003389 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003390 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003391 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003392 if (NumIvars > 0) {
3393 static bool objc_ivar = false;
3394 if (!objc_ivar) {
3395 /* struct _objc_ivar {
3396 char *ivar_name;
3397 char *ivar_type;
3398 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003399 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003400 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003401 Result += "\nstruct _objc_ivar {\n";
3402 Result += "\tchar *ivar_name;\n";
3403 Result += "\tchar *ivar_type;\n";
3404 Result += "\tint ivar_offset;\n";
3405 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003406
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003407 objc_ivar = true;
3408 }
3409
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003410 /* struct {
3411 int ivar_count;
3412 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003413 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003414 */
Mike Stump11289f42009-09-09 15:08:12 +00003415 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003416 Result += "\tint ivar_count;\n";
3417 Result += "\tstruct _objc_ivar ivar_list[";
3418 Result += utostr(NumIvars);
3419 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003420 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003421 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003422 "{\n\t";
3423 Result += utostr(NumIvars);
3424 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003425
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003426 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003427 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003428 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003429 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003430 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003431 IV != IVEnd; ++IV)
3432 IVars.push_back(*IV);
3433 IVI = IVars.begin();
3434 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003435 } else {
3436 IVI = CDecl->ivar_begin();
3437 IVE = CDecl->ivar_end();
3438 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003439 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003440 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003441 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003442 std::string TmpString, StrEncoding;
3443 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3444 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003445 Result += StrEncoding;
3446 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003447 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003448 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003449 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003450 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003451 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003452 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003453 std::string TmpString, StrEncoding;
3454 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3455 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003456 Result += StrEncoding;
3457 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003458 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003459 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003462 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003463 }
Mike Stump11289f42009-09-09 15:08:12 +00003464
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003465 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003466 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003468
3469 // If any of our property implementations have associated getters or
3470 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003471 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3472 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003473 Prop != PropEnd; ++Prop) {
3474 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3475 continue;
3476 if (!(*Prop)->getPropertyIvarDecl())
3477 continue;
3478 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3479 if (!PD)
3480 continue;
3481 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3482 InstanceMethods.push_back(Getter);
3483 if (PD->isReadOnly())
3484 continue;
3485 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3486 InstanceMethods.push_back(Setter);
3487 }
3488 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003489 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003490
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003491 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003492 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003493 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003494
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003495 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003496 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3497 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003498
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003499 // Declaration of class/meta-class metadata
3500 /* struct _objc_class {
3501 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003502 const char *super_class_name;
3503 char *name;
3504 long version;
3505 long info;
3506 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003507 struct _objc_ivar_list *ivars;
3508 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003509 struct objc_cache *cache;
3510 struct objc_protocol_list *protocols;
3511 const char *ivar_layout;
3512 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003513 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003514 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003515 static bool objc_class = false;
3516 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003517 Result += "\nstruct _objc_class {\n";
3518 Result += "\tstruct _objc_class *isa;\n";
3519 Result += "\tconst char *super_class_name;\n";
3520 Result += "\tchar *name;\n";
3521 Result += "\tlong version;\n";
3522 Result += "\tlong info;\n";
3523 Result += "\tlong instance_size;\n";
3524 Result += "\tstruct _objc_ivar_list *ivars;\n";
3525 Result += "\tstruct _objc_method_list *methods;\n";
3526 Result += "\tstruct objc_cache *cache;\n";
3527 Result += "\tstruct _objc_protocol_list *protocols;\n";
3528 Result += "\tconst char *ivar_layout;\n";
3529 Result += "\tstruct _objc_class_ext *ext;\n";
3530 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003531 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003532 }
Mike Stump11289f42009-09-09 15:08:12 +00003533
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003534 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003535 ObjCInterfaceDecl *RootClass = 0;
3536 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003537 while (SuperClass) {
3538 RootClass = SuperClass;
3539 SuperClass = SuperClass->getSuperClass();
3540 }
3541 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003542
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003543 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003544 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003545 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003546 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003547 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003548 Result += "\"";
3549
3550 if (SuperClass) {
3551 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003552 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003554 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003555 Result += "\"";
3556 }
3557 else {
3558 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003559 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += "\"";
3561 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003562 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003563 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003564 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003565 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003566 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003567 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003568 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003570 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003571 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003572 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003573 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003574 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003575 Result += ",0,0\n";
3576 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003577 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003578 Result += "\t,0,0,0,0\n";
3579 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003580
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003581 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003582 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003583 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003584 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003585 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003586 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003587 if (SuperClass) {
3588 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003589 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003590 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003591 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += "\"";
3593 }
3594 else {
3595 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003596 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003597 Result += "\"";
3598 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003599 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003600 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003601 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003602 Result += ",0";
3603 else {
3604 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003605 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003606 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003607 if (LangOpts.Microsoft)
3608 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003609 Result += ")";
3610 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003612 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003613 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003614 Result += "\n\t";
3615 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003616 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003617 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003618 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003619 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003620 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003621 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003622 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003623 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003624 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003625 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003626 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003627 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 Result += ", 0,0\n";
3629 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003630 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003631 Result += ",0,0,0\n";
3632 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003633}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003634
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003635/// RewriteImplementations - This routine rewrites all method implementations
3636/// and emits meta-data.
3637
Steve Narofff8cfd162008-11-13 20:07:04 +00003638void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003639 int ClsDefCount = ClassImplementation.size();
3640 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003641
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003642 // Rewrite implemented methods
3643 for (int i = 0; i < ClsDefCount; i++)
3644 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003645
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003646 for (int i = 0; i < CatDefCount; i++)
3647 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003648}
Mike Stump11289f42009-09-09 15:08:12 +00003649
Steve Narofff8cfd162008-11-13 20:07:04 +00003650void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3651 int ClsDefCount = ClassImplementation.size();
3652 int CatDefCount = CategoryImplementation.size();
3653
Steve Naroff30ac2222008-05-07 21:23:49 +00003654 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003655 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003656 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003657 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003658 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003659
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003660 // For each implemented category, write out all its meta data.
3661 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003662 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003663
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003664 // Write objc_symtab metadata
3665 /*
3666 struct _objc_symtab
3667 {
3668 long sel_ref_cnt;
3669 SEL *refs;
3670 short cls_def_cnt;
3671 short cat_def_cnt;
3672 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003673 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003674 */
Mike Stump11289f42009-09-09 15:08:12 +00003675
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003676 Result += "\nstruct _objc_symtab {\n";
3677 Result += "\tlong sel_ref_cnt;\n";
3678 Result += "\tSEL *refs;\n";
3679 Result += "\tshort cls_def_cnt;\n";
3680 Result += "\tshort cat_def_cnt;\n";
3681 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3682 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003683
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003684 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003685 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003686 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003687 + ", " + utostr(CatDefCount) + "\n";
3688 for (int i = 0; i < ClsDefCount; i++) {
3689 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003690 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003691 Result += "\n";
3692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 for (int i = 0; i < CatDefCount; i++) {
3695 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003696 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003697 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003698 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003699 Result += "\n";
3700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003703
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003704 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003705
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003706 /*
3707 struct _objc_module {
3708 long version;
3709 long size;
3710 const char *name;
3711 struct _objc_symtab *symtab;
3712 }
3713 */
Mike Stump11289f42009-09-09 15:08:12 +00003714
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 Result += "\nstruct _objc_module {\n";
3716 Result += "\tlong version;\n";
3717 Result += "\tlong size;\n";
3718 Result += "\tconst char *name;\n";
3719 Result += "\tstruct _objc_symtab *symtab;\n";
3720 Result += "};\n\n";
3721 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003722 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003723 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003724 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003725 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003726
3727 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003728 if (ProtocolExprDecls.size()) {
3729 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3730 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003731 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003732 E = ProtocolExprDecls.end(); I != E; ++I) {
3733 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3734 Result += (*I)->getNameAsString();
3735 Result += " = &_OBJC_PROTOCOL_";
3736 Result += (*I)->getNameAsString();
3737 Result += ";\n";
3738 }
3739 Result += "#pragma data_seg(pop)\n\n";
3740 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003741 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003742 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003743 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3744 Result += "&_OBJC_MODULES;\n";
3745 Result += "#pragma data_seg(pop)\n\n";
3746 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003747}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003748
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003749void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3750 const std::string &Name,
3751 ValueDecl *VD) {
3752 assert(BlockByRefDeclNo.count(VD) &&
3753 "RewriteByRefString: ByRef decl missing");
3754 ResultStr += "struct __Block_byref_" + Name +
3755 "_" + utostr(BlockByRefDeclNo[VD]) ;
3756}
3757
Steve Naroff677ab3a2008-10-27 17:20:55 +00003758std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3759 const char *funcName,
3760 std::string Tag) {
3761 const FunctionType *AFT = CE->getFunctionType();
3762 QualType RT = AFT->getResultType();
3763 std::string StructRef = "struct " + Tag;
3764 std::string S = "static " + RT.getAsString() + " __" +
3765 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003766
Steve Naroff677ab3a2008-10-27 17:20:55 +00003767 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003768
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003769 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003770 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003771 // block (to reference imported block decl refs).
3772 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003773 } else if (BD->param_empty()) {
3774 S += "(" + StructRef + " *__cself)";
3775 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003776 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003777 assert(FT && "SynthesizeBlockFunc: No function proto");
3778 S += '(';
3779 // first add the implicit argument.
3780 S += StructRef + " *__cself, ";
3781 std::string ParamStr;
3782 for (BlockDecl::param_iterator AI = BD->param_begin(),
3783 E = BD->param_end(); AI != E; ++AI) {
3784 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003785 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003786 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003787 S += ParamStr;
3788 }
3789 if (FT->isVariadic()) {
3790 if (!BD->param_empty()) S += ", ";
3791 S += "...";
3792 }
3793 S += ')';
3794 }
3795 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003796
Steve Naroff677ab3a2008-10-27 17:20:55 +00003797 // Create local declarations to avoid rewriting all closure decl ref exprs.
3798 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003799 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003800 E = BlockByRefDecls.end(); I != E; ++I) {
3801 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003802 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003803 std::string TypeString;
3804 RewriteByRefString(TypeString, Name, (*I));
3805 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003806 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003807 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003808 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003809 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003810 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003811 E = BlockByCopyDecls.end(); I != E; ++I) {
3812 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003813 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 // Handle nested closure invocation. For example:
3815 //
3816 // void (^myImportedClosure)(void);
3817 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003818 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003819 // void (^anotherClosure)(void);
3820 // anotherClosure = ^(void) {
3821 // myImportedClosure(); // import and invoke the closure
3822 // };
3823 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003824 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003825 S += "struct __block_impl *";
3826 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003827 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003828 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003829 }
3830 std::string RewrittenStr = RewrittenBlockExprs[CE];
3831 const char *cstr = RewrittenStr.c_str();
3832 while (*cstr++ != '{') ;
3833 S += cstr;
3834 S += "\n";
3835 return S;
3836}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003837
Steve Naroff677ab3a2008-10-27 17:20:55 +00003838std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3839 const char *funcName,
3840 std::string Tag) {
3841 std::string StructRef = "struct " + Tag;
3842 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003843
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 S += funcName;
3845 S += "_block_copy_" + utostr(i);
3846 S += "(" + StructRef;
3847 S += "*dst, " + StructRef;
3848 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003849 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003851 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003852 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003853 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003854 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003855 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003856 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003857 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003858 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003860 S += "}\n";
3861
Steve Naroff677ab3a2008-10-27 17:20:55 +00003862 S += "\nstatic void __";
3863 S += funcName;
3864 S += "_block_dispose_" + utostr(i);
3865 S += "(" + StructRef;
3866 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003867 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003869 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003870 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003871 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003872 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003873 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003874 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 }
Mike Stump11289f42009-09-09 15:08:12 +00003876 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003877 return S;
3878}
3879
Steve Naroff30484702009-12-06 21:14:13 +00003880std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3881 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003882 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003883 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003884
Steve Naroff677ab3a2008-10-27 17:20:55 +00003885 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003886 S += " struct " + Desc;
3887 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003888
Steve Naroff30484702009-12-06 21:14:13 +00003889 Constructor += "(void *fp, "; // Invoke function pointer.
3890 Constructor += "struct " + Desc; // Descriptor pointer.
3891 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003892
Steve Naroff677ab3a2008-10-27 17:20:55 +00003893 if (BlockDeclRefs.size()) {
3894 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003895 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 E = BlockByCopyDecls.end(); I != E; ++I) {
3897 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003898 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003899 std::string ArgName = "_" + FieldName;
3900 // Handle nested closure invocation. For example:
3901 //
3902 // void (^myImportedBlock)(void);
3903 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003904 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003905 // void (^anotherBlock)(void);
3906 // anotherBlock = ^(void) {
3907 // myImportedBlock(); // import and invoke the closure
3908 // };
3909 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003910 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003911 S += "struct __block_impl *";
3912 Constructor += ", void *" + ArgName;
3913 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003914 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3915 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003916 Constructor += ", " + ArgName;
3917 }
3918 S += FieldName + ";\n";
3919 }
3920 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003921 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 E = BlockByRefDecls.end(); I != E; ++I) {
3923 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003924 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 std::string ArgName = "_" + FieldName;
3926 // Handle nested closure invocation. For example:
3927 //
3928 // void (^myImportedBlock)(void);
3929 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003930 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931 // void (^anotherBlock)(void);
3932 // anotherBlock = ^(void) {
3933 // myImportedBlock(); // import and invoke the closure
3934 // };
3935 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003936 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 S += "struct __block_impl *";
3938 Constructor += ", void *" + ArgName;
3939 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003940 std::string TypeString;
3941 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003942 TypeString += " *";
3943 FieldName = TypeString + FieldName;
3944 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003945 Constructor += ", " + ArgName;
3946 }
3947 S += FieldName + "; // by ref\n";
3948 }
3949 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003950 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003951 if (GlobalVarDecl)
3952 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3953 else
3954 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003955 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003956
Steve Naroff30484702009-12-06 21:14:13 +00003957 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003958
Steve Naroff677ab3a2008-10-27 17:20:55 +00003959 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003960 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003962 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003964 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 Constructor += Name + " = (struct __block_impl *)_";
3966 else
3967 Constructor += Name + " = _";
3968 Constructor += Name + ";\n";
3969 }
3970 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003971 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003972 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003973 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003974 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003975 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003976 Constructor += Name + " = (struct __block_impl *)_";
3977 else
3978 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003979 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003980 }
3981 } else {
3982 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003983 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003984 if (GlobalVarDecl)
3985 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3986 else
3987 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003988 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3989 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003990 }
3991 Constructor += " ";
3992 Constructor += "}\n";
3993 S += Constructor;
3994 S += "};\n";
3995 return S;
3996}
3997
Steve Naroff30484702009-12-06 21:14:13 +00003998std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3999 std::string ImplTag, int i,
4000 const char *FunName,
4001 unsigned hasCopy) {
4002 std::string S = "\nstatic struct " + DescTag;
4003
4004 S += " {\n unsigned long reserved;\n";
4005 S += " unsigned long Block_size;\n";
4006 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004007 S += " void (*copy)(struct ";
4008 S += ImplTag; S += "*, struct ";
4009 S += ImplTag; S += "*);\n";
4010
4011 S += " void (*dispose)(struct ";
4012 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004013 }
4014 S += "} ";
4015
4016 S += DescTag + "_DATA = { 0, sizeof(struct ";
4017 S += ImplTag + ")";
4018 if (hasCopy) {
4019 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4020 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4021 }
4022 S += "};\n";
4023 return S;
4024}
4025
Steve Naroff677ab3a2008-10-27 17:20:55 +00004026void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004027 const char *FunName) {
4028 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004029 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004030 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 // Insert closures that were part of the function.
4032 for (unsigned i = 0; i < Blocks.size(); i++) {
4033
4034 CollectBlockDeclRefInfo(Blocks[i]);
4035
Steve Naroff30484702009-12-06 21:14:13 +00004036 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4037 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004038
Steve Naroff30484702009-12-06 21:14:13 +00004039 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040
4041 InsertText(FunLocStart, CI.c_str(), CI.size());
4042
Steve Naroff30484702009-12-06 21:14:13 +00004043 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004044
Steve Naroff677ab3a2008-10-27 17:20:55 +00004045 InsertText(FunLocStart, CF.c_str(), CF.size());
4046
4047 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004048 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004049 InsertText(FunLocStart, HF.c_str(), HF.size());
4050 }
Steve Naroff30484702009-12-06 21:14:13 +00004051 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4052 ImportedBlockDecls.size() > 0);
4053 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004054
Steve Naroff677ab3a2008-10-27 17:20:55 +00004055 BlockDeclRefs.clear();
4056 BlockByRefDecls.clear();
4057 BlockByCopyDecls.clear();
4058 BlockCallExprs.clear();
4059 ImportedBlockDecls.clear();
4060 }
4061 Blocks.clear();
4062 RewrittenBlockExprs.clear();
4063}
4064
4065void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4066 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004067 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004068
Steve Naroff677ab3a2008-10-27 17:20:55 +00004069 SynthesizeBlockLiterals(FunLocStart, FuncName);
4070}
4071
4072void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004073 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4074 //SourceLocation FunLocStart = MD->getLocStart();
4075 // FIXME: This hack works around a bug in Rewrite.InsertText().
4076 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004077 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004078 // Convert colons to underscores.
4079 std::string::size_type loc = 0;
4080 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4081 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004082
Steve Naroff677ab3a2008-10-27 17:20:55 +00004083 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4084}
4085
4086void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4087 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4088 CI != E; ++CI)
4089 if (*CI) {
4090 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4091 GetBlockDeclRefExprs(CBE->getBody());
4092 else
4093 GetBlockDeclRefExprs(*CI);
4094 }
4095 // Handle specific things.
4096 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4097 // FIXME: Handle enums.
4098 if (!isa<FunctionDecl>(CDRE->getDecl()))
4099 BlockDeclRefs.push_back(CDRE);
4100 return;
4101}
4102
4103void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4104 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4105 CI != E; ++CI)
4106 if (*CI) {
4107 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4108 GetBlockCallExprs(CBE->getBody());
4109 else
4110 GetBlockCallExprs(*CI);
4111 }
Mike Stump11289f42009-09-09 15:08:12 +00004112
Steve Naroff677ab3a2008-10-27 17:20:55 +00004113 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4114 if (CE->getCallee()->getType()->isBlockPointerType()) {
4115 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4116 }
4117 }
4118 return;
4119}
4120
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004121Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004122 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004124
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004125 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004126 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004127 } else if (const BlockDeclRefExpr *CDRE =
4128 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004129 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004130 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004131 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004132 }
4133 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4134 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4135 }
4136 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4137 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4138 else if (const ConditionalOperator *CEXPR =
4139 dyn_cast<ConditionalOperator>(BlockExp)) {
4140 Expr *LHSExp = CEXPR->getLHS();
4141 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4142 Expr *RHSExp = CEXPR->getRHS();
4143 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4144 Expr *CONDExp = CEXPR->getCond();
4145 ConditionalOperator *CondExpr =
4146 new (Context) ConditionalOperator(CONDExp,
4147 SourceLocation(), cast<Expr>(LHSStmt),
4148 SourceLocation(), cast<Expr>(RHSStmt),
4149 Exp->getType());
4150 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004151 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4152 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 } else {
4154 assert(1 && "RewriteBlockClass: Bad type");
4155 }
4156 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004157 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004159 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004160 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004161
Steve Naroff350b6652008-10-30 10:07:53 +00004162 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4163 SourceLocation(),
4164 &Context->Idents.get("__block_impl"));
4165 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004166
Steve Naroff350b6652008-10-30 10:07:53 +00004167 // Generate a funky cast.
4168 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004169
Steve Naroff350b6652008-10-30 10:07:53 +00004170 // Push the block argument type.
4171 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004173 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004174 E = FTP->arg_type_end(); I && (I != E); ++I) {
4175 QualType t = *I;
4176 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004177 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004178 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004179 t = Context->getPointerType(BPT->getPointeeType());
4180 }
4181 ArgTypes.push_back(t);
4182 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 }
Steve Naroff350b6652008-10-30 10:07:53 +00004184 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004185 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004186 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004187
Steve Naroff350b6652008-10-30 10:07:53 +00004188 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004189
John McCall97513962010-01-15 18:39:57 +00004190 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4191 CastExpr::CK_Unknown,
4192 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004193 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004194 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4195 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004196 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004197
Douglas Gregor91f84212008-12-11 16:49:14 +00004198 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004199 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004200 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004201 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4202 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCall97513962010-01-15 18:39:57 +00004204 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4205 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004206 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004207
Steve Naroff350b6652008-10-30 10:07:53 +00004208 llvm::SmallVector<Expr*, 8> BlkExprs;
4209 // Add the implicit argument.
4210 BlkExprs.push_back(BlkCast);
4211 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004212 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004214 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004216 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4217 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004218 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004219 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220}
4221
4222void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004223 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004224 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004225}
4226
Steve Naroffd9803712009-04-29 16:37:50 +00004227// We need to return the rewritten expression to handle cases where the
4228// BlockDeclRefExpr is embedded in another expression being rewritten.
4229// For example:
4230//
4231// int main() {
4232// __block Foo *f;
4233// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004234//
Steve Naroffd9803712009-04-29 16:37:50 +00004235// void (^myblock)() = ^() {
4236// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4237// i = 77;
4238// };
4239//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004240Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004241 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004242 // for each DeclRefExp where BYREFVAR is name of the variable.
4243 ValueDecl *VD;
4244 bool isArrow = true;
4245 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4246 VD = BDRE->getDecl();
4247 else {
4248 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4249 isArrow = false;
4250 }
4251
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004252 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4253 &Context->Idents.get("__forwarding"),
4254 Context->VoidPtrTy, 0,
4255 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004256 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4257 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004258 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004259
4260 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004261 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4262 &Context->Idents.get(Name),
4263 Context->VoidPtrTy, 0,
4264 /*BitWidth=*/0, /*Mutable=*/true);
4265 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004266 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004267
4268
4269
Steve Narofff26a1d42009-02-02 17:19:26 +00004270 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004271 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4272 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004273 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004274 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004275}
4276
Steve Naroffc989a7b2008-11-03 23:29:32 +00004277void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4278 SourceLocation LocStart = CE->getLParenLoc();
4279 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004280
4281 // Need to avoid trying to rewrite synthesized casts.
4282 if (LocStart.isInvalid())
4283 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004284 // Need to avoid trying to rewrite casts contained in macros.
4285 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4286 return;
Mike Stump11289f42009-09-09 15:08:12 +00004287
Steve Naroff677ab3a2008-10-27 17:20:55 +00004288 const char *startBuf = SM->getCharacterData(LocStart);
4289 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004290
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 // advance the location to startArgList.
4292 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004293
Steve Naroff677ab3a2008-10-27 17:20:55 +00004294 while (*argPtr++ && (argPtr < endBuf)) {
4295 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004296 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 // Replace the '^' with '*'.
4298 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4299 ReplaceText(LocStart, 1, "*", 1);
4300 break;
4301 }
4302 }
4303 return;
4304}
4305
4306void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4307 SourceLocation DeclLoc = FD->getLocation();
4308 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004309
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 // We have 1 or more arguments that have closure pointers.
4311 const char *startBuf = SM->getCharacterData(DeclLoc);
4312 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004313
Steve Naroff677ab3a2008-10-27 17:20:55 +00004314 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004315
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 parenCount++;
4317 // advance the location to startArgList.
4318 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4319 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004320
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004322
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 while (*argPtr++ && parenCount) {
4324 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004325 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004326 // Replace the '^' with '*'.
4327 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4328 ReplaceText(DeclLoc, 1, "*", 1);
4329 break;
Mike Stump11289f42009-09-09 15:08:12 +00004330 case '(':
4331 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 break;
Mike Stump11289f42009-09-09 15:08:12 +00004333 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004334 parenCount--;
4335 break;
4336 }
4337 }
4338 return;
4339}
4340
4341bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004342 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004343 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004344 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004345 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004346 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004347 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004349 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004350 }
4351 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004352 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004353 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004354 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004355 return true;
4356 }
4357 return false;
4358}
4359
Ted Kremenek5a201952009-02-07 01:47:29 +00004360void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4361 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 const char *argPtr = strchr(Name, '(');
4363 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004364
Steve Naroff677ab3a2008-10-27 17:20:55 +00004365 LParen = argPtr; // output the start.
4366 argPtr++; // skip past the left paren.
4367 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004368
Steve Naroff677ab3a2008-10-27 17:20:55 +00004369 while (*argPtr && parenCount) {
4370 switch (*argPtr) {
4371 case '(': parenCount++; break;
4372 case ')': parenCount--; break;
4373 default: break;
4374 }
4375 if (parenCount) argPtr++;
4376 }
4377 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4378 RParen = argPtr; // output the end
4379}
4380
4381void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4382 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4383 RewriteBlockPointerFunctionArgs(FD);
4384 return;
Mike Stump11289f42009-09-09 15:08:12 +00004385 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004386 // Handle Variables and Typedefs.
4387 SourceLocation DeclLoc = ND->getLocation();
4388 QualType DeclT;
4389 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4390 DeclT = VD->getType();
4391 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4392 DeclT = TDD->getUnderlyingType();
4393 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4394 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004395 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004396 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004397
Steve Naroff677ab3a2008-10-27 17:20:55 +00004398 const char *startBuf = SM->getCharacterData(DeclLoc);
4399 const char *endBuf = startBuf;
4400 // scan backward (from the decl location) for the end of the previous decl.
4401 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4402 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Steve Naroff677ab3a2008-10-27 17:20:55 +00004404 // *startBuf != '^' if we are dealing with a pointer to function that
4405 // may take block argument types (which will be handled below).
4406 if (*startBuf == '^') {
4407 // Replace the '^' with '*', computing a negative offset.
4408 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4409 ReplaceText(DeclLoc, 1, "*", 1);
4410 }
4411 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4412 // Replace the '^' with '*' for arguments.
4413 DeclLoc = ND->getLocation();
4414 startBuf = SM->getCharacterData(DeclLoc);
4415 const char *argListBegin, *argListEnd;
4416 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4417 while (argListBegin < argListEnd) {
4418 if (*argListBegin == '^') {
4419 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4420 ReplaceText(CaretLoc, 1, "*", 1);
4421 }
4422 argListBegin++;
4423 }
4424 }
4425 return;
4426}
4427
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004428
4429/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4430/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4431/// struct Block_byref_id_object *src) {
4432/// _Block_object_assign (&_dest->object, _src->object,
4433/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4434/// [|BLOCK_FIELD_IS_WEAK]) // object
4435/// _Block_object_assign(&_dest->object, _src->object,
4436/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4437/// [|BLOCK_FIELD_IS_WEAK]) // block
4438/// }
4439/// And:
4440/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4441/// _Block_object_dispose(_src->object,
4442/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4443/// [|BLOCK_FIELD_IS_WEAK]) // object
4444/// _Block_object_dispose(_src->object,
4445/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4446/// [|BLOCK_FIELD_IS_WEAK]) // block
4447/// }
4448
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004449std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4450 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004451 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004452 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004453 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004454 CopyDestroyCache.insert(flag);
4455 S = "static void __Block_byref_id_object_copy_";
4456 S += utostr(flag);
4457 S += "(void *dst, void *src) {\n";
4458
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004459 // offset into the object pointer is computed as:
4460 // void * + void* + int + int + void* + void *
4461 unsigned IntSize =
4462 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4463 unsigned VoidPtrSize =
4464 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4465
4466 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4467 S += " _Block_object_assign((char*)dst + ";
4468 S += utostr(offset);
4469 S += ", *(void * *) ((char*)src + ";
4470 S += utostr(offset);
4471 S += "), ";
4472 S += utostr(flag);
4473 S += ");\n}\n";
4474
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004475 S += "static void __Block_byref_id_object_dispose_";
4476 S += utostr(flag);
4477 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004478 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4479 S += utostr(offset);
4480 S += "), ";
4481 S += utostr(flag);
4482 S += ");\n}\n";
4483 return S;
4484}
4485
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004486/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4487/// the declaration into:
4488/// struct __Block_byref_ND {
4489/// void *__isa; // NULL for everything except __weak pointers
4490/// struct __Block_byref_ND *__forwarding;
4491/// int32_t __flags;
4492/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004493/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4494/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004495/// typex ND;
4496/// };
4497///
4498/// It then replaces declaration of ND variable with:
4499/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4500/// __size=sizeof(struct __Block_byref_ND),
4501/// ND=initializer-if-any};
4502///
4503///
4504void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004505 // Insert declaration for the function in which block literal is
4506 // used.
4507 if (CurFunctionDeclToDeclareForBlock)
4508 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004509 int flag = 0;
4510 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004511 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4512 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004513 SourceLocation X = ND->getLocEnd();
4514 X = SM->getInstantiationLoc(X);
4515 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004516 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004517 std::string ByrefType;
4518 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004519 ByrefType += " {\n";
4520 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004521 RewriteByRefString(ByrefType, Name, ND);
4522 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004523 ByrefType += " int __flags;\n";
4524 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004525 // Add void *__Block_byref_id_object_copy;
4526 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004527 QualType Ty = ND->getType();
4528 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4529 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004530 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4531 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004532 }
4533
4534 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004535 ByrefType += " " + Name + ";\n";
4536 ByrefType += "};\n";
4537 // Insert this type in global scope. It is needed by helper function.
4538 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4539 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4540 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004541 if (Ty.isObjCGCWeak()) {
4542 flag |= BLOCK_FIELD_IS_WEAK;
4543 isa = 1;
4544 }
4545
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004546 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004547 flag = BLOCK_BYREF_CALLER;
4548 QualType Ty = ND->getType();
4549 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4550 if (Ty->isBlockPointerType())
4551 flag |= BLOCK_FIELD_IS_BLOCK;
4552 else
4553 flag |= BLOCK_FIELD_IS_OBJECT;
4554 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004555 if (!HF.empty())
4556 InsertText(FunLocStart, HF.c_str(), HF.size());
4557 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004558
4559 // struct __Block_byref_ND ND =
4560 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4561 // initializer-if-any};
4562 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004563 unsigned flags = 0;
4564 if (HasCopyAndDispose)
4565 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004566 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004567 ByrefType.clear();
4568 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004569 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004570 ByrefType += " " + Name + " = {(void*)";
4571 ByrefType += utostr(isa);
4572 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004573 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004574 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004575 ByrefType += "sizeof(";
4576 RewriteByRefString(ByrefType, Name, ND);
4577 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004578 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004579 ByrefType += ", __Block_byref_id_object_copy_";
4580 ByrefType += utostr(flag);
4581 ByrefType += ", __Block_byref_id_object_dispose_";
4582 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004583 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004584 ByrefType += "};\n";
4585 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4586 ByrefType.c_str(), ByrefType.size());
4587 }
4588 else {
4589 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004590 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004591 ByrefType += " " + Name;
4592 ReplaceText(DeclLoc, endBuf-startBuf,
4593 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004594 ByrefType = " = {(void*)";
4595 ByrefType += utostr(isa);
4596 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004597 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004598 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004599 ByrefType += "sizeof(";
4600 RewriteByRefString(ByrefType, Name, ND);
4601 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004602 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004603 ByrefType += "__Block_byref_id_object_copy_";
4604 ByrefType += utostr(flag);
4605 ByrefType += ", __Block_byref_id_object_dispose_";
4606 ByrefType += utostr(flag);
4607 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004608 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004609 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004610
4611 // Complete the newly synthesized compound expression by inserting a right
4612 // curly brace before the end of the declaration.
4613 // FIXME: This approach avoids rewriting the initializer expression. It
4614 // also assumes there is only one declarator. For example, the following
4615 // isn't currently supported by this routine (in general):
4616 //
4617 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4618 //
4619 const char *startBuf = SM->getCharacterData(startLoc);
4620 const char *semiBuf = strchr(startBuf, ';');
4621 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4622 SourceLocation semiLoc =
4623 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4624
4625 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004626 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004627 return;
4628}
4629
Mike Stump11289f42009-09-09 15:08:12 +00004630void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004631 // Add initializers for any closure decl refs.
4632 GetBlockDeclRefExprs(Exp->getBody());
4633 if (BlockDeclRefs.size()) {
4634 // Unique all "by copy" declarations.
4635 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4636 if (!BlockDeclRefs[i]->isByRef())
4637 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4638 // Unique all "by ref" declarations.
4639 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4640 if (BlockDeclRefs[i]->isByRef()) {
4641 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4642 }
4643 // Find any imported blocks...they will need special attention.
4644 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004645 if (BlockDeclRefs[i]->isByRef() ||
4646 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4647 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004648 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004649 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4650 }
4651 }
4652}
4653
Steve Narofff4b992a2008-10-28 20:29:00 +00004654FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4655 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004656 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004657 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004658 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004659 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004660}
4661
Steve Naroffd8907b72008-10-29 18:15:37 +00004662Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004663 Blocks.push_back(Exp);
4664
4665 CollectBlockDeclRefInfo(Exp);
4666 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004667
Steve Narofff4b992a2008-10-28 20:29:00 +00004668 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004669 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004670 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004671 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004672 // Convert colons to underscores.
4673 std::string::size_type loc = 0;
4674 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4675 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004676 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004677 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004678
Steve Narofff4b992a2008-10-28 20:29:00 +00004679 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004680
Steve Narofff4b992a2008-10-28 20:29:00 +00004681 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4682 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004683
Steve Narofff4b992a2008-10-28 20:29:00 +00004684 // Get a pointer to the function type so we can cast appropriately.
4685 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4686
4687 FunctionDecl *FD;
4688 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004689
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Simulate a contructor call...
4691 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004692 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004693
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004695
Steve Naroffe2514232008-10-29 21:23:59 +00004696 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004698 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4699 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004700 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4701 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004702 InitExprs.push_back(castExpr);
4703
Steve Naroff30484702009-12-06 21:14:13 +00004704 // Initialize the block descriptor.
4705 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004706
Steve Naroff30484702009-12-06 21:14:13 +00004707 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4708 &Context->Idents.get(DescData.c_str()),
4709 Context->VoidPtrTy, 0,
4710 VarDecl::Static);
4711 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4712 new (Context) DeclRefExpr(NewVD,
4713 Context->VoidPtrTy, SourceLocation()),
4714 UnaryOperator::AddrOf,
4715 Context->getPointerType(Context->VoidPtrTy),
4716 SourceLocation());
4717 InitExprs.push_back(DescRefExpr);
4718
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 // Add initializers for any closure decl refs.
4720 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004721 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004722 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004723 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004724 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004726 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004727 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004728 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004729 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004730 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004731 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004732 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4733 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004734 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004735 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004736 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004737 }
Mike Stump11289f42009-09-09 15:08:12 +00004738 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004739 }
4740 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004741 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004742 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004743 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004744 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4745 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004746 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004747 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004748 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 }
4750 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004751 if (ImportedBlockDecls.size()) {
4752 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4753 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004754 unsigned IntSize =
4755 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004756 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4757 Context->IntTy, SourceLocation());
4758 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004759 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004760 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4761 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004762 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004763 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004764 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004765 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4766 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004767 BlockDeclRefs.clear();
4768 BlockByRefDecls.clear();
4769 BlockByCopyDecls.clear();
4770 ImportedBlockDecls.clear();
4771 return NewRep;
4772}
4773
4774//===----------------------------------------------------------------------===//
4775// Function Body / Expression rewriting
4776//===----------------------------------------------------------------------===//
4777
Steve Naroff4588d0f2008-12-04 16:24:46 +00004778// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4779// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4780// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4781// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4782// Since the rewriter isn't capable of rewriting rewritten code, it's important
4783// we get this right.
4784void RewriteObjC::CollectPropertySetters(Stmt *S) {
4785 // Perform a bottom up traversal of all children.
4786 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4787 CI != E; ++CI)
4788 if (*CI)
4789 CollectPropertySetters(*CI);
4790
4791 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4792 if (BinOp->isAssignmentOp()) {
4793 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4794 PropSetters[PRE] = BinOp;
4795 }
4796 }
4797}
4798
Steve Narofff4b992a2008-10-28 20:29:00 +00004799Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004800 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004801 isa<DoStmt>(S) || isa<ForStmt>(S))
4802 Stmts.push_back(S);
4803 else if (isa<ObjCForCollectionStmt>(S)) {
4804 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004805 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004806 }
Mike Stump11289f42009-09-09 15:08:12 +00004807
Steve Narofff4b992a2008-10-28 20:29:00 +00004808 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004809
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 // Perform a bottom up rewrite of all children.
4811 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4812 CI != E; ++CI)
4813 if (*CI) {
4814 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004815 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004816 *CI = newStmt;
4817 }
Mike Stump11289f42009-09-09 15:08:12 +00004818
Steve Narofff4b992a2008-10-28 20:29:00 +00004819 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4820 // Rewrite the block body in place.
4821 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004822
Steve Narofff4b992a2008-10-28 20:29:00 +00004823 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004824 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004825 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004826
Steve Narofff4b992a2008-10-28 20:29:00 +00004827 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4828 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004829 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004830 return blockTranscribed;
4831 }
4832 // Handle specific things.
4833 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4834 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004835
Steve Narofff4b992a2008-10-28 20:29:00 +00004836 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4837 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4838
Steve Naroff4588d0f2008-12-04 16:24:46 +00004839 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4840 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4841 if (BinOp) {
4842 // Because the rewriter doesn't allow us to rewrite rewritten code,
4843 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004844 DisableReplaceStmt = true;
4845 // Save the source range. Even if we disable the replacement, the
4846 // rewritten node will have been inserted into the tree. If the synthesized
4847 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004848 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004849 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4850 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004851 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004852 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004853 //
4854 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4855 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4856 // to see the original expression). Consider this example:
4857 //
4858 // Foo *obj1, *obj2;
4859 //
4860 // obj1.i = [obj2 rrrr];
4861 //
4862 // 'BinOp' for the previous expression looks like:
4863 //
4864 // (BinaryOperator 0x231ccf0 'int' '='
4865 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4866 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4867 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4868 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4869 //
4870 // 'newStmt' represents the rewritten message expression. For example:
4871 //
4872 // (CallExpr 0x231d300 'id':'struct objc_object *'
4873 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4874 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4875 // (CStyleCastExpr 0x231d220 'void *'
4876 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4877 //
4878 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4879 // can be used as the setter argument. ReplaceStmt() will still 'see'
4880 // the original RHS (since we haven't altered BinOp).
4881 //
Mike Stump11289f42009-09-09 15:08:12 +00004882 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004883 // node. As a result, we now leak the original AST nodes.
4884 //
Steve Naroff08628db2008-12-09 12:56:34 +00004885 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004886 } else {
4887 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004888 }
4889 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004890 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4891 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004892
Steve Narofff4b992a2008-10-28 20:29:00 +00004893 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4894 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004895
Steve Narofff4b992a2008-10-28 20:29:00 +00004896 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004897#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004898 // Before we rewrite it, put the original message expression in a comment.
4899 SourceLocation startLoc = MessExpr->getLocStart();
4900 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004901
Steve Narofff4b992a2008-10-28 20:29:00 +00004902 const char *startBuf = SM->getCharacterData(startLoc);
4903 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004904
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 std::string messString;
4906 messString += "// ";
4907 messString.append(startBuf, endBuf-startBuf+1);
4908 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004909
4910 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004911 // InsertText(clang::SourceLocation, char const*, unsigned int).
4912 // InsertText(startLoc, messString.c_str(), messString.size());
4913 // Tried this, but it didn't work either...
4914 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004915#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004916 return RewriteMessageExpr(MessExpr);
4917 }
Mike Stump11289f42009-09-09 15:08:12 +00004918
Steve Narofff4b992a2008-10-28 20:29:00 +00004919 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4920 return RewriteObjCTryStmt(StmtTry);
4921
4922 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4923 return RewriteObjCSynchronizedStmt(StmtTry);
4924
4925 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4926 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004927
Steve Narofff4b992a2008-10-28 20:29:00 +00004928 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4929 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004930
4931 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004933 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004934 OrigStmtRange.getEnd());
4935 if (BreakStmt *StmtBreakStmt =
4936 dyn_cast<BreakStmt>(S))
4937 return RewriteBreakStmt(StmtBreakStmt);
4938 if (ContinueStmt *StmtContinueStmt =
4939 dyn_cast<ContinueStmt>(S))
4940 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004941
4942 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004943 // and cast exprs.
4944 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4945 // FIXME: What we're doing here is modifying the type-specifier that
4946 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004947 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004948 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4949 // the context of an ObjCForCollectionStmt. For example:
4950 // NSArray *someArray;
4951 // for (id <FooProtocol> index in someArray) ;
4952 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4953 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004954 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004955 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004956
Steve Narofff4b992a2008-10-28 20:29:00 +00004957 // Blocks rewrite rules.
4958 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4959 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004960 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004961 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004962 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004963 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004964 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004965 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004966 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004967 if (VD->hasAttr<BlocksAttr>()) {
4968 static unsigned uniqueByrefDeclCount = 0;
4969 assert(!BlockByRefDeclNo.count(ND) &&
4970 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4971 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004972 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004973 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004974 }
4975 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004976 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004977 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004978 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004979 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4980 }
4981 }
4982 }
Mike Stump11289f42009-09-09 15:08:12 +00004983
Steve Narofff4b992a2008-10-28 20:29:00 +00004984 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4985 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004986
4987 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004988 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4989 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004990 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4991 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004992 && "Statement stack mismatch");
4993 Stmts.pop_back();
4994 }
4995 // Handle blocks rewriting.
4996 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4997 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004998 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004999 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005000 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5001 ValueDecl *VD = DRE->getDecl();
5002 if (VD->hasAttr<BlocksAttr>())
5003 return RewriteBlockDeclRefExpr(DRE);
5004 }
5005
Steve Narofff4b992a2008-10-28 20:29:00 +00005006 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005007 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005008 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005009 ReplaceStmt(S, BlockCall);
5010 return BlockCall;
5011 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005012 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005013 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005014 RewriteCastExpr(CE);
5015 }
5016#if 0
5017 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005018 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005019 // Get the new text.
5020 std::string SStr;
5021 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005022 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005023 const std::string &Str = Buf.str();
5024
5025 printf("CAST = %s\n", &Str[0]);
5026 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5027 delete S;
5028 return Replacement;
5029 }
5030#endif
5031 // Return this stmt unmodified.
5032 return S;
5033}
5034
Steve Naroffe70a52a2009-12-05 15:55:59 +00005035void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5036 for (RecordDecl::field_iterator i = RD->field_begin(),
5037 e = RD->field_end(); i != e; ++i) {
5038 FieldDecl *FD = *i;
5039 if (isTopLevelBlockPointerType(FD->getType()))
5040 RewriteBlockPointerDecl(FD);
5041 if (FD->getType()->isObjCQualifiedIdType() ||
5042 FD->getType()->isObjCQualifiedInterfaceType())
5043 RewriteObjCQualifiedInterfaceTypes(FD);
5044 }
5045}
5046
Steve Narofff4b992a2008-10-28 20:29:00 +00005047/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5048/// main file of the input.
5049void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5050 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005051 if (FD->isOverloadedOperator())
5052 return;
Mike Stump11289f42009-09-09 15:08:12 +00005053
Steve Narofff4b992a2008-10-28 20:29:00 +00005054 // Since function prototypes don't have ParmDecl's, we check the function
5055 // prototype. This enables us to rewrite function declarations and
5056 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005057 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005058
Sebastian Redla7b98a72009-04-26 20:35:05 +00005059 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005060 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005061 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005062 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005063 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005064 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005065 Body =
5066 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5067 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005068 CurrentBody = 0;
5069 if (PropParentMap) {
5070 delete PropParentMap;
5071 PropParentMap = 0;
5072 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005073 // This synthesizes and inserts the block "impl" struct, invoke function,
5074 // and any copy/dispose helper functions.
5075 InsertBlockLiteralsWithinFunction(FD);
5076 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005077 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005078 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005079 return;
5080 }
5081 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005082 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005083 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005084 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005085 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005086 Body =
5087 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5088 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005089 CurrentBody = 0;
5090 if (PropParentMap) {
5091 delete PropParentMap;
5092 PropParentMap = 0;
5093 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005094 InsertBlockLiteralsWithinMethod(MD);
5095 CurMethodDef = 0;
5096 }
5097 }
5098 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5099 ClassImplementation.push_back(CI);
5100 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5101 CategoryImplementation.push_back(CI);
5102 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5103 RewriteForwardClassDecl(CD);
5104 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5105 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005106 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005107 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005108 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005109 CheckFunctionPointerDecl(VD->getType(), VD);
5110 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005111 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 RewriteCastExpr(CE);
5113 }
5114 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005115 } else if (VD->getType()->isRecordType()) {
5116 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5117 if (RD->isDefinition())
5118 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005119 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005120 if (VD->getInit()) {
5121 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005122 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005123 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005124 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005125 CurrentBody = 0;
5126 if (PropParentMap) {
5127 delete PropParentMap;
5128 PropParentMap = 0;
5129 }
Mike Stump11289f42009-09-09 15:08:12 +00005130 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005131 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005132 GlobalVarDecl = 0;
5133
5134 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005135 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005136 RewriteCastExpr(CE);
5137 }
5138 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005139 return;
5140 }
5141 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005142 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005143 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005144 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005145 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005146 else if (TD->getUnderlyingType()->isRecordType()) {
5147 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5148 if (RD->isDefinition())
5149 RewriteRecordBody(RD);
5150 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 return;
5152 }
5153 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005154 if (RD->isDefinition())
5155 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005156 return;
5157 }
5158 // Nothing yet.
5159}
5160
Chris Lattnercf169832009-03-28 04:11:33 +00005161void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005162 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005163
Steve Narofff4b992a2008-10-28 20:29:00 +00005164 // Rewrite tabs if we care.
5165 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005166
Steve Narofff4b992a2008-10-28 20:29:00 +00005167 if (Diags.hasErrorOccurred())
5168 return;
Mike Stump11289f42009-09-09 15:08:12 +00005169
Steve Narofff4b992a2008-10-28 20:29:00 +00005170 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005171
Steve Naroffd9803712009-04-29 16:37:50 +00005172 // Here's a great place to add any extra declarations that may be needed.
5173 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005174 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005175 E = ProtocolExprDecls.end(); I != E; ++I)
5176 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5177
Mike Stump11289f42009-09-09 15:08:12 +00005178 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005180 if (ClassImplementation.size() || CategoryImplementation.size())
5181 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005182
Steve Narofff4b992a2008-10-28 20:29:00 +00005183 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5184 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005185 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005186 Rewrite.getRewriteBufferFor(MainFileID)) {
5187 //printf("Changed:\n");
5188 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5189 } else {
5190 fprintf(stderr, "No changes\n");
5191 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005192
Steve Naroffd9803712009-04-29 16:37:50 +00005193 if (ClassImplementation.size() || CategoryImplementation.size() ||
5194 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005195 // Rewrite Objective-c meta data*
5196 std::string ResultStr;
5197 SynthesizeMetaDataIntoBuffer(ResultStr);
5198 // Emit metadata.
5199 *OutFile << ResultStr;
5200 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005201 OutFile->flush();
5202}
5203