blob: 980c96ad17d9cf1391a65027c2006131ed14e653 [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
Fariborz Jahanian81310812010-01-28 01:41:20 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New, int Size=0) {
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.
Fariborz Jahanian81310812010-01-28 01:41:20 +0000180 if (!Rewrite.ReplaceStmt(Old, New, Size)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000181 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";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000621 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000622 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000623 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000624 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000625 Preamble += "#define __weak\n";
626 }
Chris Lattner187f6262008-01-31 19:38:44 +0000627}
628
629
Chris Lattner3c799d72007-10-24 17:06:59 +0000630//===----------------------------------------------------------------------===//
631// Top Level Driver Code
632//===----------------------------------------------------------------------===//
633
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000634void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000635 // Two cases: either the decl could be in the main file, or it could be in a
636 // #included file. If the former, rewrite it now. If the later, check to see
637 // if we rewrote the #include/#import.
638 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000639 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000640
Chris Lattner0bd1c972007-10-16 21:07:07 +0000641 // If this is for a builtin, ignore it.
642 if (Loc.isInvalid()) return;
643
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000644 // Look for built-in declarations that we need to refer during the rewrite.
645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000646 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000647 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000648 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000649 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000650 ConstantStringClassReference = FVD;
651 return;
652 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000653 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000654 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000655 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000656 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000657 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000658 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000659 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000660 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000661 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000662 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
663 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000664 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
665 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000666 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000667 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000668 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000669 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000670 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000671 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000672}
673
Chris Lattner3c799d72007-10-24 17:06:59 +0000674//===----------------------------------------------------------------------===//
675// Syntactic (non-AST) Rewriting Code
676//===----------------------------------------------------------------------===//
677
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000678void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000679 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000680 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
681 const char *MainBufStart = MainBuf.first;
682 const char *MainBufEnd = MainBuf.second;
683 size_t ImportLen = strlen("import");
684 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000685
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000686 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000687 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
688 if (*BufPtr == '#') {
689 if (++BufPtr == MainBufEnd)
690 return;
691 while (*BufPtr == ' ' || *BufPtr == '\t')
692 if (++BufPtr == MainBufEnd)
693 return;
694 if (!strncmp(BufPtr, "import", ImportLen)) {
695 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000696 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000697 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000698 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000699 BufPtr += ImportLen;
700 }
701 }
702 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000703}
704
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000705void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000706 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
707 const char *MainBufStart = MainBuf.first;
708 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000709
Chris Lattner3c799d72007-10-24 17:06:59 +0000710 // Loop over the whole file, looking for tabs.
711 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
712 if (*BufPtr != '\t')
713 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // Okay, we found a tab. This tab will turn into at least one character,
716 // but it depends on which 'virtual column' it is in. Compute that now.
717 unsigned VCol = 0;
718 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
719 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
720 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000721
Chris Lattner3c799d72007-10-24 17:06:59 +0000722 // Okay, now that we know the virtual column, we know how many spaces to
723 // insert. We assume 8-character tab-stops.
724 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattner3c799d72007-10-24 17:06:59 +0000726 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000727 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
728 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattner3c799d72007-10-24 17:06:59 +0000730 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000731 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000732 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000733}
734
Steve Naroff9af94912008-12-02 15:48:25 +0000735static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
736 ObjCIvarDecl *OID) {
737 std::string S;
738 S = "((struct ";
739 S += ClassDecl->getIdentifier()->getName();
740 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000741 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000742 return S;
743}
744
Steve Naroffc038b3a2008-12-02 17:36:43 +0000745void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
746 ObjCImplementationDecl *IMD,
747 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000748 SourceLocation startLoc = PID->getLocStart();
749 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000750 const char *startBuf = SM->getCharacterData(startLoc);
751 assert((*startBuf == '@') && "bogus @synthesize location");
752 const char *semiBuf = strchr(startBuf, ';');
753 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000754 SourceLocation onePastSemiLoc =
755 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000756
757 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
758 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000759
Steve Naroff9af94912008-12-02 15:48:25 +0000760 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000761 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000762 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000763 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000764
Steve Naroff003d00e2008-12-02 16:05:55 +0000765 if (!OID)
766 return;
Mike Stump11289f42009-09-09 15:08:12 +0000767
Steve Naroff003d00e2008-12-02 16:05:55 +0000768 std::string Getr;
769 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
770 Getr += "{ ";
771 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000772 // FIXME: deal with code generation implications for various property
773 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000774 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000775 Getr += "return " + getIvarAccessString(ClassDecl, OID);
776 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000778 if (PD->isReadOnly())
779 return;
Mike Stump11289f42009-09-09 15:08:12 +0000780
Steve Naroff9af94912008-12-02 15:48:25 +0000781 // Generate the 'setter' function.
782 std::string Setr;
783 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000784 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000785 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000786 // FIXME: deal with code generation implications for various property
787 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000788 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000789 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000790 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000791 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000792 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000793}
Chris Lattner16a0de42007-10-11 18:38:32 +0000794
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000795void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000796 // Get the start location and compute the semi location.
797 SourceLocation startLoc = ClassDecl->getLocation();
798 const char *startBuf = SM->getCharacterData(startLoc);
799 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000800
Chris Lattner3c799d72007-10-24 17:06:59 +0000801 // Translate to typedef's that forward reference structs with the same name
802 // as the class. As a convenience, we include the original declaration
803 // as a comment.
804 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000805 typedefString += "// @class ";
806 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
807 I != E; ++I) {
808 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
809 typedefString += ForwardDecl->getNameAsString();
810 if (I+1 != E)
811 typedefString += ", ";
812 else
813 typedefString += ";\n";
814 }
815
Chris Lattner9ee23b72009-02-20 18:04:31 +0000816 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
817 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000818 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000819 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000820 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000821 typedefString += "\n";
822 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000823 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000824 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000825 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000826 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000827 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Steve Naroff574440f2007-10-24 22:48:43 +0000830 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000831 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000832 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000833}
834
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000835void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000836 // When method is a synthesized one, such as a getter/setter there is
837 // nothing to rewrite.
838 if (Method->isSynthesized())
839 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000840 SourceLocation LocStart = Method->getLocStart();
841 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chris Lattner88ea93e2009-02-04 01:06:56 +0000843 if (SM->getInstantiationLineNumber(LocEnd) >
844 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000845 InsertText(LocStart, "#if 0\n", 6);
846 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000847 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000848 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000849 }
850}
851
Mike Stump11289f42009-09-09 15:08:12 +0000852void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000853 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000854
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000855 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000856 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000857}
858
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000859void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000860 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000861
Steve Naroff5448cf62007-10-30 13:30:57 +0000862 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000863 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000864
865 for (ObjCCategoryDecl::instmeth_iterator
866 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000867 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000868 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000869 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000870 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000871 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000872 RewriteMethodDeclaration(*I);
873
Steve Naroff5448cf62007-10-30 13:30:57 +0000874 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000875 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000876}
877
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000878void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000879 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000880
Steve Narofff921385f2007-10-30 16:42:30 +0000881 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Steve Narofff921385f2007-10-30 16:42:30 +0000883 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000884 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000885
886 for (ObjCProtocolDecl::instmeth_iterator
887 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000888 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000889 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000890 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000891 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000892 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000893 RewriteMethodDeclaration(*I);
894
Steve Narofff921385f2007-10-30 16:42:30 +0000895 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000896 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000897 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000898
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000899 // Must comment out @optional/@required
900 const char *startBuf = SM->getCharacterData(LocStart);
901 const char *endBuf = SM->getCharacterData(LocEnd);
902 for (const char *p = startBuf; p < endBuf; p++) {
903 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
904 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000905 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000906 ReplaceText(OptionalLoc, strlen("@optional"),
907 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000908
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000909 }
910 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
911 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000912 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000913 ReplaceText(OptionalLoc, strlen("@required"),
914 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000915
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000916 }
917 }
Steve Narofff921385f2007-10-30 16:42:30 +0000918}
919
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000920void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000921 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000922 if (LocStart.isInvalid())
923 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000924 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000925 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000926}
927
Mike Stump11289f42009-09-09 15:08:12 +0000928void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000929 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000930 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000931 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000932 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000933 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000934 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000935 else if (OMD->getResultType()->isFunctionPointerType() ||
936 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000937 // needs special handling, since pointer-to-functions have special
938 // syntax (where a decaration models use).
939 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000940 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000941 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000942 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000943 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000944 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000945 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000946 ResultStr += FPRetType->getResultType().getAsString();
947 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000948 }
949 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000950 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000951 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000952
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000953 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000954 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Douglas Gregorffca3a22009-01-09 17:18:27 +0000956 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000957 NameStr += "_I_";
958 else
959 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000961 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000962 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000963
964 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000965 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000966 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000967 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000968 }
Mike Stump11289f42009-09-09 15:08:12 +0000969 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000970 {
971 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000972 int len = selString.size();
973 for (int i = 0; i < len; i++)
974 if (selString[i] == ':')
975 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000976 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000977 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000978 // Remember this name for metadata emission
979 MethodInternalNames[OMD] = NameStr;
980 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 // Rewrite arguments
983 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000984
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000985 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000986 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000987 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000988 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000989 if (!LangOpts.Microsoft) {
990 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
991 ResultStr += "struct ";
992 }
993 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000994 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000995 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000996 }
997 else
Steve Naroffd9803712009-04-29 16:37:50 +0000998 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000999
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001000 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001001 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001002 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001003
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001005 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1006 E = OMD->param_end(); PI != E; ++PI) {
1007 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001009 if (PDecl->getType()->isObjCQualifiedIdType()) {
1010 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001011 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001012 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001013 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001014 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001015 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001016 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001017 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1018 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001019 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001020 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001021 ResultStr += Name;
1022 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001023 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001024 if (OMD->isVariadic())
1025 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001026 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001027
Steve Naroffb067bbd2008-07-16 14:40:40 +00001028 if (FPRetType) {
1029 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001030
Steve Naroffb067bbd2008-07-16 14:40:40 +00001031 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001032 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001033 ResultStr += "(";
1034 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1035 if (i) ResultStr += ", ";
1036 std::string ParamStr = FT->getArgType(i).getAsString();
1037 ResultStr += ParamStr;
1038 }
1039 if (FT->isVariadic()) {
1040 if (FT->getNumArgs()) ResultStr += ", ";
1041 ResultStr += "...";
1042 }
1043 ResultStr += ")";
1044 } else {
1045 ResultStr += "()";
1046 }
1047 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001048}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001049void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001050 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1051 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001053 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001054 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001055 else
Chris Lattner1780a852008-01-31 19:42:41 +00001056 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001058 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001059 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1060 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001061 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001062 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001063 ObjCMethodDecl *OMD = *I;
1064 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001065 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001066 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001067
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001068 const char *startBuf = SM->getCharacterData(LocStart);
1069 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001070 ReplaceText(LocStart, endBuf-startBuf,
1071 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001074 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001075 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1076 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001077 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001079 ObjCMethodDecl *OMD = *I;
1080 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001082 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 const char *startBuf = SM->getCharacterData(LocStart);
1085 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001086 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001087 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001089 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001090 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001091 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001092 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001093 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001094 }
1095
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001096 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001097 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001098 else
Mike Stump11289f42009-09-09 15:08:12 +00001099 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100}
1101
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001102void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001103 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001104 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001105 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001106 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001107 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001108 ResultStr += "\n";
1109 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001110 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001111 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001112 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001113 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001114 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001115 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001116 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001117 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001118 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001119
1120 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001121 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001122 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001124 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001127 for (ObjCInterfaceDecl::classmeth_iterator
1128 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001129 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001130 RewriteMethodDeclaration(*I);
1131
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001132 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001133 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001134}
1135
Steve Naroff08628db2008-12-09 12:56:34 +00001136Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1137 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001138 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1139 // This allows us to reuse all the fun and games in SynthMessageExpr().
1140 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1141 ObjCMessageExpr *MsgExpr;
1142 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1143 llvm::SmallVector<Expr *, 1> ExprVec;
1144 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Steve Naroff1042ff32008-12-08 16:43:47 +00001146 Stmt *Receiver = PropRefExpr->getBase();
1147 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1148 if (PRE && PropGetters[PRE]) {
1149 // This allows us to handle chain/nested property getters.
1150 Receiver = PropGetters[PRE];
1151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1153 PDecl->getSetterName(), PDecl->getType(),
1154 PDecl->getSetterMethodDecl(),
1155 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001156 &ExprVec[0], 1);
1157 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001158
Steve Naroff4588d0f2008-12-04 16:24:46 +00001159 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001160 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001161 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001162 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1163 // to things that stay around.
1164 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001165 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001166}
1167
Steve Naroff4588d0f2008-12-04 16:24:46 +00001168Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001169 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1170 // This allows us to reuse all the fun and games in SynthMessageExpr().
1171 ObjCMessageExpr *MsgExpr;
1172 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001173
Steve Naroff1042ff32008-12-08 16:43:47 +00001174 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001175
Steve Naroff1042ff32008-12-08 16:43:47 +00001176 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1177 if (PRE && PropGetters[PRE]) {
1178 // This allows us to handle chain/nested property getters.
1179 Receiver = PropGetters[PRE];
1180 }
Mike Stump11289f42009-09-09 15:08:12 +00001181 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1182 PDecl->getGetterName(), PDecl->getType(),
1183 PDecl->getGetterMethodDecl(),
1184 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001185 0, 0);
1186
Steve Naroff22216db2008-12-04 23:50:32 +00001187 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001188
1189 if (!PropParentMap)
1190 PropParentMap = new ParentMap(CurrentBody);
1191
1192 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1193 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1194 // We stash away the ReplacingStmt since actually doing the
1195 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1196 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001197 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1198 // to things that stay around.
1199 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001200 return PropRefExpr; // return the original...
1201 } else {
1202 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001203 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001204 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1205 // to things that stay around.
1206 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001207 return ReplacingStmt;
1208 }
Steve Narofff326f402008-12-03 00:56:33 +00001209}
1210
Mike Stump11289f42009-09-09 15:08:12 +00001211Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001212 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001213 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001214 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001215 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001216 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001217 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001218 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001219 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001220 // lookup which class implements the instance variable.
1221 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001222 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001223 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001224 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001225
Steve Naroffb1c02372008-05-08 17:52:16 +00001226 // Synthesize an explicit cast to gain access to the ivar.
1227 std::string RecName = clsDeclared->getIdentifier()->getName();
1228 RecName += "_IMPL";
1229 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001230 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001231 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001232 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1233 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001234 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1235 CastExpr::CK_Unknown,
1236 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001237 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001238 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1239 IV->getBase()->getLocEnd(),
1240 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001241 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001242 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001243 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1244 IV->getLocation(),
1245 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001246 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001247 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001248 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001249 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001250 // Get the old text, only to get its size.
1251 std::string SStr;
1252 llvm::raw_string_ostream S(SStr);
1253 IV->getBase()->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
1254 // Get the new text
1255 ReplaceStmt(IV->getBase(), PE, S.str().size());
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001256 // Cannot delete IV->getBase(), since PE points to it.
1257 // Replace the old base with the cast. This is important when doing
1258 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001259 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001260 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001261 }
Steve Naroff24840f62008-04-18 21:55:08 +00001262 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001263 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001264
Steve Naroff29ce4e52008-05-06 23:20:07 +00001265 // Explicit ivar refs need to have a cast inserted.
1266 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001267 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001268 ObjCInterfaceType *iFaceDecl =
1269 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001270 // lookup which class implements the instance variable.
1271 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001272 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001273 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001274 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001275
Steve Naroff29ce4e52008-05-06 23:20:07 +00001276 // Synthesize an explicit cast to gain access to the ivar.
1277 std::string RecName = clsDeclared->getIdentifier()->getName();
1278 RecName += "_IMPL";
1279 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001280 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001281 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001282 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1283 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001284 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1285 CastExpr::CK_Unknown,
1286 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001288 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001289 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001290 ReplaceStmt(IV->getBase(), PE);
1291 // Cannot delete IV->getBase(), since PE points to it.
1292 // Replace the old base with the cast. This is important when doing
1293 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001294 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001295 return IV;
1296 }
Steve Naroff05caa482007-11-15 11:33:00 +00001297 }
Steve Naroff24840f62008-04-18 21:55:08 +00001298 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001299}
1300
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001301/// SynthCountByEnumWithState - To print:
1302/// ((unsigned int (*)
1303/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001304/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001305/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001306/// "countByEnumeratingWithState:objects:count:"),
1307/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001308/// (id *)items, (unsigned int)16)
1309///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001310void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001311 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1312 "id *, unsigned int))(void *)objc_msgSend)";
1313 buf += "\n\t\t";
1314 buf += "((id)l_collection,\n\t\t";
1315 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1316 buf += "\n\t\t";
1317 buf += "&enumState, "
1318 "(id *)items, (unsigned int)16)";
1319}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001320
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001321/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1322/// statement to exit to its outer synthesized loop.
1323///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001324Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001325 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1326 return S;
1327 // replace break with goto __break_label
1328 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001330 SourceLocation startLoc = S->getLocStart();
1331 buf = "goto __break_label_";
1332 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001333 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001334
1335 return 0;
1336}
1337
1338/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1339/// statement to continue with its inner synthesized loop.
1340///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001341Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001342 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1343 return S;
1344 // replace continue with goto __continue_label
1345 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001347 SourceLocation startLoc = S->getLocStart();
1348 buf = "goto __continue_label_";
1349 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001350 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001351
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001352 return 0;
1353}
1354
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001355/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001356/// It rewrites:
1357/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001359/// Into:
1360/// {
Mike Stump11289f42009-09-09 15:08:12 +00001361/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001362/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001363/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001364/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001365/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001366/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001367/// if (limit) {
1368/// unsigned long startMutations = *enumState.mutationsPtr;
1369/// do {
1370/// unsigned long counter = 0;
1371/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001372/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001373/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001374/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001375/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001376/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001377/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001378/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001379/// objects:items count:16]);
1380/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001381/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001382/// }
1383/// else
1384/// elem = nil;
1385/// }
1386///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001387Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001388 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001389 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001390 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001391 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001392 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001393 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001394
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001397 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001398 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001399 std::string buf;
1400 buf = "\n{\n\t";
1401 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1402 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001403 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001404 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001405 if (ElementType->isObjCQualifiedIdType() ||
1406 ElementType->isObjCQualifiedInterfaceType())
1407 // Simply use 'id' for all qualified types.
1408 elementTypeAsString = "id";
1409 else
1410 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001411 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001412 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001413 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001414 buf += elementName;
1415 buf += ";\n\t";
1416 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001417 else {
1418 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001419 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001420 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1421 if (VD->getType()->isObjCQualifiedIdType() ||
1422 VD->getType()->isObjCQualifiedInterfaceType())
1423 // Simply use 'id' for all qualified types.
1424 elementTypeAsString = "id";
1425 else
1426 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001427 }
Mike Stump11289f42009-09-09 15:08:12 +00001428
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001429 // struct __objcFastEnumerationState enumState = { 0 };
1430 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1431 // id items[16];
1432 buf += "id items[16];\n\t";
1433 // id l_collection = (id)
1434 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001435 // Find start location of 'collection' the hard way!
1436 const char *startCollectionBuf = startBuf;
1437 startCollectionBuf += 3; // skip 'for'
1438 startCollectionBuf = strchr(startCollectionBuf, '(');
1439 startCollectionBuf++; // skip '('
1440 // find 'in' and skip it.
1441 while (*startCollectionBuf != ' ' ||
1442 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1443 (*(startCollectionBuf+3) != ' ' &&
1444 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1445 startCollectionBuf++;
1446 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001447
1448 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001449 ReplaceText(startLoc, startCollectionBuf - startBuf,
1450 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001451 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001452 SourceLocation rightParenLoc = S->getRParenLoc();
1453 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1454 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001455 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001456
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001457 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1458 // objects:items count:16];
1459 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001460 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001461 // ((unsigned int (*)
1462 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001463 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001465 // "countByEnumeratingWithState:objects:count:"),
1466 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001467 // (id *)items, (unsigned int)16);
1468 buf += "unsigned long limit =\n\t\t";
1469 SynthCountByEnumWithState(buf);
1470 buf += ";\n\t";
1471 /// if (limit) {
1472 /// unsigned long startMutations = *enumState.mutationsPtr;
1473 /// do {
1474 /// unsigned long counter = 0;
1475 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001476 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001477 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001478 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 buf += "if (limit) {\n\t";
1480 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1481 buf += "do {\n\t\t";
1482 buf += "unsigned long counter = 0;\n\t\t";
1483 buf += "do {\n\t\t\t";
1484 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1485 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1486 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001487 buf += " = (";
1488 buf += elementTypeAsString;
1489 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001491 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001492
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001493 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001495 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 /// objects:items count:16]);
1497 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001498 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001499 /// }
1500 /// else
1501 /// elem = nil;
1502 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001503 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001504 buf = ";\n\t";
1505 buf += "__continue_label_";
1506 buf += utostr(ObjCBcLabelNo.back());
1507 buf += ": ;";
1508 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 buf += "} while (counter < limit);\n\t";
1510 buf += "} while (limit = ";
1511 SynthCountByEnumWithState(buf);
1512 buf += ");\n\t";
1513 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001514 buf += " = ((";
1515 buf += elementTypeAsString;
1516 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001517 buf += "__break_label_";
1518 buf += utostr(ObjCBcLabelNo.back());
1519 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001520 buf += "}\n\t";
1521 buf += "else\n\t\t";
1522 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001523 buf += " = ((";
1524 buf += elementTypeAsString;
1525 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001527
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001528 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001529 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001530 if (isa<CompoundStmt>(S->getBody())) {
1531 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1532 InsertText(endBodyLoc, buf.c_str(), buf.size());
1533 } else {
1534 /* Need to treat single statements specially. For example:
1535 *
1536 * for (A *a in b) if (stuff()) break;
1537 * for (A *a in b) xxxyy;
1538 *
1539 * The following code simply scans ahead to the semi to find the actual end.
1540 */
1541 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1542 const char *semiBuf = strchr(stmtBuf, ';');
1543 assert(semiBuf && "Can't find ';'");
1544 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1545 InsertText(endBodyLoc, buf.c_str(), buf.size());
1546 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001547 Stmts.pop_back();
1548 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001549 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001550}
1551
Mike Stump11289f42009-09-09 15:08:12 +00001552/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001553/// This routine rewrites @synchronized(expr) stmt;
1554/// into:
1555/// objc_sync_enter(expr);
1556/// @try stmt @finally { objc_sync_exit(expr); }
1557///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001558Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559 // Get the start location and compute the semi location.
1560 SourceLocation startLoc = S->getLocStart();
1561 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001563 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001564
1565 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001566 buf = "objc_sync_enter((id)";
1567 const char *lparenBuf = startBuf;
1568 while (*lparenBuf != '(') lparenBuf++;
1569 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001570 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1571 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001572 // been rewritten! (which implies the SourceLocation's are invalid).
1573 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001574 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001575 while (*endBuf != ')') endBuf--;
1576 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001577 buf = ");\n";
1578 // declare a new scope with two variables, _stack and _rethrow.
1579 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1580 buf += "int buf[18/*32-bit i386*/];\n";
1581 buf += "char *pointers[4];} _stack;\n";
1582 buf += "id volatile _rethrow = 0;\n";
1583 buf += "objc_exception_try_enter(&_stack);\n";
1584 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001585 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001586 startLoc = S->getSynchBody()->getLocEnd();
1587 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001588
Steve Naroffad7013b2008-08-19 13:04:19 +00001589 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001590 SourceLocation lastCurlyLoc = startLoc;
1591 buf = "}\nelse {\n";
1592 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001593 buf += "}\n";
1594 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001595 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001596
1597 std::string syncBuf;
1598 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001599 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1600 CastExpr::CK_Unknown,
1601 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001602 std::string syncExprBufS;
1603 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001604 syncExpr->printPretty(syncExprBuf, *Context, 0,
1605 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001606 syncBuf += syncExprBuf.str();
1607 syncBuf += ");";
1608
1609 buf += syncBuf;
1610 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001611 buf += "}\n";
1612 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001613
Chris Lattner9cc55f52008-01-31 19:51:04 +00001614 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001615
1616 bool hasReturns = false;
1617 HasReturnStmts(S->getSynchBody(), hasReturns);
1618 if (hasReturns)
1619 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1620
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001621 return 0;
1622}
1623
Steve Naroffec60b432009-12-05 21:43:12 +00001624void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1625{
Steve Naroff6d6da252008-12-05 17:03:39 +00001626 // Perform a bottom up traversal of all children.
1627 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1628 CI != E; ++CI)
1629 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001630 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001631
Steve Naroffec60b432009-12-05 21:43:12 +00001632 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001633 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001634 TryFinallyContainsReturnDiag);
1635 }
1636 return;
1637}
1638
Steve Naroffec60b432009-12-05 21:43:12 +00001639void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1640{
1641 // Perform a bottom up traversal of all children.
1642 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1643 CI != E; ++CI)
1644 if (*CI)
1645 HasReturnStmts(*CI, hasReturns);
1646
1647 if (isa<ReturnStmt>(S))
1648 hasReturns = true;
1649 return;
1650}
1651
1652void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1653 // Perform a bottom up traversal of all children.
1654 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1655 CI != E; ++CI)
1656 if (*CI) {
1657 RewriteTryReturnStmts(*CI);
1658 }
1659 if (isa<ReturnStmt>(S)) {
1660 SourceLocation startLoc = S->getLocStart();
1661 const char *startBuf = SM->getCharacterData(startLoc);
1662
1663 const char *semiBuf = strchr(startBuf, ';');
1664 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1665 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1666
1667 std::string buf;
1668 buf = "{ objc_exception_try_exit(&_stack); return";
1669
1670 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1671 InsertText(onePastSemiLoc, "}", 1);
1672 }
1673 return;
1674}
1675
1676void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1677 // Perform a bottom up traversal of all children.
1678 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1679 CI != E; ++CI)
1680 if (*CI) {
1681 RewriteSyncReturnStmts(*CI, syncExitBuf);
1682 }
1683 if (isa<ReturnStmt>(S)) {
1684 SourceLocation startLoc = S->getLocStart();
1685 const char *startBuf = SM->getCharacterData(startLoc);
1686
1687 const char *semiBuf = strchr(startBuf, ';');
1688 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1689 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1690
1691 std::string buf;
1692 buf = "{ objc_exception_try_exit(&_stack);";
1693 buf += syncExitBuf;
1694 buf += " return";
1695
1696 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1697 InsertText(onePastSemiLoc, "}", 1);
1698 }
1699 return;
1700}
1701
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001702Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001703 // Get the start location and compute the semi location.
1704 SourceLocation startLoc = S->getLocStart();
1705 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001706
Steve Naroffbf478ec2007-11-07 04:08:17 +00001707 assert((*startBuf == '@') && "bogus @try location");
1708
1709 std::string buf;
1710 // declare a new scope with two variables, _stack and _rethrow.
1711 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1712 buf += "int buf[18/*32-bit i386*/];\n";
1713 buf += "char *pointers[4];} _stack;\n";
1714 buf += "id volatile _rethrow = 0;\n";
1715 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001716 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001717
Chris Lattner9cc55f52008-01-31 19:51:04 +00001718 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001719
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 startLoc = S->getTryBody()->getLocEnd();
1721 startBuf = SM->getCharacterData(startLoc);
1722
1723 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001724
Steve Naroffbf478ec2007-11-07 04:08:17 +00001725 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001726 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1727 if (catchList) {
1728 startLoc = startLoc.getFileLocWithOffset(1);
1729 buf = " /* @catch begin */ else {\n";
1730 buf += " id _caught = objc_exception_extract(&_stack);\n";
1731 buf += " objc_exception_try_enter (&_stack);\n";
1732 buf += " if (_setjmp(_stack.buf))\n";
1733 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1734 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001735
Steve Naroffce2dca12008-07-16 15:31:30 +00001736 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001737 } else { /* no catch list */
1738 buf = "}\nelse {\n";
1739 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1740 buf += "}";
1741 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001742 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001743 bool sawIdTypedCatch = false;
1744 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001745 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001746 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001747
Mike Stump11289f42009-09-09 15:08:12 +00001748 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001749 buf = "if ("; // we are generating code for the first catch clause
1750 else
1751 buf = "else if (";
1752 startLoc = catchList->getLocStart();
1753 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001754
Steve Naroffbf478ec2007-11-07 04:08:17 +00001755 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001756
Steve Naroffbf478ec2007-11-07 04:08:17 +00001757 const char *lParenLoc = strchr(startBuf, '(');
1758
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001759 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001760 // Now rewrite the body...
1761 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001762 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1763 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001764 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1765 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001766 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001767
Steve Naroffedb5bc62008-02-01 20:02:07 +00001768 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001769 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001770 } else if (catchDecl) {
1771 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001772 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001773 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001774 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001776 } else if (t->isObjCObjectPointerType()) {
1777 QualType InterfaceTy = t->getPointeeType();
1778 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1779 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001780 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001781 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001782 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001783 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001784 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001785 }
1786 }
1787 // Now rewrite the body...
1788 lastCatchBody = catchList->getCatchBody();
1789 SourceLocation rParenLoc = catchList->getRParenLoc();
1790 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1791 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1792 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1793 assert((*rParenBuf == ')') && "bogus @catch paren location");
1794 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001795
Steve Naroffbf478ec2007-11-07 04:08:17 +00001796 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001797 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001799 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001800 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001801 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001802 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001803 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001804 catchList = catchList->getNextCatchStmt();
1805 }
1806 // Complete the catch list...
1807 if (lastCatchBody) {
1808 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001809 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1810 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001811
Steve Naroff4adbe312008-09-11 15:29:03 +00001812 // Insert the last (implicit) else clause *before* the right curly brace.
1813 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1814 buf = "} /* last catch end */\n";
1815 buf += "else {\n";
1816 buf += " _rethrow = _caught;\n";
1817 buf += " objc_exception_try_exit(&_stack);\n";
1818 buf += "} } /* @catch end */\n";
1819 if (!S->getFinallyStmt())
1820 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001821 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001822
Steve Naroffbf478ec2007-11-07 04:08:17 +00001823 // Set lastCurlyLoc
1824 lastCurlyLoc = lastCatchBody->getLocEnd();
1825 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001826 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001827 startLoc = finalStmt->getLocStart();
1828 startBuf = SM->getCharacterData(startLoc);
1829 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001830
Steve Naroffbf478ec2007-11-07 04:08:17 +00001831 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001832 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001833
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834 Stmt *body = finalStmt->getFinallyBody();
1835 SourceLocation startLoc = body->getLocStart();
1836 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001837 assert(*SM->getCharacterData(startLoc) == '{' &&
1838 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001839 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001840 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001841
Steve Naroffbf478ec2007-11-07 04:08:17 +00001842 startLoc = startLoc.getFileLocWithOffset(1);
1843 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001844 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 endLoc = endLoc.getFileLocWithOffset(-1);
1846 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001847 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001848
Steve Naroffbf478ec2007-11-07 04:08:17 +00001849 // Set lastCurlyLoc
1850 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001851
Steve Naroff6d6da252008-12-05 17:03:39 +00001852 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001853 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001854 } else { /* no finally clause - make sure we synthesize an implicit one */
1855 buf = "{ /* implicit finally clause */\n";
1856 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1857 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1858 buf += "}";
1859 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001860
1861 // Now check for any return/continue/go statements within the @try.
1862 // The implicit finally clause won't called if the @try contains any
1863 // jump statements.
1864 bool hasReturns = false;
1865 HasReturnStmts(S->getTryBody(), hasReturns);
1866 if (hasReturns)
1867 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001868 }
1869 // Now emit the final closing curly brace...
1870 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1871 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001872 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001873 return 0;
1874}
1875
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001876Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001877 return 0;
1878}
1879
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001880Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001881 return 0;
1882}
1883
Mike Stump11289f42009-09-09 15:08:12 +00001884// This can't be done with ReplaceStmt(S, ThrowExpr), since
1885// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001886// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001887Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001888 // Get the start location and compute the semi location.
1889 SourceLocation startLoc = S->getLocStart();
1890 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001891
Steve Naroffa733c7f2007-11-07 15:32:26 +00001892 assert((*startBuf == '@') && "bogus @throw location");
1893
1894 std::string buf;
1895 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001896 if (S->getThrowExpr())
1897 buf = "objc_exception_throw(";
1898 else // add an implicit argument
1899 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001900
Steve Naroff29788342008-07-25 15:41:30 +00001901 // handle "@ throw" correctly.
1902 const char *wBuf = strchr(startBuf, 'w');
1903 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1904 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001905
Steve Naroffa733c7f2007-11-07 15:32:26 +00001906 const char *semiBuf = strchr(startBuf, ';');
1907 assert((*semiBuf == ';') && "@throw: can't find ';'");
1908 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1909 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001910 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001911 return 0;
1912}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001913
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001915 // Create a new string expression.
1916 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001917 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001918 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001919 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1920 StrEncoding.length(), false,StrType,
1921 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001922 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattner4431a1b2007-11-30 22:53:43 +00001924 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001925 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001926 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001927}
1928
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001929Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001930 if (!SelGetUidFunctionDecl)
1931 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001932 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1933 // Create a call to sel_registerName("selName").
1934 llvm::SmallVector<Expr*, 8> SelExprs;
1935 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001936 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001937 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001938 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001939 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001940 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1941 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001942 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001943 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001944 return SelExp;
1945}
1946
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001947CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001948 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001949 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001950 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001952 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001953 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001954
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001955 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001956 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001957 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001958 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001959 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001960 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCall9dd450b2009-09-21 23:43:11 +00001962 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001963
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001964 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1965 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001966}
1967
Steve Naroff50d42052007-11-01 13:24:47 +00001968static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1969 const char *&startRef, const char *&endRef) {
1970 while (startBuf < endBuf) {
1971 if (*startBuf == '<')
1972 startRef = startBuf; // mark the start.
1973 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001974 if (startRef && *startRef == '<') {
1975 endRef = startBuf; // mark the end.
1976 return true;
1977 }
1978 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001979 }
1980 startBuf++;
1981 }
1982 return false;
1983}
1984
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001985static void scanToNextArgument(const char *&argRef) {
1986 int angle = 0;
1987 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1988 if (*argRef == '<')
1989 angle++;
1990 else if (*argRef == '>')
1991 angle--;
1992 argRef++;
1993 }
1994 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1995}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001996
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001997bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian06769f92010-02-02 18:35:07 +00001998 if (const PointerType *PT = T->getAs<PointerType>()) {
1999 if (PT->getPointeeType()->isObjCQualifiedIdType())
2000 return true;
2001 }
2002 if (T->isObjCObjectPointerType()) {
2003 T = T->getPointeeType();
2004 return T->isObjCQualifiedInterfaceType();
2005 }
2006 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002007}
2008
Steve Naroff873bd842008-07-29 18:15:38 +00002009void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2010 QualType Type = E->getType();
2011 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002012 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Steve Naroffdbfc6932008-11-19 21:15:47 +00002014 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2015 Loc = ECE->getLParenLoc();
2016 EndLoc = ECE->getRParenLoc();
2017 } else {
2018 Loc = E->getLocStart();
2019 EndLoc = E->getLocEnd();
2020 }
2021 // This will defend against trying to rewrite synthesized expressions.
2022 if (Loc.isInvalid() || EndLoc.isInvalid())
2023 return;
2024
Steve Naroff873bd842008-07-29 18:15:38 +00002025 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002026 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002027 const char *startRef = 0, *endRef = 0;
2028 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2029 // Get the locations of the startRef, endRef.
2030 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2031 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2032 // Comment out the protocol references.
2033 InsertText(LessLoc, "/*", 2);
2034 InsertText(GreaterLoc, "*/", 2);
2035 }
2036 }
2037}
2038
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002039void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002040 SourceLocation Loc;
2041 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002042 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002043 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2044 Loc = VD->getLocation();
2045 Type = VD->getType();
2046 }
2047 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2048 Loc = FD->getLocation();
2049 // Check for ObjC 'id' and class types that have been adorned with protocol
2050 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002051 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002052 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002053 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002054 if (!proto)
2055 return;
2056 Type = proto->getResultType();
2057 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002058 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2059 Loc = FD->getLocation();
2060 Type = FD->getType();
2061 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002062 else
2063 return;
Mike Stump11289f42009-09-09 15:08:12 +00002064
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002065 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002066 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002067
Steve Naroff50d42052007-11-01 13:24:47 +00002068 const char *endBuf = SM->getCharacterData(Loc);
2069 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002070 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002071 startBuf--; // scan backward (from the decl location) for return type.
2072 const char *startRef = 0, *endRef = 0;
2073 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2074 // Get the locations of the startRef, endRef.
2075 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2076 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2077 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002078 InsertText(LessLoc, "/*", 2);
2079 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002080 }
2081 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002082 if (!proto)
2083 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002084 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002085 const char *startBuf = SM->getCharacterData(Loc);
2086 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002087 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2088 if (needToScanForQualifiers(proto->getArgType(i))) {
2089 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002090
Steve Naroff50d42052007-11-01 13:24:47 +00002091 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002092 // scan forward (from the decl location) for argument types.
2093 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002094 const char *startRef = 0, *endRef = 0;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002097 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002098 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002099 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002100 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002101 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002102 InsertText(LessLoc, "/*", 2);
2103 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002104 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002105 startBuf = ++endBuf;
2106 }
2107 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002108 // If the function name is derived from a macro expansion, then the
2109 // argument buffer will not follow the name. Need to speak with Chris.
2110 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002111 startBuf++; // scan forward (from the decl location) for argument types.
2112 startBuf++;
2113 }
Steve Naroff50d42052007-11-01 13:24:47 +00002114 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002115}
2116
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002117// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002118void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002119 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2120 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002121 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002122 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002123 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002124 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002125 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002126 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002127 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002128 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002129}
2130
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002131void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002132 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002133 if (FD->getIdentifier() &&
2134 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002135 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002136 return;
2137 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002138 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002139}
2140
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002141void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2142 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2143 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2144 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2145 if (!proto)
2146 return;
2147 QualType Type = proto->getResultType();
2148 std::string FdStr = Type.getAsString();
2149 FdStr += " ";
2150 FdStr += FD->getNameAsCString();
2151 FdStr += "(";
2152 unsigned numArgs = proto->getNumArgs();
2153 for (unsigned i = 0; i < numArgs; i++) {
2154 QualType ArgType = proto->getArgType(i);
2155 FdStr += ArgType.getAsString();
2156
2157 if (i+1 < numArgs)
2158 FdStr += ", ";
2159 }
2160 FdStr += ");\n";
2161 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2162 CurFunctionDeclToDeclareForBlock = 0;
2163}
2164
Steve Naroff17978c42008-03-11 17:37:02 +00002165// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002166void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002167 if (SuperContructorFunctionDecl)
2168 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002169 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002170 llvm::SmallVector<QualType, 16> ArgTys;
2171 QualType argT = Context->getObjCIdType();
2172 assert(!argT.isNull() && "Can't find 'id' type");
2173 ArgTys.push_back(argT);
2174 ArgTys.push_back(argT);
2175 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2176 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002177 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002178 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002179 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002180 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002181 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002182}
2183
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002184// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002185void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002186 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2187 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002188 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002189 assert(!argT.isNull() && "Can't find 'id' type");
2190 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002191 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002192 assert(!argT.isNull() && "Can't find 'SEL' type");
2193 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002194 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002195 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002196 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002197 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002198 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002199 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002200 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002201}
2202
Steve Naroff7fa2f042007-11-15 10:28:18 +00002203// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002204void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002205 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2206 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002207 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002208 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002209 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002210 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2211 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2212 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002213 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002214 assert(!argT.isNull() && "Can't find 'SEL' type");
2215 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002216 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002217 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002218 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002219 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002220 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002221 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002222 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002223}
2224
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002225// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002226void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002227 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2228 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002229 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002230 assert(!argT.isNull() && "Can't find 'id' type");
2231 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002232 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002233 assert(!argT.isNull() && "Can't find 'SEL' type");
2234 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002235 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002236 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002237 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002238 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002239 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002240 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002241 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002242}
2243
Mike Stump11289f42009-09-09 15:08:12 +00002244// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002245// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002246void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002247 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002248 &Context->Idents.get("objc_msgSendSuper_stret");
2249 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002250 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002251 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002252 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002253 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2254 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2255 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002256 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002257 assert(!argT.isNull() && "Can't find 'SEL' type");
2258 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002259 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002260 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002261 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002262 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002263 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002264 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002265 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002266}
2267
Steve Naroff2e4e3852008-05-08 22:02:18 +00002268// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002269void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002270 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2271 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002272 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002273 assert(!argT.isNull() && "Can't find 'id' type");
2274 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002275 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002276 assert(!argT.isNull() && "Can't find 'SEL' type");
2277 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002278 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002279 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002280 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002281 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002282 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002283 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002284 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002285}
2286
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002287// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002288void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002289 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2290 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002291 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002292 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002293 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002294 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002295 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002296 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002297 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002298 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002299}
2300
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002301// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002302void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002303 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2304 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002305 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002306 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002307 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002308 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002309 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002310 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002311 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002312 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002313}
2314
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002315Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002316 QualType strType = getConstantStringStructType();
2317
2318 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002319
2320 std::string tmpName = InFileName;
2321 unsigned i;
2322 for (i=0; i < tmpName.length(); i++) {
2323 char c = tmpName.at(i);
2324 // replace any non alphanumeric characters with '_'.
2325 if (!isalpha(c) && (c < '0' || c > '9'))
2326 tmpName[i] = '_';
2327 }
2328 S += tmpName;
2329 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002330 S += utostr(NumObjCStringLiterals++);
2331
Steve Naroff00a31762008-03-27 22:29:16 +00002332 Preamble += "static __NSConstantStringImpl " + S;
2333 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2334 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002335 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002336 std::string prettyBufS;
2337 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002338 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2339 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002340 Preamble += prettyBuf.str();
2341 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002342 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002343
2344 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2345 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002346 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002347 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2348 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002349 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002350 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002351 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002352 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2353 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002354 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002355 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002356 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002357}
2358
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002359ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002360 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002361 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002363 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002364 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002365 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002366 assert(OPT);
2367 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002368 return IT->getDecl();
2369 }
2370 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002371}
2372
2373// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002374QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002375 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002376 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002377 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002378 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002379 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002380
Steve Naroff7fa2f042007-11-15 10:28:18 +00002381 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002382 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002383 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002384 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002385
Steve Naroff7fa2f042007-11-15 10:28:18 +00002386 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002387 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002388 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2389 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002390 FieldTypes[i], 0,
2391 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002392 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002393 }
Mike Stump11289f42009-09-09 15:08:12 +00002394
Douglas Gregor91f84212008-12-11 16:49:14 +00002395 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002396 }
2397 return Context->getTagDeclType(SuperStructDecl);
2398}
2399
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002400QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002401 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002402 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002403 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002404 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002405 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002406
Steve Naroffce8e8862008-03-15 00:55:56 +00002407 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002408 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002409 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002410 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002411 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002412 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002413 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002414 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002415
Steve Naroffce8e8862008-03-15 00:55:56 +00002416 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002417 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002418 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2419 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002420 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002421 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002422 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002423 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002424 }
2425
2426 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002427 }
2428 return Context->getTagDeclType(ConstantStringDecl);
2429}
2430
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002431Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002432 if (!SelGetUidFunctionDecl)
2433 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002434 if (!MsgSendFunctionDecl)
2435 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002436 if (!MsgSendSuperFunctionDecl)
2437 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002438 if (!MsgSendStretFunctionDecl)
2439 SynthMsgSendStretFunctionDecl();
2440 if (!MsgSendSuperStretFunctionDecl)
2441 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002442 if (!MsgSendFpretFunctionDecl)
2443 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002444 if (!GetClassFunctionDecl)
2445 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002446 if (!GetMetaClassFunctionDecl)
2447 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002448
Steve Naroff7fa2f042007-11-15 10:28:18 +00002449 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002450 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2451 // May need to use objc_msgSend_stret() as well.
2452 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002453 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2454 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002455 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002456 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002457 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002458 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002459 }
Mike Stump11289f42009-09-09 15:08:12 +00002460
Steve Naroff574440f2007-10-24 22:48:43 +00002461 // Synthesize a call to objc_msgSend().
2462 llvm::SmallVector<Expr*, 8> MsgExprs;
2463 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002464
Steve Naroff574440f2007-10-24 22:48:43 +00002465 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2466 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002467 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2468 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002469 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002470 MsgSendFlavor = MsgSendSuperFunctionDecl;
2471 if (MsgSendStretFlavor)
2472 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2473 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002474
2475 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002476 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002477
2478 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002479
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002480 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002481 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002482 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2483 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002484 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002485 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002486 SourceLocation()))
2487 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002488
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002489 llvm::SmallVector<Expr*, 8> ClsExprs;
2490 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002491 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002492 SuperDecl->getIdentifier()->getNameStart(),
2493 SuperDecl->getIdentifier()->getLength(),
2494 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002495 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002496 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002497 ClsExprs.size());
2498 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002499 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002500 NoTypeInfoCStyleCastExpr(Context,
2501 Context->getObjCIdType(),
2502 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002503 // struct objc_super
2504 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002505 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002506
Steve Naroff0b844f02008-03-11 18:14:26 +00002507 if (LangOpts.Microsoft) {
2508 SynthSuperContructorFunctionDecl();
2509 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002510 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002511 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002512 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002513 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002514 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002515 // The code for super is a little tricky to prevent collision with
2516 // the structure definition in the header. The rewriter has it's own
2517 // internal definition (__rw_objc_super) that is uses. This is why
2518 // we need the cast below. For example:
2519 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2520 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002521 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002522 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002523 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002524 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2525 Context->getPointerType(superType),
2526 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002527 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002528 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002529 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2530 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002531 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002532 TypeSourceInfo *superTInfo
2533 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002534 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2535 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002536 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002537 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002538 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002539 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002540 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002541 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002542 } else {
2543 llvm::SmallVector<Expr*, 8> ClsExprs;
2544 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002545 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002546 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002547 clsName->getLength(),
2548 false, argType,
2549 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002550 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002551 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002552 ClsExprs.size());
2553 MsgExprs.push_back(Cls);
2554 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002555 } else { // instance message.
2556 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002557
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002558 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002559 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002560 if (MsgSendStretFlavor)
2561 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002562 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002563
Steve Naroff7fa2f042007-11-15 10:28:18 +00002564 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002565
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002566 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002567 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2568 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002569 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002570 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002571 SourceLocation()))
2572 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002573
Steve Naroff7fa2f042007-11-15 10:28:18 +00002574 llvm::SmallVector<Expr*, 8> ClsExprs;
2575 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002576 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002577 SuperDecl->getIdentifier()->getNameStart(),
2578 SuperDecl->getIdentifier()->getLength(),
2579 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002580 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002581 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002582 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002583 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002584 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002585 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002586 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2587 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002588 // struct objc_super
2589 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002590 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002591
Steve Naroff17978c42008-03-11 17:37:02 +00002592 if (LangOpts.Microsoft) {
2593 SynthSuperContructorFunctionDecl();
2594 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002595 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002596 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002597 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002598 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002599 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002600 // The code for super is a little tricky to prevent collision with
2601 // the structure definition in the header. The rewriter has it's own
2602 // internal definition (__rw_objc_super) that is uses. This is why
2603 // we need the cast below. For example:
2604 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2605 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002606 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002607 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002608 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002609 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2610 Context->getPointerType(superType),
2611 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002612 } else {
2613 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002614 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2615 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002616 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002617 TypeSourceInfo *superTInfo
2618 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002619 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2620 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002621 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002622 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002623 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002624 // Remove all type-casts because it may contain objc-style types; e.g.
2625 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002626 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002627 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002628 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2629 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002630 MsgExprs.push_back(recExpr);
2631 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002632 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002633 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002634 llvm::SmallVector<Expr*, 8> SelExprs;
2635 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002636 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002637 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002638 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002639 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002640 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2641 &SelExprs[0], SelExprs.size());
2642 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002643
Steve Naroff574440f2007-10-24 22:48:43 +00002644 // Now push any user supplied arguments.
2645 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002646 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002647 // Make all implicit casts explicit...ICE comes in handy:-)
2648 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2649 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002650 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002651 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002652 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002653 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2654 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002655 }
2656 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002657 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002658 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002659 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002660 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002661 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2662 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002663 }
Mike Stump11289f42009-09-09 15:08:12 +00002664 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002665 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002666 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2667 // out the argument in the original expression (since we aren't deleting
2668 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2669 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002670 }
Steve Narofff36987c2007-11-04 22:37:50 +00002671 // Generate the funky cast.
2672 CastExpr *cast;
2673 llvm::SmallVector<QualType, 8> ArgTypes;
2674 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Steve Narofff36987c2007-11-04 22:37:50 +00002676 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002677 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2678 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2679 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002680 ArgTypes.push_back(Context->getObjCIdType());
2681 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002682 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002683 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002684 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2685 E = OMD->param_end(); PI != E; ++PI) {
2686 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002687 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002688 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002689 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002690 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002691 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002692 t = Context->getPointerType(BPT->getPointeeType());
2693 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002694 ArgTypes.push_back(t);
2695 }
Chris Lattnera4997152009-02-20 18:43:26 +00002696 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2697 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002698 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002699 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002700 }
2701 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002702 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002703
Steve Narofff36987c2007-11-04 22:37:50 +00002704 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002705 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002706 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002707
Mike Stump11289f42009-09-09 15:08:12 +00002708 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002709 // If we don't do this cast, we get the following bizarre warning/note:
2710 // xx.m:13: warning: function called through a non-compatible type
2711 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002712 cast = NoTypeInfoCStyleCastExpr(Context,
2713 Context->getPointerType(Context->VoidTy),
2714 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002715
Steve Narofff36987c2007-11-04 22:37:50 +00002716 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002717 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002718 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002719 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002720 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002721 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002722 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2723 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002724
2725 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002726 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002727
John McCall9dd450b2009-09-21 23:43:11 +00002728 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002729 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002730 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002731 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002732 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002733 if (MsgSendStretFlavor) {
2734 // We have the method which returns a struct/union. Must also generate
2735 // call to objc_msgSend_stret and hang both varieties on a conditional
2736 // expression which dictate which one to envoke depending on size of
2737 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002738
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002739 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002740 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002741 SourceLocation());
2742 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002743 cast = NoTypeInfoCStyleCastExpr(Context,
2744 Context->getPointerType(Context->VoidTy),
2745 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002746 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002747 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002748 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002749 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002750 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002751 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2752 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002753
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002754 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002755 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002756
John McCall9dd450b2009-09-21 23:43:11 +00002757 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002758 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002759 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002760 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002761
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002762 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002763 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002764 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002765 Context->getSizeType(),
2766 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002767 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2768 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2769 // For X86 it is more complicated and some kind of target specific routine
2770 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002771 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002772 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002773 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002774 Context->IntTy,
2775 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002776 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2777 BinaryOperator::LE,
2778 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002779 SourceLocation());
2780 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002781 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002782 new (Context) ConditionalOperator(lessThanExpr,
2783 SourceLocation(), CE,
2784 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002785 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002786 }
Mike Stump11289f42009-09-09 15:08:12 +00002787 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002788 return ReplacingStmt;
2789}
2790
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002791Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002792 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002793
Steve Naroff574440f2007-10-24 22:48:43 +00002794 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002795 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002796
2797 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002798 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002799}
2800
Steve Naroffd9803712009-04-29 16:37:50 +00002801// typedef struct objc_object Protocol;
2802QualType RewriteObjC::getProtocolType() {
2803 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002804 TypeSourceInfo *TInfo
2805 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002806 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002807 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002808 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002809 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002810 }
2811 return Context->getTypeDeclType(ProtocolTypeDecl);
2812}
2813
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002814/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002815/// a synthesized/forward data reference (to the protocol's metadata).
2816/// The forward references (and metadata) are generated in
2817/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002818Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002819 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2820 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002821 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002822 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002823 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2824 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2825 Context->getPointerType(DRE->getType()),
2826 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002827 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2828 CastExpr::CK_Unknown,
2829 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002830 ReplaceStmt(Exp, castExpr);
2831 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002832 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002833 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002834
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002835}
2836
Mike Stump11289f42009-09-09 15:08:12 +00002837bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002838 const char *endBuf) {
2839 while (startBuf < endBuf) {
2840 if (*startBuf == '#') {
2841 // Skip whitespace.
2842 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2843 ;
2844 if (!strncmp(startBuf, "if", strlen("if")) ||
2845 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2846 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2847 !strncmp(startBuf, "define", strlen("define")) ||
2848 !strncmp(startBuf, "undef", strlen("undef")) ||
2849 !strncmp(startBuf, "else", strlen("else")) ||
2850 !strncmp(startBuf, "elif", strlen("elif")) ||
2851 !strncmp(startBuf, "endif", strlen("endif")) ||
2852 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2853 !strncmp(startBuf, "include", strlen("include")) ||
2854 !strncmp(startBuf, "import", strlen("import")) ||
2855 !strncmp(startBuf, "include_next", strlen("include_next")))
2856 return true;
2857 }
2858 startBuf++;
2859 }
2860 return false;
2861}
2862
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002863/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002864/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002865void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002866 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002867 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002868 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002869 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002870 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002871 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002872 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002873 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002874 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002875 SourceLocation LocStart = CDecl->getLocStart();
2876 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002877
Steve Naroffdde78982007-11-14 19:25:57 +00002878 const char *startBuf = SM->getCharacterData(LocStart);
2879 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002880
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002881 // If no ivars and no root or if its root, directly or indirectly,
2882 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002883 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2884 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002885 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002886 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002887 return;
2888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
2890 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002891 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002892 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002893 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002894 if (LangOpts.Microsoft)
2895 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002896
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002897 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002898 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002899 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002900 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002901 // If the buffer contains preprocessor directives, we do more fine-grained
2902 // rewrites. This is intended to fix code that looks like (which occurs in
2903 // NSURL.h, for example):
2904 //
2905 // #ifdef XYZ
2906 // @interface Foo : NSObject
2907 // #else
2908 // @interface FooBar : NSObject
2909 // #endif
2910 // {
2911 // int i;
2912 // }
2913 // @end
2914 //
2915 // This clause is segregated to avoid breaking the common case.
2916 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002917 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002918 CDecl->getClassLoc();
2919 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002920 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002921
Chris Lattnerf5b77512009-02-20 18:18:36 +00002922 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002923 // advance to the end of the referenced protocols.
2924 while (endHeader < cursor && *endHeader != '>') endHeader++;
2925 endHeader++;
2926 }
2927 // rewrite the original header
2928 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2929 } else {
2930 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002931 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002932 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002933 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002934 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002935 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002936 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002937 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002938 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002939
Steve Naroffdde78982007-11-14 19:25:57 +00002940 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002941 SourceLocation OnePastCurly =
2942 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2943 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002944 }
2945 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002946
Steve Naroffdde78982007-11-14 19:25:57 +00002947 // Now comment out any visibility specifiers.
2948 while (cursor < endBuf) {
2949 if (*cursor == '@') {
2950 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002951 // Skip whitespace.
2952 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2953 /*scan*/;
2954
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002955 // FIXME: presence of @public, etc. inside comment results in
2956 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002957 if (!strncmp(cursor, "public", strlen("public")) ||
2958 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002959 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002960 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002961 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002962 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002963 // FIXME: If there are cases where '<' is used in ivar declaration part
2964 // of user code, then scan the ivar list and use needToScanForQualifiers
2965 // for type checking.
2966 else if (*cursor == '<') {
2967 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002968 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002969 cursor = strchr(cursor, '>');
2970 cursor++;
2971 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002972 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002973 } else if (*cursor == '^') { // rewrite block specifier.
2974 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2975 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002976 }
Steve Naroffdde78982007-11-14 19:25:57 +00002977 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002978 }
Steve Naroffdde78982007-11-14 19:25:57 +00002979 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002980 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002981 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002982 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002983 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002984 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002985 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002986 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002987 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002988 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002989 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002990 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002991 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002992 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002993}
2994
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002995// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002996/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002997template<typename MethodIterator>
2998void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2999 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003000 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003001 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003002 const char *ClassName,
3003 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003004 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattner31bc07e2007-12-12 07:46:12 +00003006 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003007 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003008 SEL _cmd;
3009 char *method_types;
3010 void *_imp;
3011 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003012 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003013 Result += "\nstruct _objc_method {\n";
3014 Result += "\tSEL _cmd;\n";
3015 Result += "\tchar *method_types;\n";
3016 Result += "\tvoid *_imp;\n";
3017 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003018
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003019 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003020 }
Mike Stump11289f42009-09-09 15:08:12 +00003021
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003022 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003023
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003024 /* struct {
3025 struct _objc_method_list *next_method;
3026 int method_count;
3027 struct _objc_method method_list[];
3028 }
3029 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003030 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003031 Result += "\nstatic struct {\n";
3032 Result += "\tstruct _objc_method_list *next_method;\n";
3033 Result += "\tint method_count;\n";
3034 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003035 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003036 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003037 Result += prefix;
3038 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3039 Result += "_METHODS_";
3040 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003041 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003042 Result += IsInstanceMethod ? "inst" : "cls";
3043 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003044 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003045
Chris Lattner31bc07e2007-12-12 07:46:12 +00003046 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003047 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003048 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003049 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003050 Result += "\", \"";
3051 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003052 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003053 Result += MethodInternalNames[*MethodBegin];
3054 Result += "}\n";
3055 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3056 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003057 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003058 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003059 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003060 Result += "\", \"";
3061 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003062 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003063 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003064 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003065 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003066 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003067}
3068
Steve Naroffd9803712009-04-29 16:37:50 +00003069/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003070void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003071RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3072 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003073 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003074
3075 // Output struct protocol_methods holder of method selector and type.
3076 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3077 /* struct protocol_methods {
3078 SEL _cmd;
3079 char *method_types;
3080 }
3081 */
3082 Result += "\nstruct _protocol_methods {\n";
3083 Result += "\tstruct objc_selector *_cmd;\n";
3084 Result += "\tchar *method_types;\n";
3085 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003086
Steve Naroffd9803712009-04-29 16:37:50 +00003087 objc_protocol_methods = true;
3088 }
3089 // Do not synthesize the protocol more than once.
3090 if (ObjCSynthesizedProtocols.count(PDecl))
3091 return;
Mike Stump11289f42009-09-09 15:08:12 +00003092
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003093 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3094 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3095 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003096 /* struct _objc_protocol_method_list {
3097 int protocol_method_count;
3098 struct protocol_methods protocols[];
3099 }
Steve Naroff251084d2008-03-12 01:06:30 +00003100 */
Steve Naroffd9803712009-04-29 16:37:50 +00003101 Result += "\nstatic struct {\n";
3102 Result += "\tint protocol_method_count;\n";
3103 Result += "\tstruct _protocol_methods protocol_methods[";
3104 Result += utostr(NumMethods);
3105 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3106 Result += PDecl->getNameAsString();
3107 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3108 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003109
Steve Naroffd9803712009-04-29 16:37:50 +00003110 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003111 for (ObjCProtocolDecl::instmeth_iterator
3112 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003113 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003114 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003115 Result += "\t ,{{(struct objc_selector *)\"";
3116 else
3117 Result += "\t ,{(struct objc_selector *)\"";
3118 Result += (*I)->getSelector().getAsString().c_str();
3119 std::string MethodTypeString;
3120 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3121 Result += "\", \"";
3122 Result += MethodTypeString;
3123 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003124 }
Steve Naroffd9803712009-04-29 16:37:50 +00003125 Result += "\t }\n};\n";
3126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Steve Naroffd9803712009-04-29 16:37:50 +00003128 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003129 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3130 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003131 if (NumMethods > 0) {
3132 /* struct _objc_protocol_method_list {
3133 int protocol_method_count;
3134 struct protocol_methods protocols[];
3135 }
3136 */
3137 Result += "\nstatic struct {\n";
3138 Result += "\tint protocol_method_count;\n";
3139 Result += "\tstruct _protocol_methods protocol_methods[";
3140 Result += utostr(NumMethods);
3141 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3142 Result += PDecl->getNameAsString();
3143 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3144 "{\n\t";
3145 Result += utostr(NumMethods);
3146 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003147
Steve Naroffd9803712009-04-29 16:37:50 +00003148 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003149 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003150 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003151 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003152 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003153 Result += "\t ,{{(struct objc_selector *)\"";
3154 else
3155 Result += "\t ,{(struct objc_selector *)\"";
3156 Result += (*I)->getSelector().getAsString().c_str();
3157 std::string MethodTypeString;
3158 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3159 Result += "\", \"";
3160 Result += MethodTypeString;
3161 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003162 }
Steve Naroffd9803712009-04-29 16:37:50 +00003163 Result += "\t }\n};\n";
3164 }
3165
3166 // Output:
3167 /* struct _objc_protocol {
3168 // Objective-C 1.0 extensions
3169 struct _objc_protocol_extension *isa;
3170 char *protocol_name;
3171 struct _objc_protocol **protocol_list;
3172 struct _objc_protocol_method_list *instance_methods;
3173 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003174 };
Steve Naroffd9803712009-04-29 16:37:50 +00003175 */
3176 static bool objc_protocol = false;
3177 if (!objc_protocol) {
3178 Result += "\nstruct _objc_protocol {\n";
3179 Result += "\tstruct _objc_protocol_extension *isa;\n";
3180 Result += "\tchar *protocol_name;\n";
3181 Result += "\tstruct _objc_protocol **protocol_list;\n";
3182 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3183 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003184 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003185
Steve Naroffd9803712009-04-29 16:37:50 +00003186 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003187 }
Mike Stump11289f42009-09-09 15:08:12 +00003188
Steve Naroffd9803712009-04-29 16:37:50 +00003189 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3190 Result += PDecl->getNameAsString();
3191 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3192 "{\n\t0, \"";
3193 Result += PDecl->getNameAsString();
3194 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003195 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003196 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3197 Result += PDecl->getNameAsString();
3198 Result += ", ";
3199 }
3200 else
3201 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003202 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003203 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3204 Result += PDecl->getNameAsString();
3205 Result += "\n";
3206 }
3207 else
3208 Result += "0\n";
3209 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003210
Steve Naroffd9803712009-04-29 16:37:50 +00003211 // Mark this protocol as having been generated.
3212 if (!ObjCSynthesizedProtocols.insert(PDecl))
3213 assert(false && "protocol already synthesized");
3214
3215}
3216
3217void RewriteObjC::
3218RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3219 const char *prefix, const char *ClassName,
3220 std::string &Result) {
3221 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003222
Steve Naroffd9803712009-04-29 16:37:50 +00003223 for (unsigned i = 0; i != Protocols.size(); i++)
3224 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3225
Chris Lattner388f6e92008-07-21 21:33:21 +00003226 // Output the top lovel protocol meta-data for the class.
3227 /* struct _objc_protocol_list {
3228 struct _objc_protocol_list *next;
3229 int protocol_count;
3230 struct _objc_protocol *class_protocols[];
3231 }
3232 */
3233 Result += "\nstatic struct {\n";
3234 Result += "\tstruct _objc_protocol_list *next;\n";
3235 Result += "\tint protocol_count;\n";
3236 Result += "\tstruct _objc_protocol *class_protocols[";
3237 Result += utostr(Protocols.size());
3238 Result += "];\n} _OBJC_";
3239 Result += prefix;
3240 Result += "_PROTOCOLS_";
3241 Result += ClassName;
3242 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3243 "{\n\t0, ";
3244 Result += utostr(Protocols.size());
3245 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003246
Chris Lattner388f6e92008-07-21 21:33:21 +00003247 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003248 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003249 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattner388f6e92008-07-21 21:33:21 +00003251 for (unsigned i = 1; i != Protocols.size(); i++) {
3252 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003253 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003254 Result += "\n";
3255 }
3256 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003257}
3258
Steve Naroffd9803712009-04-29 16:37:50 +00003259
Mike Stump11289f42009-09-09 15:08:12 +00003260/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003261/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003262void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003263 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003264 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003265 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003266 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003267 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003268 CDecl = CDecl->getNextClassCategory())
3269 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3270 break;
Mike Stump11289f42009-09-09 15:08:12 +00003271
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003272 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003273 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003274 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003275
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003276 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003277 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003278 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003279
3280 // If any of our property implementations have associated getters or
3281 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003282 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3283 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003284 Prop != PropEnd; ++Prop) {
3285 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3286 continue;
3287 if (!(*Prop)->getPropertyIvarDecl())
3288 continue;
3289 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3290 if (!PD)
3291 continue;
3292 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3293 InstanceMethods.push_back(Getter);
3294 if (PD->isReadOnly())
3295 continue;
3296 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3297 InstanceMethods.push_back(Setter);
3298 }
3299 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003300 true, "CATEGORY_", FullCategoryName.c_str(),
3301 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003302
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003303 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003304 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003305 false, "CATEGORY_", FullCategoryName.c_str(),
3306 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003308 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003309 // Null CDecl is case of a category implementation with no category interface
3310 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003311 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3312 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003313 /* struct _objc_category {
3314 char *category_name;
3315 char *class_name;
3316 struct _objc_method_list *instance_methods;
3317 struct _objc_method_list *class_methods;
3318 struct _objc_protocol_list *protocols;
3319 // Objective-C 1.0 extensions
3320 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003321 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003322 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003323 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003324 */
Mike Stump11289f42009-09-09 15:08:12 +00003325
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003326 static bool objc_category = false;
3327 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003328 Result += "\nstruct _objc_category {\n";
3329 Result += "\tchar *category_name;\n";
3330 Result += "\tchar *class_name;\n";
3331 Result += "\tstruct _objc_method_list *instance_methods;\n";
3332 Result += "\tstruct _objc_method_list *class_methods;\n";
3333 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003334 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003335 Result += "\tstruct _objc_property_list *instance_properties;\n";
3336 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003337 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003338 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003339 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3340 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003341 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003342 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003343 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003344 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003345 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003346
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003347 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003348 Result += "\t, (struct _objc_method_list *)"
3349 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3350 Result += FullCategoryName;
3351 Result += "\n";
3352 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003353 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003354 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003355 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003356 Result += "\t, (struct _objc_method_list *)"
3357 "&_OBJC_CATEGORY_CLASS_METHODS_";
3358 Result += FullCategoryName;
3359 Result += "\n";
3360 }
3361 else
3362 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattnerf5b77512009-02-20 18:18:36 +00003364 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003365 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003366 Result += FullCategoryName;
3367 Result += "\n";
3368 }
3369 else
3370 Result += "\t, 0\n";
3371 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003372}
3373
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003374/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3375/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003376void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3377 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003378 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003379 if (ivar->isBitField()) {
3380 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3381 // place all bitfields at offset 0.
3382 Result += "0";
3383 } else {
3384 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003385 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003386 if (LangOpts.Microsoft)
3387 Result += "_IMPL";
3388 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003389 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003390 Result += ")";
3391 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003392}
3393
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394//===----------------------------------------------------------------------===//
3395// Meta Data Emission
3396//===----------------------------------------------------------------------===//
3397
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003398void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003399 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003400 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003401
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003402 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003403 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003404 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003405 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003406 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003407 }
Mike Stump11289f42009-09-09 15:08:12 +00003408
Chris Lattner30d23e82007-12-12 07:56:42 +00003409 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003410 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003411 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003412 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003413 if (NumIvars > 0) {
3414 static bool objc_ivar = false;
3415 if (!objc_ivar) {
3416 /* struct _objc_ivar {
3417 char *ivar_name;
3418 char *ivar_type;
3419 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003420 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003421 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003422 Result += "\nstruct _objc_ivar {\n";
3423 Result += "\tchar *ivar_name;\n";
3424 Result += "\tchar *ivar_type;\n";
3425 Result += "\tint ivar_offset;\n";
3426 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003427
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003428 objc_ivar = true;
3429 }
3430
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003431 /* struct {
3432 int ivar_count;
3433 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003434 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003435 */
Mike Stump11289f42009-09-09 15:08:12 +00003436 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003437 Result += "\tint ivar_count;\n";
3438 Result += "\tstruct _objc_ivar ivar_list[";
3439 Result += utostr(NumIvars);
3440 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003441 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003442 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003443 "{\n\t";
3444 Result += utostr(NumIvars);
3445 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003446
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003447 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003448 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003449 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003450 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003451 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003452 IV != IVEnd; ++IV)
3453 IVars.push_back(*IV);
3454 IVI = IVars.begin();
3455 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003456 } else {
3457 IVI = CDecl->ivar_begin();
3458 IVE = CDecl->ivar_end();
3459 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003460 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003461 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003462 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003463 std::string TmpString, StrEncoding;
3464 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3465 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003466 Result += StrEncoding;
3467 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003468 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003469 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003470 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003471 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003472 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003473 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003474 std::string TmpString, StrEncoding;
3475 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3476 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003477 Result += StrEncoding;
3478 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003479 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003480 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003481 }
Mike Stump11289f42009-09-09 15:08:12 +00003482
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003484 }
Mike Stump11289f42009-09-09 15:08:12 +00003485
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003486 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003487 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003488 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003489
3490 // If any of our property implementations have associated getters or
3491 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003492 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3493 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003494 Prop != PropEnd; ++Prop) {
3495 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3496 continue;
3497 if (!(*Prop)->getPropertyIvarDecl())
3498 continue;
3499 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3500 if (!PD)
3501 continue;
3502 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3503 InstanceMethods.push_back(Getter);
3504 if (PD->isReadOnly())
3505 continue;
3506 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3507 InstanceMethods.push_back(Setter);
3508 }
3509 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003510 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003511
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003512 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003513 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003514 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003515
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003516 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003517 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3518 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003519
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003520 // Declaration of class/meta-class metadata
3521 /* struct _objc_class {
3522 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003523 const char *super_class_name;
3524 char *name;
3525 long version;
3526 long info;
3527 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003528 struct _objc_ivar_list *ivars;
3529 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003530 struct objc_cache *cache;
3531 struct objc_protocol_list *protocols;
3532 const char *ivar_layout;
3533 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003534 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003535 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003536 static bool objc_class = false;
3537 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003538 Result += "\nstruct _objc_class {\n";
3539 Result += "\tstruct _objc_class *isa;\n";
3540 Result += "\tconst char *super_class_name;\n";
3541 Result += "\tchar *name;\n";
3542 Result += "\tlong version;\n";
3543 Result += "\tlong info;\n";
3544 Result += "\tlong instance_size;\n";
3545 Result += "\tstruct _objc_ivar_list *ivars;\n";
3546 Result += "\tstruct _objc_method_list *methods;\n";
3547 Result += "\tstruct objc_cache *cache;\n";
3548 Result += "\tstruct _objc_protocol_list *protocols;\n";
3549 Result += "\tconst char *ivar_layout;\n";
3550 Result += "\tstruct _objc_class_ext *ext;\n";
3551 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003552 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003553 }
Mike Stump11289f42009-09-09 15:08:12 +00003554
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003555 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003556 ObjCInterfaceDecl *RootClass = 0;
3557 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003558 while (SuperClass) {
3559 RootClass = SuperClass;
3560 SuperClass = SuperClass->getSuperClass();
3561 }
3562 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003563
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003564 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003565 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003566 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003568 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 Result += "\"";
3570
3571 if (SuperClass) {
3572 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003573 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003574 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003575 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003576 Result += "\"";
3577 }
3578 else {
3579 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003580 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003581 Result += "\"";
3582 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003583 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003584 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003585 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003586 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003587 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003588 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003589 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003590 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003591 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003593 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003594 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003595 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003596 Result += ",0,0\n";
3597 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003598 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003599 Result += "\t,0,0,0,0\n";
3600 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003601
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003602 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003603 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003604 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003605 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003606 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003607 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003608 if (SuperClass) {
3609 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003610 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003612 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003613 Result += "\"";
3614 }
3615 else {
3616 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003617 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003618 Result += "\"";
3619 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003620 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003621 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003622 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003623 Result += ",0";
3624 else {
3625 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003626 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003627 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003628 if (LangOpts.Microsoft)
3629 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003630 Result += ")";
3631 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003632 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003633 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003634 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 Result += "\n\t";
3636 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003637 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003639 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003640 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003641 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003642 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003643 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003644 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003645 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003646 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003647 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003648 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003649 Result += ", 0,0\n";
3650 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003651 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003652 Result += ",0,0,0\n";
3653 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003654}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003655
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003656/// RewriteImplementations - This routine rewrites all method implementations
3657/// and emits meta-data.
3658
Steve Narofff8cfd162008-11-13 20:07:04 +00003659void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003660 int ClsDefCount = ClassImplementation.size();
3661 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003662
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003663 // Rewrite implemented methods
3664 for (int i = 0; i < ClsDefCount; i++)
3665 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003666
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003667 for (int i = 0; i < CatDefCount; i++)
3668 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003669}
Mike Stump11289f42009-09-09 15:08:12 +00003670
Steve Narofff8cfd162008-11-13 20:07:04 +00003671void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3672 int ClsDefCount = ClassImplementation.size();
3673 int CatDefCount = CategoryImplementation.size();
3674
Steve Naroff30ac2222008-05-07 21:23:49 +00003675 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003676 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003677 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003678 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003679 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003680
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003681 // For each implemented category, write out all its meta data.
3682 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003683 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003684
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003685 // Write objc_symtab metadata
3686 /*
3687 struct _objc_symtab
3688 {
3689 long sel_ref_cnt;
3690 SEL *refs;
3691 short cls_def_cnt;
3692 short cat_def_cnt;
3693 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003694 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003695 */
Mike Stump11289f42009-09-09 15:08:12 +00003696
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003697 Result += "\nstruct _objc_symtab {\n";
3698 Result += "\tlong sel_ref_cnt;\n";
3699 Result += "\tSEL *refs;\n";
3700 Result += "\tshort cls_def_cnt;\n";
3701 Result += "\tshort cat_def_cnt;\n";
3702 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3703 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003704
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003706 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003707 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 + ", " + utostr(CatDefCount) + "\n";
3709 for (int i = 0; i < ClsDefCount; i++) {
3710 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003711 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003712 Result += "\n";
3713 }
Mike Stump11289f42009-09-09 15:08:12 +00003714
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 for (int i = 0; i < CatDefCount; i++) {
3716 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003717 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003718 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003719 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003720 Result += "\n";
3721 }
Mike Stump11289f42009-09-09 15:08:12 +00003722
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003723 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003724
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003725 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003726
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003727 /*
3728 struct _objc_module {
3729 long version;
3730 long size;
3731 const char *name;
3732 struct _objc_symtab *symtab;
3733 }
3734 */
Mike Stump11289f42009-09-09 15:08:12 +00003735
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003736 Result += "\nstruct _objc_module {\n";
3737 Result += "\tlong version;\n";
3738 Result += "\tlong size;\n";
3739 Result += "\tconst char *name;\n";
3740 Result += "\tstruct _objc_symtab *symtab;\n";
3741 Result += "};\n\n";
3742 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003743 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003744 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003745 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003746 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003747
3748 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003749 if (ProtocolExprDecls.size()) {
3750 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3751 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003752 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003753 E = ProtocolExprDecls.end(); I != E; ++I) {
3754 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3755 Result += (*I)->getNameAsString();
3756 Result += " = &_OBJC_PROTOCOL_";
3757 Result += (*I)->getNameAsString();
3758 Result += ";\n";
3759 }
3760 Result += "#pragma data_seg(pop)\n\n";
3761 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003762 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003763 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003764 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3765 Result += "&_OBJC_MODULES;\n";
3766 Result += "#pragma data_seg(pop)\n\n";
3767 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003768}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003769
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003770void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3771 const std::string &Name,
3772 ValueDecl *VD) {
3773 assert(BlockByRefDeclNo.count(VD) &&
3774 "RewriteByRefString: ByRef decl missing");
3775 ResultStr += "struct __Block_byref_" + Name +
3776 "_" + utostr(BlockByRefDeclNo[VD]) ;
3777}
3778
Steve Naroff677ab3a2008-10-27 17:20:55 +00003779std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3780 const char *funcName,
3781 std::string Tag) {
3782 const FunctionType *AFT = CE->getFunctionType();
3783 QualType RT = AFT->getResultType();
3784 std::string StructRef = "struct " + Tag;
3785 std::string S = "static " + RT.getAsString() + " __" +
3786 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003787
Steve Naroff677ab3a2008-10-27 17:20:55 +00003788 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003789
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003790 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003791 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003792 // block (to reference imported block decl refs).
3793 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003794 } else if (BD->param_empty()) {
3795 S += "(" + StructRef + " *__cself)";
3796 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003797 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003798 assert(FT && "SynthesizeBlockFunc: No function proto");
3799 S += '(';
3800 // first add the implicit argument.
3801 S += StructRef + " *__cself, ";
3802 std::string ParamStr;
3803 for (BlockDecl::param_iterator AI = BD->param_begin(),
3804 E = BD->param_end(); AI != E; ++AI) {
3805 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003806 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003807 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003808 S += ParamStr;
3809 }
3810 if (FT->isVariadic()) {
3811 if (!BD->param_empty()) S += ", ";
3812 S += "...";
3813 }
3814 S += ')';
3815 }
3816 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003817
Steve Naroff677ab3a2008-10-27 17:20:55 +00003818 // Create local declarations to avoid rewriting all closure decl ref exprs.
3819 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003820 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003821 E = BlockByRefDecls.end(); I != E; ++I) {
3822 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003823 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003824 std::string TypeString;
3825 RewriteByRefString(TypeString, Name, (*I));
3826 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003827 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003828 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003829 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003830 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003831 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003832 E = BlockByCopyDecls.end(); I != E; ++I) {
3833 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003834 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 // Handle nested closure invocation. For example:
3836 //
3837 // void (^myImportedClosure)(void);
3838 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003839 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003840 // void (^anotherClosure)(void);
3841 // anotherClosure = ^(void) {
3842 // myImportedClosure(); // import and invoke the closure
3843 // };
3844 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003845 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003846 S += "struct __block_impl *";
3847 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003848 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003849 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 }
3851 std::string RewrittenStr = RewrittenBlockExprs[CE];
3852 const char *cstr = RewrittenStr.c_str();
3853 while (*cstr++ != '{') ;
3854 S += cstr;
3855 S += "\n";
3856 return S;
3857}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003858
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3860 const char *funcName,
3861 std::string Tag) {
3862 std::string StructRef = "struct " + Tag;
3863 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003864
Steve Naroff677ab3a2008-10-27 17:20:55 +00003865 S += funcName;
3866 S += "_block_copy_" + utostr(i);
3867 S += "(" + StructRef;
3868 S += "*dst, " + StructRef;
3869 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003870 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003872 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003873 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003874 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003875 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003876 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003877 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003878 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003879 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003881 S += "}\n";
3882
Steve Naroff677ab3a2008-10-27 17:20:55 +00003883 S += "\nstatic void __";
3884 S += funcName;
3885 S += "_block_dispose_" + utostr(i);
3886 S += "(" + StructRef;
3887 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003888 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003889 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003890 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003892 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003893 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003894 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003895 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003896 }
Mike Stump11289f42009-09-09 15:08:12 +00003897 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003898 return S;
3899}
3900
Steve Naroff30484702009-12-06 21:14:13 +00003901std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3902 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003903 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003905
Steve Naroff677ab3a2008-10-27 17:20:55 +00003906 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003907 S += " struct " + Desc;
3908 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003909
Steve Naroff30484702009-12-06 21:14:13 +00003910 Constructor += "(void *fp, "; // Invoke function pointer.
3911 Constructor += "struct " + Desc; // Descriptor pointer.
3912 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003913
Steve Naroff677ab3a2008-10-27 17:20:55 +00003914 if (BlockDeclRefs.size()) {
3915 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003916 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003917 E = BlockByCopyDecls.end(); I != E; ++I) {
3918 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003919 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 std::string ArgName = "_" + FieldName;
3921 // Handle nested closure invocation. For example:
3922 //
3923 // void (^myImportedBlock)(void);
3924 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003925 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003926 // void (^anotherBlock)(void);
3927 // anotherBlock = ^(void) {
3928 // myImportedBlock(); // import and invoke the closure
3929 // };
3930 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003931 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003932 S += "struct __block_impl *";
3933 Constructor += ", void *" + ArgName;
3934 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003935 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3936 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 Constructor += ", " + ArgName;
3938 }
3939 S += FieldName + ";\n";
3940 }
3941 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003942 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003943 E = BlockByRefDecls.end(); I != E; ++I) {
3944 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003945 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003946 std::string ArgName = "_" + FieldName;
3947 // Handle nested closure invocation. For example:
3948 //
3949 // void (^myImportedBlock)(void);
3950 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003951 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003952 // void (^anotherBlock)(void);
3953 // anotherBlock = ^(void) {
3954 // myImportedBlock(); // import and invoke the closure
3955 // };
3956 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003957 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958 S += "struct __block_impl *";
3959 Constructor += ", void *" + ArgName;
3960 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003961 std::string TypeString;
3962 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003963 TypeString += " *";
3964 FieldName = TypeString + FieldName;
3965 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 Constructor += ", " + ArgName;
3967 }
3968 S += FieldName + "; // by ref\n";
3969 }
3970 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003971 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003972 if (GlobalVarDecl)
3973 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3974 else
3975 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003976 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003977
Steve Naroff30484702009-12-06 21:14:13 +00003978 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003979
Steve Naroff677ab3a2008-10-27 17:20:55 +00003980 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003981 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003982 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003983 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003984 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003985 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003986 Constructor += Name + " = (struct __block_impl *)_";
3987 else
3988 Constructor += Name + " = _";
3989 Constructor += Name + ";\n";
3990 }
3991 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003992 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003993 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003994 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003996 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003997 Constructor += Name + " = (struct __block_impl *)_";
3998 else
3999 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004000 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 }
4002 } else {
4003 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004004 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004005 if (GlobalVarDecl)
4006 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4007 else
4008 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004009 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4010 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 }
4012 Constructor += " ";
4013 Constructor += "}\n";
4014 S += Constructor;
4015 S += "};\n";
4016 return S;
4017}
4018
Steve Naroff30484702009-12-06 21:14:13 +00004019std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4020 std::string ImplTag, int i,
4021 const char *FunName,
4022 unsigned hasCopy) {
4023 std::string S = "\nstatic struct " + DescTag;
4024
4025 S += " {\n unsigned long reserved;\n";
4026 S += " unsigned long Block_size;\n";
4027 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004028 S += " void (*copy)(struct ";
4029 S += ImplTag; S += "*, struct ";
4030 S += ImplTag; S += "*);\n";
4031
4032 S += " void (*dispose)(struct ";
4033 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004034 }
4035 S += "} ";
4036
4037 S += DescTag + "_DATA = { 0, sizeof(struct ";
4038 S += ImplTag + ")";
4039 if (hasCopy) {
4040 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4041 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4042 }
4043 S += "};\n";
4044 return S;
4045}
4046
Steve Naroff677ab3a2008-10-27 17:20:55 +00004047void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004048 const char *FunName) {
4049 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004050 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004051 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 // Insert closures that were part of the function.
4053 for (unsigned i = 0; i < Blocks.size(); i++) {
4054
4055 CollectBlockDeclRefInfo(Blocks[i]);
4056
Steve Naroff30484702009-12-06 21:14:13 +00004057 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4058 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004059
Steve Naroff30484702009-12-06 21:14:13 +00004060 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004061
4062 InsertText(FunLocStart, CI.c_str(), CI.size());
4063
Steve Naroff30484702009-12-06 21:14:13 +00004064 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004065
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 InsertText(FunLocStart, CF.c_str(), CF.size());
4067
4068 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004069 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004070 InsertText(FunLocStart, HF.c_str(), HF.size());
4071 }
Steve Naroff30484702009-12-06 21:14:13 +00004072 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4073 ImportedBlockDecls.size() > 0);
4074 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004075
Steve Naroff677ab3a2008-10-27 17:20:55 +00004076 BlockDeclRefs.clear();
4077 BlockByRefDecls.clear();
4078 BlockByCopyDecls.clear();
4079 BlockCallExprs.clear();
4080 ImportedBlockDecls.clear();
4081 }
4082 Blocks.clear();
4083 RewrittenBlockExprs.clear();
4084}
4085
4086void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4087 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004088 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004089
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090 SynthesizeBlockLiterals(FunLocStart, FuncName);
4091}
4092
4093void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004094 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4095 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004096 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattnere4b95692008-11-24 03:33:13 +00004097 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004098 // Convert colons to underscores.
4099 std::string::size_type loc = 0;
4100 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4101 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004102
Steve Naroff677ab3a2008-10-27 17:20:55 +00004103 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4104}
4105
4106void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4107 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4108 CI != E; ++CI)
4109 if (*CI) {
4110 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4111 GetBlockDeclRefExprs(CBE->getBody());
4112 else
4113 GetBlockDeclRefExprs(*CI);
4114 }
4115 // Handle specific things.
4116 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4117 // FIXME: Handle enums.
4118 if (!isa<FunctionDecl>(CDRE->getDecl()))
4119 BlockDeclRefs.push_back(CDRE);
4120 return;
4121}
4122
4123void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4124 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4125 CI != E; ++CI)
4126 if (*CI) {
4127 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4128 GetBlockCallExprs(CBE->getBody());
4129 else
4130 GetBlockCallExprs(*CI);
4131 }
Mike Stump11289f42009-09-09 15:08:12 +00004132
Steve Naroff677ab3a2008-10-27 17:20:55 +00004133 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4134 if (CE->getCallee()->getType()->isBlockPointerType()) {
4135 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4136 }
4137 }
4138 return;
4139}
4140
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004141Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004142 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004144
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004145 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004146 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004147 } else if (const BlockDeclRefExpr *CDRE =
4148 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004149 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004150 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004151 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004152 }
4153 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4154 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4155 }
4156 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4157 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4158 else if (const ConditionalOperator *CEXPR =
4159 dyn_cast<ConditionalOperator>(BlockExp)) {
4160 Expr *LHSExp = CEXPR->getLHS();
4161 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4162 Expr *RHSExp = CEXPR->getRHS();
4163 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4164 Expr *CONDExp = CEXPR->getCond();
4165 ConditionalOperator *CondExpr =
4166 new (Context) ConditionalOperator(CONDExp,
4167 SourceLocation(), cast<Expr>(LHSStmt),
4168 SourceLocation(), cast<Expr>(RHSStmt),
4169 Exp->getType());
4170 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004171 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4172 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004173 } else {
4174 assert(1 && "RewriteBlockClass: Bad type");
4175 }
4176 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004177 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004178 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004179 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004180 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004181
Steve Naroff350b6652008-10-30 10:07:53 +00004182 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4183 SourceLocation(),
4184 &Context->Idents.get("__block_impl"));
4185 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186
Steve Naroff350b6652008-10-30 10:07:53 +00004187 // Generate a funky cast.
4188 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004189
Steve Naroff350b6652008-10-30 10:07:53 +00004190 // Push the block argument type.
4191 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004192 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004193 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004194 E = FTP->arg_type_end(); I && (I != E); ++I) {
4195 QualType t = *I;
4196 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004197 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004198 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004199 t = Context->getPointerType(BPT->getPointeeType());
4200 }
4201 ArgTypes.push_back(t);
4202 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004203 }
Steve Naroff350b6652008-10-30 10:07:53 +00004204 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004205 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004206 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004207
Steve Naroff350b6652008-10-30 10:07:53 +00004208 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall97513962010-01-15 18:39:57 +00004210 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4211 CastExpr::CK_Unknown,
4212 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004213 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004214 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4215 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004216 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004217
Douglas Gregor91f84212008-12-11 16:49:14 +00004218 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004219 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004220 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004221 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4222 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall97513962010-01-15 18:39:57 +00004224 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4225 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004226 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004227
Steve Naroff350b6652008-10-30 10:07:53 +00004228 llvm::SmallVector<Expr*, 8> BlkExprs;
4229 // Add the implicit argument.
4230 BlkExprs.push_back(BlkCast);
4231 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004232 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004233 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004234 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004236 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4237 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004238 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004239 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004240}
4241
4242void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004243 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004244 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245}
4246
Steve Naroffd9803712009-04-29 16:37:50 +00004247// We need to return the rewritten expression to handle cases where the
4248// BlockDeclRefExpr is embedded in another expression being rewritten.
4249// For example:
4250//
4251// int main() {
4252// __block Foo *f;
4253// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004254//
Steve Naroffd9803712009-04-29 16:37:50 +00004255// void (^myblock)() = ^() {
4256// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4257// i = 77;
4258// };
4259//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004260Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004261 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004262 // for each DeclRefExp where BYREFVAR is name of the variable.
4263 ValueDecl *VD;
4264 bool isArrow = true;
4265 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4266 VD = BDRE->getDecl();
4267 else {
4268 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4269 isArrow = false;
4270 }
4271
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004272 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4273 &Context->Idents.get("__forwarding"),
4274 Context->VoidPtrTy, 0,
4275 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004276 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4277 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004278 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004279
4280 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004281 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4282 &Context->Idents.get(Name),
4283 Context->VoidPtrTy, 0,
4284 /*BitWidth=*/0, /*Mutable=*/true);
4285 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004286 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004287
4288
4289
Steve Narofff26a1d42009-02-02 17:19:26 +00004290 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004291 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4292 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004293 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004294 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295}
4296
Steve Naroffc989a7b2008-11-03 23:29:32 +00004297void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4298 SourceLocation LocStart = CE->getLParenLoc();
4299 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004300
4301 // Need to avoid trying to rewrite synthesized casts.
4302 if (LocStart.isInvalid())
4303 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004304 // Need to avoid trying to rewrite casts contained in macros.
4305 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4306 return;
Mike Stump11289f42009-09-09 15:08:12 +00004307
Steve Naroff677ab3a2008-10-27 17:20:55 +00004308 const char *startBuf = SM->getCharacterData(LocStart);
4309 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004310 QualType QT = CE->getType();
4311 const Type* TypePtr = QT->getAs<Type>();
4312 if (isa<TypeOfExprType>(TypePtr)) {
4313 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4314 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4315 std::string TypeAsString = "(";
4316 TypeAsString += QT.getAsString();
4317 TypeAsString += ")";
4318 ReplaceText(LocStart, endBuf-startBuf+1,
4319 TypeAsString.c_str(), TypeAsString.size());
4320 return;
4321 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004322 // advance the location to startArgList.
4323 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004324
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 while (*argPtr++ && (argPtr < endBuf)) {
4326 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004327 case '^':
4328 // Replace the '^' with '*'.
4329 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4330 ReplaceText(LocStart, 1, "*", 1);
4331 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 }
4333 }
4334 return;
4335}
4336
4337void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4338 SourceLocation DeclLoc = FD->getLocation();
4339 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004340
Steve Naroff677ab3a2008-10-27 17:20:55 +00004341 // We have 1 or more arguments that have closure pointers.
4342 const char *startBuf = SM->getCharacterData(DeclLoc);
4343 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004344
Steve Naroff677ab3a2008-10-27 17:20:55 +00004345 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004346
Steve Naroff677ab3a2008-10-27 17:20:55 +00004347 parenCount++;
4348 // advance the location to startArgList.
4349 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4350 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004351
Steve Naroff677ab3a2008-10-27 17:20:55 +00004352 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004353
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 while (*argPtr++ && parenCount) {
4355 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004356 case '^':
4357 // Replace the '^' with '*'.
4358 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4359 ReplaceText(DeclLoc, 1, "*", 1);
4360 break;
4361 case '(':
4362 parenCount++;
4363 break;
4364 case ')':
4365 parenCount--;
4366 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004367 }
4368 }
4369 return;
4370}
4371
4372bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004373 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004374 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004375 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004376 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004377 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004378 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004379 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004380 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381 }
4382 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004383 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004384 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004385 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004386 return true;
4387 }
4388 return false;
4389}
4390
Ted Kremenek5a201952009-02-07 01:47:29 +00004391void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4392 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004393 const char *argPtr = strchr(Name, '(');
4394 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004395
Steve Naroff677ab3a2008-10-27 17:20:55 +00004396 LParen = argPtr; // output the start.
4397 argPtr++; // skip past the left paren.
4398 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004399
Steve Naroff677ab3a2008-10-27 17:20:55 +00004400 while (*argPtr && parenCount) {
4401 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004402 case '(': parenCount++; break;
4403 case ')': parenCount--; break;
4404 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004405 }
4406 if (parenCount) argPtr++;
4407 }
4408 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4409 RParen = argPtr; // output the end
4410}
4411
4412void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4414 RewriteBlockPointerFunctionArgs(FD);
4415 return;
Mike Stump11289f42009-09-09 15:08:12 +00004416 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004417 // Handle Variables and Typedefs.
4418 SourceLocation DeclLoc = ND->getLocation();
4419 QualType DeclT;
4420 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4421 DeclT = VD->getType();
4422 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4423 DeclT = TDD->getUnderlyingType();
4424 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4425 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004426 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004427 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004428
Steve Naroff677ab3a2008-10-27 17:20:55 +00004429 const char *startBuf = SM->getCharacterData(DeclLoc);
4430 const char *endBuf = startBuf;
4431 // scan backward (from the decl location) for the end of the previous decl.
4432 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4433 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Steve Naroff677ab3a2008-10-27 17:20:55 +00004435 // *startBuf != '^' if we are dealing with a pointer to function that
4436 // may take block argument types (which will be handled below).
4437 if (*startBuf == '^') {
4438 // Replace the '^' with '*', computing a negative offset.
4439 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4440 ReplaceText(DeclLoc, 1, "*", 1);
4441 }
4442 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4443 // Replace the '^' with '*' for arguments.
4444 DeclLoc = ND->getLocation();
4445 startBuf = SM->getCharacterData(DeclLoc);
4446 const char *argListBegin, *argListEnd;
4447 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4448 while (argListBegin < argListEnd) {
4449 if (*argListBegin == '^') {
4450 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4451 ReplaceText(CaretLoc, 1, "*", 1);
4452 }
4453 argListBegin++;
4454 }
4455 }
4456 return;
4457}
4458
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004459
4460/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4461/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4462/// struct Block_byref_id_object *src) {
4463/// _Block_object_assign (&_dest->object, _src->object,
4464/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4465/// [|BLOCK_FIELD_IS_WEAK]) // object
4466/// _Block_object_assign(&_dest->object, _src->object,
4467/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4468/// [|BLOCK_FIELD_IS_WEAK]) // block
4469/// }
4470/// And:
4471/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4472/// _Block_object_dispose(_src->object,
4473/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4474/// [|BLOCK_FIELD_IS_WEAK]) // object
4475/// _Block_object_dispose(_src->object,
4476/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4477/// [|BLOCK_FIELD_IS_WEAK]) // block
4478/// }
4479
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004480std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4481 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004482 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004483 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004484 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004485 CopyDestroyCache.insert(flag);
4486 S = "static void __Block_byref_id_object_copy_";
4487 S += utostr(flag);
4488 S += "(void *dst, void *src) {\n";
4489
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004490 // offset into the object pointer is computed as:
4491 // void * + void* + int + int + void* + void *
4492 unsigned IntSize =
4493 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4494 unsigned VoidPtrSize =
4495 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4496
4497 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4498 S += " _Block_object_assign((char*)dst + ";
4499 S += utostr(offset);
4500 S += ", *(void * *) ((char*)src + ";
4501 S += utostr(offset);
4502 S += "), ";
4503 S += utostr(flag);
4504 S += ");\n}\n";
4505
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004506 S += "static void __Block_byref_id_object_dispose_";
4507 S += utostr(flag);
4508 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004509 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4510 S += utostr(offset);
4511 S += "), ";
4512 S += utostr(flag);
4513 S += ");\n}\n";
4514 return S;
4515}
4516
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004517/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4518/// the declaration into:
4519/// struct __Block_byref_ND {
4520/// void *__isa; // NULL for everything except __weak pointers
4521/// struct __Block_byref_ND *__forwarding;
4522/// int32_t __flags;
4523/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004524/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4525/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004526/// typex ND;
4527/// };
4528///
4529/// It then replaces declaration of ND variable with:
4530/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4531/// __size=sizeof(struct __Block_byref_ND),
4532/// ND=initializer-if-any};
4533///
4534///
4535void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004536 // Insert declaration for the function in which block literal is
4537 // used.
4538 if (CurFunctionDeclToDeclareForBlock)
4539 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004540 int flag = 0;
4541 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004542 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4543 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004544 SourceLocation X = ND->getLocEnd();
4545 X = SM->getInstantiationLoc(X);
4546 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004547 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004548 std::string ByrefType;
4549 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004550 ByrefType += " {\n";
4551 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004552 RewriteByRefString(ByrefType, Name, ND);
4553 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004554 ByrefType += " int __flags;\n";
4555 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004556 // Add void *__Block_byref_id_object_copy;
4557 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004558 QualType Ty = ND->getType();
4559 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4560 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004561 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4562 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004563 }
4564
4565 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004566 ByrefType += " " + Name + ";\n";
4567 ByrefType += "};\n";
4568 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004569 SourceLocation FunLocStart;
4570 if (CurFunctionDef)
4571 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4572 else {
4573 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4574 FunLocStart = CurMethodDef->getLocStart();
4575 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004576 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004577 if (Ty.isObjCGCWeak()) {
4578 flag |= BLOCK_FIELD_IS_WEAK;
4579 isa = 1;
4580 }
4581
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004582 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004583 flag = BLOCK_BYREF_CALLER;
4584 QualType Ty = ND->getType();
4585 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4586 if (Ty->isBlockPointerType())
4587 flag |= BLOCK_FIELD_IS_BLOCK;
4588 else
4589 flag |= BLOCK_FIELD_IS_OBJECT;
4590 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004591 if (!HF.empty())
4592 InsertText(FunLocStart, HF.c_str(), HF.size());
4593 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004594
4595 // struct __Block_byref_ND ND =
4596 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4597 // initializer-if-any};
4598 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004599 unsigned flags = 0;
4600 if (HasCopyAndDispose)
4601 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004602 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004603 ByrefType.clear();
4604 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004605 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004606 ByrefType += " " + Name + " = {(void*)";
4607 ByrefType += utostr(isa);
4608 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004609 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004610 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004611 ByrefType += "sizeof(";
4612 RewriteByRefString(ByrefType, Name, ND);
4613 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004614 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004615 ByrefType += ", __Block_byref_id_object_copy_";
4616 ByrefType += utostr(flag);
4617 ByrefType += ", __Block_byref_id_object_dispose_";
4618 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004619 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004620 ByrefType += "};\n";
4621 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4622 ByrefType.c_str(), ByrefType.size());
4623 }
4624 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004625 SourceLocation startLoc;
4626 Expr *E = ND->getInit();
4627 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4628 startLoc = ECE->getLParenLoc();
4629 else
4630 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004631 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004632 endBuf = SM->getCharacterData(startLoc);
4633
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004634 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004635 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004636 ByrefType += utostr(isa);
4637 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004638 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004639 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004640 ByrefType += "sizeof(";
4641 RewriteByRefString(ByrefType, Name, ND);
4642 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004643 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004644 ByrefType += "__Block_byref_id_object_copy_";
4645 ByrefType += utostr(flag);
4646 ByrefType += ", __Block_byref_id_object_dispose_";
4647 ByrefType += utostr(flag);
4648 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004649 }
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004650 ReplaceText(DeclLoc, endBuf-startBuf,
4651 ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004652
4653 // Complete the newly synthesized compound expression by inserting a right
4654 // curly brace before the end of the declaration.
4655 // FIXME: This approach avoids rewriting the initializer expression. It
4656 // also assumes there is only one declarator. For example, the following
4657 // isn't currently supported by this routine (in general):
4658 //
4659 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4660 //
4661 const char *startBuf = SM->getCharacterData(startLoc);
4662 const char *semiBuf = strchr(startBuf, ';');
4663 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4664 SourceLocation semiLoc =
4665 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4666
4667 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004668 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004669 return;
4670}
4671
Mike Stump11289f42009-09-09 15:08:12 +00004672void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004673 // Add initializers for any closure decl refs.
4674 GetBlockDeclRefExprs(Exp->getBody());
4675 if (BlockDeclRefs.size()) {
4676 // Unique all "by copy" declarations.
4677 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4678 if (!BlockDeclRefs[i]->isByRef())
4679 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4680 // Unique all "by ref" declarations.
4681 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4682 if (BlockDeclRefs[i]->isByRef()) {
4683 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4684 }
4685 // Find any imported blocks...they will need special attention.
4686 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004687 if (BlockDeclRefs[i]->isByRef() ||
4688 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4689 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004690 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004691 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4692 }
4693 }
4694}
4695
Steve Narofff4b992a2008-10-28 20:29:00 +00004696FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4697 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004698 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004699 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004700 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004701 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004702}
4703
Steve Naroffd8907b72008-10-29 18:15:37 +00004704Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004705 Blocks.push_back(Exp);
4706
4707 CollectBlockDeclRefInfo(Exp);
4708 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004709
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004711 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004713 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 // Convert colons to underscores.
4715 std::string::size_type loc = 0;
4716 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4717 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004718 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004719 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004720
Steve Narofff4b992a2008-10-28 20:29:00 +00004721 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004722
Steve Narofff4b992a2008-10-28 20:29:00 +00004723 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4724 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004725
Steve Narofff4b992a2008-10-28 20:29:00 +00004726 // Get a pointer to the function type so we can cast appropriately.
4727 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4728
4729 FunctionDecl *FD;
4730 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004731
Steve Narofff4b992a2008-10-28 20:29:00 +00004732 // Simulate a contructor call...
4733 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004734 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004735
Steve Narofff4b992a2008-10-28 20:29:00 +00004736 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004737
Steve Naroffe2514232008-10-29 21:23:59 +00004738 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004739 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004740 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4741 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004742 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4743 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004744 InitExprs.push_back(castExpr);
4745
Steve Naroff30484702009-12-06 21:14:13 +00004746 // Initialize the block descriptor.
4747 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004748
Steve Naroff30484702009-12-06 21:14:13 +00004749 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4750 &Context->Idents.get(DescData.c_str()),
4751 Context->VoidPtrTy, 0,
4752 VarDecl::Static);
4753 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4754 new (Context) DeclRefExpr(NewVD,
4755 Context->VoidPtrTy, SourceLocation()),
4756 UnaryOperator::AddrOf,
4757 Context->getPointerType(Context->VoidPtrTy),
4758 SourceLocation());
4759 InitExprs.push_back(DescRefExpr);
4760
Steve Narofff4b992a2008-10-28 20:29:00 +00004761 // Add initializers for any closure decl refs.
4762 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004763 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004764 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004765 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004767 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004768 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004769 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004770 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004771 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004772 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004773 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004774 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4775 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004777 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004778 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 }
4782 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004783 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004784 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004785 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004786 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4787 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004788 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004789 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004790 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 }
4792 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004793 if (ImportedBlockDecls.size()) {
4794 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4795 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004796 unsigned IntSize =
4797 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004798 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4799 Context->IntTy, SourceLocation());
4800 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004801 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004802 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4803 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004804 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004805 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004806 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004807 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4808 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 BlockDeclRefs.clear();
4810 BlockByRefDecls.clear();
4811 BlockByCopyDecls.clear();
4812 ImportedBlockDecls.clear();
4813 return NewRep;
4814}
4815
4816//===----------------------------------------------------------------------===//
4817// Function Body / Expression rewriting
4818//===----------------------------------------------------------------------===//
4819
Steve Naroff4588d0f2008-12-04 16:24:46 +00004820// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4821// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4822// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4823// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4824// Since the rewriter isn't capable of rewriting rewritten code, it's important
4825// we get this right.
4826void RewriteObjC::CollectPropertySetters(Stmt *S) {
4827 // Perform a bottom up traversal of all children.
4828 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4829 CI != E; ++CI)
4830 if (*CI)
4831 CollectPropertySetters(*CI);
4832
4833 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4834 if (BinOp->isAssignmentOp()) {
4835 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4836 PropSetters[PRE] = BinOp;
4837 }
4838 }
4839}
4840
Steve Narofff4b992a2008-10-28 20:29:00 +00004841Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004842 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004843 isa<DoStmt>(S) || isa<ForStmt>(S))
4844 Stmts.push_back(S);
4845 else if (isa<ObjCForCollectionStmt>(S)) {
4846 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004847 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004848 }
Mike Stump11289f42009-09-09 15:08:12 +00004849
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 // Perform a bottom up rewrite of all children.
4853 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4854 CI != E; ++CI)
4855 if (*CI) {
4856 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004857 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004858 *CI = newStmt;
4859 }
Mike Stump11289f42009-09-09 15:08:12 +00004860
Steve Narofff4b992a2008-10-28 20:29:00 +00004861 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4862 // Rewrite the block body in place.
4863 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004866 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004867 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004868
Steve Narofff4b992a2008-10-28 20:29:00 +00004869 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4870 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004871 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004872 return blockTranscribed;
4873 }
4874 // Handle specific things.
4875 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4876 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004877
Steve Narofff4b992a2008-10-28 20:29:00 +00004878 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4879 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4880
Steve Naroff4588d0f2008-12-04 16:24:46 +00004881 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4882 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4883 if (BinOp) {
4884 // Because the rewriter doesn't allow us to rewrite rewritten code,
4885 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004886 DisableReplaceStmt = true;
4887 // Save the source range. Even if we disable the replacement, the
4888 // rewritten node will have been inserted into the tree. If the synthesized
4889 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004890 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004891 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4892 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004893 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004894 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004895 //
4896 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4897 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4898 // to see the original expression). Consider this example:
4899 //
4900 // Foo *obj1, *obj2;
4901 //
4902 // obj1.i = [obj2 rrrr];
4903 //
4904 // 'BinOp' for the previous expression looks like:
4905 //
4906 // (BinaryOperator 0x231ccf0 'int' '='
4907 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4908 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4909 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4910 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4911 //
4912 // 'newStmt' represents the rewritten message expression. For example:
4913 //
4914 // (CallExpr 0x231d300 'id':'struct objc_object *'
4915 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4916 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4917 // (CStyleCastExpr 0x231d220 'void *'
4918 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4919 //
4920 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4921 // can be used as the setter argument. ReplaceStmt() will still 'see'
4922 // the original RHS (since we haven't altered BinOp).
4923 //
Mike Stump11289f42009-09-09 15:08:12 +00004924 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004925 // node. As a result, we now leak the original AST nodes.
4926 //
Steve Naroff08628db2008-12-09 12:56:34 +00004927 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004928 } else {
4929 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004930 }
4931 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4933 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004934
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4936 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004937
Steve Narofff4b992a2008-10-28 20:29:00 +00004938 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004939#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004940 // Before we rewrite it, put the original message expression in a comment.
4941 SourceLocation startLoc = MessExpr->getLocStart();
4942 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004943
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 const char *startBuf = SM->getCharacterData(startLoc);
4945 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004946
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 std::string messString;
4948 messString += "// ";
4949 messString.append(startBuf, endBuf-startBuf+1);
4950 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004951
4952 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004953 // InsertText(clang::SourceLocation, char const*, unsigned int).
4954 // InsertText(startLoc, messString.c_str(), messString.size());
4955 // Tried this, but it didn't work either...
4956 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004957#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004958 return RewriteMessageExpr(MessExpr);
4959 }
Mike Stump11289f42009-09-09 15:08:12 +00004960
Steve Narofff4b992a2008-10-28 20:29:00 +00004961 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4962 return RewriteObjCTryStmt(StmtTry);
4963
4964 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4965 return RewriteObjCSynchronizedStmt(StmtTry);
4966
4967 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4968 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004969
Steve Narofff4b992a2008-10-28 20:29:00 +00004970 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4971 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004972
4973 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004974 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004975 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004976 OrigStmtRange.getEnd());
4977 if (BreakStmt *StmtBreakStmt =
4978 dyn_cast<BreakStmt>(S))
4979 return RewriteBreakStmt(StmtBreakStmt);
4980 if (ContinueStmt *StmtContinueStmt =
4981 dyn_cast<ContinueStmt>(S))
4982 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004983
4984 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004985 // and cast exprs.
4986 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4987 // FIXME: What we're doing here is modifying the type-specifier that
4988 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004989 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004990 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4991 // the context of an ObjCForCollectionStmt. For example:
4992 // NSArray *someArray;
4993 // for (id <FooProtocol> index in someArray) ;
4994 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4995 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004996 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004997 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004998
Steve Narofff4b992a2008-10-28 20:29:00 +00004999 // Blocks rewrite rules.
5000 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5001 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005002 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005003 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005004 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005005 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005006 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005007 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005008 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005009 if (VD->hasAttr<BlocksAttr>()) {
5010 static unsigned uniqueByrefDeclCount = 0;
5011 assert(!BlockByRefDeclNo.count(ND) &&
5012 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5013 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005014 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005015 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005016 }
5017 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005018 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005019 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005020 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5022 }
5023 }
5024 }
Mike Stump11289f42009-09-09 15:08:12 +00005025
Steve Narofff4b992a2008-10-28 20:29:00 +00005026 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5027 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005028
5029 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005030 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5031 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005032 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5033 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005034 && "Statement stack mismatch");
5035 Stmts.pop_back();
5036 }
5037 // Handle blocks rewriting.
5038 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5039 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005040 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005041 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005042 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5043 ValueDecl *VD = DRE->getDecl();
5044 if (VD->hasAttr<BlocksAttr>())
5045 return RewriteBlockDeclRefExpr(DRE);
5046 }
5047
Steve Narofff4b992a2008-10-28 20:29:00 +00005048 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005049 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005050 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005051 ReplaceStmt(S, BlockCall);
5052 return BlockCall;
5053 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005054 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005055 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 RewriteCastExpr(CE);
5057 }
5058#if 0
5059 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005060 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005061 // Get the new text.
5062 std::string SStr;
5063 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005064 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005065 const std::string &Str = Buf.str();
5066
5067 printf("CAST = %s\n", &Str[0]);
5068 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5069 delete S;
5070 return Replacement;
5071 }
5072#endif
5073 // Return this stmt unmodified.
5074 return S;
5075}
5076
Steve Naroffe70a52a2009-12-05 15:55:59 +00005077void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5078 for (RecordDecl::field_iterator i = RD->field_begin(),
5079 e = RD->field_end(); i != e; ++i) {
5080 FieldDecl *FD = *i;
5081 if (isTopLevelBlockPointerType(FD->getType()))
5082 RewriteBlockPointerDecl(FD);
5083 if (FD->getType()->isObjCQualifiedIdType() ||
5084 FD->getType()->isObjCQualifiedInterfaceType())
5085 RewriteObjCQualifiedInterfaceTypes(FD);
5086 }
5087}
5088
Steve Narofff4b992a2008-10-28 20:29:00 +00005089/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5090/// main file of the input.
5091void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005093 if (FD->isOverloadedOperator())
5094 return;
Mike Stump11289f42009-09-09 15:08:12 +00005095
Steve Narofff4b992a2008-10-28 20:29:00 +00005096 // Since function prototypes don't have ParmDecl's, we check the function
5097 // prototype. This enables us to rewrite function declarations and
5098 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005099 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005100
Sebastian Redla7b98a72009-04-26 20:35:05 +00005101 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005102 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005103 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005104 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005105 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005106 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005107 Body =
5108 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5109 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005110 CurrentBody = 0;
5111 if (PropParentMap) {
5112 delete PropParentMap;
5113 PropParentMap = 0;
5114 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 // This synthesizes and inserts the block "impl" struct, invoke function,
5116 // and any copy/dispose helper functions.
5117 InsertBlockLiteralsWithinFunction(FD);
5118 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005119 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005120 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005121 return;
5122 }
5123 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005124 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005125 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005126 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005127 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005128 Body =
5129 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5130 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005131 CurrentBody = 0;
5132 if (PropParentMap) {
5133 delete PropParentMap;
5134 PropParentMap = 0;
5135 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 InsertBlockLiteralsWithinMethod(MD);
5137 CurMethodDef = 0;
5138 }
5139 }
5140 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5141 ClassImplementation.push_back(CI);
5142 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5143 CategoryImplementation.push_back(CI);
5144 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5145 RewriteForwardClassDecl(CD);
5146 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5147 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005148 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005149 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005150 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 CheckFunctionPointerDecl(VD->getType(), VD);
5152 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005153 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005154 RewriteCastExpr(CE);
5155 }
5156 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005157 } else if (VD->getType()->isRecordType()) {
5158 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5159 if (RD->isDefinition())
5160 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005161 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005162 if (VD->getInit()) {
5163 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005164 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005165 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005166 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005167 CurrentBody = 0;
5168 if (PropParentMap) {
5169 delete PropParentMap;
5170 PropParentMap = 0;
5171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005173 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005174 GlobalVarDecl = 0;
5175
5176 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005177 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005178 RewriteCastExpr(CE);
5179 }
5180 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005181 return;
5182 }
5183 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005184 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005185 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005186 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005187 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005188 else if (TD->getUnderlyingType()->isRecordType()) {
5189 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5190 if (RD->isDefinition())
5191 RewriteRecordBody(RD);
5192 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005193 return;
5194 }
5195 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005196 if (RD->isDefinition())
5197 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005198 return;
5199 }
5200 // Nothing yet.
5201}
5202
Chris Lattnercf169832009-03-28 04:11:33 +00005203void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005204 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005205
Steve Narofff4b992a2008-10-28 20:29:00 +00005206 // Rewrite tabs if we care.
5207 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005208
Steve Narofff4b992a2008-10-28 20:29:00 +00005209 if (Diags.hasErrorOccurred())
5210 return;
Mike Stump11289f42009-09-09 15:08:12 +00005211
Steve Narofff4b992a2008-10-28 20:29:00 +00005212 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005213
Steve Naroffd9803712009-04-29 16:37:50 +00005214 // Here's a great place to add any extra declarations that may be needed.
5215 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005216 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005217 E = ProtocolExprDecls.end(); I != E; ++I)
5218 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5219
Mike Stump11289f42009-09-09 15:08:12 +00005220 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005221 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005222 if (ClassImplementation.size() || CategoryImplementation.size())
5223 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005224
Steve Narofff4b992a2008-10-28 20:29:00 +00005225 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5226 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005227 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005228 Rewrite.getRewriteBufferFor(MainFileID)) {
5229 //printf("Changed:\n");
5230 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5231 } else {
5232 fprintf(stderr, "No changes\n");
5233 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005234
Steve Naroffd9803712009-04-29 16:37:50 +00005235 if (ClassImplementation.size() || CategoryImplementation.size() ||
5236 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005237 // Rewrite Objective-c meta data*
5238 std::string ResultStr;
5239 SynthesizeMetaDataIntoBuffer(ResultStr);
5240 // Emit metadata.
5241 *OutFile << ResultStr;
5242 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005243 OutFile->flush();
5244}
5245