blob: 13577762cbd65bcb7eb39b3263502814f52474d8 [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 Naroff6d6da252008-12-05 17:03:39 +0000258 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000259 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000260 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000261 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
262 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
263 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000264 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
265 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000266 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000267 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000268 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000269 Stmt *RewriteBreakStmt(BreakStmt *S);
270 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000271 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000273 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000274 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000275 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000276 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000277 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000278 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000279 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000280 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000281 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000282
Chris Lattner3c799d72007-10-24 17:06:59 +0000283 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000284 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000285 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000289
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000290 template<typename MethodIterator>
291 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
292 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000293 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000294 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000295 const char *ClassName,
296 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Steve Naroffd9803712009-04-29 16:37:50 +0000298 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
299 const char *prefix,
300 const char *ClassName,
301 std::string &Result);
302 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000303 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000304 const char *ClassName,
305 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000306 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000307 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000308 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
309 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000310 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000311 void RewriteImplementations();
312 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000313
Steve Naroff677ab3a2008-10-27 17:20:55 +0000314 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000315 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000316 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Steve Naroff677ab3a2008-10-27 17:20:55 +0000318 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
319 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000320
321 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000322 void RewriteBlockCall(CallExpr *Exp);
323 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroffd9803712009-04-29 16:37:50 +0000324 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000326
327 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000328 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000329 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000330 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000331 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000332 bool hasCopyDisposeHelpers);
Steve Naroff350b6652008-10-30 10:07:53 +0000333 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000334 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
335 const char *FunName);
Mike Stump11289f42009-09-09 15:08:12 +0000336
Steve Naroff677ab3a2008-10-27 17:20:55 +0000337 void CollectBlockDeclRefInfo(BlockExpr *Exp);
338 void GetBlockCallExprs(Stmt *S);
339 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff677ab3a2008-10-27 17:20:55 +0000341 // We avoid calling Type::isBlockPointerType(), since it operates on the
342 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000343 bool isTopLevelBlockPointerType(QualType T) {
344 return isa<BlockPointerType>(T);
345 }
Mike Stump11289f42009-09-09 15:08:12 +0000346
Steve Naroff677ab3a2008-10-27 17:20:55 +0000347 // FIXME: This predicate seems like it would be useful to add to ASTContext.
348 bool isObjCType(QualType T) {
349 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
350 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000351
Steve Naroff677ab3a2008-10-27 17:20:55 +0000352 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000353
Steve Naroff677ab3a2008-10-27 17:20:55 +0000354 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
355 OCT == Context->getCanonicalType(Context->getObjCClassType()))
356 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000357
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000358 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000359 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000360 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 return true;
362 }
363 return false;
364 }
365 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000366 void GetExtentOfArgList(const char *Name, const char *&LParen,
367 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000368 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000369
Steve Narofff4b992a2008-10-28 20:29:00 +0000370 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000371 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Steve Naroffd9803712009-04-29 16:37:50 +0000373 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000374 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000375 if (From[i] == '"')
376 To += "\\\"";
377 else
378 To += From[i];
379 }
380 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000381 };
382}
383
Mike Stump11289f42009-09-09 15:08:12 +0000384void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
385 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000386 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000387 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000389 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 // All the args are checked/rewritten. Don't call twice!
391 RewriteBlockPointerDecl(D);
392 break;
393 }
394 }
395}
396
397void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000398 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000399 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000400 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000401}
402
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000403static bool IsHeaderFile(const std::string &Filename) {
404 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000405
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000406 if (DotPos == std::string::npos) {
407 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000408 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000409 }
Mike Stump11289f42009-09-09 15:08:12 +0000410
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000411 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
412 // C header: .h
413 // C++ header: .hh or .H;
414 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000415}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000416
Eli Friedman94cf21e2009-05-18 22:20:00 +0000417RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000418 Diagnostic &D, const LangOptions &LOpts,
419 bool silenceMacroWarn)
420 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
421 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000422 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000423 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000424 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000425 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000426 "rewriter doesn't support user-specified control flow semantics "
427 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000428}
429
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000430ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
431 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000432 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000433 const LangOptions &LOpts,
434 bool SilenceRewriteMacroWarning) {
435 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000436}
Chris Lattnere99c8322007-10-11 00:43:27 +0000437
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000438void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000439 Context = &context;
440 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000441 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000442 MsgSendFunctionDecl = 0;
443 MsgSendSuperFunctionDecl = 0;
444 MsgSendStretFunctionDecl = 0;
445 MsgSendSuperStretFunctionDecl = 0;
446 MsgSendFpretFunctionDecl = 0;
447 GetClassFunctionDecl = 0;
448 GetMetaClassFunctionDecl = 0;
449 SelGetUidFunctionDecl = 0;
450 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000451 ConstantStringClassReference = 0;
452 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453 CurMethodDef = 0;
454 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000455 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000456 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000457 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000458 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000459 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000460 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000461 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000462 PropParentMap = 0;
463 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000464 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattner187f6262008-01-31 19:38:44 +0000466 // Get the ID and start/end of the main file.
467 MainFileID = SM->getMainFileID();
468 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
469 MainFileStart = MainBuf->getBufferStart();
470 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattner184e65d2009-04-14 23:22:57 +0000472 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner187f6262008-01-31 19:38:44 +0000474 // declaring objc_selector outside the parameter list removes a silly
475 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000476 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000477 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000478 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000479 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000480 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000481 if (LangOpts.Microsoft) {
482 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000483 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
484 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000485 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000486 }
Steve Naroff00a31762008-03-27 22:29:16 +0000487 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000488 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
489 Preamble += "typedef struct objc_object Protocol;\n";
490 Preamble += "#define _REWRITER_typedef_Protocol\n";
491 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000492 if (LangOpts.Microsoft) {
493 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
494 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
495 } else
496 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
497 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000498 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000499 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000500 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000501 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000502 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000504 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000505 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000506 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000508 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000510 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
515 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000516 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000517 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000521 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
522 Preamble += "struct __objcFastEnumerationState {\n\t";
523 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000524 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "unsigned long *mutationsPtr;\n\t";
526 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000528 Preamble += "#define __FASTENUMERATIONSTATE\n";
529 Preamble += "#endif\n";
530 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
531 Preamble += "struct __NSConstantStringImpl {\n";
532 Preamble += " int *isa;\n";
533 Preamble += " int flags;\n";
534 Preamble += " char *str;\n";
535 Preamble += " long length;\n";
536 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000537 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
538 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
539 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000541 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000542 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
543 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000544 // Blocks preamble.
545 Preamble += "#ifndef BLOCK_IMPL\n";
546 Preamble += "#define BLOCK_IMPL\n";
547 Preamble += "struct __block_impl {\n";
548 Preamble += " void *isa;\n";
549 Preamble += " int Flags;\n";
550 Preamble += " int Size;\n";
551 Preamble += " void *FuncPtr;\n";
552 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000553 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
557 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000558 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000559 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000560 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
561 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000562 Preamble += "#define __attribute__(X)\n";
563 }
Chris Lattner187f6262008-01-31 19:38:44 +0000564}
565
566
Chris Lattner3c799d72007-10-24 17:06:59 +0000567//===----------------------------------------------------------------------===//
568// Top Level Driver Code
569//===----------------------------------------------------------------------===//
570
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000571void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000572 // Two cases: either the decl could be in the main file, or it could be in a
573 // #included file. If the former, rewrite it now. If the later, check to see
574 // if we rewrote the #include/#import.
575 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000576 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner0bd1c972007-10-16 21:07:07 +0000578 // If this is for a builtin, ignore it.
579 if (Loc.isInvalid()) return;
580
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000581 // Look for built-in declarations that we need to refer during the rewrite.
582 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000583 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000584 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000585 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000586 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000587 ConstantStringClassReference = FVD;
588 return;
589 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000590 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000591 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000592 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000593 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000594 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000595 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000596 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000597 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000598 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000599 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
600 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000601 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
602 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000603 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000604 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000605 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000606 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000607 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000608 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000609}
610
Chris Lattner3c799d72007-10-24 17:06:59 +0000611//===----------------------------------------------------------------------===//
612// Syntactic (non-AST) Rewriting Code
613//===----------------------------------------------------------------------===//
614
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000615void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000616 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000617 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
618 const char *MainBufStart = MainBuf.first;
619 const char *MainBufEnd = MainBuf.second;
620 size_t ImportLen = strlen("import");
621 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000622
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000623 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000624 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
625 if (*BufPtr == '#') {
626 if (++BufPtr == MainBufEnd)
627 return;
628 while (*BufPtr == ' ' || *BufPtr == '\t')
629 if (++BufPtr == MainBufEnd)
630 return;
631 if (!strncmp(BufPtr, "import", ImportLen)) {
632 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000633 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000634 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000635 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000636 BufPtr += ImportLen;
637 }
638 }
639 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000640}
641
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000642void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000643 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
644 const char *MainBufStart = MainBuf.first;
645 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner3c799d72007-10-24 17:06:59 +0000647 // Loop over the whole file, looking for tabs.
648 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
649 if (*BufPtr != '\t')
650 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000651
Chris Lattner3c799d72007-10-24 17:06:59 +0000652 // Okay, we found a tab. This tab will turn into at least one character,
653 // but it depends on which 'virtual column' it is in. Compute that now.
654 unsigned VCol = 0;
655 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
656 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
657 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000658
Chris Lattner3c799d72007-10-24 17:06:59 +0000659 // Okay, now that we know the virtual column, we know how many spaces to
660 // insert. We assume 8-character tab-stops.
661 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner3c799d72007-10-24 17:06:59 +0000663 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000664 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
665 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner3c799d72007-10-24 17:06:59 +0000667 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000668 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000669 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000670}
671
Steve Naroff9af94912008-12-02 15:48:25 +0000672static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
673 ObjCIvarDecl *OID) {
674 std::string S;
675 S = "((struct ";
676 S += ClassDecl->getIdentifier()->getName();
677 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000678 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000679 return S;
680}
681
Steve Naroffc038b3a2008-12-02 17:36:43 +0000682void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
683 ObjCImplementationDecl *IMD,
684 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000685 SourceLocation startLoc = PID->getLocStart();
686 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000687 const char *startBuf = SM->getCharacterData(startLoc);
688 assert((*startBuf == '@') && "bogus @synthesize location");
689 const char *semiBuf = strchr(startBuf, ';');
690 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000691 SourceLocation onePastSemiLoc =
692 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000693
694 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
695 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000696
Steve Naroff9af94912008-12-02 15:48:25 +0000697 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000698 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000699 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000700 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000701
Steve Naroff003d00e2008-12-02 16:05:55 +0000702 if (!OID)
703 return;
Mike Stump11289f42009-09-09 15:08:12 +0000704
Steve Naroff003d00e2008-12-02 16:05:55 +0000705 std::string Getr;
706 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
707 Getr += "{ ";
708 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000709 // FIXME: deal with code generation implications for various property
710 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000711 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000712 Getr += "return " + getIvarAccessString(ClassDecl, OID);
713 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000714 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000715 if (PD->isReadOnly())
716 return;
Mike Stump11289f42009-09-09 15:08:12 +0000717
Steve Naroff9af94912008-12-02 15:48:25 +0000718 // Generate the 'setter' function.
719 std::string Setr;
720 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000721 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000722 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000723 // FIXME: deal with code generation implications for various property
724 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000725 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000726 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000727 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000728 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000729 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000730}
Chris Lattner16a0de42007-10-11 18:38:32 +0000731
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000732void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000733 // Get the start location and compute the semi location.
734 SourceLocation startLoc = ClassDecl->getLocation();
735 const char *startBuf = SM->getCharacterData(startLoc);
736 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner3c799d72007-10-24 17:06:59 +0000738 // Translate to typedef's that forward reference structs with the same name
739 // as the class. As a convenience, we include the original declaration
740 // as a comment.
741 std::string typedefString;
742 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000743 typedefString.append(startBuf, semiPtr-startBuf+1);
744 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000745 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
746 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000747 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000749 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000752 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000753 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000755 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Steve Naroff574440f2007-10-24 22:48:43 +0000759 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000761 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000762}
763
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattner88ea93e2009-02-04 01:06:56 +0000768 if (SM->getInstantiationLineNumber(LocEnd) >
769 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000770 InsertText(LocStart, "#if 0\n", 6);
771 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000772 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000773 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000774 }
775}
776
Mike Stump11289f42009-09-09 15:08:12 +0000777void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000779
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000780 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000783}
784
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Steve Naroff5448cf62007-10-30 13:30:57 +0000788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000790
791 for (ObjCCategoryDecl::instmeth_iterator
792 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000793 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000794 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000795 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000796 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000797 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000798 RewriteMethodDeclaration(*I);
799
Steve Naroff5448cf62007-10-30 13:30:57 +0000800 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000801 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000802}
803
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000804void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000805 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000806
Steve Narofff921385f2007-10-30 16:42:30 +0000807 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000808
Steve Narofff921385f2007-10-30 16:42:30 +0000809 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000810 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000811
812 for (ObjCProtocolDecl::instmeth_iterator
813 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000814 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000815 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000816 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000817 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000818 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000819 RewriteMethodDeclaration(*I);
820
Steve Narofff921385f2007-10-30 16:42:30 +0000821 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000822 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000823 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000824
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000825 // Must comment out @optional/@required
826 const char *startBuf = SM->getCharacterData(LocStart);
827 const char *endBuf = SM->getCharacterData(LocEnd);
828 for (const char *p = startBuf; p < endBuf; p++) {
829 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
830 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000831 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000832 ReplaceText(OptionalLoc, strlen("@optional"),
833 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000834
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000835 }
836 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
837 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000838 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000839 ReplaceText(OptionalLoc, strlen("@required"),
840 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000841
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000842 }
843 }
Steve Narofff921385f2007-10-30 16:42:30 +0000844}
845
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000846void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000847 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000848 if (LocStart.isInvalid())
849 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000850 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000851 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000852}
853
Mike Stump11289f42009-09-09 15:08:12 +0000854void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000855 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000856 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000857 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000858 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000859 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000860 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000861 else if (OMD->getResultType()->isFunctionPointerType() ||
862 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000863 // needs special handling, since pointer-to-functions have special
864 // syntax (where a decaration models use).
865 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000866 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000867 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000868 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000869 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000870 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000871 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000872 ResultStr += FPRetType->getResultType().getAsString();
873 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000874 }
875 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000876 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000877 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000878
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000879 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000880 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Douglas Gregorffca3a22009-01-09 17:18:27 +0000882 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000883 NameStr += "_I_";
884 else
885 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000887 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000888 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000889
890 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000891 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000892 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000893 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000896 {
897 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000898 int len = selString.size();
899 for (int i = 0; i < len; i++)
900 if (selString[i] == ':')
901 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000902 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000903 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000904 // Remember this name for metadata emission
905 MethodInternalNames[OMD] = NameStr;
906 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000908 // Rewrite arguments
909 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000910
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000911 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000912 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000913 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000915 if (!LangOpts.Microsoft) {
916 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
917 ResultStr += "struct ";
918 }
919 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000920 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000921 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000922 }
923 else
Steve Naroffd9803712009-04-29 16:37:50 +0000924 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000925
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000926 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000927 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000928 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000929
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000930 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000931 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
932 E = OMD->param_end(); PI != E; ++PI) {
933 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000934 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000935 if (PDecl->getType()->isObjCQualifiedIdType()) {
936 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000937 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000938 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000939 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000940 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000942 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000943 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
944 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000945 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000946 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000947 ResultStr += Name;
948 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000949 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000950 if (OMD->isVariadic())
951 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000952 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000953
Steve Naroffb067bbd2008-07-16 14:40:40 +0000954 if (FPRetType) {
955 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000956
Steve Naroffb067bbd2008-07-16 14:40:40 +0000957 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000958 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000959 ResultStr += "(";
960 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
961 if (i) ResultStr += ", ";
962 std::string ParamStr = FT->getArgType(i).getAsString();
963 ResultStr += ParamStr;
964 }
965 if (FT->isVariadic()) {
966 if (FT->getNumArgs()) ResultStr += ", ";
967 ResultStr += "...";
968 }
969 ResultStr += ")";
970 } else {
971 ResultStr += "()";
972 }
973 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000974}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000975void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000976 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
977 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000978
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000979 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000980 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000981 else
Chris Lattner1780a852008-01-31 19:42:41 +0000982 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000983
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000984 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000985 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
986 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000987 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000988 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000989 ObjCMethodDecl *OMD = *I;
990 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000991 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000992 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000993
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000994 const char *startBuf = SM->getCharacterData(LocStart);
995 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000996 ReplaceText(LocStart, endBuf-startBuf,
997 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001000 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001001 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1002 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001003 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001008 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001009
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001014 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001015 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001016 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001017 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001018 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001019 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001020 }
1021
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001022 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001023 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001024 else
Mike Stump11289f42009-09-09 15:08:12 +00001025 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001026}
1027
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001028void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001029 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001030 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001031 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001032 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001033 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001034 ResultStr += "\n";
1035 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001037 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001038 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001039 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001040 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001041 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001042 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001043 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001044 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001045
1046 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001047 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001048 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001049 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001050 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001051 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001052 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001053 for (ObjCInterfaceDecl::classmeth_iterator
1054 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001055 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
1057
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001058 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001059 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001060}
1061
Steve Naroff08628db2008-12-09 12:56:34 +00001062Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1063 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001064 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1065 // This allows us to reuse all the fun and games in SynthMessageExpr().
1066 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1067 ObjCMessageExpr *MsgExpr;
1068 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1069 llvm::SmallVector<Expr *, 1> ExprVec;
1070 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001071
Steve Naroff1042ff32008-12-08 16:43:47 +00001072 Stmt *Receiver = PropRefExpr->getBase();
1073 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1074 if (PRE && PropGetters[PRE]) {
1075 // This allows us to handle chain/nested property getters.
1076 Receiver = PropGetters[PRE];
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1079 PDecl->getSetterName(), PDecl->getType(),
1080 PDecl->getSetterMethodDecl(),
1081 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001082 &ExprVec[0], 1);
1083 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Steve Naroff4588d0f2008-12-04 16:24:46 +00001085 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001086 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001087 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001088 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1089 // to things that stay around.
1090 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001091 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001092}
1093
Steve Naroff4588d0f2008-12-04 16:24:46 +00001094Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001095 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1096 // This allows us to reuse all the fun and games in SynthMessageExpr().
1097 ObjCMessageExpr *MsgExpr;
1098 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001099
Steve Naroff1042ff32008-12-08 16:43:47 +00001100 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001101
Steve Naroff1042ff32008-12-08 16:43:47 +00001102 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1103 if (PRE && PropGetters[PRE]) {
1104 // This allows us to handle chain/nested property getters.
1105 Receiver = PropGetters[PRE];
1106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1108 PDecl->getGetterName(), PDecl->getType(),
1109 PDecl->getGetterMethodDecl(),
1110 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001111 0, 0);
1112
Steve Naroff22216db2008-12-04 23:50:32 +00001113 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001114
1115 if (!PropParentMap)
1116 PropParentMap = new ParentMap(CurrentBody);
1117
1118 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1119 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1120 // We stash away the ReplacingStmt since actually doing the
1121 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1122 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001123 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1124 // to things that stay around.
1125 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001126 return PropRefExpr; // return the original...
1127 } else {
1128 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001129 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001130 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1131 // to things that stay around.
1132 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001133 return ReplacingStmt;
1134 }
Steve Narofff326f402008-12-03 00:56:33 +00001135}
1136
Mike Stump11289f42009-09-09 15:08:12 +00001137Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001138 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001139 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001140 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001141 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001142 ObjCInterfaceType *iFaceDecl =
1143 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001144 // lookup which class implements the instance variable.
1145 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001146 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001147 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001148 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001149
Steve Naroffb1c02372008-05-08 17:52:16 +00001150 // Synthesize an explicit cast to gain access to the ivar.
1151 std::string RecName = clsDeclared->getIdentifier()->getName();
1152 RecName += "_IMPL";
1153 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001154 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001155 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001156 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1157 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001158 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001159 CastExpr::CK_Unknown,
1160 IV->getBase(),
1161 castT,SourceLocation(),
1162 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001163 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001164 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1165 IV->getBase()->getLocEnd(),
1166 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001167 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001168 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001169 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1170 IV->getLocation(),
1171 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001172 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001173 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001174 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001175 }
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001177 ReplaceStmt(IV->getBase(), PE);
1178 // Cannot delete IV->getBase(), since PE points to it.
1179 // Replace the old base with the cast. This is important when doing
1180 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001181 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001182 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001183 }
Steve Naroff24840f62008-04-18 21:55:08 +00001184 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001185 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001186
Steve Naroff29ce4e52008-05-06 23:20:07 +00001187 // Explicit ivar refs need to have a cast inserted.
1188 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001189 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001190 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001191 // lookup which class implements the instance variable.
1192 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001193 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001194 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001195 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001196
Steve Naroff29ce4e52008-05-06 23:20:07 +00001197 // Synthesize an explicit cast to gain access to the ivar.
1198 std::string RecName = clsDeclared->getIdentifier()->getName();
1199 RecName += "_IMPL";
1200 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001201 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001202 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001203 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1204 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001205 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001206 CastExpr::CK_Unknown,
1207 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001208 castT, SourceLocation(),
1209 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001210 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001211 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001212 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001213 ReplaceStmt(IV->getBase(), PE);
1214 // Cannot delete IV->getBase(), since PE points to it.
1215 // Replace the old base with the cast. This is important when doing
1216 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001217 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001218 return IV;
1219 }
Steve Naroff05caa482007-11-15 11:33:00 +00001220 }
Steve Naroff24840f62008-04-18 21:55:08 +00001221 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001222}
1223
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001224/// SynthCountByEnumWithState - To print:
1225/// ((unsigned int (*)
1226/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001227/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001228/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001229/// "countByEnumeratingWithState:objects:count:"),
1230/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001231/// (id *)items, (unsigned int)16)
1232///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001233void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001234 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1235 "id *, unsigned int))(void *)objc_msgSend)";
1236 buf += "\n\t\t";
1237 buf += "((id)l_collection,\n\t\t";
1238 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1239 buf += "\n\t\t";
1240 buf += "&enumState, "
1241 "(id *)items, (unsigned int)16)";
1242}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001243
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001244/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1245/// statement to exit to its outer synthesized loop.
1246///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001247Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001248 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1249 return S;
1250 // replace break with goto __break_label
1251 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001252
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001253 SourceLocation startLoc = S->getLocStart();
1254 buf = "goto __break_label_";
1255 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001256 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001257
1258 return 0;
1259}
1260
1261/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1262/// statement to continue with its inner synthesized loop.
1263///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001264Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001265 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1266 return S;
1267 // replace continue with goto __continue_label
1268 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001269
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001270 SourceLocation startLoc = S->getLocStart();
1271 buf = "goto __continue_label_";
1272 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001273 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001274
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001275 return 0;
1276}
1277
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001278/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001279/// It rewrites:
1280/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001281
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001282/// Into:
1283/// {
Mike Stump11289f42009-09-09 15:08:12 +00001284/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001285/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001286/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001287/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001288/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001289/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001290/// if (limit) {
1291/// unsigned long startMutations = *enumState.mutationsPtr;
1292/// do {
1293/// unsigned long counter = 0;
1294/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001295/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001296/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001297/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001298/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001299/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001300/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001301/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001302/// objects:items count:16]);
1303/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001304/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001305/// }
1306/// else
1307/// elem = nil;
1308/// }
1309///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001310Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001311 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001312 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001313 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001314 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001315 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001316 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001317
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001318 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001319 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001320 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001321 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001322 std::string buf;
1323 buf = "\n{\n\t";
1324 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1325 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001326 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001327 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001328 if (ElementType->isObjCQualifiedIdType() ||
1329 ElementType->isObjCQualifiedInterfaceType())
1330 // Simply use 'id' for all qualified types.
1331 elementTypeAsString = "id";
1332 else
1333 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001334 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001336 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001337 buf += elementName;
1338 buf += ";\n\t";
1339 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001340 else {
1341 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001342 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001343 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1344 if (VD->getType()->isObjCQualifiedIdType() ||
1345 VD->getType()->isObjCQualifiedInterfaceType())
1346 // Simply use 'id' for all qualified types.
1347 elementTypeAsString = "id";
1348 else
1349 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001350 }
Mike Stump11289f42009-09-09 15:08:12 +00001351
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001352 // struct __objcFastEnumerationState enumState = { 0 };
1353 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1354 // id items[16];
1355 buf += "id items[16];\n\t";
1356 // id l_collection = (id)
1357 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001358 // Find start location of 'collection' the hard way!
1359 const char *startCollectionBuf = startBuf;
1360 startCollectionBuf += 3; // skip 'for'
1361 startCollectionBuf = strchr(startCollectionBuf, '(');
1362 startCollectionBuf++; // skip '('
1363 // find 'in' and skip it.
1364 while (*startCollectionBuf != ' ' ||
1365 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1366 (*(startCollectionBuf+3) != ' ' &&
1367 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1368 startCollectionBuf++;
1369 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001370
1371 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001372 ReplaceText(startLoc, startCollectionBuf - startBuf,
1373 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001374 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001375 SourceLocation rightParenLoc = S->getRParenLoc();
1376 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1377 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001379
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1381 // objects:items count:16];
1382 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001383 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384 // ((unsigned int (*)
1385 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001386 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001388 // "countByEnumeratingWithState:objects:count:"),
1389 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001390 // (id *)items, (unsigned int)16);
1391 buf += "unsigned long limit =\n\t\t";
1392 SynthCountByEnumWithState(buf);
1393 buf += ";\n\t";
1394 /// if (limit) {
1395 /// unsigned long startMutations = *enumState.mutationsPtr;
1396 /// do {
1397 /// unsigned long counter = 0;
1398 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001399 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001400 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001401 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001402 buf += "if (limit) {\n\t";
1403 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1404 buf += "do {\n\t\t";
1405 buf += "unsigned long counter = 0;\n\t\t";
1406 buf += "do {\n\t\t\t";
1407 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1408 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1409 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001410 buf += " = (";
1411 buf += elementTypeAsString;
1412 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001414 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001415
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001416 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001417 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001418 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001419 /// objects:items count:16]);
1420 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001421 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001422 /// }
1423 /// else
1424 /// elem = nil;
1425 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001426 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001427 buf = ";\n\t";
1428 buf += "__continue_label_";
1429 buf += utostr(ObjCBcLabelNo.back());
1430 buf += ": ;";
1431 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001432 buf += "} while (counter < limit);\n\t";
1433 buf += "} while (limit = ";
1434 SynthCountByEnumWithState(buf);
1435 buf += ");\n\t";
1436 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001437 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001438 buf += "__break_label_";
1439 buf += utostr(ObjCBcLabelNo.back());
1440 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001441 buf += "}\n\t";
1442 buf += "else\n\t\t";
1443 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001444 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001445 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001446
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001447 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001448 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001449 if (isa<CompoundStmt>(S->getBody())) {
1450 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1451 InsertText(endBodyLoc, buf.c_str(), buf.size());
1452 } else {
1453 /* Need to treat single statements specially. For example:
1454 *
1455 * for (A *a in b) if (stuff()) break;
1456 * for (A *a in b) xxxyy;
1457 *
1458 * The following code simply scans ahead to the semi to find the actual end.
1459 */
1460 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1461 const char *semiBuf = strchr(stmtBuf, ';');
1462 assert(semiBuf && "Can't find ';'");
1463 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1464 InsertText(endBodyLoc, buf.c_str(), buf.size());
1465 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001466 Stmts.pop_back();
1467 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001469}
1470
Mike Stump11289f42009-09-09 15:08:12 +00001471/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001472/// This routine rewrites @synchronized(expr) stmt;
1473/// into:
1474/// objc_sync_enter(expr);
1475/// @try stmt @finally { objc_sync_exit(expr); }
1476///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001477Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001478 // Get the start location and compute the semi location.
1479 SourceLocation startLoc = S->getLocStart();
1480 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001481
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001482 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001483
1484 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001485 buf = "objc_sync_enter((id)";
1486 const char *lparenBuf = startBuf;
1487 while (*lparenBuf != '(') lparenBuf++;
1488 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001489 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1490 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001491 // been rewritten! (which implies the SourceLocation's are invalid).
1492 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001493 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001494 while (*endBuf != ')') endBuf--;
1495 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001496 buf = ");\n";
1497 // declare a new scope with two variables, _stack and _rethrow.
1498 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1499 buf += "int buf[18/*32-bit i386*/];\n";
1500 buf += "char *pointers[4];} _stack;\n";
1501 buf += "id volatile _rethrow = 0;\n";
1502 buf += "objc_exception_try_enter(&_stack);\n";
1503 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001504 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001505 startLoc = S->getSynchBody()->getLocEnd();
1506 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Steve Naroffad7013b2008-08-19 13:04:19 +00001508 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001509 SourceLocation lastCurlyLoc = startLoc;
1510 buf = "}\nelse {\n";
1511 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001512 buf += "}\n";
1513 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001514 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffd7ebc052008-07-16 19:47:39 +00001515 buf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001516 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001517 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001518 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001519 Context->getObjCIdType(),
1520 SourceLocation(),
1521 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001522 std::string syncExprBufS;
1523 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001524 syncExpr->printPretty(syncExprBuf, *Context, 0,
1525 PrintingPolicy(LangOpts));
Steve Naroffd7ebc052008-07-16 19:47:39 +00001526 buf += syncExprBuf.str();
1527 buf += ");\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001528 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1529 buf += "}\n";
1530 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattner9cc55f52008-01-31 19:51:04 +00001532 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001533 return 0;
1534}
1535
Mike Stump11289f42009-09-09 15:08:12 +00001536void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
Steve Naroff6d6da252008-12-05 17:03:39 +00001537 // Perform a bottom up traversal of all children.
1538 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1539 CI != E; ++CI)
1540 if (*CI)
1541 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1542
Mike Stump11289f42009-09-09 15:08:12 +00001543 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
Steve Naroff6d6da252008-12-05 17:03:39 +00001544 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001545 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001546 TryFinallyContainsReturnDiag);
1547 }
1548 return;
1549}
1550
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001551Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001552 // Get the start location and compute the semi location.
1553 SourceLocation startLoc = S->getLocStart();
1554 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001555
Steve Naroffbf478ec2007-11-07 04:08:17 +00001556 assert((*startBuf == '@') && "bogus @try location");
1557
1558 std::string buf;
1559 // declare a new scope with two variables, _stack and _rethrow.
1560 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1561 buf += "int buf[18/*32-bit i386*/];\n";
1562 buf += "char *pointers[4];} _stack;\n";
1563 buf += "id volatile _rethrow = 0;\n";
1564 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001565 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001566
Chris Lattner9cc55f52008-01-31 19:51:04 +00001567 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001568
Steve Naroffbf478ec2007-11-07 04:08:17 +00001569 startLoc = S->getTryBody()->getLocEnd();
1570 startBuf = SM->getCharacterData(startLoc);
1571
1572 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001573
Steve Naroffbf478ec2007-11-07 04:08:17 +00001574 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001575 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1576 if (catchList) {
1577 startLoc = startLoc.getFileLocWithOffset(1);
1578 buf = " /* @catch begin */ else {\n";
1579 buf += " id _caught = objc_exception_extract(&_stack);\n";
1580 buf += " objc_exception_try_enter (&_stack);\n";
1581 buf += " if (_setjmp(_stack.buf))\n";
1582 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1583 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001584
Steve Naroffce2dca12008-07-16 15:31:30 +00001585 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001586 } else { /* no catch list */
1587 buf = "}\nelse {\n";
1588 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1589 buf += "}";
1590 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001591 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001592 bool sawIdTypedCatch = false;
1593 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001594 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001595 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001596
Mike Stump11289f42009-09-09 15:08:12 +00001597 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001598 buf = "if ("; // we are generating code for the first catch clause
1599 else
1600 buf = "else if (";
1601 startLoc = catchList->getLocStart();
1602 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001603
Steve Naroffbf478ec2007-11-07 04:08:17 +00001604 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001605
Steve Naroffbf478ec2007-11-07 04:08:17 +00001606 const char *lParenLoc = strchr(startBuf, '(');
1607
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001608 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001609 // Now rewrite the body...
1610 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001611 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1612 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001613 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1614 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001615 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001616
Steve Naroffedb5bc62008-02-01 20:02:07 +00001617 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001618 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001619 } else if (catchDecl) {
1620 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001621 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001622 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001623 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001624 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001625 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001626 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001627
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001628 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001629 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001630 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001631 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001632 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001633 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001634 }
1635 }
1636 // Now rewrite the body...
1637 lastCatchBody = catchList->getCatchBody();
1638 SourceLocation rParenLoc = catchList->getRParenLoc();
1639 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1640 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1641 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1642 assert((*rParenBuf == ')') && "bogus @catch paren location");
1643 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001644
Steve Naroffbf478ec2007-11-07 04:08:17 +00001645 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001646 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001647 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001648 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001649 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001650 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001651 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001652 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001653 catchList = catchList->getNextCatchStmt();
1654 }
1655 // Complete the catch list...
1656 if (lastCatchBody) {
1657 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001658 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1659 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001660
Steve Naroff4adbe312008-09-11 15:29:03 +00001661 // Insert the last (implicit) else clause *before* the right curly brace.
1662 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1663 buf = "} /* last catch end */\n";
1664 buf += "else {\n";
1665 buf += " _rethrow = _caught;\n";
1666 buf += " objc_exception_try_exit(&_stack);\n";
1667 buf += "} } /* @catch end */\n";
1668 if (!S->getFinallyStmt())
1669 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001670 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001671
Steve Naroffbf478ec2007-11-07 04:08:17 +00001672 // Set lastCurlyLoc
1673 lastCurlyLoc = lastCatchBody->getLocEnd();
1674 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001675 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001676 startLoc = finalStmt->getLocStart();
1677 startBuf = SM->getCharacterData(startLoc);
1678 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001679
Steve Naroffbf478ec2007-11-07 04:08:17 +00001680 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001681 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001682
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 Stmt *body = finalStmt->getFinallyBody();
1684 SourceLocation startLoc = body->getLocStart();
1685 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001686 assert(*SM->getCharacterData(startLoc) == '{' &&
1687 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001688 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001689 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001690
Steve Naroffbf478ec2007-11-07 04:08:17 +00001691 startLoc = startLoc.getFileLocWithOffset(1);
1692 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001693 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001694 endLoc = endLoc.getFileLocWithOffset(-1);
1695 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001696 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001697
Steve Naroffbf478ec2007-11-07 04:08:17 +00001698 // Set lastCurlyLoc
1699 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001700
Steve Naroff6d6da252008-12-05 17:03:39 +00001701 // Now check for any return/continue/go statements within the @try.
1702 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001703 } else { /* no finally clause - make sure we synthesize an implicit one */
1704 buf = "{ /* implicit finally clause */\n";
1705 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1706 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1707 buf += "}";
1708 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001709 }
1710 // Now emit the final closing curly brace...
1711 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1712 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001713 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001714 return 0;
1715}
1716
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001717Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001718 return 0;
1719}
1720
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001721Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001722 return 0;
1723}
1724
Mike Stump11289f42009-09-09 15:08:12 +00001725// This can't be done with ReplaceStmt(S, ThrowExpr), since
1726// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001727// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001728Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001729 // Get the start location and compute the semi location.
1730 SourceLocation startLoc = S->getLocStart();
1731 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001732
Steve Naroffa733c7f2007-11-07 15:32:26 +00001733 assert((*startBuf == '@') && "bogus @throw location");
1734
1735 std::string buf;
1736 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001737 if (S->getThrowExpr())
1738 buf = "objc_exception_throw(";
1739 else // add an implicit argument
1740 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001741
Steve Naroff29788342008-07-25 15:41:30 +00001742 // handle "@ throw" correctly.
1743 const char *wBuf = strchr(startBuf, 'w');
1744 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1745 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroffa733c7f2007-11-07 15:32:26 +00001747 const char *semiBuf = strchr(startBuf, ';');
1748 assert((*semiBuf == ';') && "@throw: can't find ';'");
1749 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1750 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001751 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001752 return 0;
1753}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001754
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001755Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001756 // Create a new string expression.
1757 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001758 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001759 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001760 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1761 StrEncoding.length(), false,StrType,
1762 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001763 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattner4431a1b2007-11-30 22:53:43 +00001765 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001766 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001767 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001768}
1769
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001770Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001771 if (!SelGetUidFunctionDecl)
1772 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001773 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1774 // Create a call to sel_registerName("selName").
1775 llvm::SmallVector<Expr*, 8> SelExprs;
1776 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001777 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001778 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001779 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001780 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001781 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1782 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001783 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001784 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001785 return SelExp;
1786}
1787
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001788CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001789 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001790 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001791 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001792
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001793 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001794 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001795
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001796 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001797 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001798 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001799 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001800 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001801 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001802
John McCall9dd450b2009-09-21 23:43:11 +00001803 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001804
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001805 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1806 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001807}
1808
Steve Naroff50d42052007-11-01 13:24:47 +00001809static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1810 const char *&startRef, const char *&endRef) {
1811 while (startBuf < endBuf) {
1812 if (*startBuf == '<')
1813 startRef = startBuf; // mark the start.
1814 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001815 if (startRef && *startRef == '<') {
1816 endRef = startBuf; // mark the end.
1817 return true;
1818 }
1819 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001820 }
1821 startBuf++;
1822 }
1823 return false;
1824}
1825
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001826static void scanToNextArgument(const char *&argRef) {
1827 int angle = 0;
1828 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1829 if (*argRef == '<')
1830 angle++;
1831 else if (*argRef == '>')
1832 angle--;
1833 argRef++;
1834 }
1835 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1836}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001837
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001838bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001839 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001840}
1841
Steve Naroff873bd842008-07-29 18:15:38 +00001842void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1843 QualType Type = E->getType();
1844 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001845 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Steve Naroffdbfc6932008-11-19 21:15:47 +00001847 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1848 Loc = ECE->getLParenLoc();
1849 EndLoc = ECE->getRParenLoc();
1850 } else {
1851 Loc = E->getLocStart();
1852 EndLoc = E->getLocEnd();
1853 }
1854 // This will defend against trying to rewrite synthesized expressions.
1855 if (Loc.isInvalid() || EndLoc.isInvalid())
1856 return;
1857
Steve Naroff873bd842008-07-29 18:15:38 +00001858 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001859 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001860 const char *startRef = 0, *endRef = 0;
1861 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1862 // Get the locations of the startRef, endRef.
1863 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1864 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1865 // Comment out the protocol references.
1866 InsertText(LessLoc, "/*", 2);
1867 InsertText(GreaterLoc, "*/", 2);
1868 }
1869 }
1870}
1871
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001872void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001873 SourceLocation Loc;
1874 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001875 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001876 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1877 Loc = VD->getLocation();
1878 Type = VD->getType();
1879 }
1880 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1881 Loc = FD->getLocation();
1882 // Check for ObjC 'id' and class types that have been adorned with protocol
1883 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001884 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001885 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001886 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001887 if (!proto)
1888 return;
1889 Type = proto->getResultType();
1890 }
1891 else
1892 return;
Mike Stump11289f42009-09-09 15:08:12 +00001893
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001894 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001895 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001896
Steve Naroff50d42052007-11-01 13:24:47 +00001897 const char *endBuf = SM->getCharacterData(Loc);
1898 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00001899 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00001900 startBuf--; // scan backward (from the decl location) for return type.
1901 const char *startRef = 0, *endRef = 0;
1902 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1903 // Get the locations of the startRef, endRef.
1904 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1905 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1906 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00001907 InsertText(LessLoc, "/*", 2);
1908 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00001909 }
1910 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001911 if (!proto)
1912 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00001913 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001914 const char *startBuf = SM->getCharacterData(Loc);
1915 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00001916 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1917 if (needToScanForQualifiers(proto->getArgType(i))) {
1918 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001919
Steve Naroff50d42052007-11-01 13:24:47 +00001920 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001921 // scan forward (from the decl location) for argument types.
1922 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00001923 const char *startRef = 0, *endRef = 0;
1924 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1925 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00001926 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001927 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00001928 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001929 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00001930 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00001931 InsertText(LessLoc, "/*", 2);
1932 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00001933 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001934 startBuf = ++endBuf;
1935 }
1936 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00001937 // If the function name is derived from a macro expansion, then the
1938 // argument buffer will not follow the name. Need to speak with Chris.
1939 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001940 startBuf++; // scan forward (from the decl location) for argument types.
1941 startBuf++;
1942 }
Steve Naroff50d42052007-11-01 13:24:47 +00001943 }
Steve Naroff37e011c2007-10-31 04:38:33 +00001944}
1945
Fariborz Jahanian31e18502007-12-04 21:47:40 +00001946// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001947void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00001948 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1949 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00001950 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001951 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00001952 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00001953 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00001954 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00001955 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001956 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001957 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00001958}
1959
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001960void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001961 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00001962 if (FD->getIdentifier() &&
1963 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001964 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00001965 return;
1966 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001967 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001968}
1969
Steve Naroff17978c42008-03-11 17:37:02 +00001970// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001971void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00001972 if (SuperContructorFunctionDecl)
1973 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00001974 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00001975 llvm::SmallVector<QualType, 16> ArgTys;
1976 QualType argT = Context->getObjCIdType();
1977 assert(!argT.isNull() && "Can't find 'id' type");
1978 ArgTys.push_back(argT);
1979 ArgTys.push_back(argT);
1980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1981 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00001982 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00001983 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00001984 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001985 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001986 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00001987}
1988
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001989// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001993 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001994 assert(!argT.isNull() && "Can't find 'id' type");
1995 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001996 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00001997 assert(!argT.isNull() && "Can't find 'SEL' type");
1998 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001999 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002000 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002001 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002002 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002003 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002004 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002005 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002006}
2007
Steve Naroff7fa2f042007-11-15 10:28:18 +00002008// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002009void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002010 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2011 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002012 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002013 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002014 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002015 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2016 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2017 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002022 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002024 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002025 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002026 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002027 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002028}
2029
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002030// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002031void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002032 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2033 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002034 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002035 assert(!argT.isNull() && "Can't find 'id' type");
2036 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002037 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002038 assert(!argT.isNull() && "Can't find 'SEL' type");
2039 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002040 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002041 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002042 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002043 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002044 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002045 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002046 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002047}
2048
Mike Stump11289f42009-09-09 15:08:12 +00002049// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002050// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002051void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002052 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002053 &Context->Idents.get("objc_msgSendSuper_stret");
2054 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002055 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002056 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002057 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002058 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2059 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2060 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002064 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002065 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002067 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002068 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002069 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002070 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002071}
2072
Steve Naroff2e4e3852008-05-08 22:02:18 +00002073// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002074void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002075 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2076 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002077 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002078 assert(!argT.isNull() && "Can't find 'id' type");
2079 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002080 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002081 assert(!argT.isNull() && "Can't find 'SEL' type");
2082 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002083 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002084 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002085 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002086 MsgSendFpretFunctionDecl = 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);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002090}
2091
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002092// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002093void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002094 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2095 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002096 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002097 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002098 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002099 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002100 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002101 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002102 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002103 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002104}
2105
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002106// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002107void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002108 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2109 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002110 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002111 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002112 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002113 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002114 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002115 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002116 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002117 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002118}
2119
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002120Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002121 QualType strType = getConstantStringStructType();
2122
2123 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002124
2125 std::string tmpName = InFileName;
2126 unsigned i;
2127 for (i=0; i < tmpName.length(); i++) {
2128 char c = tmpName.at(i);
2129 // replace any non alphanumeric characters with '_'.
2130 if (!isalpha(c) && (c < '0' || c > '9'))
2131 tmpName[i] = '_';
2132 }
2133 S += tmpName;
2134 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002135 S += utostr(NumObjCStringLiterals++);
2136
Steve Naroff00a31762008-03-27 22:29:16 +00002137 Preamble += "static __NSConstantStringImpl " + S;
2138 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2139 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002140 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002141 std::string prettyBufS;
2142 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002143 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2144 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002145 Preamble += prettyBuf.str();
2146 Preamble += ",";
Steve Naroffdad80ba2008-03-15 01:36:04 +00002147 // The minus 2 removes the begin/end double quotes.
Steve Naroff00a31762008-03-27 22:29:16 +00002148 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002149
2150 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2151 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002152 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002153 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2154 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002155 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002156 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002157 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002158 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002159 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002160 Unop, Exp->getType(),
2161 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002162 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002163 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002164 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002165 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002166}
2167
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002168ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002169 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002170 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002171
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002172 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002173 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002174 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002175 assert(OPT);
2176 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002177 return IT->getDecl();
2178 }
2179 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002180}
2181
2182// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002183QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002184 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002185 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002186 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002187 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002188 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002189
Steve Naroff7fa2f042007-11-15 10:28:18 +00002190 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002191 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002192 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002193 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002194
Steve Naroff7fa2f042007-11-15 10:28:18 +00002195 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002196 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002197 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2198 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002199 FieldTypes[i], 0,
2200 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002201 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002202 }
Mike Stump11289f42009-09-09 15:08:12 +00002203
Douglas Gregor91f84212008-12-11 16:49:14 +00002204 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002205 }
2206 return Context->getTagDeclType(SuperStructDecl);
2207}
2208
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002209QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002210 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002211 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002212 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002213 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002214 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002215
Steve Naroffce8e8862008-03-15 00:55:56 +00002216 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002217 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002218 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002219 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002220 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002221 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002222 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002223 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002224
Steve Naroffce8e8862008-03-15 00:55:56 +00002225 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002226 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002227 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2228 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002229 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002230 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002231 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002232 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002233 }
2234
2235 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002236 }
2237 return Context->getTagDeclType(ConstantStringDecl);
2238}
2239
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002240Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002241 if (!SelGetUidFunctionDecl)
2242 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002243 if (!MsgSendFunctionDecl)
2244 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002245 if (!MsgSendSuperFunctionDecl)
2246 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002247 if (!MsgSendStretFunctionDecl)
2248 SynthMsgSendStretFunctionDecl();
2249 if (!MsgSendSuperStretFunctionDecl)
2250 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002251 if (!MsgSendFpretFunctionDecl)
2252 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002253 if (!GetClassFunctionDecl)
2254 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002255 if (!GetMetaClassFunctionDecl)
2256 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002257
Steve Naroff7fa2f042007-11-15 10:28:18 +00002258 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002259 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2260 // May need to use objc_msgSend_stret() as well.
2261 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002262 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2263 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002264 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002265 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002266 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002267 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002268 }
Mike Stump11289f42009-09-09 15:08:12 +00002269
Steve Naroff574440f2007-10-24 22:48:43 +00002270 // Synthesize a call to objc_msgSend().
2271 llvm::SmallVector<Expr*, 8> MsgExprs;
2272 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002273
Steve Naroff574440f2007-10-24 22:48:43 +00002274 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2275 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002276 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2277 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002278 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002279 MsgSendFlavor = MsgSendSuperFunctionDecl;
2280 if (MsgSendStretFlavor)
2281 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2282 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002283
2284 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002285 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002286
2287 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002288
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002289 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002290 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002291 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002292 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002293 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002294 Context->getObjCIdType(),
2295 SourceLocation()),
2296 Context->getObjCIdType(),
2297 SourceLocation(), SourceLocation())); // set the 'receiver'.
2298
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002299 llvm::SmallVector<Expr*, 8> ClsExprs;
2300 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002301 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002302 SuperDecl->getIdentifier()->getNameStart(),
2303 SuperDecl->getIdentifier()->getLength(),
2304 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002305 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002306 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002307 ClsExprs.size());
2308 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002309 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002310 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002311 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002312 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002313 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002314 // struct objc_super
2315 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002316 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Steve Naroff0b844f02008-03-11 18:14:26 +00002318 if (LangOpts.Microsoft) {
2319 SynthSuperContructorFunctionDecl();
2320 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002321 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002322 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002323 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002324 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002325 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002326 // The code for super is a little tricky to prevent collision with
2327 // the structure definition in the header. The rewriter has it's own
2328 // internal definition (__rw_objc_super) that is uses. This is why
2329 // we need the cast below. For example:
2330 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2331 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002332 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002333 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002334 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002335 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2336 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002337 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002338 SourceLocation(), SourceLocation());
2339 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002340 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002341 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2342 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002343 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002344 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002345 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002346 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002347 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002348 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002349 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002350 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002351 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002352 } else {
2353 llvm::SmallVector<Expr*, 8> ClsExprs;
2354 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002355 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002356 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002357 clsName->getLength(),
2358 false, argType,
2359 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002360 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002361 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002362 ClsExprs.size());
2363 MsgExprs.push_back(Cls);
2364 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002365 } else { // instance message.
2366 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002367
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002368 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002369 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002370 if (MsgSendStretFlavor)
2371 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002372 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002373
Steve Naroff7fa2f042007-11-15 10:28:18 +00002374 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002375
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002376 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002377 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002378 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002379 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002380 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002381 SourceLocation()),
2382 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002383 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002384
Steve Naroff7fa2f042007-11-15 10:28:18 +00002385 llvm::SmallVector<Expr*, 8> ClsExprs;
2386 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002387 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002388 SuperDecl->getIdentifier()->getNameStart(),
2389 SuperDecl->getIdentifier()->getLength(),
2390 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002391 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002392 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002393 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002394 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002395 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002396 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002397 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002398 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002399 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002400 // struct objc_super
2401 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002402 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002403
Steve Naroff17978c42008-03-11 17:37:02 +00002404 if (LangOpts.Microsoft) {
2405 SynthSuperContructorFunctionDecl();
2406 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002407 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002408 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002409 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002410 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002411 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002412 // The code for super is a little tricky to prevent collision with
2413 // the structure definition in the header. The rewriter has it's own
2414 // internal definition (__rw_objc_super) that is uses. This is why
2415 // we need the cast below. For example:
2416 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2417 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002418 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002419 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002420 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002421 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002422 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002423 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002424 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002425 } else {
2426 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002427 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2428 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002429 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002430 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002431 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002432 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002433 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002434 // Remove all type-casts because it may contain objc-style types; e.g.
2435 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002436 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002437 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002438 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002439 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002440 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002441 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002442 MsgExprs.push_back(recExpr);
2443 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002444 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002445 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002446 llvm::SmallVector<Expr*, 8> SelExprs;
2447 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002448 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002449 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002450 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002451 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002452 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2453 &SelExprs[0], SelExprs.size());
2454 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002455
Steve Naroff574440f2007-10-24 22:48:43 +00002456 // Now push any user supplied arguments.
2457 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002458 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002459 // Make all implicit casts explicit...ICE comes in handy:-)
2460 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2461 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002462 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002463 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002464 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002465 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002466 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002467 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002468 }
2469 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002470 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002471 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002472 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002473 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002474 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002475 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002476 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002477 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002480 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002481 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2482 // out the argument in the original expression (since we aren't deleting
2483 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2484 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002485 }
Steve Narofff36987c2007-11-04 22:37:50 +00002486 // Generate the funky cast.
2487 CastExpr *cast;
2488 llvm::SmallVector<QualType, 8> ArgTypes;
2489 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002490
Steve Narofff36987c2007-11-04 22:37:50 +00002491 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002492 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2493 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2494 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002495 ArgTypes.push_back(Context->getObjCIdType());
2496 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002497 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002498 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002499 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2500 E = OMD->param_end(); PI != E; ++PI) {
2501 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002502 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002503 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002504 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002505 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002506 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002507 t = Context->getPointerType(BPT->getPointeeType());
2508 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002509 ArgTypes.push_back(t);
2510 }
Chris Lattnera4997152009-02-20 18:43:26 +00002511 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2512 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002513 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002514 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002515 }
2516 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002517 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002518
Steve Narofff36987c2007-11-04 22:37:50 +00002519 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002520 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002521 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002522
Mike Stump11289f42009-09-09 15:08:12 +00002523 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002524 // If we don't do this cast, we get the following bizarre warning/note:
2525 // xx.m:13: warning: function called through a non-compatible type
2526 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002527 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2528 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002529 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002530 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002531
Steve Narofff36987c2007-11-04 22:37:50 +00002532 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002533 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002534 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002535 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002536 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002537 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002538 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2539 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002540 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002541
2542 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002543 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002544
John McCall9dd450b2009-09-21 23:43:11 +00002545 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002546 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002547 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002548 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002549 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002550 if (MsgSendStretFlavor) {
2551 // We have the method which returns a struct/union. Must also generate
2552 // call to objc_msgSend_stret and hang both varieties on a conditional
2553 // expression which dictate which one to envoke depending on size of
2554 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002555
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002556 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002557 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002558 SourceLocation());
2559 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002560 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2561 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002562 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002563 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002564 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002565 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002566 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002567 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002568 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002569 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2570 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002571
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002572 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002573 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002574
John McCall9dd450b2009-09-21 23:43:11 +00002575 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002576 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002577 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002578 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002579
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002580 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002581 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCall4c98fd82009-11-04 07:28:41 +00002582 Context->getTrivialDeclaratorInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002583 Context->getSizeType(),
2584 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002585 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2586 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2587 // For X86 it is more complicated and some kind of target specific routine
2588 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002589 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002590 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002591 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002592 Context->IntTy,
2593 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002594 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2595 BinaryOperator::LE,
2596 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002597 SourceLocation());
2598 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002599 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002600 new (Context) ConditionalOperator(lessThanExpr,
2601 SourceLocation(), CE,
2602 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002603 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002606 return ReplacingStmt;
2607}
2608
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002609Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002610 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002611
Steve Naroff574440f2007-10-24 22:48:43 +00002612 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002613 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002614
2615 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002616 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002617}
2618
Steve Naroffd9803712009-04-29 16:37:50 +00002619// typedef struct objc_object Protocol;
2620QualType RewriteObjC::getProtocolType() {
2621 if (!ProtocolTypeDecl) {
John McCall703a3f82009-10-24 08:00:42 +00002622 DeclaratorInfo *DInfo
2623 = Context->getTrivialDeclaratorInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002624 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002625 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002626 &Context->Idents.get("Protocol"),
John McCall703a3f82009-10-24 08:00:42 +00002627 DInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002628 }
2629 return Context->getTypeDeclType(ProtocolTypeDecl);
2630}
2631
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002632/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002633/// a synthesized/forward data reference (to the protocol's metadata).
2634/// The forward references (and metadata) are generated in
2635/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002636Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002637 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2638 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002639 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002640 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002641 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2642 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2643 Context->getPointerType(DRE->getType()),
2644 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002645 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2646 CastExpr::CK_Unknown,
2647 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002648 SourceLocation(), SourceLocation());
2649 ReplaceStmt(Exp, castExpr);
2650 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002651 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002652 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002653
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002654}
2655
Mike Stump11289f42009-09-09 15:08:12 +00002656bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002657 const char *endBuf) {
2658 while (startBuf < endBuf) {
2659 if (*startBuf == '#') {
2660 // Skip whitespace.
2661 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2662 ;
2663 if (!strncmp(startBuf, "if", strlen("if")) ||
2664 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2665 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2666 !strncmp(startBuf, "define", strlen("define")) ||
2667 !strncmp(startBuf, "undef", strlen("undef")) ||
2668 !strncmp(startBuf, "else", strlen("else")) ||
2669 !strncmp(startBuf, "elif", strlen("elif")) ||
2670 !strncmp(startBuf, "endif", strlen("endif")) ||
2671 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2672 !strncmp(startBuf, "include", strlen("include")) ||
2673 !strncmp(startBuf, "import", strlen("import")) ||
2674 !strncmp(startBuf, "include_next", strlen("include_next")))
2675 return true;
2676 }
2677 startBuf++;
2678 }
2679 return false;
2680}
2681
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002682/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002683/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002684void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002685 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002686 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002687 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002688 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002689 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002690 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002691 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002692 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002693 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002694 SourceLocation LocStart = CDecl->getLocStart();
2695 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002696
Steve Naroffdde78982007-11-14 19:25:57 +00002697 const char *startBuf = SM->getCharacterData(LocStart);
2698 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002699
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002700 // If no ivars and no root or if its root, directly or indirectly,
2701 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002702 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2703 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002704 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002705 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002706 return;
2707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
2709 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002710 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002711 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002712 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002713 if (LangOpts.Microsoft)
2714 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002715
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002716 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002717 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002718 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002719 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002720 // If the buffer contains preprocessor directives, we do more fine-grained
2721 // rewrites. This is intended to fix code that looks like (which occurs in
2722 // NSURL.h, for example):
2723 //
2724 // #ifdef XYZ
2725 // @interface Foo : NSObject
2726 // #else
2727 // @interface FooBar : NSObject
2728 // #endif
2729 // {
2730 // int i;
2731 // }
2732 // @end
2733 //
2734 // This clause is segregated to avoid breaking the common case.
2735 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002736 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002737 CDecl->getClassLoc();
2738 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002739 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002740
Chris Lattnerf5b77512009-02-20 18:18:36 +00002741 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002742 // advance to the end of the referenced protocols.
2743 while (endHeader < cursor && *endHeader != '>') endHeader++;
2744 endHeader++;
2745 }
2746 // rewrite the original header
2747 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2748 } else {
2749 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002750 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002751 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002752 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002753 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002754 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002755 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002756 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002757 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002758
Steve Naroffdde78982007-11-14 19:25:57 +00002759 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002760 SourceLocation OnePastCurly =
2761 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2762 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002763 }
2764 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002765
Steve Naroffdde78982007-11-14 19:25:57 +00002766 // Now comment out any visibility specifiers.
2767 while (cursor < endBuf) {
2768 if (*cursor == '@') {
2769 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002770 // Skip whitespace.
2771 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2772 /*scan*/;
2773
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002774 // FIXME: presence of @public, etc. inside comment results in
2775 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002776 if (!strncmp(cursor, "public", strlen("public")) ||
2777 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002778 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002779 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002780 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002781 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002782 // FIXME: If there are cases where '<' is used in ivar declaration part
2783 // of user code, then scan the ivar list and use needToScanForQualifiers
2784 // for type checking.
2785 else if (*cursor == '<') {
2786 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002787 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002788 cursor = strchr(cursor, '>');
2789 cursor++;
2790 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002791 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002792 } else if (*cursor == '^') { // rewrite block specifier.
2793 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2794 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002795 }
Steve Naroffdde78982007-11-14 19:25:57 +00002796 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002797 }
Steve Naroffdde78982007-11-14 19:25:57 +00002798 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002799 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002800 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002801 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002802 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002803 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002804 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002805 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002806 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002807 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002808 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002809 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002810 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002811 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002812}
2813
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002814// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002815/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002816template<typename MethodIterator>
2817void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2818 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002819 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002820 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002821 const char *ClassName,
2822 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002823 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002825 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002826 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002827 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002828 SEL _cmd;
2829 char *method_types;
2830 void *_imp;
2831 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002832 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002833 Result += "\nstruct _objc_method {\n";
2834 Result += "\tSEL _cmd;\n";
2835 Result += "\tchar *method_types;\n";
2836 Result += "\tvoid *_imp;\n";
2837 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002838
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002839 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002842 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002843
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002844 /* struct {
2845 struct _objc_method_list *next_method;
2846 int method_count;
2847 struct _objc_method method_list[];
2848 }
2849 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002850 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002851 Result += "\nstatic struct {\n";
2852 Result += "\tstruct _objc_method_list *next_method;\n";
2853 Result += "\tint method_count;\n";
2854 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002855 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002856 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002857 Result += prefix;
2858 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2859 Result += "_METHODS_";
2860 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002861 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002862 Result += IsInstanceMethod ? "inst" : "cls";
2863 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002864 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002865
Chris Lattner31bc07e2007-12-12 07:46:12 +00002866 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002867 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002868 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002869 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002870 Result += "\", \"";
2871 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002872 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002873 Result += MethodInternalNames[*MethodBegin];
2874 Result += "}\n";
2875 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2876 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002877 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002878 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002879 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002880 Result += "\", \"";
2881 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002882 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002883 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002884 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002885 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002886 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002887}
2888
Steve Naroffd9803712009-04-29 16:37:50 +00002889/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002890void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002891RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2892 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002893 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002894
2895 // Output struct protocol_methods holder of method selector and type.
2896 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2897 /* struct protocol_methods {
2898 SEL _cmd;
2899 char *method_types;
2900 }
2901 */
2902 Result += "\nstruct _protocol_methods {\n";
2903 Result += "\tstruct objc_selector *_cmd;\n";
2904 Result += "\tchar *method_types;\n";
2905 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002906
Steve Naroffd9803712009-04-29 16:37:50 +00002907 objc_protocol_methods = true;
2908 }
2909 // Do not synthesize the protocol more than once.
2910 if (ObjCSynthesizedProtocols.count(PDecl))
2911 return;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002913 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2914 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2915 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00002916 /* struct _objc_protocol_method_list {
2917 int protocol_method_count;
2918 struct protocol_methods protocols[];
2919 }
Steve Naroff251084d2008-03-12 01:06:30 +00002920 */
Steve Naroffd9803712009-04-29 16:37:50 +00002921 Result += "\nstatic struct {\n";
2922 Result += "\tint protocol_method_count;\n";
2923 Result += "\tstruct _protocol_methods protocol_methods[";
2924 Result += utostr(NumMethods);
2925 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2926 Result += PDecl->getNameAsString();
2927 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2928 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00002929
Steve Naroffd9803712009-04-29 16:37:50 +00002930 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00002931 for (ObjCProtocolDecl::instmeth_iterator
2932 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00002933 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002934 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00002935 Result += "\t ,{{(struct objc_selector *)\"";
2936 else
2937 Result += "\t ,{(struct objc_selector *)\"";
2938 Result += (*I)->getSelector().getAsString().c_str();
2939 std::string MethodTypeString;
2940 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2941 Result += "\", \"";
2942 Result += MethodTypeString;
2943 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00002944 }
Steve Naroffd9803712009-04-29 16:37:50 +00002945 Result += "\t }\n};\n";
2946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Steve Naroffd9803712009-04-29 16:37:50 +00002948 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002949 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2950 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00002951 if (NumMethods > 0) {
2952 /* struct _objc_protocol_method_list {
2953 int protocol_method_count;
2954 struct protocol_methods protocols[];
2955 }
2956 */
2957 Result += "\nstatic struct {\n";
2958 Result += "\tint protocol_method_count;\n";
2959 Result += "\tstruct _protocol_methods protocol_methods[";
2960 Result += utostr(NumMethods);
2961 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2962 Result += PDecl->getNameAsString();
2963 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2964 "{\n\t";
2965 Result += utostr(NumMethods);
2966 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00002967
Steve Naroffd9803712009-04-29 16:37:50 +00002968 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00002969 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002970 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00002971 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002972 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00002973 Result += "\t ,{{(struct objc_selector *)\"";
2974 else
2975 Result += "\t ,{(struct objc_selector *)\"";
2976 Result += (*I)->getSelector().getAsString().c_str();
2977 std::string MethodTypeString;
2978 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2979 Result += "\", \"";
2980 Result += MethodTypeString;
2981 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002982 }
Steve Naroffd9803712009-04-29 16:37:50 +00002983 Result += "\t }\n};\n";
2984 }
2985
2986 // Output:
2987 /* struct _objc_protocol {
2988 // Objective-C 1.0 extensions
2989 struct _objc_protocol_extension *isa;
2990 char *protocol_name;
2991 struct _objc_protocol **protocol_list;
2992 struct _objc_protocol_method_list *instance_methods;
2993 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00002994 };
Steve Naroffd9803712009-04-29 16:37:50 +00002995 */
2996 static bool objc_protocol = false;
2997 if (!objc_protocol) {
2998 Result += "\nstruct _objc_protocol {\n";
2999 Result += "\tstruct _objc_protocol_extension *isa;\n";
3000 Result += "\tchar *protocol_name;\n";
3001 Result += "\tstruct _objc_protocol **protocol_list;\n";
3002 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3003 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003004 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003005
Steve Naroffd9803712009-04-29 16:37:50 +00003006 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003007 }
Mike Stump11289f42009-09-09 15:08:12 +00003008
Steve Naroffd9803712009-04-29 16:37:50 +00003009 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3010 Result += PDecl->getNameAsString();
3011 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3012 "{\n\t0, \"";
3013 Result += PDecl->getNameAsString();
3014 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003015 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003016 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3017 Result += PDecl->getNameAsString();
3018 Result += ", ";
3019 }
3020 else
3021 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003022 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003023 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3024 Result += PDecl->getNameAsString();
3025 Result += "\n";
3026 }
3027 else
3028 Result += "0\n";
3029 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003030
Steve Naroffd9803712009-04-29 16:37:50 +00003031 // Mark this protocol as having been generated.
3032 if (!ObjCSynthesizedProtocols.insert(PDecl))
3033 assert(false && "protocol already synthesized");
3034
3035}
3036
3037void RewriteObjC::
3038RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3039 const char *prefix, const char *ClassName,
3040 std::string &Result) {
3041 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003042
Steve Naroffd9803712009-04-29 16:37:50 +00003043 for (unsigned i = 0; i != Protocols.size(); i++)
3044 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3045
Chris Lattner388f6e92008-07-21 21:33:21 +00003046 // Output the top lovel protocol meta-data for the class.
3047 /* struct _objc_protocol_list {
3048 struct _objc_protocol_list *next;
3049 int protocol_count;
3050 struct _objc_protocol *class_protocols[];
3051 }
3052 */
3053 Result += "\nstatic struct {\n";
3054 Result += "\tstruct _objc_protocol_list *next;\n";
3055 Result += "\tint protocol_count;\n";
3056 Result += "\tstruct _objc_protocol *class_protocols[";
3057 Result += utostr(Protocols.size());
3058 Result += "];\n} _OBJC_";
3059 Result += prefix;
3060 Result += "_PROTOCOLS_";
3061 Result += ClassName;
3062 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3063 "{\n\t0, ";
3064 Result += utostr(Protocols.size());
3065 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003066
Chris Lattner388f6e92008-07-21 21:33:21 +00003067 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003068 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003069 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003070
Chris Lattner388f6e92008-07-21 21:33:21 +00003071 for (unsigned i = 1; i != Protocols.size(); i++) {
3072 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003073 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003074 Result += "\n";
3075 }
3076 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003077}
3078
Steve Naroffd9803712009-04-29 16:37:50 +00003079
Mike Stump11289f42009-09-09 15:08:12 +00003080/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003081/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003082void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003083 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003084 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003085 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003086 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003087 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003088 CDecl = CDecl->getNextClassCategory())
3089 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3090 break;
Mike Stump11289f42009-09-09 15:08:12 +00003091
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003092 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003093 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003094 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003095
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003096 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003097 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003098 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003099
3100 // If any of our property implementations have associated getters or
3101 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003102 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3103 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003104 Prop != PropEnd; ++Prop) {
3105 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3106 continue;
3107 if (!(*Prop)->getPropertyIvarDecl())
3108 continue;
3109 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3110 if (!PD)
3111 continue;
3112 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3113 InstanceMethods.push_back(Getter);
3114 if (PD->isReadOnly())
3115 continue;
3116 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3117 InstanceMethods.push_back(Setter);
3118 }
3119 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003120 true, "CATEGORY_", FullCategoryName.c_str(),
3121 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003122
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003123 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003124 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003125 false, "CATEGORY_", FullCategoryName.c_str(),
3126 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003127
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003128 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003129 // Null CDecl is case of a category implementation with no category interface
3130 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003131 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3132 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003133 /* struct _objc_category {
3134 char *category_name;
3135 char *class_name;
3136 struct _objc_method_list *instance_methods;
3137 struct _objc_method_list *class_methods;
3138 struct _objc_protocol_list *protocols;
3139 // Objective-C 1.0 extensions
3140 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003141 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003142 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003143 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003144 */
Mike Stump11289f42009-09-09 15:08:12 +00003145
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003146 static bool objc_category = false;
3147 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003148 Result += "\nstruct _objc_category {\n";
3149 Result += "\tchar *category_name;\n";
3150 Result += "\tchar *class_name;\n";
3151 Result += "\tstruct _objc_method_list *instance_methods;\n";
3152 Result += "\tstruct _objc_method_list *class_methods;\n";
3153 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003154 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003155 Result += "\tstruct _objc_property_list *instance_properties;\n";
3156 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003157 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003158 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003159 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3160 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003161 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003162 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003163 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003164 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003165 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003166
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003167 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003168 Result += "\t, (struct _objc_method_list *)"
3169 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3170 Result += FullCategoryName;
3171 Result += "\n";
3172 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003173 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003174 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003175 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003176 Result += "\t, (struct _objc_method_list *)"
3177 "&_OBJC_CATEGORY_CLASS_METHODS_";
3178 Result += FullCategoryName;
3179 Result += "\n";
3180 }
3181 else
3182 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003183
Chris Lattnerf5b77512009-02-20 18:18:36 +00003184 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003185 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003186 Result += FullCategoryName;
3187 Result += "\n";
3188 }
3189 else
3190 Result += "\t, 0\n";
3191 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003192}
3193
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003194/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3195/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003196void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3197 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003198 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003199 if (ivar->isBitField()) {
3200 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3201 // place all bitfields at offset 0.
3202 Result += "0";
3203 } else {
3204 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003205 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003206 if (LangOpts.Microsoft)
3207 Result += "_IMPL";
3208 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003209 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003210 Result += ")";
3211 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003212}
3213
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003214//===----------------------------------------------------------------------===//
3215// Meta Data Emission
3216//===----------------------------------------------------------------------===//
3217
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003218void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003219 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003220 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003221
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003222 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003223 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003224 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003225 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003226 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003227 }
Mike Stump11289f42009-09-09 15:08:12 +00003228
Chris Lattner30d23e82007-12-12 07:56:42 +00003229 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003230 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003231 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003232 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 if (NumIvars > 0) {
3234 static bool objc_ivar = false;
3235 if (!objc_ivar) {
3236 /* struct _objc_ivar {
3237 char *ivar_name;
3238 char *ivar_type;
3239 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003240 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003241 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003242 Result += "\nstruct _objc_ivar {\n";
3243 Result += "\tchar *ivar_name;\n";
3244 Result += "\tchar *ivar_type;\n";
3245 Result += "\tint ivar_offset;\n";
3246 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003247
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003248 objc_ivar = true;
3249 }
3250
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003251 /* struct {
3252 int ivar_count;
3253 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003254 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003255 */
Mike Stump11289f42009-09-09 15:08:12 +00003256 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003257 Result += "\tint ivar_count;\n";
3258 Result += "\tstruct _objc_ivar ivar_list[";
3259 Result += utostr(NumIvars);
3260 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003261 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003262 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003263 "{\n\t";
3264 Result += utostr(NumIvars);
3265 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003266
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003267 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003268 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003269 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003270 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003271 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003272 IV != IVEnd; ++IV)
3273 IVars.push_back(*IV);
3274 IVI = IVars.begin();
3275 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003276 } else {
3277 IVI = CDecl->ivar_begin();
3278 IVE = CDecl->ivar_end();
3279 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003280 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003281 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003282 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003283 std::string TmpString, StrEncoding;
3284 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3285 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003286 Result += StrEncoding;
3287 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003288 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003289 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003290 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003291 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003292 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003293 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003294 std::string TmpString, StrEncoding;
3295 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3296 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003297 Result += StrEncoding;
3298 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003299 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003300 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003301 }
Mike Stump11289f42009-09-09 15:08:12 +00003302
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003303 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003304 }
Mike Stump11289f42009-09-09 15:08:12 +00003305
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003306 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003307 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003308 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003309
3310 // If any of our property implementations have associated getters or
3311 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003312 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3313 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003314 Prop != PropEnd; ++Prop) {
3315 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3316 continue;
3317 if (!(*Prop)->getPropertyIvarDecl())
3318 continue;
3319 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3320 if (!PD)
3321 continue;
3322 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3323 InstanceMethods.push_back(Getter);
3324 if (PD->isReadOnly())
3325 continue;
3326 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3327 InstanceMethods.push_back(Setter);
3328 }
3329 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003330 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003331
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003332 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003333 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003334 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003336 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003337 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3338 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003339
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003340 // Declaration of class/meta-class metadata
3341 /* struct _objc_class {
3342 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003343 const char *super_class_name;
3344 char *name;
3345 long version;
3346 long info;
3347 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003348 struct _objc_ivar_list *ivars;
3349 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003350 struct objc_cache *cache;
3351 struct objc_protocol_list *protocols;
3352 const char *ivar_layout;
3353 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003354 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003355 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003356 static bool objc_class = false;
3357 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003358 Result += "\nstruct _objc_class {\n";
3359 Result += "\tstruct _objc_class *isa;\n";
3360 Result += "\tconst char *super_class_name;\n";
3361 Result += "\tchar *name;\n";
3362 Result += "\tlong version;\n";
3363 Result += "\tlong info;\n";
3364 Result += "\tlong instance_size;\n";
3365 Result += "\tstruct _objc_ivar_list *ivars;\n";
3366 Result += "\tstruct _objc_method_list *methods;\n";
3367 Result += "\tstruct objc_cache *cache;\n";
3368 Result += "\tstruct _objc_protocol_list *protocols;\n";
3369 Result += "\tconst char *ivar_layout;\n";
3370 Result += "\tstruct _objc_class_ext *ext;\n";
3371 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003372 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003373 }
Mike Stump11289f42009-09-09 15:08:12 +00003374
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003375 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003376 ObjCInterfaceDecl *RootClass = 0;
3377 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003378 while (SuperClass) {
3379 RootClass = SuperClass;
3380 SuperClass = SuperClass->getSuperClass();
3381 }
3382 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003383
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003384 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003385 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003386 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003387 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003388 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003389 Result += "\"";
3390
3391 if (SuperClass) {
3392 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003393 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003394 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003395 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003396 Result += "\"";
3397 }
3398 else {
3399 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003400 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003401 Result += "\"";
3402 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003403 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003404 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003407 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003408 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003409 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003410 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003411 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003412 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003413 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003414 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003415 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003416 Result += ",0,0\n";
3417 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003418 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003419 Result += "\t,0,0,0,0\n";
3420 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003421
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003422 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003423 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003424 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003425 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003426 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003427 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003428 if (SuperClass) {
3429 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003430 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003431 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003432 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003433 Result += "\"";
3434 }
3435 else {
3436 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003437 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003438 Result += "\"";
3439 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003440 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003441 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003442 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003443 Result += ",0";
3444 else {
3445 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003446 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003447 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003448 if (LangOpts.Microsoft)
3449 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003450 Result += ")";
3451 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003452 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003453 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003454 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003455 Result += "\n\t";
3456 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003457 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003458 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003459 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003460 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003461 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003462 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003463 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003464 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003465 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003466 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003467 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003468 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003469 Result += ", 0,0\n";
3470 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003471 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003472 Result += ",0,0,0\n";
3473 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003474}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003475
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003476/// RewriteImplementations - This routine rewrites all method implementations
3477/// and emits meta-data.
3478
Steve Narofff8cfd162008-11-13 20:07:04 +00003479void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003480 int ClsDefCount = ClassImplementation.size();
3481 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003482
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003483 // Rewrite implemented methods
3484 for (int i = 0; i < ClsDefCount; i++)
3485 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003486
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003487 for (int i = 0; i < CatDefCount; i++)
3488 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003489}
Mike Stump11289f42009-09-09 15:08:12 +00003490
Steve Narofff8cfd162008-11-13 20:07:04 +00003491void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3492 int ClsDefCount = ClassImplementation.size();
3493 int CatDefCount = CategoryImplementation.size();
3494
Steve Naroff30ac2222008-05-07 21:23:49 +00003495 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003496 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003497 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003498 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003499 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003500
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003501 // For each implemented category, write out all its meta data.
3502 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003503 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003504
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003505 // Write objc_symtab metadata
3506 /*
3507 struct _objc_symtab
3508 {
3509 long sel_ref_cnt;
3510 SEL *refs;
3511 short cls_def_cnt;
3512 short cat_def_cnt;
3513 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003514 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003515 */
Mike Stump11289f42009-09-09 15:08:12 +00003516
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003517 Result += "\nstruct _objc_symtab {\n";
3518 Result += "\tlong sel_ref_cnt;\n";
3519 Result += "\tSEL *refs;\n";
3520 Result += "\tshort cls_def_cnt;\n";
3521 Result += "\tshort cat_def_cnt;\n";
3522 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3523 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003524
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003525 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003526 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003527 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 + ", " + utostr(CatDefCount) + "\n";
3529 for (int i = 0; i < ClsDefCount; i++) {
3530 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003531 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003532 Result += "\n";
3533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 for (int i = 0; i < CatDefCount; i++) {
3536 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003537 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003538 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003539 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 Result += "\n";
3541 }
Mike Stump11289f42009-09-09 15:08:12 +00003542
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003543 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003544
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003545 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003546
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003547 /*
3548 struct _objc_module {
3549 long version;
3550 long size;
3551 const char *name;
3552 struct _objc_symtab *symtab;
3553 }
3554 */
Mike Stump11289f42009-09-09 15:08:12 +00003555
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 Result += "\nstruct _objc_module {\n";
3557 Result += "\tlong version;\n";
3558 Result += "\tlong size;\n";
3559 Result += "\tconst char *name;\n";
3560 Result += "\tstruct _objc_symtab *symtab;\n";
3561 Result += "};\n\n";
3562 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003563 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003564 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003565 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003566 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003567
3568 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003569 if (ProtocolExprDecls.size()) {
3570 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3571 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003572 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003573 E = ProtocolExprDecls.end(); I != E; ++I) {
3574 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3575 Result += (*I)->getNameAsString();
3576 Result += " = &_OBJC_PROTOCOL_";
3577 Result += (*I)->getNameAsString();
3578 Result += ";\n";
3579 }
3580 Result += "#pragma data_seg(pop)\n\n";
3581 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003582 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003583 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003584 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3585 Result += "&_OBJC_MODULES;\n";
3586 Result += "#pragma data_seg(pop)\n\n";
3587 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003588}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003589
Steve Naroff677ab3a2008-10-27 17:20:55 +00003590std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3591 const char *funcName,
3592 std::string Tag) {
3593 const FunctionType *AFT = CE->getFunctionType();
3594 QualType RT = AFT->getResultType();
3595 std::string StructRef = "struct " + Tag;
3596 std::string S = "static " + RT.getAsString() + " __" +
3597 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003598
Steve Naroff677ab3a2008-10-27 17:20:55 +00003599 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003600
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003601 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003602 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003603 // block (to reference imported block decl refs).
3604 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003605 } else if (BD->param_empty()) {
3606 S += "(" + StructRef + " *__cself)";
3607 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003608 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003609 assert(FT && "SynthesizeBlockFunc: No function proto");
3610 S += '(';
3611 // first add the implicit argument.
3612 S += StructRef + " *__cself, ";
3613 std::string ParamStr;
3614 for (BlockDecl::param_iterator AI = BD->param_begin(),
3615 E = BD->param_end(); AI != E; ++AI) {
3616 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003617 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003618 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003619 S += ParamStr;
3620 }
3621 if (FT->isVariadic()) {
3622 if (!BD->param_empty()) S += ", ";
3623 S += "...";
3624 }
3625 S += ')';
3626 }
3627 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003628
Steve Naroff677ab3a2008-10-27 17:20:55 +00003629 // Create local declarations to avoid rewriting all closure decl ref exprs.
3630 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003631 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003632 E = BlockByRefDecls.end(); I != E; ++I) {
3633 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003634 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003635 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003636 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003637 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003638 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003639 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003640 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003641 E = BlockByCopyDecls.end(); I != E; ++I) {
3642 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003643 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003644 // Handle nested closure invocation. For example:
3645 //
3646 // void (^myImportedClosure)(void);
3647 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003648 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003649 // void (^anotherClosure)(void);
3650 // anotherClosure = ^(void) {
3651 // myImportedClosure(); // import and invoke the closure
3652 // };
3653 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003654 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003655 S += "struct __block_impl *";
3656 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003657 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003658 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003659 }
3660 std::string RewrittenStr = RewrittenBlockExprs[CE];
3661 const char *cstr = RewrittenStr.c_str();
3662 while (*cstr++ != '{') ;
3663 S += cstr;
3664 S += "\n";
3665 return S;
3666}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003667
Steve Naroff677ab3a2008-10-27 17:20:55 +00003668std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3669 const char *funcName,
3670 std::string Tag) {
3671 std::string StructRef = "struct " + Tag;
3672 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003673
Steve Naroff677ab3a2008-10-27 17:20:55 +00003674 S += funcName;
3675 S += "_block_copy_" + utostr(i);
3676 S += "(" + StructRef;
3677 S += "*dst, " + StructRef;
3678 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003679 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003680 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003681 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003682 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003683 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003684 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003685 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003686 }
3687 S += "\nstatic void __";
3688 S += funcName;
3689 S += "_block_dispose_" + utostr(i);
3690 S += "(" + StructRef;
3691 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003692 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003693 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003694 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003695 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003696 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003697 }
Mike Stump11289f42009-09-09 15:08:12 +00003698 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003699 return S;
3700}
3701
3702std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3703 bool hasCopyDisposeHelpers) {
Steve Naroff295570a2008-10-30 12:09:33 +00003704 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003705 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003706
Steve Naroff677ab3a2008-10-27 17:20:55 +00003707 S += " {\n struct __block_impl impl;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003708
Steve Naroff677ab3a2008-10-27 17:20:55 +00003709 if (hasCopyDisposeHelpers)
3710 S += " void *copy;\n void *dispose;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003711
Steve Naroff677ab3a2008-10-27 17:20:55 +00003712 Constructor += "(void *fp";
Mike Stump11289f42009-09-09 15:08:12 +00003713
Steve Naroff677ab3a2008-10-27 17:20:55 +00003714 if (hasCopyDisposeHelpers)
3715 Constructor += ", void *copyHelp, void *disposeHelp";
Mike Stump11289f42009-09-09 15:08:12 +00003716
Steve Naroff677ab3a2008-10-27 17:20:55 +00003717 if (BlockDeclRefs.size()) {
3718 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003719 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003720 E = BlockByCopyDecls.end(); I != E; ++I) {
3721 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003722 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003723 std::string ArgName = "_" + FieldName;
3724 // Handle nested closure invocation. For example:
3725 //
3726 // void (^myImportedBlock)(void);
3727 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003728 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003729 // void (^anotherBlock)(void);
3730 // anotherBlock = ^(void) {
3731 // myImportedBlock(); // import and invoke the closure
3732 // };
3733 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003734 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003735 S += "struct __block_impl *";
3736 Constructor += ", void *" + ArgName;
3737 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003738 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3739 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003740 Constructor += ", " + ArgName;
3741 }
3742 S += FieldName + ";\n";
3743 }
3744 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003745 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003746 E = BlockByRefDecls.end(); I != E; ++I) {
3747 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003748 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003749 std::string ArgName = "_" + FieldName;
3750 // Handle nested closure invocation. For example:
3751 //
3752 // void (^myImportedBlock)(void);
3753 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003754 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003755 // void (^anotherBlock)(void);
3756 // anotherBlock = ^(void) {
3757 // myImportedBlock(); // import and invoke the closure
3758 // };
3759 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003760 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003761 S += "struct __block_impl *";
3762 Constructor += ", void *" + ArgName;
3763 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003764 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003765 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003766 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003767 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003768 Constructor += ", " + ArgName;
3769 }
3770 S += FieldName + "; // by ref\n";
3771 }
3772 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003773 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003774 if (GlobalVarDecl)
3775 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3776 else
3777 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3778 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003779 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003780
Steve Naroff677ab3a2008-10-27 17:20:55 +00003781 if (hasCopyDisposeHelpers)
3782 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003783
Steve Naroff677ab3a2008-10-27 17:20:55 +00003784 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003785 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003786 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003787 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003788 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003789 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003790 Constructor += Name + " = (struct __block_impl *)_";
3791 else
3792 Constructor += Name + " = _";
3793 Constructor += Name + ";\n";
3794 }
3795 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003796 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003797 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003798 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003799 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003800 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 Constructor += Name + " = (struct __block_impl *)_";
3802 else
3803 Constructor += Name + " = _";
3804 Constructor += Name + ";\n";
3805 }
3806 } else {
3807 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003808 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003809 if (GlobalVarDecl)
3810 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3811 else
3812 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3813 Constructor += " impl.Size = sizeof(";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3815 if (hasCopyDisposeHelpers)
3816 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3817 }
3818 Constructor += " ";
3819 Constructor += "}\n";
3820 S += Constructor;
3821 S += "};\n";
3822 return S;
3823}
3824
3825void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3826 const char *FunName) {
3827 // Insert closures that were part of the function.
3828 for (unsigned i = 0; i < Blocks.size(); i++) {
3829
3830 CollectBlockDeclRefInfo(Blocks[i]);
3831
3832 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003833
3834 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 ImportedBlockDecls.size() > 0);
3836
3837 InsertText(FunLocStart, CI.c_str(), CI.size());
3838
3839 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00003840
Steve Naroff677ab3a2008-10-27 17:20:55 +00003841 InsertText(FunLocStart, CF.c_str(), CF.size());
3842
3843 if (ImportedBlockDecls.size()) {
3844 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3845 InsertText(FunLocStart, HF.c_str(), HF.size());
3846 }
Mike Stump11289f42009-09-09 15:08:12 +00003847
Steve Naroff677ab3a2008-10-27 17:20:55 +00003848 BlockDeclRefs.clear();
3849 BlockByRefDecls.clear();
3850 BlockByCopyDecls.clear();
3851 BlockCallExprs.clear();
3852 ImportedBlockDecls.clear();
3853 }
3854 Blocks.clear();
3855 RewrittenBlockExprs.clear();
3856}
3857
3858void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3859 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003860 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003861
Steve Naroff677ab3a2008-10-27 17:20:55 +00003862 SynthesizeBlockLiterals(FunLocStart, FuncName);
3863}
3864
3865void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003866 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3867 //SourceLocation FunLocStart = MD->getLocStart();
3868 // FIXME: This hack works around a bug in Rewrite.InsertText().
3869 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003870 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 // Convert colons to underscores.
3872 std::string::size_type loc = 0;
3873 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3874 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00003875
Steve Naroff677ab3a2008-10-27 17:20:55 +00003876 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3877}
3878
3879void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3880 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3881 CI != E; ++CI)
3882 if (*CI) {
3883 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3884 GetBlockDeclRefExprs(CBE->getBody());
3885 else
3886 GetBlockDeclRefExprs(*CI);
3887 }
3888 // Handle specific things.
3889 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3890 // FIXME: Handle enums.
3891 if (!isa<FunctionDecl>(CDRE->getDecl()))
3892 BlockDeclRefs.push_back(CDRE);
3893 return;
3894}
3895
3896void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3897 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3898 CI != E; ++CI)
3899 if (*CI) {
3900 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3901 GetBlockCallExprs(CBE->getBody());
3902 else
3903 GetBlockCallExprs(*CI);
3904 }
Mike Stump11289f42009-09-09 15:08:12 +00003905
Steve Naroff677ab3a2008-10-27 17:20:55 +00003906 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3907 if (CE->getCallee()->getType()->isBlockPointerType()) {
3908 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3909 }
3910 }
3911 return;
3912}
3913
Steve Naroff350b6652008-10-30 10:07:53 +00003914Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003915 // Navigate to relevant type information.
3916 const char *closureName = 0;
3917 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003918
Steve Naroff677ab3a2008-10-27 17:20:55 +00003919 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003920 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003921 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003923 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003924 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00003926 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003927 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 } else {
3929 assert(1 && "RewriteBlockClass: Bad type");
3930 }
3931 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003932 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003934 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003936
Steve Naroff350b6652008-10-30 10:07:53 +00003937 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3938 SourceLocation(),
3939 &Context->Idents.get("__block_impl"));
3940 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941
Steve Naroff350b6652008-10-30 10:07:53 +00003942 // Generate a funky cast.
3943 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003944
Steve Naroff350b6652008-10-30 10:07:53 +00003945 // Push the block argument type.
3946 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00003948 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00003949 E = FTP->arg_type_end(); I && (I != E); ++I) {
3950 QualType t = *I;
3951 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00003952 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003953 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00003954 t = Context->getPointerType(BPT->getPointeeType());
3955 }
3956 ArgTypes.push_back(t);
3957 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958 }
Steve Naroff350b6652008-10-30 10:07:53 +00003959 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00003960 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00003961 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003962
Steve Naroff350b6652008-10-30 10:07:53 +00003963 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003964
3965 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00003966 CastExpr::CK_Unknown,
3967 Exp->getCallee(),
Ted Kremenek5a201952009-02-07 01:47:29 +00003968 PtrBlock, SourceLocation(),
3969 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003970 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003971 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3972 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003973 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003974
Douglas Gregor91f84212008-12-11 16:49:14 +00003975 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003976 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003977 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00003978 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3979 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00003980
Anders Carlssona2615922009-07-31 00:48:10 +00003981 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
3982 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00003983 PtrToFuncCastType,
3984 SourceLocation(),
3985 SourceLocation());
3986 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003987
Steve Naroff350b6652008-10-30 10:07:53 +00003988 llvm::SmallVector<Expr*, 8> BlkExprs;
3989 // Add the implicit argument.
3990 BlkExprs.push_back(BlkCast);
3991 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003992 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003993 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003994 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003996 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3997 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00003998 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003999 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000}
4001
4002void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff350b6652008-10-30 10:07:53 +00004003 Stmt *BlockCall = SynthesizeBlockCall(Exp);
4004 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004005}
4006
Steve Naroffd9803712009-04-29 16:37:50 +00004007// We need to return the rewritten expression to handle cases where the
4008// BlockDeclRefExpr is embedded in another expression being rewritten.
4009// For example:
4010//
4011// int main() {
4012// __block Foo *f;
4013// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004014//
Steve Naroffd9803712009-04-29 16:37:50 +00004015// void (^myblock)() = ^() {
4016// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4017// i = 77;
4018// };
4019//}
4020Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004021 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004022 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004023 Context->getPointerType(BDRE->getType()),
4024 SourceLocation());
4025 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004026 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004027 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004028 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004029}
4030
Steve Naroffc989a7b2008-11-03 23:29:32 +00004031void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4032 SourceLocation LocStart = CE->getLParenLoc();
4033 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004034
4035 // Need to avoid trying to rewrite synthesized casts.
4036 if (LocStart.isInvalid())
4037 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004038 // Need to avoid trying to rewrite casts contained in macros.
4039 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4040 return;
Mike Stump11289f42009-09-09 15:08:12 +00004041
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 const char *startBuf = SM->getCharacterData(LocStart);
4043 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004044
Steve Naroff677ab3a2008-10-27 17:20:55 +00004045 // advance the location to startArgList.
4046 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004047
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 while (*argPtr++ && (argPtr < endBuf)) {
4049 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004050 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004051 // Replace the '^' with '*'.
4052 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4053 ReplaceText(LocStart, 1, "*", 1);
4054 break;
4055 }
4056 }
4057 return;
4058}
4059
4060void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4061 SourceLocation DeclLoc = FD->getLocation();
4062 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004063
Steve Naroff677ab3a2008-10-27 17:20:55 +00004064 // We have 1 or more arguments that have closure pointers.
4065 const char *startBuf = SM->getCharacterData(DeclLoc);
4066 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004067
Steve Naroff677ab3a2008-10-27 17:20:55 +00004068 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004069
Steve Naroff677ab3a2008-10-27 17:20:55 +00004070 parenCount++;
4071 // advance the location to startArgList.
4072 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4073 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004074
Steve Naroff677ab3a2008-10-27 17:20:55 +00004075 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004076
Steve Naroff677ab3a2008-10-27 17:20:55 +00004077 while (*argPtr++ && parenCount) {
4078 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004079 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 // Replace the '^' with '*'.
4081 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4082 ReplaceText(DeclLoc, 1, "*", 1);
4083 break;
Mike Stump11289f42009-09-09 15:08:12 +00004084 case '(':
4085 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004086 break;
Mike Stump11289f42009-09-09 15:08:12 +00004087 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004088 parenCount--;
4089 break;
4090 }
4091 }
4092 return;
4093}
4094
4095bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004096 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004097 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004098 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004099 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004101 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004103 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004104 }
4105 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004106 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004107 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004108 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 return true;
4110 }
4111 return false;
4112}
4113
Ted Kremenek5a201952009-02-07 01:47:29 +00004114void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4115 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 const char *argPtr = strchr(Name, '(');
4117 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004118
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 LParen = argPtr; // output the start.
4120 argPtr++; // skip past the left paren.
4121 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004122
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 while (*argPtr && parenCount) {
4124 switch (*argPtr) {
4125 case '(': parenCount++; break;
4126 case ')': parenCount--; break;
4127 default: break;
4128 }
4129 if (parenCount) argPtr++;
4130 }
4131 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4132 RParen = argPtr; // output the end
4133}
4134
4135void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4137 RewriteBlockPointerFunctionArgs(FD);
4138 return;
Mike Stump11289f42009-09-09 15:08:12 +00004139 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004140 // Handle Variables and Typedefs.
4141 SourceLocation DeclLoc = ND->getLocation();
4142 QualType DeclT;
4143 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4144 DeclT = VD->getType();
4145 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4146 DeclT = TDD->getUnderlyingType();
4147 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4148 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004149 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004150 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004151
Steve Naroff677ab3a2008-10-27 17:20:55 +00004152 const char *startBuf = SM->getCharacterData(DeclLoc);
4153 const char *endBuf = startBuf;
4154 // scan backward (from the decl location) for the end of the previous decl.
4155 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4156 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004157
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158 // *startBuf != '^' if we are dealing with a pointer to function that
4159 // may take block argument types (which will be handled below).
4160 if (*startBuf == '^') {
4161 // Replace the '^' with '*', computing a negative offset.
4162 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4163 ReplaceText(DeclLoc, 1, "*", 1);
4164 }
4165 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4166 // Replace the '^' with '*' for arguments.
4167 DeclLoc = ND->getLocation();
4168 startBuf = SM->getCharacterData(DeclLoc);
4169 const char *argListBegin, *argListEnd;
4170 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4171 while (argListBegin < argListEnd) {
4172 if (*argListBegin == '^') {
4173 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4174 ReplaceText(CaretLoc, 1, "*", 1);
4175 }
4176 argListBegin++;
4177 }
4178 }
4179 return;
4180}
4181
Mike Stump11289f42009-09-09 15:08:12 +00004182void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183 // Add initializers for any closure decl refs.
4184 GetBlockDeclRefExprs(Exp->getBody());
4185 if (BlockDeclRefs.size()) {
4186 // Unique all "by copy" declarations.
4187 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4188 if (!BlockDeclRefs[i]->isByRef())
4189 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4190 // Unique all "by ref" declarations.
4191 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4192 if (BlockDeclRefs[i]->isByRef()) {
4193 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4194 }
4195 // Find any imported blocks...they will need special attention.
4196 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004197 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004198 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004199 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4200 }
4201 }
4202}
4203
Steve Narofff4b992a2008-10-28 20:29:00 +00004204FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4205 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004206 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004207 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004208 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004209 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004210}
4211
Steve Naroffd8907b72008-10-29 18:15:37 +00004212Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004213 Blocks.push_back(Exp);
4214
4215 CollectBlockDeclRefInfo(Exp);
4216 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004217
Steve Narofff4b992a2008-10-28 20:29:00 +00004218 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004219 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004220 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004221 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004222 // Convert colons to underscores.
4223 std::string::size_type loc = 0;
4224 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4225 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004226 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004227 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004228
Steve Narofff4b992a2008-10-28 20:29:00 +00004229 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004230
Steve Narofff4b992a2008-10-28 20:29:00 +00004231 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4232 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004233
Steve Narofff4b992a2008-10-28 20:29:00 +00004234 // Get a pointer to the function type so we can cast appropriately.
4235 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4236
4237 FunctionDecl *FD;
4238 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004239
Steve Narofff4b992a2008-10-28 20:29:00 +00004240 // Simulate a contructor call...
4241 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004242 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004243
Steve Narofff4b992a2008-10-28 20:29:00 +00004244 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004245
Steve Naroffe2514232008-10-29 21:23:59 +00004246 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004247 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004248 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4249 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004250 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4251 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004252 Context->VoidPtrTy, SourceLocation(),
4253 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004254 InitExprs.push_back(castExpr);
4255
Steve Narofff4b992a2008-10-28 20:29:00 +00004256 if (ImportedBlockDecls.size()) {
4257 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004258 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004259 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004260 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4261 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004262 Context->VoidPtrTy, SourceLocation(),
4263 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004264 InitExprs.push_back(castExpr);
4265
Steve Narofff4b992a2008-10-28 20:29:00 +00004266 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffe2514232008-10-29 21:23:59 +00004267 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004268 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004269 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4270 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004271 Context->VoidPtrTy, SourceLocation(),
4272 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004273 InitExprs.push_back(castExpr);
Steve Narofff4b992a2008-10-28 20:29:00 +00004274 }
4275 // Add initializers for any closure decl refs.
4276 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004277 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004278 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004279 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004280 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004281 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004282 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004283 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004284 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004285 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004286 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004287 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004288 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4289 CastExpr::CK_Unknown, Arg,
4290 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004291 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004292 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004293 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004294 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004295 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004296 }
Mike Stump11289f42009-09-09 15:08:12 +00004297 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004298 }
4299 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004300 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004301 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004302 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004303 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4304 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004305 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004306 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004307 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004308 }
4309 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004310 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4311 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004312 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004313 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004314 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004315 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004316 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004317 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004318 BlockDeclRefs.clear();
4319 BlockByRefDecls.clear();
4320 BlockByCopyDecls.clear();
4321 ImportedBlockDecls.clear();
4322 return NewRep;
4323}
4324
4325//===----------------------------------------------------------------------===//
4326// Function Body / Expression rewriting
4327//===----------------------------------------------------------------------===//
4328
Steve Naroff4588d0f2008-12-04 16:24:46 +00004329// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4330// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4331// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4332// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4333// Since the rewriter isn't capable of rewriting rewritten code, it's important
4334// we get this right.
4335void RewriteObjC::CollectPropertySetters(Stmt *S) {
4336 // Perform a bottom up traversal of all children.
4337 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4338 CI != E; ++CI)
4339 if (*CI)
4340 CollectPropertySetters(*CI);
4341
4342 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4343 if (BinOp->isAssignmentOp()) {
4344 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4345 PropSetters[PRE] = BinOp;
4346 }
4347 }
4348}
4349
Steve Narofff4b992a2008-10-28 20:29:00 +00004350Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004351 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004352 isa<DoStmt>(S) || isa<ForStmt>(S))
4353 Stmts.push_back(S);
4354 else if (isa<ObjCForCollectionStmt>(S)) {
4355 Stmts.push_back(S);
4356 ObjCBcLabelNo.push_back(++BcLabelCount);
4357 }
Mike Stump11289f42009-09-09 15:08:12 +00004358
Steve Narofff4b992a2008-10-28 20:29:00 +00004359 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004360
Steve Narofff4b992a2008-10-28 20:29:00 +00004361 // Perform a bottom up rewrite of all children.
4362 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4363 CI != E; ++CI)
4364 if (*CI) {
4365 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004366 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004367 *CI = newStmt;
4368 }
Mike Stump11289f42009-09-09 15:08:12 +00004369
Steve Narofff4b992a2008-10-28 20:29:00 +00004370 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4371 // Rewrite the block body in place.
4372 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004373
Steve Narofff4b992a2008-10-28 20:29:00 +00004374 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004375 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4376 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004377
Steve Narofff4b992a2008-10-28 20:29:00 +00004378 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4379 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004380 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004381 return blockTranscribed;
4382 }
4383 // Handle specific things.
4384 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4385 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004386
Steve Narofff4b992a2008-10-28 20:29:00 +00004387 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4388 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4389
Steve Naroff4588d0f2008-12-04 16:24:46 +00004390 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4391 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4392 if (BinOp) {
4393 // Because the rewriter doesn't allow us to rewrite rewritten code,
4394 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004395 DisableReplaceStmt = true;
4396 // Save the source range. Even if we disable the replacement, the
4397 // rewritten node will have been inserted into the tree. If the synthesized
4398 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004399 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004400 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4401 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004402 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004403 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004404 //
4405 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4406 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4407 // to see the original expression). Consider this example:
4408 //
4409 // Foo *obj1, *obj2;
4410 //
4411 // obj1.i = [obj2 rrrr];
4412 //
4413 // 'BinOp' for the previous expression looks like:
4414 //
4415 // (BinaryOperator 0x231ccf0 'int' '='
4416 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4417 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4418 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4419 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4420 //
4421 // 'newStmt' represents the rewritten message expression. For example:
4422 //
4423 // (CallExpr 0x231d300 'id':'struct objc_object *'
4424 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4425 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4426 // (CStyleCastExpr 0x231d220 'void *'
4427 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4428 //
4429 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4430 // can be used as the setter argument. ReplaceStmt() will still 'see'
4431 // the original RHS (since we haven't altered BinOp).
4432 //
Mike Stump11289f42009-09-09 15:08:12 +00004433 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004434 // node. As a result, we now leak the original AST nodes.
4435 //
Steve Naroff08628db2008-12-09 12:56:34 +00004436 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004437 } else {
4438 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004439 }
4440 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004441 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4442 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004443
Steve Narofff4b992a2008-10-28 20:29:00 +00004444 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4445 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004446
Steve Narofff4b992a2008-10-28 20:29:00 +00004447 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004448#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004449 // Before we rewrite it, put the original message expression in a comment.
4450 SourceLocation startLoc = MessExpr->getLocStart();
4451 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004452
Steve Narofff4b992a2008-10-28 20:29:00 +00004453 const char *startBuf = SM->getCharacterData(startLoc);
4454 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004455
Steve Narofff4b992a2008-10-28 20:29:00 +00004456 std::string messString;
4457 messString += "// ";
4458 messString.append(startBuf, endBuf-startBuf+1);
4459 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004460
4461 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004462 // InsertText(clang::SourceLocation, char const*, unsigned int).
4463 // InsertText(startLoc, messString.c_str(), messString.size());
4464 // Tried this, but it didn't work either...
4465 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004466#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004467 return RewriteMessageExpr(MessExpr);
4468 }
Mike Stump11289f42009-09-09 15:08:12 +00004469
Steve Narofff4b992a2008-10-28 20:29:00 +00004470 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4471 return RewriteObjCTryStmt(StmtTry);
4472
4473 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4474 return RewriteObjCSynchronizedStmt(StmtTry);
4475
4476 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4477 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004478
Steve Narofff4b992a2008-10-28 20:29:00 +00004479 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4480 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004481
4482 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004483 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004484 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004485 OrigStmtRange.getEnd());
4486 if (BreakStmt *StmtBreakStmt =
4487 dyn_cast<BreakStmt>(S))
4488 return RewriteBreakStmt(StmtBreakStmt);
4489 if (ContinueStmt *StmtContinueStmt =
4490 dyn_cast<ContinueStmt>(S))
4491 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004492
4493 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004494 // and cast exprs.
4495 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4496 // FIXME: What we're doing here is modifying the type-specifier that
4497 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004498 // a separate type-specifier that we can rewrite.
Steve Narofff4b992a2008-10-28 20:29:00 +00004499 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004500
Steve Narofff4b992a2008-10-28 20:29:00 +00004501 // Blocks rewrite rules.
4502 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4503 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004504 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004505 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004506 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004507 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004508 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004509 CheckFunctionPointerDecl(ND->getType(), ND);
4510 }
4511 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004512 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004513 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004514 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004515 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4516 }
4517 }
4518 }
Mike Stump11289f42009-09-09 15:08:12 +00004519
Steve Narofff4b992a2008-10-28 20:29:00 +00004520 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4521 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004522
4523 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004524 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4525 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004526 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4527 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004528 && "Statement stack mismatch");
4529 Stmts.pop_back();
4530 }
4531 // Handle blocks rewriting.
4532 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4533 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004534 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004535 }
4536 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004537 if (CE->getCallee()->getType()->isBlockPointerType()) {
4538 Stmt *BlockCall = SynthesizeBlockCall(CE);
4539 ReplaceStmt(S, BlockCall);
4540 return BlockCall;
4541 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004542 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004543 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004544 RewriteCastExpr(CE);
4545 }
4546#if 0
4547 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004548 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004549 // Get the new text.
4550 std::string SStr;
4551 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004552 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004553 const std::string &Str = Buf.str();
4554
4555 printf("CAST = %s\n", &Str[0]);
4556 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4557 delete S;
4558 return Replacement;
4559 }
4560#endif
4561 // Return this stmt unmodified.
4562 return S;
4563}
4564
4565/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4566/// main file of the input.
4567void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004569 if (FD->isOverloadedOperator())
4570 return;
Mike Stump11289f42009-09-09 15:08:12 +00004571
Steve Narofff4b992a2008-10-28 20:29:00 +00004572 // Since function prototypes don't have ParmDecl's, we check the function
4573 // prototype. This enables us to rewrite function declarations and
4574 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004575 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004576
Sebastian Redla7b98a72009-04-26 20:35:05 +00004577 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004578 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004579 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004580 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004581 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004582 Body =
4583 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4584 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004585 CurrentBody = 0;
4586 if (PropParentMap) {
4587 delete PropParentMap;
4588 PropParentMap = 0;
4589 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004590 // This synthesizes and inserts the block "impl" struct, invoke function,
4591 // and any copy/dispose helper functions.
4592 InsertBlockLiteralsWithinFunction(FD);
4593 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004594 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004595 return;
4596 }
4597 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004598 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004599 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004600 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004601 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004602 Body =
4603 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4604 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004605 CurrentBody = 0;
4606 if (PropParentMap) {
4607 delete PropParentMap;
4608 PropParentMap = 0;
4609 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004610 InsertBlockLiteralsWithinMethod(MD);
4611 CurMethodDef = 0;
4612 }
4613 }
4614 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4615 ClassImplementation.push_back(CI);
4616 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4617 CategoryImplementation.push_back(CI);
4618 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4619 RewriteForwardClassDecl(CD);
4620 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4621 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004622 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004623 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004624 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004625 CheckFunctionPointerDecl(VD->getType(), VD);
4626 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004627 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004628 RewriteCastExpr(CE);
4629 }
4630 }
4631 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004632 if (VD->getInit()) {
4633 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004634 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004635 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004636 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004637 CurrentBody = 0;
4638 if (PropParentMap) {
4639 delete PropParentMap;
4640 PropParentMap = 0;
4641 }
Mike Stump11289f42009-09-09 15:08:12 +00004642 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004643 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004644 GlobalVarDecl = 0;
4645
4646 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004647 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004648 RewriteCastExpr(CE);
4649 }
4650 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 return;
4652 }
4653 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004654 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004656 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4658 return;
4659 }
4660 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4661 if (RD->isDefinition()) {
Mike Stump11289f42009-09-09 15:08:12 +00004662 for (RecordDecl::field_iterator i = RD->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004663 e = RD->field_end(); i != e; ++i) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004664 FieldDecl *FD = *i;
Steve Naroffa5c0db82008-12-11 21:05:33 +00004665 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004666 RewriteBlockPointerDecl(FD);
4667 }
4668 }
4669 return;
4670 }
4671 // Nothing yet.
4672}
4673
Chris Lattnercf169832009-03-28 04:11:33 +00004674void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004675 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004676
Steve Narofff4b992a2008-10-28 20:29:00 +00004677 // Rewrite tabs if we care.
4678 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004679
Steve Narofff4b992a2008-10-28 20:29:00 +00004680 if (Diags.hasErrorOccurred())
4681 return;
Mike Stump11289f42009-09-09 15:08:12 +00004682
Steve Narofff4b992a2008-10-28 20:29:00 +00004683 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004684
Steve Naroffd9803712009-04-29 16:37:50 +00004685 // Here's a great place to add any extra declarations that may be needed.
4686 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004687 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004688 E = ProtocolExprDecls.end(); I != E; ++I)
4689 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004693 if (ClassImplementation.size() || CategoryImplementation.size())
4694 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004695
Steve Narofff4b992a2008-10-28 20:29:00 +00004696 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4697 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004698 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004699 Rewrite.getRewriteBufferFor(MainFileID)) {
4700 //printf("Changed:\n");
4701 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4702 } else {
4703 fprintf(stderr, "No changes\n");
4704 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004705
Steve Naroffd9803712009-04-29 16:37:50 +00004706 if (ClassImplementation.size() || CategoryImplementation.size() ||
4707 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004708 // Rewrite Objective-c meta data*
4709 std::string ResultStr;
4710 SynthesizeMetaDataIntoBuffer(ResultStr);
4711 // Emit metadata.
4712 *OutFile << ResultStr;
4713 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 OutFile->flush();
4715}
4716