blob: 656d61b133df0a74bfcfbe6982c9d9044511a63e [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"
Chris Lattnere99c8322007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000030
Chris Lattnere99c8322007-10-11 00:43:27 +000031namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner0bd1c972007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattnerc6d91c02007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000040 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000045
Ted Kremenek1b0ea822008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump11289f42009-09-09 15:08:12 +000056
Steve Naroffce8e8862008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000058
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000069
Steve Naroffa397efd2007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000073
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +000076
Steve Naroff7fa2f042007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +000081
Steve Naroffd9803712009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +000084
Fariborz Jahanian159ee392008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +000087
Steve Narofff9e7c902008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Naroff00a31762008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +000099
Steve Naroff677ab3a2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff4588d0f2008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Naroff22216db2008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000117
Steve Naroff677ab3a2008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000120
Steve Naroff08628db2008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000122
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000124 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattner3c799d72007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattnercf169832009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattner2e0d2602008-01-31 19:37:57 +0000142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000147
Steve Naroff08628db2008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff22216db2008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000160 }
Steve Naroff08628db2008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Naroff00a31762008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner1780a852008-01-31 19:42:41 +0000195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner9cc55f52008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner9cc55f52008-01-31 19:51:04 +0000203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000205
Chris Lattner9cc55f52008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner9cc55f52008-01-31 19:51:04 +0000214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner3c799d72007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Steve Naroff1042ff32008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner69534692007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000253 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000258 void WarnAboutReturnGotoStmts(Stmt *S);
259 void HasReturnStmts(Stmt *S, bool &hasReturns);
260 void RewriteTryReturnStmts(Stmt *S);
261 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000263 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000264 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
265 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
266 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000267 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
268 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000269 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000270 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000271 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000272 Stmt *RewriteBreakStmt(BreakStmt *S);
273 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000274 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000276 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000278 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000279 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000280 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000281 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000282 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000283 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000284 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner3c799d72007-10-24 17:06:59 +0000286 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000289
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000291 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000293 template<typename MethodIterator>
294 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
295 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000296 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000297 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000298 const char *ClassName,
299 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Steve Naroffd9803712009-04-29 16:37:50 +0000301 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
305 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000306 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000307 const char *ClassName,
308 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000309 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000310 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000311 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
312 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000313 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000314 void RewriteImplementations();
315 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Steve Naroff677ab3a2008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Steve Naroff677ab3a2008-10-27 17:20:55 +0000321 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
322 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000323
324 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000325 void RewriteBlockCall(CallExpr *Exp);
326 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000327 void RewriteByRefVar(VarDecl *VD);
Steve Naroffd9803712009-04-29 16:37:50 +0000328 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000329 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000330
331 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000332 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000333 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000334 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000335 std::string SynthesizeBlockImpl(BlockExpr *CE,
336 std::string Tag, std::string Desc);
337 std::string SynthesizeBlockDescriptor(std::string DescTag,
338 std::string ImplTag,
339 int i, const char *funcName,
340 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000341 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000342 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
343 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000344 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000345
Steve Naroff677ab3a2008-10-27 17:20:55 +0000346 void CollectBlockDeclRefInfo(BlockExpr *Exp);
347 void GetBlockCallExprs(Stmt *S);
348 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 // We avoid calling Type::isBlockPointerType(), since it operates on the
351 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000352 bool isTopLevelBlockPointerType(QualType T) {
353 return isa<BlockPointerType>(T);
354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 // FIXME: This predicate seems like it would be useful to add to ASTContext.
357 bool isObjCType(QualType T) {
358 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
359 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
364 OCT == Context->getCanonicalType(Context->getObjCClassType()))
365 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000366
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000367 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000368 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000369 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000370 return true;
371 }
372 return false;
373 }
374 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000375 void GetExtentOfArgList(const char *Name, const char *&LParen,
376 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000377 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000378
Steve Narofff4b992a2008-10-28 20:29:00 +0000379 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000380 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Steve Naroffd9803712009-04-29 16:37:50 +0000382 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000383 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000384 if (From[i] == '"')
385 To += "\\\"";
386 else
387 To += From[i];
388 }
389 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000390 };
391}
392
Mike Stump11289f42009-09-09 15:08:12 +0000393void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
394 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000395 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000396 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000398 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000399 // All the args are checked/rewritten. Don't call twice!
400 RewriteBlockPointerDecl(D);
401 break;
402 }
403 }
404}
405
406void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000407 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000408 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000409 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000410}
411
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000412static bool IsHeaderFile(const std::string &Filename) {
413 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000414
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000415 if (DotPos == std::string::npos) {
416 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000417 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000420 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
421 // C header: .h
422 // C++ header: .hh or .H;
423 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000424}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000425
Eli Friedman94cf21e2009-05-18 22:20:00 +0000426RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000427 Diagnostic &D, const LangOptions &LOpts,
428 bool silenceMacroWarn)
429 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
430 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000431 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000432 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000433 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000434 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000435 "rewriter doesn't support user-specified control flow semantics "
436 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000437}
438
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000439ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
440 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000441 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000442 const LangOptions &LOpts,
443 bool SilenceRewriteMacroWarning) {
444 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000445}
Chris Lattnere99c8322007-10-11 00:43:27 +0000446
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000447void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000448 Context = &context;
449 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000450 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000451 MsgSendFunctionDecl = 0;
452 MsgSendSuperFunctionDecl = 0;
453 MsgSendStretFunctionDecl = 0;
454 MsgSendSuperStretFunctionDecl = 0;
455 MsgSendFpretFunctionDecl = 0;
456 GetClassFunctionDecl = 0;
457 GetMetaClassFunctionDecl = 0;
458 SelGetUidFunctionDecl = 0;
459 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000460 ConstantStringClassReference = 0;
461 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000462 CurMethodDef = 0;
463 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000464 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000465 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000466 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000467 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000468 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000469 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000470 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000471 PropParentMap = 0;
472 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000473 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattner187f6262008-01-31 19:38:44 +0000475 // Get the ID and start/end of the main file.
476 MainFileID = SM->getMainFileID();
477 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
478 MainFileStart = MainBuf->getBufferStart();
479 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner184e65d2009-04-14 23:22:57 +0000481 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000482
Chris Lattner187f6262008-01-31 19:38:44 +0000483 // declaring objc_selector outside the parameter list removes a silly
484 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000485 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000486 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000487 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000488 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000489 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000490 if (LangOpts.Microsoft) {
491 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000492 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
493 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000494 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000495 }
Steve Naroff00a31762008-03-27 22:29:16 +0000496 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000497 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
498 Preamble += "typedef struct objc_object Protocol;\n";
499 Preamble += "#define _REWRITER_typedef_Protocol\n";
500 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000501 if (LangOpts.Microsoft) {
502 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
503 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
504 } else
505 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
506 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000507 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000509 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000511 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000512 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000513 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000514 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000515 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000516 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000517 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000518 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000519 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000520 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
521 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
522 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
523 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
524 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000525 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000526 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
528 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
529 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000530 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
531 Preamble += "struct __objcFastEnumerationState {\n\t";
532 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000533 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "unsigned long *mutationsPtr;\n\t";
535 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000537 Preamble += "#define __FASTENUMERATIONSTATE\n";
538 Preamble += "#endif\n";
539 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
540 Preamble += "struct __NSConstantStringImpl {\n";
541 Preamble += " int *isa;\n";
542 Preamble += " int flags;\n";
543 Preamble += " char *str;\n";
544 Preamble += " long length;\n";
545 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000546 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
547 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
548 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000549 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000550 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
552 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000553 // Blocks preamble.
554 Preamble += "#ifndef BLOCK_IMPL\n";
555 Preamble += "#define BLOCK_IMPL\n";
556 Preamble += "struct __block_impl {\n";
557 Preamble += " void *isa;\n";
558 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000559 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000560 Preamble += " void *FuncPtr;\n";
561 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000562 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000563 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000564 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
565 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
566 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
567 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
568 Preamble += "#else\n";
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +0000569 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_assign(void *, const void *, const int);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000571 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
572 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
573 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000574 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000575 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000576 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
577 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000578 Preamble += "#define __attribute__(X)\n";
579 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000580 else
581 Preamble += "#define __block\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000582}
583
584
Chris Lattner3c799d72007-10-24 17:06:59 +0000585//===----------------------------------------------------------------------===//
586// Top Level Driver Code
587//===----------------------------------------------------------------------===//
588
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000589void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000590 // Two cases: either the decl could be in the main file, or it could be in a
591 // #included file. If the former, rewrite it now. If the later, check to see
592 // if we rewrote the #include/#import.
593 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000594 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattner0bd1c972007-10-16 21:07:07 +0000596 // If this is for a builtin, ignore it.
597 if (Loc.isInvalid()) return;
598
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000599 // Look for built-in declarations that we need to refer during the rewrite.
600 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000601 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000602 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000603 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000604 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000605 ConstantStringClassReference = FVD;
606 return;
607 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000608 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000609 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000610 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000611 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000612 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000613 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000614 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000615 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000616 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000617 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
618 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000619 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
620 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000621 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000622 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000623 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000624 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000625 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000626 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000627}
628
Chris Lattner3c799d72007-10-24 17:06:59 +0000629//===----------------------------------------------------------------------===//
630// Syntactic (non-AST) Rewriting Code
631//===----------------------------------------------------------------------===//
632
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000633void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000634 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000635 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
636 const char *MainBufStart = MainBuf.first;
637 const char *MainBufEnd = MainBuf.second;
638 size_t ImportLen = strlen("import");
639 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000640
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000641 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000642 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
643 if (*BufPtr == '#') {
644 if (++BufPtr == MainBufEnd)
645 return;
646 while (*BufPtr == ' ' || *BufPtr == '\t')
647 if (++BufPtr == MainBufEnd)
648 return;
649 if (!strncmp(BufPtr, "import", ImportLen)) {
650 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000651 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000652 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000653 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000654 BufPtr += ImportLen;
655 }
656 }
657 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000658}
659
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000660void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000661 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
662 const char *MainBufStart = MainBuf.first;
663 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattner3c799d72007-10-24 17:06:59 +0000665 // Loop over the whole file, looking for tabs.
666 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
667 if (*BufPtr != '\t')
668 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattner3c799d72007-10-24 17:06:59 +0000670 // Okay, we found a tab. This tab will turn into at least one character,
671 // but it depends on which 'virtual column' it is in. Compute that now.
672 unsigned VCol = 0;
673 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
674 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
675 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattner3c799d72007-10-24 17:06:59 +0000677 // Okay, now that we know the virtual column, we know how many spaces to
678 // insert. We assume 8-character tab-stops.
679 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner3c799d72007-10-24 17:06:59 +0000681 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000682 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
683 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattner3c799d72007-10-24 17:06:59 +0000685 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000686 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000687 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000688}
689
Steve Naroff9af94912008-12-02 15:48:25 +0000690static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
691 ObjCIvarDecl *OID) {
692 std::string S;
693 S = "((struct ";
694 S += ClassDecl->getIdentifier()->getName();
695 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000696 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000697 return S;
698}
699
Steve Naroffc038b3a2008-12-02 17:36:43 +0000700void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
701 ObjCImplementationDecl *IMD,
702 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000703 SourceLocation startLoc = PID->getLocStart();
704 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000705 const char *startBuf = SM->getCharacterData(startLoc);
706 assert((*startBuf == '@') && "bogus @synthesize location");
707 const char *semiBuf = strchr(startBuf, ';');
708 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000709 SourceLocation onePastSemiLoc =
710 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000711
712 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
713 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000714
Steve Naroff9af94912008-12-02 15:48:25 +0000715 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000716 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000717 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000718 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000719
Steve Naroff003d00e2008-12-02 16:05:55 +0000720 if (!OID)
721 return;
Mike Stump11289f42009-09-09 15:08:12 +0000722
Steve Naroff003d00e2008-12-02 16:05:55 +0000723 std::string Getr;
724 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
725 Getr += "{ ";
726 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000727 // FIXME: deal with code generation implications for various property
728 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000729 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000730 Getr += "return " + getIvarAccessString(ClassDecl, OID);
731 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000732 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000733 if (PD->isReadOnly())
734 return;
Mike Stump11289f42009-09-09 15:08:12 +0000735
Steve Naroff9af94912008-12-02 15:48:25 +0000736 // Generate the 'setter' function.
737 std::string Setr;
738 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000739 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000740 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000741 // FIXME: deal with code generation implications for various property
742 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000743 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000744 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000745 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000746 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000747 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000748}
Chris Lattner16a0de42007-10-11 18:38:32 +0000749
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000750void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000751 // Get the start location and compute the semi location.
752 SourceLocation startLoc = ClassDecl->getLocation();
753 const char *startBuf = SM->getCharacterData(startLoc);
754 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner3c799d72007-10-24 17:06:59 +0000756 // Translate to typedef's that forward reference structs with the same name
757 // as the class. As a convenience, we include the original declaration
758 // as a comment.
759 std::string typedefString;
760 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000761 typedefString.append(startBuf, semiPtr-startBuf+1);
762 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000763 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
764 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000765 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000766 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000767 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000768 typedefString += "\n";
769 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000770 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000771 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000772 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000773 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000774 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Steve Naroff574440f2007-10-24 22:48:43 +0000777 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000778 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000779 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000780}
781
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000782void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000783 SourceLocation LocStart = Method->getLocStart();
784 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattner88ea93e2009-02-04 01:06:56 +0000786 if (SM->getInstantiationLineNumber(LocEnd) >
787 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000788 InsertText(LocStart, "#if 0\n", 6);
789 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000790 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000791 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000792 }
793}
794
Mike Stump11289f42009-09-09 15:08:12 +0000795void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000796 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000797
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000798 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000800 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000801}
802
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000803void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000804 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000805
Steve Naroff5448cf62007-10-30 13:30:57 +0000806 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000807 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000808
809 for (ObjCCategoryDecl::instmeth_iterator
810 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000811 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000812 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000813 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000814 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000815 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000816 RewriteMethodDeclaration(*I);
817
Steve Naroff5448cf62007-10-30 13:30:57 +0000818 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000819 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000820}
821
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000822void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000823 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000824
Steve Narofff921385f2007-10-30 16:42:30 +0000825 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000826
Steve Narofff921385f2007-10-30 16:42:30 +0000827 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000828 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000829
830 for (ObjCProtocolDecl::instmeth_iterator
831 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000832 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000833 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000834 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000835 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000836 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000837 RewriteMethodDeclaration(*I);
838
Steve Narofff921385f2007-10-30 16:42:30 +0000839 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000840 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000841 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000842
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000843 // Must comment out @optional/@required
844 const char *startBuf = SM->getCharacterData(LocStart);
845 const char *endBuf = SM->getCharacterData(LocEnd);
846 for (const char *p = startBuf; p < endBuf; p++) {
847 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
848 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000849 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000850 ReplaceText(OptionalLoc, strlen("@optional"),
851 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000852
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000853 }
854 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
855 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000856 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000857 ReplaceText(OptionalLoc, strlen("@required"),
858 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000859
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000860 }
861 }
Steve Narofff921385f2007-10-30 16:42:30 +0000862}
863
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000864void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000865 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000866 if (LocStart.isInvalid())
867 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000868 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000869 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000870}
871
Mike Stump11289f42009-09-09 15:08:12 +0000872void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000873 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000874 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000875 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000876 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000877 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000878 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000879 else if (OMD->getResultType()->isFunctionPointerType() ||
880 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000881 // needs special handling, since pointer-to-functions have special
882 // syntax (where a decaration models use).
883 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000884 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000885 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000886 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000887 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000888 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000889 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000890 ResultStr += FPRetType->getResultType().getAsString();
891 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000892 }
893 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000894 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000895 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000896
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000897 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000898 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregorffca3a22009-01-09 17:18:27 +0000900 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000901 NameStr += "_I_";
902 else
903 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000904
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000905 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000906 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000907
908 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000909 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000910 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000911 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000912 }
Mike Stump11289f42009-09-09 15:08:12 +0000913 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000914 {
915 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000916 int len = selString.size();
917 for (int i = 0; i < len; i++)
918 if (selString[i] == ':')
919 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000920 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000921 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000922 // Remember this name for metadata emission
923 MethodInternalNames[OMD] = NameStr;
924 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000925
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000926 // Rewrite arguments
927 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000928
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000929 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000930 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000931 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000932 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000933 if (!LangOpts.Microsoft) {
934 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
935 ResultStr += "struct ";
936 }
937 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000938 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000939 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000940 }
941 else
Steve Naroffd9803712009-04-29 16:37:50 +0000942 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000943
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000944 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000945 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000946 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000947
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000948 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000949 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
950 E = OMD->param_end(); PI != E; ++PI) {
951 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000952 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000953 if (PDecl->getType()->isObjCQualifiedIdType()) {
954 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000955 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000956 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000957 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000958 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000959 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000961 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
962 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000963 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000964 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000965 ResultStr += Name;
966 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000967 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000968 if (OMD->isVariadic())
969 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000970 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000971
Steve Naroffb067bbd2008-07-16 14:40:40 +0000972 if (FPRetType) {
973 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000974
Steve Naroffb067bbd2008-07-16 14:40:40 +0000975 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000976 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000977 ResultStr += "(";
978 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
979 if (i) ResultStr += ", ";
980 std::string ParamStr = FT->getArgType(i).getAsString();
981 ResultStr += ParamStr;
982 }
983 if (FT->isVariadic()) {
984 if (FT->getNumArgs()) ResultStr += ", ";
985 ResultStr += "...";
986 }
987 ResultStr += ")";
988 } else {
989 ResultStr += "()";
990 }
991 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000993void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000994 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
995 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000996
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000997 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000998 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000999 else
Chris Lattner1780a852008-01-31 19:42:41 +00001000 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001001
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001002 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001003 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1004 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001005 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001006 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001007 ObjCMethodDecl *OMD = *I;
1008 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001009 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001010 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001011
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 const char *startBuf = SM->getCharacterData(LocStart);
1013 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001014 ReplaceText(LocStart, endBuf-startBuf,
1015 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001016 }
Mike Stump11289f42009-09-09 15:08:12 +00001017
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001018 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001019 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1020 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001021 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001022 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001023 ObjCMethodDecl *OMD = *I;
1024 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001025 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001026 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001028 const char *startBuf = SM->getCharacterData(LocStart);
1029 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001030 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001031 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001032 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001033 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001034 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001035 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001036 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001037 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001038 }
1039
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001040 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001041 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001042 else
Mike Stump11289f42009-09-09 15:08:12 +00001043 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044}
1045
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001046void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001047 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001048 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001049 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001050 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001051 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001052 ResultStr += "\n";
1053 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001054 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001055 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001056 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001057 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001058 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001059 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001060 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001061 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001062 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001063
1064 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001065 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001066 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001067 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001068 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001069 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001070 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001071 for (ObjCInterfaceDecl::classmeth_iterator
1072 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001073 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001074 RewriteMethodDeclaration(*I);
1075
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001076 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001077 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001078}
1079
Steve Naroff08628db2008-12-09 12:56:34 +00001080Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1081 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001082 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1083 // This allows us to reuse all the fun and games in SynthMessageExpr().
1084 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1085 ObjCMessageExpr *MsgExpr;
1086 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1087 llvm::SmallVector<Expr *, 1> ExprVec;
1088 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001089
Steve Naroff1042ff32008-12-08 16:43:47 +00001090 Stmt *Receiver = PropRefExpr->getBase();
1091 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1092 if (PRE && PropGetters[PRE]) {
1093 // This allows us to handle chain/nested property getters.
1094 Receiver = PropGetters[PRE];
1095 }
Mike Stump11289f42009-09-09 15:08:12 +00001096 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1097 PDecl->getSetterName(), PDecl->getType(),
1098 PDecl->getSetterMethodDecl(),
1099 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001100 &ExprVec[0], 1);
1101 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001102
Steve Naroff4588d0f2008-12-04 16:24:46 +00001103 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001104 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001105 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001106 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1107 // to things that stay around.
1108 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001109 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001110}
1111
Steve Naroff4588d0f2008-12-04 16:24:46 +00001112Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001113 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1114 // This allows us to reuse all the fun and games in SynthMessageExpr().
1115 ObjCMessageExpr *MsgExpr;
1116 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001117
Steve Naroff1042ff32008-12-08 16:43:47 +00001118 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001119
Steve Naroff1042ff32008-12-08 16:43:47 +00001120 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1121 if (PRE && PropGetters[PRE]) {
1122 // This allows us to handle chain/nested property getters.
1123 Receiver = PropGetters[PRE];
1124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1126 PDecl->getGetterName(), PDecl->getType(),
1127 PDecl->getGetterMethodDecl(),
1128 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001129 0, 0);
1130
Steve Naroff22216db2008-12-04 23:50:32 +00001131 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001132
1133 if (!PropParentMap)
1134 PropParentMap = new ParentMap(CurrentBody);
1135
1136 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1137 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1138 // We stash away the ReplacingStmt since actually doing the
1139 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1140 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001141 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1142 // to things that stay around.
1143 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001144 return PropRefExpr; // return the original...
1145 } else {
1146 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001147 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001148 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1149 // to things that stay around.
1150 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001151 return ReplacingStmt;
1152 }
Steve Narofff326f402008-12-03 00:56:33 +00001153}
1154
Mike Stump11289f42009-09-09 15:08:12 +00001155Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001156 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001157 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001158 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001159 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001160 ObjCInterfaceType *iFaceDecl =
1161 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001162 // lookup which class implements the instance variable.
1163 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001164 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001165 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001166 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001167
Steve Naroffb1c02372008-05-08 17:52:16 +00001168 // Synthesize an explicit cast to gain access to the ivar.
1169 std::string RecName = clsDeclared->getIdentifier()->getName();
1170 RecName += "_IMPL";
1171 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001172 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001173 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001174 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1175 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001176 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001177 CastExpr::CK_Unknown,
1178 IV->getBase(),
1179 castT,SourceLocation(),
1180 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001181 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001182 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1183 IV->getBase()->getLocEnd(),
1184 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001185 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001186 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001187 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1188 IV->getLocation(),
1189 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001190 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001191 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001192 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001195 ReplaceStmt(IV->getBase(), PE);
1196 // Cannot delete IV->getBase(), since PE points to it.
1197 // Replace the old base with the cast. This is important when doing
1198 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001199 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001200 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001201 }
Steve Naroff24840f62008-04-18 21:55:08 +00001202 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001203 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001204
Steve Naroff29ce4e52008-05-06 23:20:07 +00001205 // Explicit ivar refs need to have a cast inserted.
1206 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001207 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001208 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001209 // lookup which class implements the instance variable.
1210 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001211 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001212 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001213 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001214
Steve Naroff29ce4e52008-05-06 23:20:07 +00001215 // Synthesize an explicit cast to gain access to the ivar.
1216 std::string RecName = clsDeclared->getIdentifier()->getName();
1217 RecName += "_IMPL";
1218 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001219 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001220 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001221 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1222 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001223 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001224 CastExpr::CK_Unknown,
1225 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001226 castT, SourceLocation(),
1227 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001228 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001229 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001230 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001231 ReplaceStmt(IV->getBase(), PE);
1232 // Cannot delete IV->getBase(), since PE points to it.
1233 // Replace the old base with the cast. This is important when doing
1234 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001235 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001236 return IV;
1237 }
Steve Naroff05caa482007-11-15 11:33:00 +00001238 }
Steve Naroff24840f62008-04-18 21:55:08 +00001239 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001240}
1241
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001242/// SynthCountByEnumWithState - To print:
1243/// ((unsigned int (*)
1244/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001245/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001246/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001247/// "countByEnumeratingWithState:objects:count:"),
1248/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001249/// (id *)items, (unsigned int)16)
1250///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001251void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001252 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1253 "id *, unsigned int))(void *)objc_msgSend)";
1254 buf += "\n\t\t";
1255 buf += "((id)l_collection,\n\t\t";
1256 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1257 buf += "\n\t\t";
1258 buf += "&enumState, "
1259 "(id *)items, (unsigned int)16)";
1260}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001261
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001262/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1263/// statement to exit to its outer synthesized loop.
1264///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001265Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001266 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1267 return S;
1268 // replace break with goto __break_label
1269 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001271 SourceLocation startLoc = S->getLocStart();
1272 buf = "goto __break_label_";
1273 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001274 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001275
1276 return 0;
1277}
1278
1279/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1280/// statement to continue with its inner synthesized loop.
1281///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001282Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001283 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1284 return S;
1285 // replace continue with goto __continue_label
1286 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001287
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001288 SourceLocation startLoc = S->getLocStart();
1289 buf = "goto __continue_label_";
1290 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001291 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001292
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001293 return 0;
1294}
1295
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001296/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001297/// It rewrites:
1298/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001299
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001300/// Into:
1301/// {
Mike Stump11289f42009-09-09 15:08:12 +00001302/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001303/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001304/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001305/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001306/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001307/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001308/// if (limit) {
1309/// unsigned long startMutations = *enumState.mutationsPtr;
1310/// do {
1311/// unsigned long counter = 0;
1312/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001313/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001314/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001315/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001316/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001317/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001318/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001319/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001320/// objects:items count:16]);
1321/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001322/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001323/// }
1324/// else
1325/// elem = nil;
1326/// }
1327///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001328Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001329 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001330 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001331 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001332 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001333 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001334 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001335
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001336 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001337 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001338 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001339 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001340 std::string buf;
1341 buf = "\n{\n\t";
1342 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1343 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001344 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001345 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001346 if (ElementType->isObjCQualifiedIdType() ||
1347 ElementType->isObjCQualifiedInterfaceType())
1348 // Simply use 'id' for all qualified types.
1349 elementTypeAsString = "id";
1350 else
1351 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001352 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001353 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001354 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001355 buf += elementName;
1356 buf += ";\n\t";
1357 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001358 else {
1359 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001360 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001361 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1362 if (VD->getType()->isObjCQualifiedIdType() ||
1363 VD->getType()->isObjCQualifiedInterfaceType())
1364 // Simply use 'id' for all qualified types.
1365 elementTypeAsString = "id";
1366 else
1367 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001368 }
Mike Stump11289f42009-09-09 15:08:12 +00001369
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001370 // struct __objcFastEnumerationState enumState = { 0 };
1371 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1372 // id items[16];
1373 buf += "id items[16];\n\t";
1374 // id l_collection = (id)
1375 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001376 // Find start location of 'collection' the hard way!
1377 const char *startCollectionBuf = startBuf;
1378 startCollectionBuf += 3; // skip 'for'
1379 startCollectionBuf = strchr(startCollectionBuf, '(');
1380 startCollectionBuf++; // skip '('
1381 // find 'in' and skip it.
1382 while (*startCollectionBuf != ' ' ||
1383 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1384 (*(startCollectionBuf+3) != ' ' &&
1385 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1386 startCollectionBuf++;
1387 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001388
1389 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001390 ReplaceText(startLoc, startCollectionBuf - startBuf,
1391 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001392 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001393 SourceLocation rightParenLoc = S->getRParenLoc();
1394 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1395 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001397
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001398 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1399 // objects:items count:16];
1400 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001401 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402 // ((unsigned int (*)
1403 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001404 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001405 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001406 // "countByEnumeratingWithState:objects:count:"),
1407 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001408 // (id *)items, (unsigned int)16);
1409 buf += "unsigned long limit =\n\t\t";
1410 SynthCountByEnumWithState(buf);
1411 buf += ";\n\t";
1412 /// if (limit) {
1413 /// unsigned long startMutations = *enumState.mutationsPtr;
1414 /// do {
1415 /// unsigned long counter = 0;
1416 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001417 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001418 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001419 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001420 buf += "if (limit) {\n\t";
1421 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1422 buf += "do {\n\t\t";
1423 buf += "unsigned long counter = 0;\n\t\t";
1424 buf += "do {\n\t\t\t";
1425 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1426 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1427 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001428 buf += " = (";
1429 buf += elementTypeAsString;
1430 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001431 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001432 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001433
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001434 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001435 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001436 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001437 /// objects:items count:16]);
1438 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001439 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001440 /// }
1441 /// else
1442 /// elem = nil;
1443 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001444 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001445 buf = ";\n\t";
1446 buf += "__continue_label_";
1447 buf += utostr(ObjCBcLabelNo.back());
1448 buf += ": ;";
1449 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001450 buf += "} while (counter < limit);\n\t";
1451 buf += "} while (limit = ";
1452 SynthCountByEnumWithState(buf);
1453 buf += ");\n\t";
1454 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001455 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001456 buf += "__break_label_";
1457 buf += utostr(ObjCBcLabelNo.back());
1458 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001459 buf += "}\n\t";
1460 buf += "else\n\t\t";
1461 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001462 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001464
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001465 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001466 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001467 if (isa<CompoundStmt>(S->getBody())) {
1468 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1469 InsertText(endBodyLoc, buf.c_str(), buf.size());
1470 } else {
1471 /* Need to treat single statements specially. For example:
1472 *
1473 * for (A *a in b) if (stuff()) break;
1474 * for (A *a in b) xxxyy;
1475 *
1476 * The following code simply scans ahead to the semi to find the actual end.
1477 */
1478 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1479 const char *semiBuf = strchr(stmtBuf, ';');
1480 assert(semiBuf && "Can't find ';'");
1481 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1482 InsertText(endBodyLoc, buf.c_str(), buf.size());
1483 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001484 Stmts.pop_back();
1485 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001486 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001487}
1488
Mike Stump11289f42009-09-09 15:08:12 +00001489/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001490/// This routine rewrites @synchronized(expr) stmt;
1491/// into:
1492/// objc_sync_enter(expr);
1493/// @try stmt @finally { objc_sync_exit(expr); }
1494///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001495Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001496 // Get the start location and compute the semi location.
1497 SourceLocation startLoc = S->getLocStart();
1498 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001500 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001501
1502 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001503 buf = "objc_sync_enter((id)";
1504 const char *lparenBuf = startBuf;
1505 while (*lparenBuf != '(') lparenBuf++;
1506 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001507 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1508 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001509 // been rewritten! (which implies the SourceLocation's are invalid).
1510 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001511 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001512 while (*endBuf != ')') endBuf--;
1513 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001514 buf = ");\n";
1515 // declare a new scope with two variables, _stack and _rethrow.
1516 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1517 buf += "int buf[18/*32-bit i386*/];\n";
1518 buf += "char *pointers[4];} _stack;\n";
1519 buf += "id volatile _rethrow = 0;\n";
1520 buf += "objc_exception_try_enter(&_stack);\n";
1521 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001522 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001523 startLoc = S->getSynchBody()->getLocEnd();
1524 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001525
Steve Naroffad7013b2008-08-19 13:04:19 +00001526 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001527 SourceLocation lastCurlyLoc = startLoc;
1528 buf = "}\nelse {\n";
1529 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001530 buf += "}\n";
1531 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001532 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001533
1534 std::string syncBuf;
1535 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001536 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001537 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001538 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001539 Context->getObjCIdType(),
1540 SourceLocation(),
1541 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001542 std::string syncExprBufS;
1543 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001544 syncExpr->printPretty(syncExprBuf, *Context, 0,
1545 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001546 syncBuf += syncExprBuf.str();
1547 syncBuf += ");";
1548
1549 buf += syncBuf;
1550 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001551 buf += "}\n";
1552 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001553
Chris Lattner9cc55f52008-01-31 19:51:04 +00001554 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001555
1556 bool hasReturns = false;
1557 HasReturnStmts(S->getSynchBody(), hasReturns);
1558 if (hasReturns)
1559 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1560
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001561 return 0;
1562}
1563
Steve Naroffec60b432009-12-05 21:43:12 +00001564void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1565{
Steve Naroff6d6da252008-12-05 17:03:39 +00001566 // Perform a bottom up traversal of all children.
1567 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1568 CI != E; ++CI)
1569 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001570 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001571
Steve Naroffec60b432009-12-05 21:43:12 +00001572 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001573 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001574 TryFinallyContainsReturnDiag);
1575 }
1576 return;
1577}
1578
Steve Naroffec60b432009-12-05 21:43:12 +00001579void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1580{
1581 // Perform a bottom up traversal of all children.
1582 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1583 CI != E; ++CI)
1584 if (*CI)
1585 HasReturnStmts(*CI, hasReturns);
1586
1587 if (isa<ReturnStmt>(S))
1588 hasReturns = true;
1589 return;
1590}
1591
1592void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1593 // Perform a bottom up traversal of all children.
1594 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1595 CI != E; ++CI)
1596 if (*CI) {
1597 RewriteTryReturnStmts(*CI);
1598 }
1599 if (isa<ReturnStmt>(S)) {
1600 SourceLocation startLoc = S->getLocStart();
1601 const char *startBuf = SM->getCharacterData(startLoc);
1602
1603 const char *semiBuf = strchr(startBuf, ';');
1604 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1605 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1606
1607 std::string buf;
1608 buf = "{ objc_exception_try_exit(&_stack); return";
1609
1610 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1611 InsertText(onePastSemiLoc, "}", 1);
1612 }
1613 return;
1614}
1615
1616void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1617 // Perform a bottom up traversal of all children.
1618 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1619 CI != E; ++CI)
1620 if (*CI) {
1621 RewriteSyncReturnStmts(*CI, syncExitBuf);
1622 }
1623 if (isa<ReturnStmt>(S)) {
1624 SourceLocation startLoc = S->getLocStart();
1625 const char *startBuf = SM->getCharacterData(startLoc);
1626
1627 const char *semiBuf = strchr(startBuf, ';');
1628 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1629 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1630
1631 std::string buf;
1632 buf = "{ objc_exception_try_exit(&_stack);";
1633 buf += syncExitBuf;
1634 buf += " return";
1635
1636 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1637 InsertText(onePastSemiLoc, "}", 1);
1638 }
1639 return;
1640}
1641
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001642Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001643 // Get the start location and compute the semi location.
1644 SourceLocation startLoc = S->getLocStart();
1645 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001646
Steve Naroffbf478ec2007-11-07 04:08:17 +00001647 assert((*startBuf == '@') && "bogus @try location");
1648
1649 std::string buf;
1650 // declare a new scope with two variables, _stack and _rethrow.
1651 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1652 buf += "int buf[18/*32-bit i386*/];\n";
1653 buf += "char *pointers[4];} _stack;\n";
1654 buf += "id volatile _rethrow = 0;\n";
1655 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001656 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001657
Chris Lattner9cc55f52008-01-31 19:51:04 +00001658 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001659
Steve Naroffbf478ec2007-11-07 04:08:17 +00001660 startLoc = S->getTryBody()->getLocEnd();
1661 startBuf = SM->getCharacterData(startLoc);
1662
1663 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001664
Steve Naroffbf478ec2007-11-07 04:08:17 +00001665 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001666 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1667 if (catchList) {
1668 startLoc = startLoc.getFileLocWithOffset(1);
1669 buf = " /* @catch begin */ else {\n";
1670 buf += " id _caught = objc_exception_extract(&_stack);\n";
1671 buf += " objc_exception_try_enter (&_stack);\n";
1672 buf += " if (_setjmp(_stack.buf))\n";
1673 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1674 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001675
Steve Naroffce2dca12008-07-16 15:31:30 +00001676 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001677 } else { /* no catch list */
1678 buf = "}\nelse {\n";
1679 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1680 buf += "}";
1681 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001682 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 bool sawIdTypedCatch = false;
1684 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001685 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001686 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001687
Mike Stump11289f42009-09-09 15:08:12 +00001688 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001689 buf = "if ("; // we are generating code for the first catch clause
1690 else
1691 buf = "else if (";
1692 startLoc = catchList->getLocStart();
1693 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Steve Naroffbf478ec2007-11-07 04:08:17 +00001695 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001696
Steve Naroffbf478ec2007-11-07 04:08:17 +00001697 const char *lParenLoc = strchr(startBuf, '(');
1698
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001699 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001700 // Now rewrite the body...
1701 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001702 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1703 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001704 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1705 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001706 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001707
Steve Naroffedb5bc62008-02-01 20:02:07 +00001708 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001709 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001710 } else if (catchDecl) {
1711 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001712 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001713 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001714 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001715 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001716 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001717 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001718
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001719 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001721 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001722 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001723 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001724 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001725 }
1726 }
1727 // Now rewrite the body...
1728 lastCatchBody = catchList->getCatchBody();
1729 SourceLocation rParenLoc = catchList->getRParenLoc();
1730 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1731 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1732 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1733 assert((*rParenBuf == ')') && "bogus @catch paren location");
1734 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001735
Steve Naroffbf478ec2007-11-07 04:08:17 +00001736 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001737 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001739 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001740 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001741 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001742 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001743 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001744 catchList = catchList->getNextCatchStmt();
1745 }
1746 // Complete the catch list...
1747 if (lastCatchBody) {
1748 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001749 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1750 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001751
Steve Naroff4adbe312008-09-11 15:29:03 +00001752 // Insert the last (implicit) else clause *before* the right curly brace.
1753 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1754 buf = "} /* last catch end */\n";
1755 buf += "else {\n";
1756 buf += " _rethrow = _caught;\n";
1757 buf += " objc_exception_try_exit(&_stack);\n";
1758 buf += "} } /* @catch end */\n";
1759 if (!S->getFinallyStmt())
1760 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001761 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001762
Steve Naroffbf478ec2007-11-07 04:08:17 +00001763 // Set lastCurlyLoc
1764 lastCurlyLoc = lastCatchBody->getLocEnd();
1765 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001766 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001767 startLoc = finalStmt->getLocStart();
1768 startBuf = SM->getCharacterData(startLoc);
1769 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001770
Steve Naroffbf478ec2007-11-07 04:08:17 +00001771 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001772 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001773
Steve Naroffbf478ec2007-11-07 04:08:17 +00001774 Stmt *body = finalStmt->getFinallyBody();
1775 SourceLocation startLoc = body->getLocStart();
1776 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001777 assert(*SM->getCharacterData(startLoc) == '{' &&
1778 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001779 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001780 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001781
Steve Naroffbf478ec2007-11-07 04:08:17 +00001782 startLoc = startLoc.getFileLocWithOffset(1);
1783 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001784 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001785 endLoc = endLoc.getFileLocWithOffset(-1);
1786 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001787 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001788
Steve Naroffbf478ec2007-11-07 04:08:17 +00001789 // Set lastCurlyLoc
1790 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001791
Steve Naroff6d6da252008-12-05 17:03:39 +00001792 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001793 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001794 } else { /* no finally clause - make sure we synthesize an implicit one */
1795 buf = "{ /* implicit finally clause */\n";
1796 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1797 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1798 buf += "}";
1799 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001800
1801 // Now check for any return/continue/go statements within the @try.
1802 // The implicit finally clause won't called if the @try contains any
1803 // jump statements.
1804 bool hasReturns = false;
1805 HasReturnStmts(S->getTryBody(), hasReturns);
1806 if (hasReturns)
1807 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001808 }
1809 // Now emit the final closing curly brace...
1810 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1811 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001812 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001813 return 0;
1814}
1815
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001816Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001817 return 0;
1818}
1819
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001820Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001821 return 0;
1822}
1823
Mike Stump11289f42009-09-09 15:08:12 +00001824// This can't be done with ReplaceStmt(S, ThrowExpr), since
1825// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001826// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001827Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001828 // Get the start location and compute the semi location.
1829 SourceLocation startLoc = S->getLocStart();
1830 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001831
Steve Naroffa733c7f2007-11-07 15:32:26 +00001832 assert((*startBuf == '@') && "bogus @throw location");
1833
1834 std::string buf;
1835 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001836 if (S->getThrowExpr())
1837 buf = "objc_exception_throw(";
1838 else // add an implicit argument
1839 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001840
Steve Naroff29788342008-07-25 15:41:30 +00001841 // handle "@ throw" correctly.
1842 const char *wBuf = strchr(startBuf, 'w');
1843 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1844 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001845
Steve Naroffa733c7f2007-11-07 15:32:26 +00001846 const char *semiBuf = strchr(startBuf, ';');
1847 assert((*semiBuf == ';') && "@throw: can't find ';'");
1848 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1849 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001850 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001851 return 0;
1852}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001853
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001854Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001855 // Create a new string expression.
1856 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001857 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001858 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001859 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1860 StrEncoding.length(), false,StrType,
1861 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001862 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001863
Chris Lattner4431a1b2007-11-30 22:53:43 +00001864 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001865 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001866 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001867}
1868
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001869Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001870 if (!SelGetUidFunctionDecl)
1871 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001872 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1873 // Create a call to sel_registerName("selName").
1874 llvm::SmallVector<Expr*, 8> SelExprs;
1875 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001876 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001877 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001878 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001879 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001880 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1881 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001882 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001883 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001884 return SelExp;
1885}
1886
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001887CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001888 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001889 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001890 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001891
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001892 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001893 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001894
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001895 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001896 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001897 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001898 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001899 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001900 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001901
John McCall9dd450b2009-09-21 23:43:11 +00001902 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001903
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001904 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1905 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001906}
1907
Steve Naroff50d42052007-11-01 13:24:47 +00001908static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1909 const char *&startRef, const char *&endRef) {
1910 while (startBuf < endBuf) {
1911 if (*startBuf == '<')
1912 startRef = startBuf; // mark the start.
1913 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001914 if (startRef && *startRef == '<') {
1915 endRef = startBuf; // mark the end.
1916 return true;
1917 }
1918 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001919 }
1920 startBuf++;
1921 }
1922 return false;
1923}
1924
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001925static void scanToNextArgument(const char *&argRef) {
1926 int angle = 0;
1927 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1928 if (*argRef == '<')
1929 angle++;
1930 else if (*argRef == '>')
1931 angle--;
1932 argRef++;
1933 }
1934 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1935}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001936
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001937bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001938 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001939}
1940
Steve Naroff873bd842008-07-29 18:15:38 +00001941void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1942 QualType Type = E->getType();
1943 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001944 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001945
Steve Naroffdbfc6932008-11-19 21:15:47 +00001946 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1947 Loc = ECE->getLParenLoc();
1948 EndLoc = ECE->getRParenLoc();
1949 } else {
1950 Loc = E->getLocStart();
1951 EndLoc = E->getLocEnd();
1952 }
1953 // This will defend against trying to rewrite synthesized expressions.
1954 if (Loc.isInvalid() || EndLoc.isInvalid())
1955 return;
1956
Steve Naroff873bd842008-07-29 18:15:38 +00001957 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001958 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001959 const char *startRef = 0, *endRef = 0;
1960 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1961 // Get the locations of the startRef, endRef.
1962 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1963 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1964 // Comment out the protocol references.
1965 InsertText(LessLoc, "/*", 2);
1966 InsertText(GreaterLoc, "*/", 2);
1967 }
1968 }
1969}
1970
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001971void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001972 SourceLocation Loc;
1973 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001974 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001975 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1976 Loc = VD->getLocation();
1977 Type = VD->getType();
1978 }
1979 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1980 Loc = FD->getLocation();
1981 // Check for ObjC 'id' and class types that have been adorned with protocol
1982 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001983 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001984 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001985 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001986 if (!proto)
1987 return;
1988 Type = proto->getResultType();
1989 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00001990 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
1991 Loc = FD->getLocation();
1992 Type = FD->getType();
1993 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001994 else
1995 return;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001997 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001998 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001999
Steve Naroff50d42052007-11-01 13:24:47 +00002000 const char *endBuf = SM->getCharacterData(Loc);
2001 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002002 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002003 startBuf--; // scan backward (from the decl location) for return type.
2004 const char *startRef = 0, *endRef = 0;
2005 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2006 // Get the locations of the startRef, endRef.
2007 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2008 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2009 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002010 InsertText(LessLoc, "/*", 2);
2011 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002012 }
2013 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002014 if (!proto)
2015 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002016 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002017 const char *startBuf = SM->getCharacterData(Loc);
2018 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002019 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2020 if (needToScanForQualifiers(proto->getArgType(i))) {
2021 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroff50d42052007-11-01 13:24:47 +00002023 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002024 // scan forward (from the decl location) for argument types.
2025 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002026 const char *startRef = 0, *endRef = 0;
2027 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2028 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002029 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002030 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002031 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002032 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002033 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002034 InsertText(LessLoc, "/*", 2);
2035 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002036 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002037 startBuf = ++endBuf;
2038 }
2039 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002040 // If the function name is derived from a macro expansion, then the
2041 // argument buffer will not follow the name. Need to speak with Chris.
2042 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002043 startBuf++; // scan forward (from the decl location) for argument types.
2044 startBuf++;
2045 }
Steve Naroff50d42052007-11-01 13:24:47 +00002046 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002047}
2048
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002049// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002050void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002051 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2052 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002053 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002054 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002055 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002056 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002057 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002058 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002059 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002060 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002061}
2062
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002063void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002064 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002065 if (FD->getIdentifier() &&
2066 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002067 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002068 return;
2069 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002070 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002071}
2072
Steve Naroff17978c42008-03-11 17:37:02 +00002073// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002074void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002075 if (SuperContructorFunctionDecl)
2076 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002077 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002078 llvm::SmallVector<QualType, 16> ArgTys;
2079 QualType argT = Context->getObjCIdType();
2080 assert(!argT.isNull() && "Can't find 'id' type");
2081 ArgTys.push_back(argT);
2082 ArgTys.push_back(argT);
2083 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2084 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002085 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002086 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002087 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002088 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002089 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002090}
2091
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002092// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002093void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002094 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2095 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002096 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002097 assert(!argT.isNull() && "Can't find 'id' type");
2098 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002099 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002100 assert(!argT.isNull() && "Can't find 'SEL' type");
2101 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002102 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002103 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002104 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002105 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002106 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002107 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002108 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002109}
2110
Steve Naroff7fa2f042007-11-15 10:28:18 +00002111// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002112void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002113 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2114 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002115 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002116 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002117 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002118 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2119 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2120 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002121 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002122 assert(!argT.isNull() && "Can't find 'SEL' type");
2123 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002124 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002125 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002126 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002127 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002128 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002129 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002130 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002131}
2132
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002133// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002134void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002135 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2136 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002137 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002138 assert(!argT.isNull() && "Can't find 'id' type");
2139 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002140 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002141 assert(!argT.isNull() && "Can't find 'SEL' type");
2142 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002143 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002144 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002145 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002146 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002147 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002148 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002149 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002150}
2151
Mike Stump11289f42009-09-09 15:08:12 +00002152// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002153// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002154void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002155 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002156 &Context->Idents.get("objc_msgSendSuper_stret");
2157 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002158 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002159 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002160 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002161 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2162 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2163 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002164 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002165 assert(!argT.isNull() && "Can't find 'SEL' type");
2166 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002167 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002168 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002169 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002170 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002171 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002172 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002173 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002174}
2175
Steve Naroff2e4e3852008-05-08 22:02:18 +00002176// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002177void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002178 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2179 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002180 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002181 assert(!argT.isNull() && "Can't find 'id' type");
2182 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002183 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002184 assert(!argT.isNull() && "Can't find 'SEL' type");
2185 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002186 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002187 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002188 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002189 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002190 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002191 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002192 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002193}
2194
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002195// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002196void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002197 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2198 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002199 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002200 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002201 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002202 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002203 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002204 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002205 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002206 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002207}
2208
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002209// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002210void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002211 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2212 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002213 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002214 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002215 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002216 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002217 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002218 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002219 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002220 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002221}
2222
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002223Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002224 QualType strType = getConstantStringStructType();
2225
2226 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002227
2228 std::string tmpName = InFileName;
2229 unsigned i;
2230 for (i=0; i < tmpName.length(); i++) {
2231 char c = tmpName.at(i);
2232 // replace any non alphanumeric characters with '_'.
2233 if (!isalpha(c) && (c < '0' || c > '9'))
2234 tmpName[i] = '_';
2235 }
2236 S += tmpName;
2237 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002238 S += utostr(NumObjCStringLiterals++);
2239
Steve Naroff00a31762008-03-27 22:29:16 +00002240 Preamble += "static __NSConstantStringImpl " + S;
2241 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2242 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002243 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002244 std::string prettyBufS;
2245 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002246 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2247 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002248 Preamble += prettyBuf.str();
2249 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002250 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002251
2252 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2253 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002254 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002255 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2256 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002257 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002258 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002259 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002260 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002261 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002262 Unop, Exp->getType(),
2263 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002264 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002265 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002266 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002267 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002268}
2269
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002270ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002271 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002272 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002273
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002274 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002275 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002276 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002277 assert(OPT);
2278 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002279 return IT->getDecl();
2280 }
2281 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002282}
2283
2284// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002285QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002286 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002287 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002288 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002289 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002290 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002291
Steve Naroff7fa2f042007-11-15 10:28:18 +00002292 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002293 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002294 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002295 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002296
Steve Naroff7fa2f042007-11-15 10:28:18 +00002297 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002298 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002299 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2300 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002301 FieldTypes[i], 0,
2302 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002303 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Douglas Gregor91f84212008-12-11 16:49:14 +00002306 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002307 }
2308 return Context->getTagDeclType(SuperStructDecl);
2309}
2310
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002311QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002312 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002313 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002314 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002315 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002316 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002317
Steve Naroffce8e8862008-03-15 00:55:56 +00002318 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002319 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002320 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002321 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002322 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002323 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002324 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002325 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002326
Steve Naroffce8e8862008-03-15 00:55:56 +00002327 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002328 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002329 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2330 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002331 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002332 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002333 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002334 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002335 }
2336
2337 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002338 }
2339 return Context->getTagDeclType(ConstantStringDecl);
2340}
2341
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002342Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002343 if (!SelGetUidFunctionDecl)
2344 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002345 if (!MsgSendFunctionDecl)
2346 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002347 if (!MsgSendSuperFunctionDecl)
2348 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002349 if (!MsgSendStretFunctionDecl)
2350 SynthMsgSendStretFunctionDecl();
2351 if (!MsgSendSuperStretFunctionDecl)
2352 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002353 if (!MsgSendFpretFunctionDecl)
2354 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002355 if (!GetClassFunctionDecl)
2356 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002357 if (!GetMetaClassFunctionDecl)
2358 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002359
Steve Naroff7fa2f042007-11-15 10:28:18 +00002360 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002361 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2362 // May need to use objc_msgSend_stret() as well.
2363 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002364 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2365 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002366 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002367 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002368 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002369 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002370 }
Mike Stump11289f42009-09-09 15:08:12 +00002371
Steve Naroff574440f2007-10-24 22:48:43 +00002372 // Synthesize a call to objc_msgSend().
2373 llvm::SmallVector<Expr*, 8> MsgExprs;
2374 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002375
Steve Naroff574440f2007-10-24 22:48:43 +00002376 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2377 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002378 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2379 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002380 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002381 MsgSendFlavor = MsgSendSuperFunctionDecl;
2382 if (MsgSendStretFlavor)
2383 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2384 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002385
2386 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002387 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002388
2389 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002391 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002392 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002393 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002394 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002395 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002396 Context->getObjCIdType(),
2397 SourceLocation()),
2398 Context->getObjCIdType(),
2399 SourceLocation(), SourceLocation())); // set the 'receiver'.
2400
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002401 llvm::SmallVector<Expr*, 8> ClsExprs;
2402 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002403 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002404 SuperDecl->getIdentifier()->getNameStart(),
2405 SuperDecl->getIdentifier()->getLength(),
2406 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002407 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002408 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002409 ClsExprs.size());
2410 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002411 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002412 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002413 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002414 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002415 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002416 // struct objc_super
2417 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002418 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002419
Steve Naroff0b844f02008-03-11 18:14:26 +00002420 if (LangOpts.Microsoft) {
2421 SynthSuperContructorFunctionDecl();
2422 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002423 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002424 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002425 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002426 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002427 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002428 // The code for super is a little tricky to prevent collision with
2429 // the structure definition in the header. The rewriter has it's own
2430 // internal definition (__rw_objc_super) that is uses. This is why
2431 // we need the cast below. For example:
2432 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2433 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002434 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002435 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002436 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002437 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2438 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002439 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002440 SourceLocation(), SourceLocation());
2441 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002442 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002443 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2444 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002445 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002446 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002447 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002448 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002449 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002450 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002451 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002452 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002453 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002454 } else {
2455 llvm::SmallVector<Expr*, 8> ClsExprs;
2456 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002457 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002458 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002459 clsName->getLength(),
2460 false, argType,
2461 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002462 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002463 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002464 ClsExprs.size());
2465 MsgExprs.push_back(Cls);
2466 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002467 } else { // instance message.
2468 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002469
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002470 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002471 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002472 if (MsgSendStretFlavor)
2473 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002474 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002475
Steve Naroff7fa2f042007-11-15 10:28:18 +00002476 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002477
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002478 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002479 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002480 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002481 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002482 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002483 SourceLocation()),
2484 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002485 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002486
Steve Naroff7fa2f042007-11-15 10:28:18 +00002487 llvm::SmallVector<Expr*, 8> ClsExprs;
2488 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002489 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002490 SuperDecl->getIdentifier()->getNameStart(),
2491 SuperDecl->getIdentifier()->getLength(),
2492 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002493 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002494 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002495 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002496 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002497 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002498 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002499 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002500 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002501 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002502 // struct objc_super
2503 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002504 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Steve Naroff17978c42008-03-11 17:37:02 +00002506 if (LangOpts.Microsoft) {
2507 SynthSuperContructorFunctionDecl();
2508 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002509 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002510 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002511 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002512 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002513 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002514 // The code for super is a little tricky to prevent collision with
2515 // the structure definition in the header. The rewriter has it's own
2516 // internal definition (__rw_objc_super) that is uses. This is why
2517 // we need the cast below. For example:
2518 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2519 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002520 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002521 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002522 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002523 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002524 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002525 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002526 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002527 } else {
2528 // (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());
Ted Kremenek5a201952009-02-07 01:47:29 +00002532 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002533 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002534 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002535 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002536 // Remove all type-casts because it may contain objc-style types; e.g.
2537 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002538 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002539 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002540 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002541 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002542 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002543 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002544 MsgExprs.push_back(recExpr);
2545 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002546 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002547 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002548 llvm::SmallVector<Expr*, 8> SelExprs;
2549 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002550 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002551 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002552 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002553 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002554 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2555 &SelExprs[0], SelExprs.size());
2556 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002557
Steve Naroff574440f2007-10-24 22:48:43 +00002558 // Now push any user supplied arguments.
2559 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002560 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002561 // Make all implicit casts explicit...ICE comes in handy:-)
2562 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2563 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002564 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002565 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002566 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002567 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002568 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002569 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002570 }
2571 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002572 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002573 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002574 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002575 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002576 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002577 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002578 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002579 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002582 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002583 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2584 // out the argument in the original expression (since we aren't deleting
2585 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2586 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002587 }
Steve Narofff36987c2007-11-04 22:37:50 +00002588 // Generate the funky cast.
2589 CastExpr *cast;
2590 llvm::SmallVector<QualType, 8> ArgTypes;
2591 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002592
Steve Narofff36987c2007-11-04 22:37:50 +00002593 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002594 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2595 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2596 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002597 ArgTypes.push_back(Context->getObjCIdType());
2598 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002599 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002600 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002601 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2602 E = OMD->param_end(); PI != E; ++PI) {
2603 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002604 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002605 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002606 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002607 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002608 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002609 t = Context->getPointerType(BPT->getPointeeType());
2610 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002611 ArgTypes.push_back(t);
2612 }
Chris Lattnera4997152009-02-20 18:43:26 +00002613 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2614 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002615 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002616 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002617 }
2618 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002619 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Narofff36987c2007-11-04 22:37:50 +00002621 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002622 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002623 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002624
Mike Stump11289f42009-09-09 15:08:12 +00002625 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002626 // If we don't do this cast, we get the following bizarre warning/note:
2627 // xx.m:13: warning: function called through a non-compatible type
2628 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002629 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2630 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002631 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002632 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002633
Steve Narofff36987c2007-11-04 22:37:50 +00002634 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002635 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002636 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002637 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002638 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002639 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002640 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2641 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002642 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002643
2644 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002645 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002646
John McCall9dd450b2009-09-21 23:43:11 +00002647 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002648 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002649 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002650 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002651 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002652 if (MsgSendStretFlavor) {
2653 // We have the method which returns a struct/union. Must also generate
2654 // call to objc_msgSend_stret and hang both varieties on a conditional
2655 // expression which dictate which one to envoke depending on size of
2656 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002657
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002658 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002659 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002660 SourceLocation());
2661 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002662 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2663 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002664 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002665 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002666 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002667 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002668 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002669 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002670 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002671 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2672 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002673
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002674 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002675 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002676
John McCall9dd450b2009-09-21 23:43:11 +00002677 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002678 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002679 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002680 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002681
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002682 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002683 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002684 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002685 Context->getSizeType(),
2686 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002687 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2688 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2689 // For X86 it is more complicated and some kind of target specific routine
2690 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002691 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002692 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002693 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002694 Context->IntTy,
2695 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002696 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2697 BinaryOperator::LE,
2698 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002699 SourceLocation());
2700 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002701 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002702 new (Context) ConditionalOperator(lessThanExpr,
2703 SourceLocation(), CE,
2704 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002705 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002706 }
Mike Stump11289f42009-09-09 15:08:12 +00002707 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002708 return ReplacingStmt;
2709}
2710
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002711Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002712 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002713
Steve Naroff574440f2007-10-24 22:48:43 +00002714 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002715 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002716
2717 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002718 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002719}
2720
Steve Naroffd9803712009-04-29 16:37:50 +00002721// typedef struct objc_object Protocol;
2722QualType RewriteObjC::getProtocolType() {
2723 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002724 TypeSourceInfo *TInfo
2725 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002726 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002727 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002728 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002729 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002730 }
2731 return Context->getTypeDeclType(ProtocolTypeDecl);
2732}
2733
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002734/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002735/// a synthesized/forward data reference (to the protocol's metadata).
2736/// The forward references (and metadata) are generated in
2737/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002738Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002739 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2740 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002741 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002742 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002743 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2744 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2745 Context->getPointerType(DRE->getType()),
2746 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002747 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2748 CastExpr::CK_Unknown,
2749 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002750 SourceLocation(), SourceLocation());
2751 ReplaceStmt(Exp, castExpr);
2752 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002753 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002754 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002755
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002756}
2757
Mike Stump11289f42009-09-09 15:08:12 +00002758bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002759 const char *endBuf) {
2760 while (startBuf < endBuf) {
2761 if (*startBuf == '#') {
2762 // Skip whitespace.
2763 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2764 ;
2765 if (!strncmp(startBuf, "if", strlen("if")) ||
2766 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2767 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2768 !strncmp(startBuf, "define", strlen("define")) ||
2769 !strncmp(startBuf, "undef", strlen("undef")) ||
2770 !strncmp(startBuf, "else", strlen("else")) ||
2771 !strncmp(startBuf, "elif", strlen("elif")) ||
2772 !strncmp(startBuf, "endif", strlen("endif")) ||
2773 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2774 !strncmp(startBuf, "include", strlen("include")) ||
2775 !strncmp(startBuf, "import", strlen("import")) ||
2776 !strncmp(startBuf, "include_next", strlen("include_next")))
2777 return true;
2778 }
2779 startBuf++;
2780 }
2781 return false;
2782}
2783
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002784/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002785/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002786void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002787 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002788 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002789 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002790 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002791 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002792 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002793 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002794 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002795 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002796 SourceLocation LocStart = CDecl->getLocStart();
2797 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002798
Steve Naroffdde78982007-11-14 19:25:57 +00002799 const char *startBuf = SM->getCharacterData(LocStart);
2800 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002802 // If no ivars and no root or if its root, directly or indirectly,
2803 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002804 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2805 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002806 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002807 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002808 return;
2809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
2811 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002812 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002813 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002814 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002815 if (LangOpts.Microsoft)
2816 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002817
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002818 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002819 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002820 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002821 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002822 // If the buffer contains preprocessor directives, we do more fine-grained
2823 // rewrites. This is intended to fix code that looks like (which occurs in
2824 // NSURL.h, for example):
2825 //
2826 // #ifdef XYZ
2827 // @interface Foo : NSObject
2828 // #else
2829 // @interface FooBar : NSObject
2830 // #endif
2831 // {
2832 // int i;
2833 // }
2834 // @end
2835 //
2836 // This clause is segregated to avoid breaking the common case.
2837 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002838 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002839 CDecl->getClassLoc();
2840 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002841 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002842
Chris Lattnerf5b77512009-02-20 18:18:36 +00002843 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002844 // advance to the end of the referenced protocols.
2845 while (endHeader < cursor && *endHeader != '>') endHeader++;
2846 endHeader++;
2847 }
2848 // rewrite the original header
2849 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2850 } else {
2851 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002852 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002853 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002854 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002855 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002856 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002857 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002858 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002859 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002860
Steve Naroffdde78982007-11-14 19:25:57 +00002861 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002862 SourceLocation OnePastCurly =
2863 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2864 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002865 }
2866 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002867
Steve Naroffdde78982007-11-14 19:25:57 +00002868 // Now comment out any visibility specifiers.
2869 while (cursor < endBuf) {
2870 if (*cursor == '@') {
2871 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002872 // Skip whitespace.
2873 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2874 /*scan*/;
2875
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002876 // FIXME: presence of @public, etc. inside comment results in
2877 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002878 if (!strncmp(cursor, "public", strlen("public")) ||
2879 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002880 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002881 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002882 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002883 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002884 // FIXME: If there are cases where '<' is used in ivar declaration part
2885 // of user code, then scan the ivar list and use needToScanForQualifiers
2886 // for type checking.
2887 else if (*cursor == '<') {
2888 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002889 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002890 cursor = strchr(cursor, '>');
2891 cursor++;
2892 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002893 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002894 } else if (*cursor == '^') { // rewrite block specifier.
2895 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2896 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002897 }
Steve Naroffdde78982007-11-14 19:25:57 +00002898 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002899 }
Steve Naroffdde78982007-11-14 19:25:57 +00002900 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002901 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002902 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002903 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002904 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002905 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002906 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002907 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002908 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002909 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002910 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002911 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002912 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002913 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002914}
2915
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002916// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002917/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002918template<typename MethodIterator>
2919void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2920 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002921 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002922 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002923 const char *ClassName,
2924 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002925 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002927 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002928 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002929 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002930 SEL _cmd;
2931 char *method_types;
2932 void *_imp;
2933 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002934 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002935 Result += "\nstruct _objc_method {\n";
2936 Result += "\tSEL _cmd;\n";
2937 Result += "\tchar *method_types;\n";
2938 Result += "\tvoid *_imp;\n";
2939 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002940
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002941 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002944 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002945
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002946 /* struct {
2947 struct _objc_method_list *next_method;
2948 int method_count;
2949 struct _objc_method method_list[];
2950 }
2951 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002952 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002953 Result += "\nstatic struct {\n";
2954 Result += "\tstruct _objc_method_list *next_method;\n";
2955 Result += "\tint method_count;\n";
2956 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002957 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002958 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002959 Result += prefix;
2960 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2961 Result += "_METHODS_";
2962 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002963 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002964 Result += IsInstanceMethod ? "inst" : "cls";
2965 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002966 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002967
Chris Lattner31bc07e2007-12-12 07:46:12 +00002968 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002969 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002970 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002971 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002972 Result += "\", \"";
2973 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002974 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002975 Result += MethodInternalNames[*MethodBegin];
2976 Result += "}\n";
2977 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2978 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002979 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002980 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002981 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002982 Result += "\", \"";
2983 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002984 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002985 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002986 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002987 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002988 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002989}
2990
Steve Naroffd9803712009-04-29 16:37:50 +00002991/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002992void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002993RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2994 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002995 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002996
2997 // Output struct protocol_methods holder of method selector and type.
2998 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2999 /* struct protocol_methods {
3000 SEL _cmd;
3001 char *method_types;
3002 }
3003 */
3004 Result += "\nstruct _protocol_methods {\n";
3005 Result += "\tstruct objc_selector *_cmd;\n";
3006 Result += "\tchar *method_types;\n";
3007 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003008
Steve Naroffd9803712009-04-29 16:37:50 +00003009 objc_protocol_methods = true;
3010 }
3011 // Do not synthesize the protocol more than once.
3012 if (ObjCSynthesizedProtocols.count(PDecl))
3013 return;
Mike Stump11289f42009-09-09 15:08:12 +00003014
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003015 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3016 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3017 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003018 /* struct _objc_protocol_method_list {
3019 int protocol_method_count;
3020 struct protocol_methods protocols[];
3021 }
Steve Naroff251084d2008-03-12 01:06:30 +00003022 */
Steve Naroffd9803712009-04-29 16:37:50 +00003023 Result += "\nstatic struct {\n";
3024 Result += "\tint protocol_method_count;\n";
3025 Result += "\tstruct _protocol_methods protocol_methods[";
3026 Result += utostr(NumMethods);
3027 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3028 Result += PDecl->getNameAsString();
3029 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3030 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003031
Steve Naroffd9803712009-04-29 16:37:50 +00003032 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003033 for (ObjCProtocolDecl::instmeth_iterator
3034 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003035 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003036 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003037 Result += "\t ,{{(struct objc_selector *)\"";
3038 else
3039 Result += "\t ,{(struct objc_selector *)\"";
3040 Result += (*I)->getSelector().getAsString().c_str();
3041 std::string MethodTypeString;
3042 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3043 Result += "\", \"";
3044 Result += MethodTypeString;
3045 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003046 }
Steve Naroffd9803712009-04-29 16:37:50 +00003047 Result += "\t }\n};\n";
3048 }
Mike Stump11289f42009-09-09 15:08:12 +00003049
Steve Naroffd9803712009-04-29 16:37:50 +00003050 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003051 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3052 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003053 if (NumMethods > 0) {
3054 /* struct _objc_protocol_method_list {
3055 int protocol_method_count;
3056 struct protocol_methods protocols[];
3057 }
3058 */
3059 Result += "\nstatic struct {\n";
3060 Result += "\tint protocol_method_count;\n";
3061 Result += "\tstruct _protocol_methods protocol_methods[";
3062 Result += utostr(NumMethods);
3063 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3064 Result += PDecl->getNameAsString();
3065 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3066 "{\n\t";
3067 Result += utostr(NumMethods);
3068 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003069
Steve Naroffd9803712009-04-29 16:37:50 +00003070 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003071 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003073 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003074 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003075 Result += "\t ,{{(struct objc_selector *)\"";
3076 else
3077 Result += "\t ,{(struct objc_selector *)\"";
3078 Result += (*I)->getSelector().getAsString().c_str();
3079 std::string MethodTypeString;
3080 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3081 Result += "\", \"";
3082 Result += MethodTypeString;
3083 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003084 }
Steve Naroffd9803712009-04-29 16:37:50 +00003085 Result += "\t }\n};\n";
3086 }
3087
3088 // Output:
3089 /* struct _objc_protocol {
3090 // Objective-C 1.0 extensions
3091 struct _objc_protocol_extension *isa;
3092 char *protocol_name;
3093 struct _objc_protocol **protocol_list;
3094 struct _objc_protocol_method_list *instance_methods;
3095 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003096 };
Steve Naroffd9803712009-04-29 16:37:50 +00003097 */
3098 static bool objc_protocol = false;
3099 if (!objc_protocol) {
3100 Result += "\nstruct _objc_protocol {\n";
3101 Result += "\tstruct _objc_protocol_extension *isa;\n";
3102 Result += "\tchar *protocol_name;\n";
3103 Result += "\tstruct _objc_protocol **protocol_list;\n";
3104 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3105 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003106 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003107
Steve Naroffd9803712009-04-29 16:37:50 +00003108 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003109 }
Mike Stump11289f42009-09-09 15:08:12 +00003110
Steve Naroffd9803712009-04-29 16:37:50 +00003111 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3112 Result += PDecl->getNameAsString();
3113 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3114 "{\n\t0, \"";
3115 Result += PDecl->getNameAsString();
3116 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003117 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003118 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3119 Result += PDecl->getNameAsString();
3120 Result += ", ";
3121 }
3122 else
3123 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003124 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003125 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3126 Result += PDecl->getNameAsString();
3127 Result += "\n";
3128 }
3129 else
3130 Result += "0\n";
3131 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003132
Steve Naroffd9803712009-04-29 16:37:50 +00003133 // Mark this protocol as having been generated.
3134 if (!ObjCSynthesizedProtocols.insert(PDecl))
3135 assert(false && "protocol already synthesized");
3136
3137}
3138
3139void RewriteObjC::
3140RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3141 const char *prefix, const char *ClassName,
3142 std::string &Result) {
3143 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003144
Steve Naroffd9803712009-04-29 16:37:50 +00003145 for (unsigned i = 0; i != Protocols.size(); i++)
3146 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3147
Chris Lattner388f6e92008-07-21 21:33:21 +00003148 // Output the top lovel protocol meta-data for the class.
3149 /* struct _objc_protocol_list {
3150 struct _objc_protocol_list *next;
3151 int protocol_count;
3152 struct _objc_protocol *class_protocols[];
3153 }
3154 */
3155 Result += "\nstatic struct {\n";
3156 Result += "\tstruct _objc_protocol_list *next;\n";
3157 Result += "\tint protocol_count;\n";
3158 Result += "\tstruct _objc_protocol *class_protocols[";
3159 Result += utostr(Protocols.size());
3160 Result += "];\n} _OBJC_";
3161 Result += prefix;
3162 Result += "_PROTOCOLS_";
3163 Result += ClassName;
3164 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3165 "{\n\t0, ";
3166 Result += utostr(Protocols.size());
3167 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003168
Chris Lattner388f6e92008-07-21 21:33:21 +00003169 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003170 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003171 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003172
Chris Lattner388f6e92008-07-21 21:33:21 +00003173 for (unsigned i = 1; i != Protocols.size(); i++) {
3174 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003175 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003176 Result += "\n";
3177 }
3178 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003179}
3180
Steve Naroffd9803712009-04-29 16:37:50 +00003181
Mike Stump11289f42009-09-09 15:08:12 +00003182/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003183/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003184void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003185 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003186 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003187 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003188 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003189 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003190 CDecl = CDecl->getNextClassCategory())
3191 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3192 break;
Mike Stump11289f42009-09-09 15:08:12 +00003193
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003194 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003195 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003196 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003197
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003198 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003199 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003200 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003201
3202 // If any of our property implementations have associated getters or
3203 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003204 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3205 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003206 Prop != PropEnd; ++Prop) {
3207 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3208 continue;
3209 if (!(*Prop)->getPropertyIvarDecl())
3210 continue;
3211 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3212 if (!PD)
3213 continue;
3214 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3215 InstanceMethods.push_back(Getter);
3216 if (PD->isReadOnly())
3217 continue;
3218 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3219 InstanceMethods.push_back(Setter);
3220 }
3221 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003222 true, "CATEGORY_", FullCategoryName.c_str(),
3223 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003224
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003225 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003226 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003227 false, "CATEGORY_", FullCategoryName.c_str(),
3228 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003229
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003230 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003231 // Null CDecl is case of a category implementation with no category interface
3232 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003233 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3234 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003235 /* struct _objc_category {
3236 char *category_name;
3237 char *class_name;
3238 struct _objc_method_list *instance_methods;
3239 struct _objc_method_list *class_methods;
3240 struct _objc_protocol_list *protocols;
3241 // Objective-C 1.0 extensions
3242 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003243 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003244 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003245 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003246 */
Mike Stump11289f42009-09-09 15:08:12 +00003247
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003248 static bool objc_category = false;
3249 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003250 Result += "\nstruct _objc_category {\n";
3251 Result += "\tchar *category_name;\n";
3252 Result += "\tchar *class_name;\n";
3253 Result += "\tstruct _objc_method_list *instance_methods;\n";
3254 Result += "\tstruct _objc_method_list *class_methods;\n";
3255 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003256 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003257 Result += "\tstruct _objc_property_list *instance_properties;\n";
3258 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003259 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003260 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003261 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3262 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003263 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003264 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003265 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003266 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003267 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003268
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003269 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003270 Result += "\t, (struct _objc_method_list *)"
3271 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3272 Result += FullCategoryName;
3273 Result += "\n";
3274 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003275 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003276 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003277 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003278 Result += "\t, (struct _objc_method_list *)"
3279 "&_OBJC_CATEGORY_CLASS_METHODS_";
3280 Result += FullCategoryName;
3281 Result += "\n";
3282 }
3283 else
3284 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003285
Chris Lattnerf5b77512009-02-20 18:18:36 +00003286 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003287 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003288 Result += FullCategoryName;
3289 Result += "\n";
3290 }
3291 else
3292 Result += "\t, 0\n";
3293 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003294}
3295
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003296/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3297/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003298void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3299 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003300 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003301 if (ivar->isBitField()) {
3302 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3303 // place all bitfields at offset 0.
3304 Result += "0";
3305 } else {
3306 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003307 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003308 if (LangOpts.Microsoft)
3309 Result += "_IMPL";
3310 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003311 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003312 Result += ")";
3313 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003314}
3315
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003316//===----------------------------------------------------------------------===//
3317// Meta Data Emission
3318//===----------------------------------------------------------------------===//
3319
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003320void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003321 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003322 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003323
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003324 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003325 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003326 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003327 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003328 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003329 }
Mike Stump11289f42009-09-09 15:08:12 +00003330
Chris Lattner30d23e82007-12-12 07:56:42 +00003331 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003332 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003333 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003334 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003335 if (NumIvars > 0) {
3336 static bool objc_ivar = false;
3337 if (!objc_ivar) {
3338 /* struct _objc_ivar {
3339 char *ivar_name;
3340 char *ivar_type;
3341 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003342 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003343 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003344 Result += "\nstruct _objc_ivar {\n";
3345 Result += "\tchar *ivar_name;\n";
3346 Result += "\tchar *ivar_type;\n";
3347 Result += "\tint ivar_offset;\n";
3348 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003349
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003350 objc_ivar = true;
3351 }
3352
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003353 /* struct {
3354 int ivar_count;
3355 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003356 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003357 */
Mike Stump11289f42009-09-09 15:08:12 +00003358 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003359 Result += "\tint ivar_count;\n";
3360 Result += "\tstruct _objc_ivar ivar_list[";
3361 Result += utostr(NumIvars);
3362 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003363 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003364 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003365 "{\n\t";
3366 Result += utostr(NumIvars);
3367 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003368
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003369 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003370 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003371 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003372 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003373 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003374 IV != IVEnd; ++IV)
3375 IVars.push_back(*IV);
3376 IVI = IVars.begin();
3377 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003378 } else {
3379 IVI = CDecl->ivar_begin();
3380 IVE = CDecl->ivar_end();
3381 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003382 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003383 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003384 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003385 std::string TmpString, StrEncoding;
3386 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3387 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003388 Result += StrEncoding;
3389 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003390 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003391 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003392 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003393 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003394 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003395 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003396 std::string TmpString, StrEncoding;
3397 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3398 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003399 Result += StrEncoding;
3400 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003401 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003402 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003406 }
Mike Stump11289f42009-09-09 15:08:12 +00003407
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003408 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003409 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003410 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003411
3412 // If any of our property implementations have associated getters or
3413 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003414 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3415 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003416 Prop != PropEnd; ++Prop) {
3417 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3418 continue;
3419 if (!(*Prop)->getPropertyIvarDecl())
3420 continue;
3421 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3422 if (!PD)
3423 continue;
3424 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3425 InstanceMethods.push_back(Getter);
3426 if (PD->isReadOnly())
3427 continue;
3428 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3429 InstanceMethods.push_back(Setter);
3430 }
3431 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003432 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003433
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003434 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003435 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003436 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003437
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003438 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003439 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3440 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003441
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003442 // Declaration of class/meta-class metadata
3443 /* struct _objc_class {
3444 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003445 const char *super_class_name;
3446 char *name;
3447 long version;
3448 long info;
3449 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003450 struct _objc_ivar_list *ivars;
3451 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003452 struct objc_cache *cache;
3453 struct objc_protocol_list *protocols;
3454 const char *ivar_layout;
3455 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003456 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003457 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003458 static bool objc_class = false;
3459 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003460 Result += "\nstruct _objc_class {\n";
3461 Result += "\tstruct _objc_class *isa;\n";
3462 Result += "\tconst char *super_class_name;\n";
3463 Result += "\tchar *name;\n";
3464 Result += "\tlong version;\n";
3465 Result += "\tlong info;\n";
3466 Result += "\tlong instance_size;\n";
3467 Result += "\tstruct _objc_ivar_list *ivars;\n";
3468 Result += "\tstruct _objc_method_list *methods;\n";
3469 Result += "\tstruct objc_cache *cache;\n";
3470 Result += "\tstruct _objc_protocol_list *protocols;\n";
3471 Result += "\tconst char *ivar_layout;\n";
3472 Result += "\tstruct _objc_class_ext *ext;\n";
3473 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003474 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003475 }
Mike Stump11289f42009-09-09 15:08:12 +00003476
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003477 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003478 ObjCInterfaceDecl *RootClass = 0;
3479 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003480 while (SuperClass) {
3481 RootClass = SuperClass;
3482 SuperClass = SuperClass->getSuperClass();
3483 }
3484 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003485
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003486 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003487 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003488 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003489 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003490 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003491 Result += "\"";
3492
3493 if (SuperClass) {
3494 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003495 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003496 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003497 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003498 Result += "\"";
3499 }
3500 else {
3501 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003502 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003503 Result += "\"";
3504 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003505 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003506 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003507 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003508 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003509 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003510 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003511 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003513 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003514 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003515 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003516 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003517 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003518 Result += ",0,0\n";
3519 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003520 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003521 Result += "\t,0,0,0,0\n";
3522 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003523
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003524 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003525 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003526 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003527 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003529 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003530 if (SuperClass) {
3531 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003532 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003534 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 Result += "\"";
3536 }
3537 else {
3538 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003539 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 Result += "\"";
3541 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003542 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003543 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003544 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003545 Result += ",0";
3546 else {
3547 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003548 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003549 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003550 if (LangOpts.Microsoft)
3551 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003552 Result += ")";
3553 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003554 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003555 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003556 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003557 Result += "\n\t";
3558 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003559 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003561 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003562 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003563 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003564 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003566 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003568 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003569 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003570 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003571 Result += ", 0,0\n";
3572 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003573 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003574 Result += ",0,0,0\n";
3575 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003576}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003577
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003578/// RewriteImplementations - This routine rewrites all method implementations
3579/// and emits meta-data.
3580
Steve Narofff8cfd162008-11-13 20:07:04 +00003581void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003582 int ClsDefCount = ClassImplementation.size();
3583 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003584
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003585 // Rewrite implemented methods
3586 for (int i = 0; i < ClsDefCount; i++)
3587 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003588
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003589 for (int i = 0; i < CatDefCount; i++)
3590 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003591}
Mike Stump11289f42009-09-09 15:08:12 +00003592
Steve Narofff8cfd162008-11-13 20:07:04 +00003593void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3594 int ClsDefCount = ClassImplementation.size();
3595 int CatDefCount = CategoryImplementation.size();
3596
Steve Naroff30ac2222008-05-07 21:23:49 +00003597 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003598 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003599 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003600 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003601 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003602
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003603 // For each implemented category, write out all its meta data.
3604 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003605 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003606
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003607 // Write objc_symtab metadata
3608 /*
3609 struct _objc_symtab
3610 {
3611 long sel_ref_cnt;
3612 SEL *refs;
3613 short cls_def_cnt;
3614 short cat_def_cnt;
3615 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003616 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003617 */
Mike Stump11289f42009-09-09 15:08:12 +00003618
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003619 Result += "\nstruct _objc_symtab {\n";
3620 Result += "\tlong sel_ref_cnt;\n";
3621 Result += "\tSEL *refs;\n";
3622 Result += "\tshort cls_def_cnt;\n";
3623 Result += "\tshort cat_def_cnt;\n";
3624 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3625 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003626
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003627 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003628 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003629 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003630 + ", " + utostr(CatDefCount) + "\n";
3631 for (int i = 0; i < ClsDefCount; i++) {
3632 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003633 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003634 Result += "\n";
3635 }
Mike Stump11289f42009-09-09 15:08:12 +00003636
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 for (int i = 0; i < CatDefCount; i++) {
3638 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003639 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003640 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003641 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "\n";
3643 }
Mike Stump11289f42009-09-09 15:08:12 +00003644
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003645 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003646
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003647 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003648
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003649 /*
3650 struct _objc_module {
3651 long version;
3652 long size;
3653 const char *name;
3654 struct _objc_symtab *symtab;
3655 }
3656 */
Mike Stump11289f42009-09-09 15:08:12 +00003657
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003658 Result += "\nstruct _objc_module {\n";
3659 Result += "\tlong version;\n";
3660 Result += "\tlong size;\n";
3661 Result += "\tconst char *name;\n";
3662 Result += "\tstruct _objc_symtab *symtab;\n";
3663 Result += "};\n\n";
3664 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003665 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003666 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003667 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003668 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003669
3670 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003671 if (ProtocolExprDecls.size()) {
3672 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3673 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003674 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003675 E = ProtocolExprDecls.end(); I != E; ++I) {
3676 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3677 Result += (*I)->getNameAsString();
3678 Result += " = &_OBJC_PROTOCOL_";
3679 Result += (*I)->getNameAsString();
3680 Result += ";\n";
3681 }
3682 Result += "#pragma data_seg(pop)\n\n";
3683 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003684 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003685 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003686 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3687 Result += "&_OBJC_MODULES;\n";
3688 Result += "#pragma data_seg(pop)\n\n";
3689 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003690}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003691
Steve Naroff677ab3a2008-10-27 17:20:55 +00003692std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3693 const char *funcName,
3694 std::string Tag) {
3695 const FunctionType *AFT = CE->getFunctionType();
3696 QualType RT = AFT->getResultType();
3697 std::string StructRef = "struct " + Tag;
3698 std::string S = "static " + RT.getAsString() + " __" +
3699 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003700
Steve Naroff677ab3a2008-10-27 17:20:55 +00003701 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003703 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003704 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003705 // block (to reference imported block decl refs).
3706 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003707 } else if (BD->param_empty()) {
3708 S += "(" + StructRef + " *__cself)";
3709 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003710 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003711 assert(FT && "SynthesizeBlockFunc: No function proto");
3712 S += '(';
3713 // first add the implicit argument.
3714 S += StructRef + " *__cself, ";
3715 std::string ParamStr;
3716 for (BlockDecl::param_iterator AI = BD->param_begin(),
3717 E = BD->param_end(); AI != E; ++AI) {
3718 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003719 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003720 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003721 S += ParamStr;
3722 }
3723 if (FT->isVariadic()) {
3724 if (!BD->param_empty()) S += ", ";
3725 S += "...";
3726 }
3727 S += ')';
3728 }
3729 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003730
Steve Naroff677ab3a2008-10-27 17:20:55 +00003731 // Create local declarations to avoid rewriting all closure decl ref exprs.
3732 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003733 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003734 E = BlockByRefDecls.end(); I != E; ++I) {
3735 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003736 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003737 std::string TypeString = "struct __Block_byref_" + Name + " *";
3738 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003739 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003740 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003741 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003742 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003743 E = BlockByCopyDecls.end(); I != E; ++I) {
3744 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003745 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003746 // Handle nested closure invocation. For example:
3747 //
3748 // void (^myImportedClosure)(void);
3749 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003750 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003751 // void (^anotherClosure)(void);
3752 // anotherClosure = ^(void) {
3753 // myImportedClosure(); // import and invoke the closure
3754 // };
3755 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003756 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003757 S += "struct __block_impl *";
3758 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003759 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003760 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003761 }
3762 std::string RewrittenStr = RewrittenBlockExprs[CE];
3763 const char *cstr = RewrittenStr.c_str();
3764 while (*cstr++ != '{') ;
3765 S += cstr;
3766 S += "\n";
3767 return S;
3768}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003769
Steve Naroff677ab3a2008-10-27 17:20:55 +00003770std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3771 const char *funcName,
3772 std::string Tag) {
3773 std::string StructRef = "struct " + Tag;
3774 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003775
Steve Naroff677ab3a2008-10-27 17:20:55 +00003776 S += funcName;
3777 S += "_block_copy_" + utostr(i);
3778 S += "(" + StructRef;
3779 S += "*dst, " + StructRef;
3780 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003781 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003783 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003784 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003785 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003786 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003787 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003788 }
3789 S += "\nstatic void __";
3790 S += funcName;
3791 S += "_block_dispose_" + utostr(i);
3792 S += "(" + StructRef;
3793 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003794 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003795 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003796 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003797 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003798 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003799 }
Mike Stump11289f42009-09-09 15:08:12 +00003800 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 return S;
3802}
3803
Steve Naroff30484702009-12-06 21:14:13 +00003804std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3805 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003806 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003807 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003808
Steve Naroff677ab3a2008-10-27 17:20:55 +00003809 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003810 S += " struct " + Desc;
3811 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003812
Steve Naroff30484702009-12-06 21:14:13 +00003813 Constructor += "(void *fp, "; // Invoke function pointer.
3814 Constructor += "struct " + Desc; // Descriptor pointer.
3815 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003816
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 if (BlockDeclRefs.size()) {
3818 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003819 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003820 E = BlockByCopyDecls.end(); I != E; ++I) {
3821 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003822 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003823 std::string ArgName = "_" + FieldName;
3824 // Handle nested closure invocation. For example:
3825 //
3826 // void (^myImportedBlock)(void);
3827 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003828 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003829 // void (^anotherBlock)(void);
3830 // anotherBlock = ^(void) {
3831 // myImportedBlock(); // import and invoke the closure
3832 // };
3833 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003834 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 S += "struct __block_impl *";
3836 Constructor += ", void *" + ArgName;
3837 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003838 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3839 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003840 Constructor += ", " + ArgName;
3841 }
3842 S += FieldName + ";\n";
3843 }
3844 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003845 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003846 E = BlockByRefDecls.end(); I != E; ++I) {
3847 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003848 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003849 std::string ArgName = "_" + FieldName;
3850 // Handle nested closure invocation. For example:
3851 //
3852 // void (^myImportedBlock)(void);
3853 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003854 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003855 // void (^anotherBlock)(void);
3856 // anotherBlock = ^(void) {
3857 // myImportedBlock(); // import and invoke the closure
3858 // };
3859 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003860 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003861 S += "struct __block_impl *";
3862 Constructor += ", void *" + ArgName;
3863 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003864 std::string TypeString = "struct __Block_byref_" + FieldName;
3865 TypeString += " *";
3866 FieldName = TypeString + FieldName;
3867 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 Constructor += ", " + ArgName;
3869 }
3870 S += FieldName + "; // by ref\n";
3871 }
3872 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003873 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003874 if (GlobalVarDecl)
3875 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3876 else
3877 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003878 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003879
Steve Naroff30484702009-12-06 21:14:13 +00003880 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003881
Steve Naroff677ab3a2008-10-27 17:20:55 +00003882 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003883 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003884 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003885 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003887 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888 Constructor += Name + " = (struct __block_impl *)_";
3889 else
3890 Constructor += Name + " = _";
3891 Constructor += Name + ";\n";
3892 }
3893 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003894 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003895 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003896 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003898 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003899 Constructor += Name + " = (struct __block_impl *)_";
3900 else
3901 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003902 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 }
3904 } else {
3905 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003906 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003907 if (GlobalVarDecl)
3908 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3909 else
3910 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003911 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3912 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913 }
3914 Constructor += " ";
3915 Constructor += "}\n";
3916 S += Constructor;
3917 S += "};\n";
3918 return S;
3919}
3920
Steve Naroff30484702009-12-06 21:14:13 +00003921std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3922 std::string ImplTag, int i,
3923 const char *FunName,
3924 unsigned hasCopy) {
3925 std::string S = "\nstatic struct " + DescTag;
3926
3927 S += " {\n unsigned long reserved;\n";
3928 S += " unsigned long Block_size;\n";
3929 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003930 S += " void (*copy)(struct ";
3931 S += ImplTag; S += "*, struct ";
3932 S += ImplTag; S += "*);\n";
3933
3934 S += " void (*dispose)(struct ";
3935 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003936 }
3937 S += "} ";
3938
3939 S += DescTag + "_DATA = { 0, sizeof(struct ";
3940 S += ImplTag + ")";
3941 if (hasCopy) {
3942 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3943 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3944 }
3945 S += "};\n";
3946 return S;
3947}
3948
Steve Naroff677ab3a2008-10-27 17:20:55 +00003949void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3950 const char *FunName) {
3951 // Insert closures that were part of the function.
3952 for (unsigned i = 0; i < Blocks.size(); i++) {
3953
3954 CollectBlockDeclRefInfo(Blocks[i]);
3955
Steve Naroff30484702009-12-06 21:14:13 +00003956 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3957 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003958
Steve Naroff30484702009-12-06 21:14:13 +00003959 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003960
3961 InsertText(FunLocStart, CI.c_str(), CI.size());
3962
Steve Naroff30484702009-12-06 21:14:13 +00003963 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003964
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 InsertText(FunLocStart, CF.c_str(), CF.size());
3966
3967 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003968 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003969 InsertText(FunLocStart, HF.c_str(), HF.size());
3970 }
Steve Naroff30484702009-12-06 21:14:13 +00003971 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3972 ImportedBlockDecls.size() > 0);
3973 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00003974
Steve Naroff677ab3a2008-10-27 17:20:55 +00003975 BlockDeclRefs.clear();
3976 BlockByRefDecls.clear();
3977 BlockByCopyDecls.clear();
3978 BlockCallExprs.clear();
3979 ImportedBlockDecls.clear();
3980 }
3981 Blocks.clear();
3982 RewrittenBlockExprs.clear();
3983}
3984
3985void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3986 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003987 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003988
Steve Naroff677ab3a2008-10-27 17:20:55 +00003989 SynthesizeBlockLiterals(FunLocStart, FuncName);
3990}
3991
3992void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003993 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3994 //SourceLocation FunLocStart = MD->getLocStart();
3995 // FIXME: This hack works around a bug in Rewrite.InsertText().
3996 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003997 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003998 // Convert colons to underscores.
3999 std::string::size_type loc = 0;
4000 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4001 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004002
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4004}
4005
4006void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4007 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4008 CI != E; ++CI)
4009 if (*CI) {
4010 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4011 GetBlockDeclRefExprs(CBE->getBody());
4012 else
4013 GetBlockDeclRefExprs(*CI);
4014 }
4015 // Handle specific things.
4016 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4017 // FIXME: Handle enums.
4018 if (!isa<FunctionDecl>(CDRE->getDecl()))
4019 BlockDeclRefs.push_back(CDRE);
4020 return;
4021}
4022
4023void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4024 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4025 CI != E; ++CI)
4026 if (*CI) {
4027 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4028 GetBlockCallExprs(CBE->getBody());
4029 else
4030 GetBlockCallExprs(*CI);
4031 }
Mike Stump11289f42009-09-09 15:08:12 +00004032
Steve Naroff677ab3a2008-10-27 17:20:55 +00004033 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4034 if (CE->getCallee()->getType()->isBlockPointerType()) {
4035 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4036 }
4037 }
4038 return;
4039}
4040
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004041Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004043 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004044
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004045 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004046 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004047 } else if (const BlockDeclRefExpr *CDRE =
4048 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004049 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004050 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004051 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004052 }
4053 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4054 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4055 }
4056 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4057 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4058 else if (const ConditionalOperator *CEXPR =
4059 dyn_cast<ConditionalOperator>(BlockExp)) {
4060 Expr *LHSExp = CEXPR->getLHS();
4061 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4062 Expr *RHSExp = CEXPR->getRHS();
4063 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4064 Expr *CONDExp = CEXPR->getCond();
4065 ConditionalOperator *CondExpr =
4066 new (Context) ConditionalOperator(CONDExp,
4067 SourceLocation(), cast<Expr>(LHSStmt),
4068 SourceLocation(), cast<Expr>(RHSStmt),
4069 Exp->getType());
4070 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004071 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4072 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004073 } else {
4074 assert(1 && "RewriteBlockClass: Bad type");
4075 }
4076 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004077 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004078 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004079 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004081
Steve Naroff350b6652008-10-30 10:07:53 +00004082 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4083 SourceLocation(),
4084 &Context->Idents.get("__block_impl"));
4085 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086
Steve Naroff350b6652008-10-30 10:07:53 +00004087 // Generate a funky cast.
4088 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004089
Steve Naroff350b6652008-10-30 10:07:53 +00004090 // Push the block argument type.
4091 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004092 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004093 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004094 E = FTP->arg_type_end(); I && (I != E); ++I) {
4095 QualType t = *I;
4096 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004097 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004098 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004099 t = Context->getPointerType(BPT->getPointeeType());
4100 }
4101 ArgTypes.push_back(t);
4102 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004103 }
Steve Naroff350b6652008-10-30 10:07:53 +00004104 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004105 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004106 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004107
Steve Naroff350b6652008-10-30 10:07:53 +00004108 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004109
4110 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004111 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004112 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004113 PtrBlock, SourceLocation(),
4114 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004115 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004116 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4117 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004118 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004119
Douglas Gregor91f84212008-12-11 16:49:14 +00004120 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004121 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004122 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004123 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4124 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004125
Anders Carlssona2615922009-07-31 00:48:10 +00004126 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4127 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004128 PtrToFuncCastType,
4129 SourceLocation(),
4130 SourceLocation());
4131 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004132
Steve Naroff350b6652008-10-30 10:07:53 +00004133 llvm::SmallVector<Expr*, 8> BlkExprs;
4134 // Add the implicit argument.
4135 BlkExprs.push_back(BlkCast);
4136 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004137 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004139 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004141 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4142 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004143 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004144 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004145}
4146
4147void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004148 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004149 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004150}
4151
Steve Naroffd9803712009-04-29 16:37:50 +00004152// We need to return the rewritten expression to handle cases where the
4153// BlockDeclRefExpr is embedded in another expression being rewritten.
4154// For example:
4155//
4156// int main() {
4157// __block Foo *f;
4158// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004159//
Steve Naroffd9803712009-04-29 16:37:50 +00004160// void (^myblock)() = ^() {
4161// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4162// i = 77;
4163// };
4164//}
4165Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004166 // FIXME: Add more elaborate code generation required by the ABI.
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004167 // That is, must generate BYREFVAR->__forwarding->BYREFVAR for each
4168 // BDRE where BYREFVAR is name of the variable.
Ted Kremenek5a201952009-02-07 01:47:29 +00004169 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004170 Context->getPointerType(BDRE->getType()),
4171 SourceLocation());
4172 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004173 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004174 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004175 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176}
4177
Steve Naroffc989a7b2008-11-03 23:29:32 +00004178void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4179 SourceLocation LocStart = CE->getLParenLoc();
4180 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004181
4182 // Need to avoid trying to rewrite synthesized casts.
4183 if (LocStart.isInvalid())
4184 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004185 // Need to avoid trying to rewrite casts contained in macros.
4186 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4187 return;
Mike Stump11289f42009-09-09 15:08:12 +00004188
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 const char *startBuf = SM->getCharacterData(LocStart);
4190 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004191
Steve Naroff677ab3a2008-10-27 17:20:55 +00004192 // advance the location to startArgList.
4193 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004194
Steve Naroff677ab3a2008-10-27 17:20:55 +00004195 while (*argPtr++ && (argPtr < endBuf)) {
4196 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004197 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004198 // Replace the '^' with '*'.
4199 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4200 ReplaceText(LocStart, 1, "*", 1);
4201 break;
4202 }
4203 }
4204 return;
4205}
4206
4207void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4208 SourceLocation DeclLoc = FD->getLocation();
4209 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 // We have 1 or more arguments that have closure pointers.
4212 const char *startBuf = SM->getCharacterData(DeclLoc);
4213 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004214
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004216
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 parenCount++;
4218 // advance the location to startArgList.
4219 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4220 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004221
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004223
Steve Naroff677ab3a2008-10-27 17:20:55 +00004224 while (*argPtr++ && parenCount) {
4225 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004226 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004227 // Replace the '^' with '*'.
4228 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4229 ReplaceText(DeclLoc, 1, "*", 1);
4230 break;
Mike Stump11289f42009-09-09 15:08:12 +00004231 case '(':
4232 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004233 break;
Mike Stump11289f42009-09-09 15:08:12 +00004234 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004235 parenCount--;
4236 break;
4237 }
4238 }
4239 return;
4240}
4241
4242bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004243 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004244 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004246 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004248 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004249 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004250 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 }
4252 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004253 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004255 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004256 return true;
4257 }
4258 return false;
4259}
4260
Ted Kremenek5a201952009-02-07 01:47:29 +00004261void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4262 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004263 const char *argPtr = strchr(Name, '(');
4264 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004265
Steve Naroff677ab3a2008-10-27 17:20:55 +00004266 LParen = argPtr; // output the start.
4267 argPtr++; // skip past the left paren.
4268 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004269
Steve Naroff677ab3a2008-10-27 17:20:55 +00004270 while (*argPtr && parenCount) {
4271 switch (*argPtr) {
4272 case '(': parenCount++; break;
4273 case ')': parenCount--; break;
4274 default: break;
4275 }
4276 if (parenCount) argPtr++;
4277 }
4278 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4279 RParen = argPtr; // output the end
4280}
4281
4282void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4283 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4284 RewriteBlockPointerFunctionArgs(FD);
4285 return;
Mike Stump11289f42009-09-09 15:08:12 +00004286 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 // Handle Variables and Typedefs.
4288 SourceLocation DeclLoc = ND->getLocation();
4289 QualType DeclT;
4290 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4291 DeclT = VD->getType();
4292 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4293 DeclT = TDD->getUnderlyingType();
4294 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4295 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004296 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004298
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 const char *startBuf = SM->getCharacterData(DeclLoc);
4300 const char *endBuf = startBuf;
4301 // scan backward (from the decl location) for the end of the previous decl.
4302 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4303 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004304
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 // *startBuf != '^' if we are dealing with a pointer to function that
4306 // may take block argument types (which will be handled below).
4307 if (*startBuf == '^') {
4308 // Replace the '^' with '*', computing a negative offset.
4309 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4310 ReplaceText(DeclLoc, 1, "*", 1);
4311 }
4312 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4313 // Replace the '^' with '*' for arguments.
4314 DeclLoc = ND->getLocation();
4315 startBuf = SM->getCharacterData(DeclLoc);
4316 const char *argListBegin, *argListEnd;
4317 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4318 while (argListBegin < argListEnd) {
4319 if (*argListBegin == '^') {
4320 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4321 ReplaceText(CaretLoc, 1, "*", 1);
4322 }
4323 argListBegin++;
4324 }
4325 }
4326 return;
4327}
4328
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004329/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4330/// the declaration into:
4331/// struct __Block_byref_ND {
4332/// void *__isa; // NULL for everything except __weak pointers
4333/// struct __Block_byref_ND *__forwarding;
4334/// int32_t __flags;
4335/// int32_t __size;
4336/// void *__ByrefKeepFuncPtr; // Only if variable is __block ObjC object
4337/// void *__ByrefDestroyFuncPtr; // Only if variable is __block ObjC object
4338/// typex ND;
4339/// };
4340///
4341/// It then replaces declaration of ND variable with:
4342/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4343/// __size=sizeof(struct __Block_byref_ND),
4344/// ND=initializer-if-any};
4345///
4346///
4347void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4348 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4349 const char *startBuf = SM->getCharacterData(DeclLoc);
4350 const char *endBuf = SM->getCharacterData(ND->getLocEnd());
4351 std::string Name(ND->getNameAsString());
4352 std::string ByrefType = "struct __Block_byref_";
4353 ByrefType += Name;
4354 ByrefType += " {\n";
4355 ByrefType += " void *__isa;\n";
4356 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4357 ByrefType += " int __flags;\n";
4358 ByrefType += " int __size;\n";
4359 // FIXME. Add void *__ByrefKeepFuncPtr; void *__ByrefDestroyFuncPtr;
4360 // if needed.
4361 ND->getType().getAsStringInternal(Name, Context->PrintingPolicy);
4362 ByrefType += " " + Name + ";\n";
4363 ByrefType += "};\n";
4364 // Insert this type in global scope. It is needed by helper function.
4365 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4366 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4367 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
4368
4369 // struct __Block_byref_ND ND =
4370 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4371 // initializer-if-any};
4372 bool hasInit = (ND->getInit() != 0);
4373 Name = ND->getNameAsString();
4374 ByrefType = "struct __Block_byref_" + Name;
4375 if (!hasInit) {
4376 ByrefType += " " + Name + " = ";
4377 ByrefType += "{0, &" + Name + ", ";
4378 // FIXME. Compute the flag.
4379 ByrefType += "0, ";
4380 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
4381 ByrefType += "};\n";
4382 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4383 ByrefType.c_str(), ByrefType.size());
4384 }
4385 else {
4386 SourceLocation startLoc = ND->getInit()->getLocStart();
4387 ByrefType += " " + Name;
4388 ReplaceText(DeclLoc, endBuf-startBuf,
4389 ByrefType.c_str(), ByrefType.size());
4390 ByrefType = " = {0, &" + Name + ", ";
4391 // FIXME. Compute the flag.
4392 ByrefType += "0, ";
4393 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
4394 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004395
4396 // Complete the newly synthesized compound expression by inserting a right
4397 // curly brace before the end of the declaration.
4398 // FIXME: This approach avoids rewriting the initializer expression. It
4399 // also assumes there is only one declarator. For example, the following
4400 // isn't currently supported by this routine (in general):
4401 //
4402 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4403 //
4404 const char *startBuf = SM->getCharacterData(startLoc);
4405 const char *semiBuf = strchr(startBuf, ';');
4406 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4407 SourceLocation semiLoc =
4408 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4409
4410 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004411 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004412 return;
4413}
4414
Mike Stump11289f42009-09-09 15:08:12 +00004415void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004416 // Add initializers for any closure decl refs.
4417 GetBlockDeclRefExprs(Exp->getBody());
4418 if (BlockDeclRefs.size()) {
4419 // Unique all "by copy" declarations.
4420 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4421 if (!BlockDeclRefs[i]->isByRef())
4422 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4423 // Unique all "by ref" declarations.
4424 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4425 if (BlockDeclRefs[i]->isByRef()) {
4426 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4427 }
4428 // Find any imported blocks...they will need special attention.
4429 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004430 if (BlockDeclRefs[i]->isByRef() ||
4431 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4432 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004433 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004434 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4435 }
4436 }
4437}
4438
Steve Narofff4b992a2008-10-28 20:29:00 +00004439FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4440 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004441 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004442 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004443 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004444 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004445}
4446
Steve Naroffd8907b72008-10-29 18:15:37 +00004447Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004448 Blocks.push_back(Exp);
4449
4450 CollectBlockDeclRefInfo(Exp);
4451 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004452
Steve Narofff4b992a2008-10-28 20:29:00 +00004453 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004454 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004455 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004456 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004457 // Convert colons to underscores.
4458 std::string::size_type loc = 0;
4459 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4460 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004461 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004462 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004463
Steve Narofff4b992a2008-10-28 20:29:00 +00004464 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004465
Steve Narofff4b992a2008-10-28 20:29:00 +00004466 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4467 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004468
Steve Narofff4b992a2008-10-28 20:29:00 +00004469 // Get a pointer to the function type so we can cast appropriately.
4470 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4471
4472 FunctionDecl *FD;
4473 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Narofff4b992a2008-10-28 20:29:00 +00004475 // Simulate a contructor call...
4476 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004477 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004478
Steve Narofff4b992a2008-10-28 20:29:00 +00004479 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004480
Steve Naroffe2514232008-10-29 21:23:59 +00004481 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004482 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004483 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4484 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004485 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4486 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004487 Context->VoidPtrTy, SourceLocation(),
4488 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004489 InitExprs.push_back(castExpr);
4490
Steve Naroff30484702009-12-06 21:14:13 +00004491 // Initialize the block descriptor.
4492 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004493
Steve Naroff30484702009-12-06 21:14:13 +00004494 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4495 &Context->Idents.get(DescData.c_str()),
4496 Context->VoidPtrTy, 0,
4497 VarDecl::Static);
4498 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4499 new (Context) DeclRefExpr(NewVD,
4500 Context->VoidPtrTy, SourceLocation()),
4501 UnaryOperator::AddrOf,
4502 Context->getPointerType(Context->VoidPtrTy),
4503 SourceLocation());
4504 InitExprs.push_back(DescRefExpr);
4505
Steve Narofff4b992a2008-10-28 20:29:00 +00004506 // Add initializers for any closure decl refs.
4507 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004508 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004509 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004510 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004511 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004512 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004513 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004514 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004515 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004516 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004517 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004518 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004519 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4520 CastExpr::CK_Unknown, Arg,
4521 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004522 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004523 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004524 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004525 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004526 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004527 }
Mike Stump11289f42009-09-09 15:08:12 +00004528 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004529 }
4530 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004531 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004532 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004533 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004534 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4535 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004536 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004537 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004538 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004539 }
4540 }
Steve Naroff30484702009-12-06 21:14:13 +00004541 if (ImportedBlockDecls.size()) { // generate "1<<25" to indicate we have helper functions.
4542 unsigned IntSize =
4543 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4544 BinaryOperator *Exp = new (Context) BinaryOperator(
4545 new (Context) IntegerLiteral(llvm::APInt(IntSize, 1),
4546 Context->IntTy,SourceLocation()),
4547 new (Context) IntegerLiteral(llvm::APInt(IntSize, 25),
4548 Context->IntTy, SourceLocation()),
4549 BinaryOperator::Shl, Context->IntTy, SourceLocation());
4550 InitExprs.push_back(Exp);
4551 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004552 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4553 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004554 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004555 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004556 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004557 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004558 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004559 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004560 BlockDeclRefs.clear();
4561 BlockByRefDecls.clear();
4562 BlockByCopyDecls.clear();
4563 ImportedBlockDecls.clear();
4564 return NewRep;
4565}
4566
4567//===----------------------------------------------------------------------===//
4568// Function Body / Expression rewriting
4569//===----------------------------------------------------------------------===//
4570
Steve Naroff4588d0f2008-12-04 16:24:46 +00004571// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4572// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4573// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4574// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4575// Since the rewriter isn't capable of rewriting rewritten code, it's important
4576// we get this right.
4577void RewriteObjC::CollectPropertySetters(Stmt *S) {
4578 // Perform a bottom up traversal of all children.
4579 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4580 CI != E; ++CI)
4581 if (*CI)
4582 CollectPropertySetters(*CI);
4583
4584 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4585 if (BinOp->isAssignmentOp()) {
4586 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4587 PropSetters[PRE] = BinOp;
4588 }
4589 }
4590}
4591
Steve Narofff4b992a2008-10-28 20:29:00 +00004592Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004593 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004594 isa<DoStmt>(S) || isa<ForStmt>(S))
4595 Stmts.push_back(S);
4596 else if (isa<ObjCForCollectionStmt>(S)) {
4597 Stmts.push_back(S);
Anders Carlsson3caa2b42009-12-22 06:13:42 +00004598 ++BcLabelCount;
4599 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004600 }
Mike Stump11289f42009-09-09 15:08:12 +00004601
Steve Narofff4b992a2008-10-28 20:29:00 +00004602 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004603
Steve Narofff4b992a2008-10-28 20:29:00 +00004604 // Perform a bottom up rewrite of all children.
4605 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4606 CI != E; ++CI)
4607 if (*CI) {
4608 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004609 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004610 *CI = newStmt;
4611 }
Mike Stump11289f42009-09-09 15:08:12 +00004612
Steve Narofff4b992a2008-10-28 20:29:00 +00004613 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4614 // Rewrite the block body in place.
4615 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004616
Steve Narofff4b992a2008-10-28 20:29:00 +00004617 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004618 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4619 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004620
Steve Narofff4b992a2008-10-28 20:29:00 +00004621 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4622 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004623 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004624 return blockTranscribed;
4625 }
4626 // Handle specific things.
4627 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4628 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004629
Steve Narofff4b992a2008-10-28 20:29:00 +00004630 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4631 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4632
Steve Naroff4588d0f2008-12-04 16:24:46 +00004633 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4634 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4635 if (BinOp) {
4636 // Because the rewriter doesn't allow us to rewrite rewritten code,
4637 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004638 DisableReplaceStmt = true;
4639 // Save the source range. Even if we disable the replacement, the
4640 // rewritten node will have been inserted into the tree. If the synthesized
4641 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004642 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004643 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4644 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004645 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004646 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004647 //
4648 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4649 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4650 // to see the original expression). Consider this example:
4651 //
4652 // Foo *obj1, *obj2;
4653 //
4654 // obj1.i = [obj2 rrrr];
4655 //
4656 // 'BinOp' for the previous expression looks like:
4657 //
4658 // (BinaryOperator 0x231ccf0 'int' '='
4659 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4660 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4661 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4662 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4663 //
4664 // 'newStmt' represents the rewritten message expression. For example:
4665 //
4666 // (CallExpr 0x231d300 'id':'struct objc_object *'
4667 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4668 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4669 // (CStyleCastExpr 0x231d220 'void *'
4670 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4671 //
4672 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4673 // can be used as the setter argument. ReplaceStmt() will still 'see'
4674 // the original RHS (since we haven't altered BinOp).
4675 //
Mike Stump11289f42009-09-09 15:08:12 +00004676 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004677 // node. As a result, we now leak the original AST nodes.
4678 //
Steve Naroff08628db2008-12-09 12:56:34 +00004679 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004680 } else {
4681 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004682 }
4683 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004684 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4685 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4688 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004689
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004691#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 // Before we rewrite it, put the original message expression in a comment.
4693 SourceLocation startLoc = MessExpr->getLocStart();
4694 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004695
Steve Narofff4b992a2008-10-28 20:29:00 +00004696 const char *startBuf = SM->getCharacterData(startLoc);
4697 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004698
Steve Narofff4b992a2008-10-28 20:29:00 +00004699 std::string messString;
4700 messString += "// ";
4701 messString.append(startBuf, endBuf-startBuf+1);
4702 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004703
4704 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004705 // InsertText(clang::SourceLocation, char const*, unsigned int).
4706 // InsertText(startLoc, messString.c_str(), messString.size());
4707 // Tried this, but it didn't work either...
4708 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004709#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 return RewriteMessageExpr(MessExpr);
4711 }
Mike Stump11289f42009-09-09 15:08:12 +00004712
Steve Narofff4b992a2008-10-28 20:29:00 +00004713 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4714 return RewriteObjCTryStmt(StmtTry);
4715
4716 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4717 return RewriteObjCSynchronizedStmt(StmtTry);
4718
4719 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4720 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004721
Steve Narofff4b992a2008-10-28 20:29:00 +00004722 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4723 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004724
4725 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004726 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004727 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004728 OrigStmtRange.getEnd());
4729 if (BreakStmt *StmtBreakStmt =
4730 dyn_cast<BreakStmt>(S))
4731 return RewriteBreakStmt(StmtBreakStmt);
4732 if (ContinueStmt *StmtContinueStmt =
4733 dyn_cast<ContinueStmt>(S))
4734 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004735
4736 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004737 // and cast exprs.
4738 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4739 // FIXME: What we're doing here is modifying the type-specifier that
4740 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004741 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004742 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4743 // the context of an ObjCForCollectionStmt. For example:
4744 // NSArray *someArray;
4745 // for (id <FooProtocol> index in someArray) ;
4746 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4747 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004748 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004749 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004750
Steve Narofff4b992a2008-10-28 20:29:00 +00004751 // Blocks rewrite rules.
4752 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4753 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004754 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004755 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004756 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004758 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004759 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004760 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4761 if (VD->hasAttr<BlocksAttr>())
4762 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004763 }
4764 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004765 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004767 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004768 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4769 }
4770 }
4771 }
Mike Stump11289f42009-09-09 15:08:12 +00004772
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4774 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004775
4776 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004777 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4778 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004779 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4780 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 && "Statement stack mismatch");
4782 Stmts.pop_back();
4783 }
4784 // Handle blocks rewriting.
4785 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4786 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004787 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004788 }
4789 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004790 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004791 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004792 ReplaceStmt(S, BlockCall);
4793 return BlockCall;
4794 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004796 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004797 RewriteCastExpr(CE);
4798 }
4799#if 0
4800 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004801 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004802 // Get the new text.
4803 std::string SStr;
4804 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004805 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004806 const std::string &Str = Buf.str();
4807
4808 printf("CAST = %s\n", &Str[0]);
4809 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4810 delete S;
4811 return Replacement;
4812 }
4813#endif
4814 // Return this stmt unmodified.
4815 return S;
4816}
4817
Steve Naroffe70a52a2009-12-05 15:55:59 +00004818void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4819 for (RecordDecl::field_iterator i = RD->field_begin(),
4820 e = RD->field_end(); i != e; ++i) {
4821 FieldDecl *FD = *i;
4822 if (isTopLevelBlockPointerType(FD->getType()))
4823 RewriteBlockPointerDecl(FD);
4824 if (FD->getType()->isObjCQualifiedIdType() ||
4825 FD->getType()->isObjCQualifiedInterfaceType())
4826 RewriteObjCQualifiedInterfaceTypes(FD);
4827 }
4828}
4829
Steve Narofff4b992a2008-10-28 20:29:00 +00004830/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4831/// main file of the input.
4832void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4833 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004834 if (FD->isOverloadedOperator())
4835 return;
Mike Stump11289f42009-09-09 15:08:12 +00004836
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 // Since function prototypes don't have ParmDecl's, we check the function
4838 // prototype. This enables us to rewrite function declarations and
4839 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004840 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004841
Sebastian Redla7b98a72009-04-26 20:35:05 +00004842 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004843 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004844 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004845 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004846 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004847 Body =
4848 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4849 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004850 CurrentBody = 0;
4851 if (PropParentMap) {
4852 delete PropParentMap;
4853 PropParentMap = 0;
4854 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004855 // This synthesizes and inserts the block "impl" struct, invoke function,
4856 // and any copy/dispose helper functions.
4857 InsertBlockLiteralsWithinFunction(FD);
4858 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004859 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004860 return;
4861 }
4862 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004863 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004864 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004865 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004866 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004867 Body =
4868 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4869 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004870 CurrentBody = 0;
4871 if (PropParentMap) {
4872 delete PropParentMap;
4873 PropParentMap = 0;
4874 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004875 InsertBlockLiteralsWithinMethod(MD);
4876 CurMethodDef = 0;
4877 }
4878 }
4879 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4880 ClassImplementation.push_back(CI);
4881 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4882 CategoryImplementation.push_back(CI);
4883 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4884 RewriteForwardClassDecl(CD);
4885 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4886 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004887 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004888 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004889 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004890 CheckFunctionPointerDecl(VD->getType(), VD);
4891 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004892 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004893 RewriteCastExpr(CE);
4894 }
4895 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004896 } else if (VD->getType()->isRecordType()) {
4897 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4898 if (RD->isDefinition())
4899 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004901 if (VD->getInit()) {
4902 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004903 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004904 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004905 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004906 CurrentBody = 0;
4907 if (PropParentMap) {
4908 delete PropParentMap;
4909 PropParentMap = 0;
4910 }
Mike Stump11289f42009-09-09 15:08:12 +00004911 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004912 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004913 GlobalVarDecl = 0;
4914
4915 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004916 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004917 RewriteCastExpr(CE);
4918 }
4919 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004920 return;
4921 }
4922 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004923 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004924 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004925 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004926 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004927 else if (TD->getUnderlyingType()->isRecordType()) {
4928 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4929 if (RD->isDefinition())
4930 RewriteRecordBody(RD);
4931 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 return;
4933 }
4934 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004935 if (RD->isDefinition())
4936 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004937 return;
4938 }
4939 // Nothing yet.
4940}
4941
Chris Lattnercf169832009-03-28 04:11:33 +00004942void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004943 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004944
Steve Narofff4b992a2008-10-28 20:29:00 +00004945 // Rewrite tabs if we care.
4946 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004947
Steve Narofff4b992a2008-10-28 20:29:00 +00004948 if (Diags.hasErrorOccurred())
4949 return;
Mike Stump11289f42009-09-09 15:08:12 +00004950
Steve Narofff4b992a2008-10-28 20:29:00 +00004951 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004952
Steve Naroffd9803712009-04-29 16:37:50 +00004953 // Here's a great place to add any extra declarations that may be needed.
4954 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004955 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004956 E = ProtocolExprDecls.end(); I != E; ++I)
4957 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4958
Mike Stump11289f42009-09-09 15:08:12 +00004959 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004961 if (ClassImplementation.size() || CategoryImplementation.size())
4962 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004963
Steve Narofff4b992a2008-10-28 20:29:00 +00004964 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4965 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004966 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004967 Rewrite.getRewriteBufferFor(MainFileID)) {
4968 //printf("Changed:\n");
4969 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4970 } else {
4971 fprintf(stderr, "No changes\n");
4972 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004973
Steve Naroffd9803712009-04-29 16:37:50 +00004974 if (ClassImplementation.size() || CategoryImplementation.size() ||
4975 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004976 // Rewrite Objective-c meta data*
4977 std::string ResultStr;
4978 SynthesizeMetaDataIntoBuffer(ResultStr);
4979 // Emit metadata.
4980 *OutFile << ResultStr;
4981 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004982 OutFile->flush();
4983}
4984