blob: 842b63010f4df1e3964a90c6f30839be27d84e60 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000044 unsigned TryFinallyContainsReturnDiag;
45
Chris Lattner01c57482007-10-17 22:35:30 +000046 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000047 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000048 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000049 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000050 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000051 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000052
Ted Kremeneka526c5c2008-01-07 19:49:32 +000053 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
54 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
55 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000056 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000057 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
58 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000059 llvm::SmallVector<Stmt *, 32> Stmts;
60 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000061
Steve Naroffd82a9ab2008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000075
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000079
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff874e2322007-11-15 10:28:18 +000083 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000084 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000087
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffa7b402d2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000100
Steve Naroff54055232008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroffc77a6362008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000110 // This maps a property to it's synthesied message expression.
111 // This allows us to rewrite chained getters (e.g. o.a.b.c).
112 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
113
Steve Naroff4c3580e2008-12-04 23:50:32 +0000114 // This maps an original source AST to it's rewritten form. This allows
115 // us to avoid rewriting the same node twice (which is very uncommon).
116 // This is needed to support some of the exotic property rewriting.
117 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000118
Steve Naroff54055232008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffb619d952008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000125 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerf04da132007-10-24 17:06:59 +0000128 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000129 virtual void HandleTopLevelDecl(DeclGroupRef D) {
130 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
131 HandleTopLevelSingleDecl(*I);
132 }
133 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000135 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000136 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
139
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000141
142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
144
145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000147
Steve Naroffb619d952008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff4c3580e2008-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 Lattner0a14eee2008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000160 }
Steve Naroffb619d952008-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);
173 New->printPretty(S);
174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
178 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 Naroffba92b2e2008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000191 SilenceRewriteMacroWarning)
192 return;
193
194 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
195 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000196
Chris Lattneraadaf782008-01-31 19:51:04 +0000197 void RemoveText(SourceLocation Loc, unsigned StrLen) {
198 // If removal succeeded or warning disabled return with no warning.
199 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
200 return;
201
202 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
203 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000204
Chris Lattneraadaf782008-01-31 19:51:04 +0000205 void ReplaceText(SourceLocation Start, unsigned OrigLength,
206 const char *NewStr, unsigned NewLength) {
207 // If removal succeeded or warning disabled return with no warning.
208 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
209 SilenceRewriteMacroWarning)
210 return;
211
212 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
213 }
214
Chris Lattnerf04da132007-10-24 17:06:59 +0000215 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000216 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000217 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000219 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000220 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
221 ObjCImplementationDecl *IMD,
222 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000224 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000225 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
226 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
227 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
228 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
229 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000230 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000231 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000232 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000233 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000234 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000236 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000237 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000238 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000239
Chris Lattnerf04da132007-10-24 17:06:59 +0000240 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000241 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000242 void CollectPropertySetters(Stmt *S);
243
Steve Naroff8599e7a2008-12-08 16:43:47 +0000244 Stmt *CurrentBody;
245 ParentMap *PropParentMap; // created lazily.
246
Chris Lattnere64b7772007-10-24 16:57:36 +0000247 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000248 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000249 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000250 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
251 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000252 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000253 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000254 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000255 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000256 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000258 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000259 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
260 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
261 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000262 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
263 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000264 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
265 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000266 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000267 Stmt *RewriteBreakStmt(BreakStmt *S);
268 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 void SynthCountByEnumWithState(std::string &buf);
270
Steve Naroff09b266e2007-10-30 23:14:51 +0000271 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000272 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000273 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000274 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000275 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000276 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000277 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000278 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000279 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000280 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000281
Chris Lattnerf04da132007-10-24 17:06:59 +0000282 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000284 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000285
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
290 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000291 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000292 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000293 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000294 const char *ClassName,
295 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296
Chris Lattner780f3292008-07-21 21:32:27 +0000297 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
298 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000300 const char *ClassName,
301 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000302 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000303 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000304 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
305 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000307 void RewriteImplementations();
308 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000309
310 // Block rewriting.
Douglas Gregor72564e72009-02-26 23:50:07 +0000311 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000312 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
313
314 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
315 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
316
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000317 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000318 void RewriteBlockCall(CallExpr *Exp);
319 void RewriteBlockPointerDecl(NamedDecl *VD);
320 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
321 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
322
323 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
324 const char *funcName, std::string Tag);
325 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
326 const char *funcName, std::string Tag);
327 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
328 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000329 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000330 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
331 const char *FunName);
332
333 void CollectBlockDeclRefInfo(BlockExpr *Exp);
334 void GetBlockCallExprs(Stmt *S);
335 void GetBlockDeclRefExprs(Stmt *S);
336
337 // We avoid calling Type::isBlockPointerType(), since it operates on the
338 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000339 bool isTopLevelBlockPointerType(QualType T) {
340 return isa<BlockPointerType>(T);
341 }
Steve Naroff54055232008-10-27 17:20:55 +0000342
343 // FIXME: This predicate seems like it would be useful to add to ASTContext.
344 bool isObjCType(QualType T) {
345 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
346 return false;
347
348 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
349
350 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
351 OCT == Context->getCanonicalType(Context->getObjCClassType()))
352 return true;
353
354 if (const PointerType *PT = OCT->getAsPointerType()) {
355 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
356 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
357 return true;
358 }
359 return false;
360 }
361 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000362 void GetExtentOfArgList(const char *Name, const char *&LParen,
363 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000368 };
369}
370
Douglas Gregor72564e72009-02-26 23:50:07 +0000371void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff54055232008-10-27 17:20:55 +0000372 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000373 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
374 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000387 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000388}
389
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroffb29b4272008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000413 "rewriter doesn't support user-specified control flow semantics "
414 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000415}
416
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000417ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000418 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000419 Diagnostic &Diags,
420 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000421 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000422}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000423
Steve Naroffb29b4272008-04-14 22:03:09 +0000424void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000425 Context = &context;
426 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000427 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000428 MsgSendFunctionDecl = 0;
429 MsgSendSuperFunctionDecl = 0;
430 MsgSendStretFunctionDecl = 0;
431 MsgSendSuperStretFunctionDecl = 0;
432 MsgSendFpretFunctionDecl = 0;
433 GetClassFunctionDecl = 0;
434 GetMetaClassFunctionDecl = 0;
435 SelGetUidFunctionDecl = 0;
436 CFStringFunctionDecl = 0;
437 GetProtocolFunctionDecl = 0;
438 ConstantStringClassReference = 0;
439 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000440 CurMethodDef = 0;
441 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000442 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000443 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000444 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000445 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000446 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000447 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000448 PropParentMap = 0;
449 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000450 DisableReplaceStmt = false;
451
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000452 // Get the ID and start/end of the main file.
453 MainFileID = SM->getMainFileID();
454 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
455 MainFileStart = MainBuf->getBufferStart();
456 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457
Chris Lattner2c78b872009-04-14 23:22:57 +0000458 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000459
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000460 // declaring objc_selector outside the parameter list removes a silly
461 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000462 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000463 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000464 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000465 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000466 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000467 if (LangOpts.Microsoft) {
468 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000469 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
470 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000472 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000473 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000474 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
475 Preamble += "typedef struct objc_object Protocol;\n";
476 Preamble += "#define _REWRITER_typedef_Protocol\n";
477 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000478 if (LangOpts.Microsoft) {
479 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
480 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
481 } else
482 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000492 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000496 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000502 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000503 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
505 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
506 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000507 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
508 Preamble += "struct __objcFastEnumerationState {\n\t";
509 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000510 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000511 Preamble += "unsigned long *mutationsPtr;\n\t";
512 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000514 Preamble += "#define __FASTENUMERATIONSTATE\n";
515 Preamble += "#endif\n";
516 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
517 Preamble += "struct __NSConstantStringImpl {\n";
518 Preamble += " int *isa;\n";
519 Preamble += " int flags;\n";
520 Preamble += " char *str;\n";
521 Preamble += " long length;\n";
522 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000523 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
524 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
525 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000527 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000528 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
529 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000530 // Blocks preamble.
531 Preamble += "#ifndef BLOCK_IMPL\n";
532 Preamble += "#define BLOCK_IMPL\n";
533 Preamble += "struct __block_impl {\n";
534 Preamble += " void *isa;\n";
535 Preamble += " int Flags;\n";
536 Preamble += " int Size;\n";
537 Preamble += " void *FuncPtr;\n";
538 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000539 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
542 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000544 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000545 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000546 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
547 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000548 Preamble += "#define __attribute__(X)\n";
549 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550}
551
552
Chris Lattnerf04da132007-10-24 17:06:59 +0000553//===----------------------------------------------------------------------===//
554// Top Level Driver Code
555//===----------------------------------------------------------------------===//
556
Chris Lattner682bf922009-03-29 16:50:03 +0000557void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000558 // Two cases: either the decl could be in the main file, or it could be in a
559 // #included file. If the former, rewrite it now. If the later, check to see
560 // if we rewrote the #include/#import.
561 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000562 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000563
564 // If this is for a builtin, ignore it.
565 if (Loc.isInvalid()) return;
566
Steve Naroffebf2b562007-10-23 23:50:29 +0000567 // Look for built-in declarations that we need to refer during the rewrite.
568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000569 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000570 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000571 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000572 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000573 ConstantStringClassReference = FVD;
574 return;
575 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000576 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000577 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000578 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000579 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000580 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000581 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000582 } else if (ObjCForwardProtocolDecl *FP =
583 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000584 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000585 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
586 // Recurse into linkage specifications
Douglas Gregor6ab35242009-04-09 21:40:53 +0000587 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
588 DIEnd = LSD->decls_end(*Context);
Douglas Gregord0434102009-01-09 00:49:46 +0000589 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000590 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000591 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000592 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000593 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000594 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000595}
596
Chris Lattnerf04da132007-10-24 17:06:59 +0000597//===----------------------------------------------------------------------===//
598// Syntactic (non-AST) Rewriting Code
599//===----------------------------------------------------------------------===//
600
Steve Naroffb29b4272008-04-14 22:03:09 +0000601void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000602 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000603 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
604 const char *MainBufStart = MainBuf.first;
605 const char *MainBufEnd = MainBuf.second;
606 size_t ImportLen = strlen("import");
607 size_t IncludeLen = strlen("include");
608
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000609 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000610 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
611 if (*BufPtr == '#') {
612 if (++BufPtr == MainBufEnd)
613 return;
614 while (*BufPtr == ' ' || *BufPtr == '\t')
615 if (++BufPtr == MainBufEnd)
616 return;
617 if (!strncmp(BufPtr, "import", ImportLen)) {
618 // replace import with include
619 SourceLocation ImportLoc =
620 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000621 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000622 BufPtr += ImportLen;
623 }
624 }
625 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000626}
627
Steve Naroffb29b4272008-04-14 22:03:09 +0000628void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000629 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
630 const char *MainBufStart = MainBuf.first;
631 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000632
Chris Lattnerf04da132007-10-24 17:06:59 +0000633 // Loop over the whole file, looking for tabs.
634 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
635 if (*BufPtr != '\t')
636 continue;
637
638 // Okay, we found a tab. This tab will turn into at least one character,
639 // but it depends on which 'virtual column' it is in. Compute that now.
640 unsigned VCol = 0;
641 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
642 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
643 ++VCol;
644
645 // Okay, now that we know the virtual column, we know how many spaces to
646 // insert. We assume 8-character tab-stops.
647 unsigned Spaces = 8-(VCol & 7);
648
649 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000650 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
651 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000652
653 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000654 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000655 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000656}
657
Steve Naroffeb0646c2008-12-02 15:48:25 +0000658static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
659 ObjCIvarDecl *OID) {
660 std::string S;
661 S = "((struct ";
662 S += ClassDecl->getIdentifier()->getName();
663 S += "_IMPL *)self)->";
664 S += OID->getNameAsCString();
665 return S;
666}
667
Steve Naroffa0876e82008-12-02 17:36:43 +0000668void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
669 ObjCImplementationDecl *IMD,
670 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000671 SourceLocation startLoc = PID->getLocStart();
672 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000673 const char *startBuf = SM->getCharacterData(startLoc);
674 assert((*startBuf == '@') && "bogus @synthesize location");
675 const char *semiBuf = strchr(startBuf, ';');
676 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000677 SourceLocation onePastSemiLoc =
678 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000679
680 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
681 return; // FIXME: is this correct?
682
683 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000684 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000685 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000686 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000687
688 if (!OID)
689 return;
690
691 std::string Getr;
692 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
693 Getr += "{ ";
694 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000695 // FIXME: deal with code generation implications for various property
696 // attributes (copy, retain, nonatomic).
697 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000698 Getr += "return " + getIvarAccessString(ClassDecl, OID);
699 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000700 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000701
702 // Add the rewritten getter to trigger meta data generation. An alternate, and
703 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
704 // with properties explicitly. The following addInstanceMethod() required far
705 // less code change (and actually models what the rewriter is doing).
706 if (IMD)
707 IMD->addInstanceMethod(PD->getGetterMethodDecl());
708 else
709 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000710
711 if (PD->isReadOnly())
712 return;
713
714 // Generate the 'setter' function.
715 std::string Setr;
716 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000717 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000718 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000719 // FIXME: deal with code generation implications for various property
720 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000721 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000722 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000723 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000724 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000725 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000726
727 // Add the rewritten setter to trigger meta data generation.
728 if (IMD)
729 IMD->addInstanceMethod(PD->getSetterMethodDecl());
730 else
731 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000732}
Chris Lattner8a12c272007-10-11 18:38:32 +0000733
Steve Naroffb29b4272008-04-14 22:03:09 +0000734void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000735 // Get the start location and compute the semi location.
736 SourceLocation startLoc = ClassDecl->getLocation();
737 const char *startBuf = SM->getCharacterData(startLoc);
738 const char *semiPtr = strchr(startBuf, ';');
739
740 // Translate to typedef's that forward reference structs with the same name
741 // as the class. As a convenience, we include the original declaration
742 // as a comment.
743 std::string typedefString;
744 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000745 typedefString.append(startBuf, semiPtr-startBuf+1);
746 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000747 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
748 I != E; ++I) {
749 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000750 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "\n";
753 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000756 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000757 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000758 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000759 }
760
761 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000762 ReplaceText(startLoc, semiPtr-startBuf+1,
763 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000764}
765
Steve Naroffb29b4272008-04-14 22:03:09 +0000766void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000767 SourceLocation LocStart = Method->getLocStart();
768 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000769
Chris Lattner30fc9332009-02-04 01:06:56 +0000770 if (SM->getInstantiationLineNumber(LocEnd) >
771 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000772 InsertText(LocStart, "#if 0\n", 6);
773 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000774 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000775 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000776 }
777}
778
Steve Naroff6327e0d2009-01-11 01:06:09 +0000779void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000780{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000781 SourceLocation Loc = prop->getLocation();
782
783 ReplaceText(Loc, 0, "// ", 3);
784
785 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000786}
787
Steve Naroffb29b4272008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000793
Douglas Gregor6ab35242009-04-09 21:40:53 +0000794 for (ObjCCategoryDecl::instmeth_iterator
795 I = CatDecl->instmeth_begin(*Context),
796 E = CatDecl->instmeth_end(*Context);
797 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000799 for (ObjCCategoryDecl::classmeth_iterator
800 I = CatDecl->classmeth_begin(*Context),
801 E = CatDecl->classmeth_end(*Context);
802 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000803 RewriteMethodDeclaration(*I);
804
Steve Naroff423cb562007-10-30 13:30:57 +0000805 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000806 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000807}
808
Steve Naroffb29b4272008-04-14 22:03:09 +0000809void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000811
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812 SourceLocation LocStart = PDecl->getLocStart();
813
814 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000815 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000816
Douglas Gregor6ab35242009-04-09 21:40:53 +0000817 for (ObjCProtocolDecl::instmeth_iterator
818 I = PDecl->instmeth_begin(*Context),
819 E = PDecl->instmeth_end(*Context);
820 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000821 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000822 for (ObjCProtocolDecl::classmeth_iterator
823 I = PDecl->classmeth_begin(*Context),
824 E = PDecl->classmeth_end(*Context);
825 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000826 RewriteMethodDeclaration(*I);
827
Steve Naroff752d6ef2007-10-30 16:42:30 +0000828 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000829 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000830 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000831
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000832 // Must comment out @optional/@required
833 const char *startBuf = SM->getCharacterData(LocStart);
834 const char *endBuf = SM->getCharacterData(LocEnd);
835 for (const char *p = startBuf; p < endBuf; p++) {
836 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
837 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000838 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000839 ReplaceText(OptionalLoc, strlen("@optional"),
840 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000841
842 }
843 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
844 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000845 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000846 ReplaceText(OptionalLoc, strlen("@required"),
847 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000848
849 }
850 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000851}
852
Steve Naroffb29b4272008-04-14 22:03:09 +0000853void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000854 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000855 if (LocStart.isInvalid())
856 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000857 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000858 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000859}
860
Steve Naroffb29b4272008-04-14 22:03:09 +0000861void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000863 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000864 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000865 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000866 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000867 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000868 else if (OMD->getResultType()->isFunctionPointerType() ||
869 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000870 // needs special handling, since pointer-to-functions have special
871 // syntax (where a decaration models use).
872 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000873 QualType PointeeTy;
874 if (const PointerType* PT = retType->getAsPointerType())
875 PointeeTy = PT->getPointeeType();
876 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
877 PointeeTy = BPT->getPointeeType();
878 if ((FPRetType = PointeeTy->getAsFunctionType())) {
879 ResultStr += FPRetType->getResultType().getAsString();
880 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000881 }
882 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000883 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000884 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000885
886 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000887 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000889 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000890 NameStr += "_I_";
891 else
892 NameStr += "_C_";
893
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000894 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000895 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000897 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000898 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000899 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000900 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 }
Steve Naroff563b8282008-04-04 22:23:44 +0000902 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000903 {
904 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905 int len = selString.size();
906 for (int i = 0; i < len; i++)
907 if (selString[i] == ':')
908 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000909 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000910 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000911 // Remember this name for metadata emission
912 MethodInternalNames[OMD] = NameStr;
913 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914
915 // Rewrite arguments
916 ResultStr += "(";
917
918 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000919 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000920 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000921 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000922 if (!LangOpts.Microsoft) {
923 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
924 ResultStr += "struct ";
925 }
926 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000927 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000928 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929 }
930 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932
933 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000934 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000935 ResultStr += " _cmd";
936
937 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000938 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
939 E = OMD->param_end(); PI != E; ++PI) {
940 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000941 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000942 if (PDecl->getType()->isObjCQualifiedIdType()) {
943 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000944 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000945 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000946 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000947 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000948 // Make sure we convert "t (^)(...)" to "t (*)(...)".
949 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
950 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
951 } else
952 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000953 ResultStr += Name;
954 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000956 if (OMD->isVariadic())
957 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000958 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000959
Steve Naroff76e429d2008-07-16 14:40:40 +0000960 if (FPRetType) {
961 ResultStr += ")"; // close the precedence "scope" for "*".
962
963 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000964 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000965 ResultStr += "(";
966 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
967 if (i) ResultStr += ", ";
968 std::string ParamStr = FT->getArgType(i).getAsString();
969 ResultStr += ParamStr;
970 }
971 if (FT->isVariadic()) {
972 if (FT->getNumArgs()) ResultStr += ", ";
973 ResultStr += "...";
974 }
975 ResultStr += ")";
976 } else {
977 ResultStr += "()";
978 }
979 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000980}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000981void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000982 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
983 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000984
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000985 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000986 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000987 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000988 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000989
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000991 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
992 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 ObjCMethodDecl *OMD = *I;
995 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 SourceLocation LocStart = OMD->getLocStart();
Douglas Gregor72971342009-04-18 00:02:19 +0000997 SourceLocation LocEnd = OMD->getBody(*Context)->getLocStart();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(LocStart, endBuf-startBuf,
1002 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 }
1004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001006 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1007 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001009 ObjCMethodDecl *OMD = *I;
1010 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001011 SourceLocation LocStart = OMD->getLocStart();
Douglas Gregor72971342009-04-18 00:02:19 +00001012 SourceLocation LocEnd = OMD->getBody(*Context)->getLocStart();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001013
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001016 ReplaceText(LocStart, endBuf-startBuf,
1017 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001018 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001019 for (ObjCCategoryImplDecl::propimpl_iterator
1020 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1021 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001022 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001023 }
1024
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001025 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001026 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001027 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001028 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001029}
1030
Steve Naroffb29b4272008-04-14 22:03:09 +00001031void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001032 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001034 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001035 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001037 ResultStr += "\n";
1038 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001039 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001040 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001041 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001042 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001043 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001044 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001045 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001046 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001048
Douglas Gregor6ab35242009-04-09 21:40:53 +00001049 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1050 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001051 RewriteProperty(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001052 for (ObjCInterfaceDecl::instmeth_iterator
1053 I = ClassDecl->instmeth_begin(*Context),
1054 E = ClassDecl->instmeth_end(*Context);
1055 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001056 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001057 for (ObjCInterfaceDecl::classmeth_iterator
1058 I = ClassDecl->classmeth_begin(*Context),
1059 E = ClassDecl->classmeth_end(*Context);
1060 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001061 RewriteMethodDeclaration(*I);
1062
Steve Naroff2feac5e2007-10-30 03:43:13 +00001063 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001064 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001065}
1066
Steve Naroffb619d952008-12-09 12:56:34 +00001067Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1068 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001069 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1070 // This allows us to reuse all the fun and games in SynthMessageExpr().
1071 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1072 ObjCMessageExpr *MsgExpr;
1073 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1074 llvm::SmallVector<Expr *, 1> ExprVec;
1075 ExprVec.push_back(newStmt);
1076
Steve Naroff8599e7a2008-12-08 16:43:47 +00001077 Stmt *Receiver = PropRefExpr->getBase();
1078 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1079 if (PRE && PropGetters[PRE]) {
1080 // This allows us to handle chain/nested property getters.
1081 Receiver = PropGetters[PRE];
1082 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001083 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001084 PDecl->getSetterName(), PDecl->getType(),
1085 PDecl->getSetterMethodDecl(),
1086 SourceLocation(), SourceLocation(),
1087 &ExprVec[0], 1);
1088 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1089
1090 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001091 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001092 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001093 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1094 // to things that stay around.
1095 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001096 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001097}
1098
Steve Naroffc77a6362008-12-04 16:24:46 +00001099Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001100 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1101 // This allows us to reuse all the fun and games in SynthMessageExpr().
1102 ObjCMessageExpr *MsgExpr;
1103 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1104
Steve Naroff8599e7a2008-12-08 16:43:47 +00001105 Stmt *Receiver = PropRefExpr->getBase();
1106
1107 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1108 if (PRE && PropGetters[PRE]) {
1109 // This allows us to handle chain/nested property getters.
1110 Receiver = PropGetters[PRE];
1111 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001112 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001113 PDecl->getGetterName(), PDecl->getType(),
1114 PDecl->getGetterMethodDecl(),
1115 SourceLocation(), SourceLocation(),
1116 0, 0);
1117
Steve Naroff4c3580e2008-12-04 23:50:32 +00001118 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001119
1120 if (!PropParentMap)
1121 PropParentMap = new ParentMap(CurrentBody);
1122
1123 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1124 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1125 // We stash away the ReplacingStmt since actually doing the
1126 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1127 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001128 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1129 // to things that stay around.
1130 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001131 return PropRefExpr; // return the original...
1132 } else {
1133 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001134 // delete PropRefExpr; elsewhere...
1135 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1136 // to things that stay around.
1137 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001138 return ReplacingStmt;
1139 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001140}
1141
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001142Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1143 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001144 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001145 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001146 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001147 ObjCInterfaceType *iFaceDecl =
1148 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001149 // lookup which class implements the instance variable.
1150 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001151 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1152 D->getIdentifier(),
1153 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001154 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1155
1156 // Synthesize an explicit cast to gain access to the ivar.
1157 std::string RecName = clsDeclared->getIdentifier()->getName();
1158 RecName += "_IMPL";
1159 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001160 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001161 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001162 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1163 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001164 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1165 castT,SourceLocation(),
1166 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001167 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001168 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1169 IV->getBase()->getLocEnd(),
1170 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001171 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001172 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001173 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1174 IV->getLocation(),
1175 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001176 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001177 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001178 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001179 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001180
1181 ReplaceStmt(IV->getBase(), PE);
1182 // Cannot delete IV->getBase(), since PE points to it.
1183 // Replace the old base with the cast. This is important when doing
1184 // embedded rewrites. For example, [newInv->_container addObject:0].
1185 IV->setBase(PE);
1186 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001187 }
Steve Naroff84472a82008-04-18 21:55:08 +00001188 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001189 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1190
1191 // Explicit ivar refs need to have a cast inserted.
1192 // FIXME: consider sharing some of this code with the code above.
1193 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001194 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001195 // lookup which class implements the instance variable.
1196 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001197 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1198 D->getIdentifier(),
1199 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001200 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1201
1202 // Synthesize an explicit cast to gain access to the ivar.
1203 std::string RecName = clsDeclared->getIdentifier()->getName();
1204 RecName += "_IMPL";
1205 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001206 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001207 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001208 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1209 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001210 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1211 castT, SourceLocation(),
1212 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001213 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001214 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001215 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001216 ReplaceStmt(IV->getBase(), PE);
1217 // Cannot delete IV->getBase(), since PE points to it.
1218 // Replace the old base with the cast. This is important when doing
1219 // embedded rewrites. For example, [newInv->_container addObject:0].
1220 IV->setBase(PE);
1221 return IV;
1222 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001223 }
Steve Naroff84472a82008-04-18 21:55:08 +00001224 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001225}
1226
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001227/// SynthCountByEnumWithState - To print:
1228/// ((unsigned int (*)
1229/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1230/// (void *)objc_msgSend)((id)l_collection,
1231/// sel_registerName(
1232/// "countByEnumeratingWithState:objects:count:"),
1233/// &enumState,
1234/// (id *)items, (unsigned int)16)
1235///
Steve Naroffb29b4272008-04-14 22:03:09 +00001236void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001237 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1238 "id *, unsigned int))(void *)objc_msgSend)";
1239 buf += "\n\t\t";
1240 buf += "((id)l_collection,\n\t\t";
1241 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1242 buf += "\n\t\t";
1243 buf += "&enumState, "
1244 "(id *)items, (unsigned int)16)";
1245}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001246
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001247/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1248/// statement to exit to its outer synthesized loop.
1249///
Steve Naroffb29b4272008-04-14 22:03:09 +00001250Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001251 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1252 return S;
1253 // replace break with goto __break_label
1254 std::string buf;
1255
1256 SourceLocation startLoc = S->getLocStart();
1257 buf = "goto __break_label_";
1258 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001259 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001260
1261 return 0;
1262}
1263
1264/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1265/// statement to continue with its inner synthesized loop.
1266///
Steve Naroffb29b4272008-04-14 22:03:09 +00001267Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001268 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1269 return S;
1270 // replace continue with goto __continue_label
1271 std::string buf;
1272
1273 SourceLocation startLoc = S->getLocStart();
1274 buf = "goto __continue_label_";
1275 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001276 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001277
1278 return 0;
1279}
1280
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001281/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001282/// It rewrites:
1283/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001284
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001285/// Into:
1286/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001287/// type elem;
1288/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001289/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001290/// id l_collection = (id)collection;
1291/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1292/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001293/// if (limit) {
1294/// unsigned long startMutations = *enumState.mutationsPtr;
1295/// do {
1296/// unsigned long counter = 0;
1297/// do {
1298/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001299/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001300/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001301/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001302/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001303/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001304/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1305/// objects:items count:16]);
1306/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001307/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001308/// }
1309/// else
1310/// elem = nil;
1311/// }
1312///
Steve Naroffb29b4272008-04-14 22:03:09 +00001313Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001314 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001315 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1316 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1317 "ObjCForCollectionStmt Statement stack mismatch");
1318 assert(!ObjCBcLabelNo.empty() &&
1319 "ObjCForCollectionStmt - Label No stack empty");
1320
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001322 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001323 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001324 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001325 std::string buf;
1326 buf = "\n{\n\t";
1327 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1328 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001329 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001330 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001331 elementTypeAsString = ElementType.getAsString();
1332 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001333 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001334 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001335 buf += elementName;
1336 buf += ";\n\t";
1337 }
Chris Lattner06767512008-04-08 05:52:18 +00001338 else {
1339 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001340 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001341 elementTypeAsString
1342 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001343 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344
1345 // struct __objcFastEnumerationState enumState = { 0 };
1346 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1347 // id items[16];
1348 buf += "id items[16];\n\t";
1349 // id l_collection = (id)
1350 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001351 // Find start location of 'collection' the hard way!
1352 const char *startCollectionBuf = startBuf;
1353 startCollectionBuf += 3; // skip 'for'
1354 startCollectionBuf = strchr(startCollectionBuf, '(');
1355 startCollectionBuf++; // skip '('
1356 // find 'in' and skip it.
1357 while (*startCollectionBuf != ' ' ||
1358 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1359 (*(startCollectionBuf+3) != ' ' &&
1360 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1361 startCollectionBuf++;
1362 startCollectionBuf += 3;
1363
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001364 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001365 ReplaceText(startLoc, startCollectionBuf - startBuf,
1366 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001367 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001368 SourceLocation rightParenLoc = S->getRParenLoc();
1369 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1370 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001371 buf = ";\n\t";
1372
1373 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1374 // objects:items count:16];
1375 // which is synthesized into:
1376 // unsigned int limit =
1377 // ((unsigned int (*)
1378 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1379 // (void *)objc_msgSend)((id)l_collection,
1380 // sel_registerName(
1381 // "countByEnumeratingWithState:objects:count:"),
1382 // (struct __objcFastEnumerationState *)&state,
1383 // (id *)items, (unsigned int)16);
1384 buf += "unsigned long limit =\n\t\t";
1385 SynthCountByEnumWithState(buf);
1386 buf += ";\n\t";
1387 /// if (limit) {
1388 /// unsigned long startMutations = *enumState.mutationsPtr;
1389 /// do {
1390 /// unsigned long counter = 0;
1391 /// do {
1392 /// if (startMutations != *enumState.mutationsPtr)
1393 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001394 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001395 buf += "if (limit) {\n\t";
1396 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1397 buf += "do {\n\t\t";
1398 buf += "unsigned long counter = 0;\n\t\t";
1399 buf += "do {\n\t\t\t";
1400 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1401 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1402 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001403 buf += " = (";
1404 buf += elementTypeAsString;
1405 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001406 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001407 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001408
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001409 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410 /// } while (counter < limit);
1411 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1412 /// objects:items count:16]);
1413 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001414 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415 /// }
1416 /// else
1417 /// elem = nil;
1418 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419 ///
1420 buf = ";\n\t";
1421 buf += "__continue_label_";
1422 buf += utostr(ObjCBcLabelNo.back());
1423 buf += ": ;";
1424 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 buf += "} while (counter < limit);\n\t";
1426 buf += "} while (limit = ";
1427 SynthCountByEnumWithState(buf);
1428 buf += ");\n\t";
1429 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001430 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001431 buf += "__break_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
1433 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434 buf += "}\n\t";
1435 buf += "else\n\t\t";
1436 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001437 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001438 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001439
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001441 if (isa<CompoundStmt>(S->getBody())) {
1442 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1443 InsertText(endBodyLoc, buf.c_str(), buf.size());
1444 } else {
1445 /* Need to treat single statements specially. For example:
1446 *
1447 * for (A *a in b) if (stuff()) break;
1448 * for (A *a in b) xxxyy;
1449 *
1450 * The following code simply scans ahead to the semi to find the actual end.
1451 */
1452 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1453 const char *semiBuf = strchr(stmtBuf, ';');
1454 assert(semiBuf && "Can't find ';'");
1455 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1456 InsertText(endBodyLoc, buf.c_str(), buf.size());
1457 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458 Stmts.pop_back();
1459 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001461}
1462
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001463/// RewriteObjCSynchronizedStmt -
1464/// This routine rewrites @synchronized(expr) stmt;
1465/// into:
1466/// objc_sync_enter(expr);
1467/// @try stmt @finally { objc_sync_exit(expr); }
1468///
Steve Naroffb29b4272008-04-14 22:03:09 +00001469Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001470 // Get the start location and compute the semi location.
1471 SourceLocation startLoc = S->getLocStart();
1472 const char *startBuf = SM->getCharacterData(startLoc);
1473
1474 assert((*startBuf == '@') && "bogus @synchronized location");
1475
1476 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001477 buf = "objc_sync_enter((id)";
1478 const char *lparenBuf = startBuf;
1479 while (*lparenBuf != '(') lparenBuf++;
1480 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001481 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1482 // the sync expression is typically a message expression that's already
1483 // been rewritten! (which implies the SourceLocation's are invalid).
1484 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001485 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001486 while (*endBuf != ')') endBuf--;
1487 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001488 buf = ");\n";
1489 // declare a new scope with two variables, _stack and _rethrow.
1490 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1491 buf += "int buf[18/*32-bit i386*/];\n";
1492 buf += "char *pointers[4];} _stack;\n";
1493 buf += "id volatile _rethrow = 0;\n";
1494 buf += "objc_exception_try_enter(&_stack);\n";
1495 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001496 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001497 startLoc = S->getSynchBody()->getLocEnd();
1498 startBuf = SM->getCharacterData(startLoc);
1499
Steve Naroffc7089f12008-08-19 13:04:19 +00001500 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001501 SourceLocation lastCurlyLoc = startLoc;
1502 buf = "}\nelse {\n";
1503 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1504 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001505 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001506 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1507 S->getSynchExpr(),
1508 Context->getObjCIdType(),
1509 SourceLocation(),
1510 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001511 std::string syncExprBufS;
1512 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001513 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001514 buf += syncExprBuf.str();
1515 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001516 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1517 buf += "}\n";
1518 buf += "}";
1519
Chris Lattneraadaf782008-01-31 19:51:04 +00001520 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001521 return 0;
1522}
1523
Steve Naroff8c565152008-12-05 17:03:39 +00001524void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1525 // Perform a bottom up traversal of all children.
1526 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1527 CI != E; ++CI)
1528 if (*CI)
1529 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1530
1531 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1532 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1533 Diags.Report(Context->getFullLoc(S->getLocStart()),
1534 TryFinallyContainsReturnDiag);
1535 }
1536 return;
1537}
1538
Steve Naroffb29b4272008-04-14 22:03:09 +00001539Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001540 // Get the start location and compute the semi location.
1541 SourceLocation startLoc = S->getLocStart();
1542 const char *startBuf = SM->getCharacterData(startLoc);
1543
1544 assert((*startBuf == '@') && "bogus @try location");
1545
1546 std::string buf;
1547 // declare a new scope with two variables, _stack and _rethrow.
1548 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1549 buf += "int buf[18/*32-bit i386*/];\n";
1550 buf += "char *pointers[4];} _stack;\n";
1551 buf += "id volatile _rethrow = 0;\n";
1552 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001553 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001554
Chris Lattneraadaf782008-01-31 19:51:04 +00001555 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001556
1557 startLoc = S->getTryBody()->getLocEnd();
1558 startBuf = SM->getCharacterData(startLoc);
1559
1560 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001561
Steve Naroff75730982007-11-07 04:08:17 +00001562 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001563 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1564 if (catchList) {
1565 startLoc = startLoc.getFileLocWithOffset(1);
1566 buf = " /* @catch begin */ else {\n";
1567 buf += " id _caught = objc_exception_extract(&_stack);\n";
1568 buf += " objc_exception_try_enter (&_stack);\n";
1569 buf += " if (_setjmp(_stack.buf))\n";
1570 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1571 buf += " else { /* @catch continue */";
1572
1573 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001574 } else { /* no catch list */
1575 buf = "}\nelse {\n";
1576 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1577 buf += "}";
1578 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001579 }
Steve Naroff75730982007-11-07 04:08:17 +00001580 bool sawIdTypedCatch = false;
1581 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001582 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001583 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001584
1585 if (catchList == S->getCatchStmts())
1586 buf = "if ("; // we are generating code for the first catch clause
1587 else
1588 buf = "else if (";
1589 startLoc = catchList->getLocStart();
1590 startBuf = SM->getCharacterData(startLoc);
1591
1592 assert((*startBuf == '@') && "bogus @catch location");
1593
1594 const char *lParenLoc = strchr(startBuf, '(');
1595
Steve Naroffbe4b3332008-02-01 22:08:12 +00001596 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001597 // Now rewrite the body...
1598 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001599 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1600 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001601 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1602 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001603 assert((*bodyBuf == '{') && "bogus @catch body location");
1604
1605 buf += "1) { id _tmp = _caught;";
1606 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1607 buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001608 } else if (catchDecl) {
1609 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001610 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001611 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001612 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001613 sawIdTypedCatch = true;
1614 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001615 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001616
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001617 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001618 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001619 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001620 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001621 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001622 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001623 }
1624 }
1625 // Now rewrite the body...
1626 lastCatchBody = catchList->getCatchBody();
1627 SourceLocation rParenLoc = catchList->getRParenLoc();
1628 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1629 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1630 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1631 assert((*rParenBuf == ')') && "bogus @catch paren location");
1632 assert((*bodyBuf == '{') && "bogus @catch body location");
1633
1634 buf = " = _caught;";
1635 // Here we replace ") {" with "= _caught;" (which initializes and
1636 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001637 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001638 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001639 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001640 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001641 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001642 catchList = catchList->getNextCatchStmt();
1643 }
1644 // Complete the catch list...
1645 if (lastCatchBody) {
1646 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001647 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1648 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001649
Steve Naroff378f47a2008-09-11 15:29:03 +00001650 // Insert the last (implicit) else clause *before* the right curly brace.
1651 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1652 buf = "} /* last catch end */\n";
1653 buf += "else {\n";
1654 buf += " _rethrow = _caught;\n";
1655 buf += " objc_exception_try_exit(&_stack);\n";
1656 buf += "} } /* @catch end */\n";
1657 if (!S->getFinallyStmt())
1658 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001659 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001660
1661 // Set lastCurlyLoc
1662 lastCurlyLoc = lastCatchBody->getLocEnd();
1663 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001665 startLoc = finalStmt->getLocStart();
1666 startBuf = SM->getCharacterData(startLoc);
1667 assert((*startBuf == '@') && "bogus @finally start");
1668
1669 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001670 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001671
1672 Stmt *body = finalStmt->getFinallyBody();
1673 SourceLocation startLoc = body->getLocStart();
1674 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001675 assert(*SM->getCharacterData(startLoc) == '{' &&
1676 "bogus @finally body location");
1677 assert(*SM->getCharacterData(endLoc) == '}' &&
1678 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001679
1680 startLoc = startLoc.getFileLocWithOffset(1);
1681 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001682 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001683 endLoc = endLoc.getFileLocWithOffset(-1);
1684 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001685 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001686
1687 // Set lastCurlyLoc
1688 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001689
1690 // Now check for any return/continue/go statements within the @try.
1691 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001692 } else { /* no finally clause - make sure we synthesize an implicit one */
1693 buf = "{ /* implicit finally clause */\n";
1694 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1695 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1696 buf += "}";
1697 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001698 }
1699 // Now emit the final closing curly brace...
1700 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1701 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001702 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001703 return 0;
1704}
1705
Steve Naroffb29b4272008-04-14 22:03:09 +00001706Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001707 return 0;
1708}
1709
Steve Naroffb29b4272008-04-14 22:03:09 +00001710Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001711 return 0;
1712}
1713
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001714// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001715// the throw expression is typically a message expression that's already
1716// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001717Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001718 // Get the start location and compute the semi location.
1719 SourceLocation startLoc = S->getLocStart();
1720 const char *startBuf = SM->getCharacterData(startLoc);
1721
1722 assert((*startBuf == '@') && "bogus @throw location");
1723
1724 std::string buf;
1725 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001726 if (S->getThrowExpr())
1727 buf = "objc_exception_throw(";
1728 else // add an implicit argument
1729 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001730
1731 // handle "@ throw" correctly.
1732 const char *wBuf = strchr(startBuf, 'w');
1733 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1734 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1735
Steve Naroff2bd03922007-11-07 15:32:26 +00001736 const char *semiBuf = strchr(startBuf, ';');
1737 assert((*semiBuf == ';') && "@throw: can't find ';'");
1738 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1739 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001740 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001741 return 0;
1742}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001743
Steve Naroffb29b4272008-04-14 22:03:09 +00001744Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001745 // Create a new string expression.
1746 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001747 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001748 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001749 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1750 StrEncoding.length(), false,StrType,
1751 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001752 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001753
Chris Lattner07506182007-11-30 22:53:43 +00001754 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001755 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001756 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001757}
1758
Steve Naroffb29b4272008-04-14 22:03:09 +00001759Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001760 if (!SelGetUidFunctionDecl)
1761 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001762 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1763 // Create a call to sel_registerName("selName").
1764 llvm::SmallVector<Expr*, 8> SelExprs;
1765 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001766 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001767 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001768 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001769 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001770 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1771 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001772 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001773 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001774 return SelExp;
1775}
1776
Steve Naroffb29b4272008-04-14 22:03:09 +00001777CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001778 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001779 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001780 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001781
1782 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001783 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001784
1785 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001786 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001787 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001788 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001789
1790 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001791
Ted Kremenek668bf912009-02-09 20:51:47 +00001792 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1793 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001794}
1795
Steve Naroffd5255f52007-11-01 13:24:47 +00001796static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1797 const char *&startRef, const char *&endRef) {
1798 while (startBuf < endBuf) {
1799 if (*startBuf == '<')
1800 startRef = startBuf; // mark the start.
1801 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001802 if (startRef && *startRef == '<') {
1803 endRef = startBuf; // mark the end.
1804 return true;
1805 }
1806 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001807 }
1808 startBuf++;
1809 }
1810 return false;
1811}
1812
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001813static void scanToNextArgument(const char *&argRef) {
1814 int angle = 0;
1815 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1816 if (*argRef == '<')
1817 angle++;
1818 else if (*argRef == '>')
1819 angle--;
1820 argRef++;
1821 }
1822 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1823}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001824
Steve Naroffb29b4272008-04-14 22:03:09 +00001825bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001826
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001827 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001828 return true;
1829
Steve Naroffd5255f52007-11-01 13:24:47 +00001830 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001831 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001832 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001833 return true; // we have "Class <Protocol> *".
1834 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001835 return false;
1836}
1837
Steve Naroff4f95b752008-07-29 18:15:38 +00001838void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1839 QualType Type = E->getType();
1840 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001841 SourceLocation Loc, EndLoc;
1842
1843 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1844 Loc = ECE->getLParenLoc();
1845 EndLoc = ECE->getRParenLoc();
1846 } else {
1847 Loc = E->getLocStart();
1848 EndLoc = E->getLocEnd();
1849 }
1850 // This will defend against trying to rewrite synthesized expressions.
1851 if (Loc.isInvalid() || EndLoc.isInvalid())
1852 return;
1853
Steve Naroff4f95b752008-07-29 18:15:38 +00001854 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001855 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001856 const char *startRef = 0, *endRef = 0;
1857 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1858 // Get the locations of the startRef, endRef.
1859 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1860 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1861 // Comment out the protocol references.
1862 InsertText(LessLoc, "/*", 2);
1863 InsertText(GreaterLoc, "*/", 2);
1864 }
1865 }
1866}
1867
Steve Naroffb29b4272008-04-14 22:03:09 +00001868void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001869 SourceLocation Loc;
1870 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001871 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001872 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1873 Loc = VD->getLocation();
1874 Type = VD->getType();
1875 }
1876 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1877 Loc = FD->getLocation();
1878 // Check for ObjC 'id' and class types that have been adorned with protocol
1879 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1880 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1881 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001882 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001883 if (!proto)
1884 return;
1885 Type = proto->getResultType();
1886 }
1887 else
1888 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001889
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001890 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001891 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001892
1893 const char *endBuf = SM->getCharacterData(Loc);
1894 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001895 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001896 startBuf--; // scan backward (from the decl location) for return type.
1897 const char *startRef = 0, *endRef = 0;
1898 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1899 // Get the locations of the startRef, endRef.
1900 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1901 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1902 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001903 InsertText(LessLoc, "/*", 2);
1904 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001905 }
1906 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001907 if (!proto)
1908 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001909 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001910 const char *startBuf = SM->getCharacterData(Loc);
1911 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001912 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1913 if (needToScanForQualifiers(proto->getArgType(i))) {
1914 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001915
Steve Naroffd5255f52007-11-01 13:24:47 +00001916 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001917 // scan forward (from the decl location) for argument types.
1918 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001919 const char *startRef = 0, *endRef = 0;
1920 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1921 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001922 SourceLocation LessLoc =
1923 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1924 SourceLocation GreaterLoc =
1925 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001926 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001927 InsertText(LessLoc, "/*", 2);
1928 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001929 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001930 startBuf = ++endBuf;
1931 }
1932 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001933 // If the function name is derived from a macro expansion, then the
1934 // argument buffer will not follow the name. Need to speak with Chris.
1935 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001936 startBuf++; // scan forward (from the decl location) for argument types.
1937 startBuf++;
1938 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001939 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001940}
1941
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001942// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001943void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001944 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1945 llvm::SmallVector<QualType, 16> ArgTys;
1946 ArgTys.push_back(Context->getPointerType(
1947 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001949 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001950 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001951 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001952 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001953 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001954 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001955}
1956
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001957// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001958void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001959 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1960 llvm::SmallVector<QualType, 16> ArgTys;
1961 ArgTys.push_back(Context->getPointerType(
1962 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001963 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001964 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001965 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001966 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001967 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001968 SelGetProtoIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001969 FunctionDecl::Extern, false);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001970}
1971
Steve Naroffb29b4272008-04-14 22:03:09 +00001972void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001973 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001974 if (FD->getIdentifier() &&
1975 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001976 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001977 return;
1978 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001980}
1981
Steve Naroffc0a123c2008-03-11 17:37:02 +00001982// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001983void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001984 if (SuperContructorFunctionDecl)
1985 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001986 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001987 llvm::SmallVector<QualType, 16> ArgTys;
1988 QualType argT = Context->getObjCIdType();
1989 assert(!argT.isNull() && "Can't find 'id' type");
1990 ArgTys.push_back(argT);
1991 ArgTys.push_back(argT);
1992 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1993 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001994 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001995 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001996 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001997 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001998 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001999}
2000
Steve Naroff09b266e2007-10-30 23:14:51 +00002001// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002002void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002003 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2004 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002005 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002006 assert(!argT.isNull() && "Can't find 'id' type");
2007 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002009 assert(!argT.isNull() && "Can't find 'SEL' type");
2010 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002011 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002012 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002013 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002014 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002015 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002016 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002017 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002018}
2019
Steve Naroff874e2322007-11-15 10:28:18 +00002020// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002021void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002022 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2023 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002024 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002025 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002026 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002027 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2028 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2029 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002030 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002031 assert(!argT.isNull() && "Can't find 'SEL' type");
2032 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002033 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002034 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002035 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002036 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002037 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002038 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002039 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002040}
2041
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002042// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002043void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002044 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2045 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002046 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002047 assert(!argT.isNull() && "Can't find 'id' type");
2048 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002049 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 assert(!argT.isNull() && "Can't find 'SEL' type");
2051 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002052 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002053 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002054 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002055 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002056 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002057 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002058 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002059}
2060
2061// SynthMsgSendSuperStretFunctionDecl -
2062// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002063void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002064 IdentifierInfo *msgSendIdent =
2065 &Context->Idents.get("objc_msgSendSuper_stret");
2066 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002067 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002068 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002069 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002070 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2071 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2072 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002074 assert(!argT.isNull() && "Can't find 'SEL' type");
2075 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002076 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002077 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002078 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002079 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002080 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002081 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002082 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002083}
2084
Steve Naroff1284db82008-05-08 22:02:18 +00002085// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002086void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002087 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2088 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002090 assert(!argT.isNull() && "Can't find 'id' type");
2091 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002093 assert(!argT.isNull() && "Can't find 'SEL' type");
2094 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002095 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002096 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002097 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002098 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002099 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002100 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002101 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002102}
2103
Steve Naroff09b266e2007-10-30 23:14:51 +00002104// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002105void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002106 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2107 llvm::SmallVector<QualType, 16> ArgTys;
2108 ArgTys.push_back(Context->getPointerType(
2109 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002111 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002112 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002113 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002114 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002115 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002116 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002117}
2118
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002119// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002120void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002121 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2122 llvm::SmallVector<QualType, 16> ArgTys;
2123 ArgTys.push_back(Context->getPointerType(
2124 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002125 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002126 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002127 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002128 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002129 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002130 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002131 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002132}
2133
Steve Naroffb29b4272008-04-14 22:03:09 +00002134Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002135 QualType strType = getConstantStringStructType();
2136
2137 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002138
2139 std::string tmpName = InFileName;
2140 unsigned i;
2141 for (i=0; i < tmpName.length(); i++) {
2142 char c = tmpName.at(i);
2143 // replace any non alphanumeric characters with '_'.
2144 if (!isalpha(c) && (c < '0' || c > '9'))
2145 tmpName[i] = '_';
2146 }
2147 S += tmpName;
2148 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002149 S += utostr(NumObjCStringLiterals++);
2150
Steve Naroffba92b2e2008-03-27 22:29:16 +00002151 Preamble += "static __NSConstantStringImpl " + S;
2152 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2153 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002154 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002155 std::string prettyBufS;
2156 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002157 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002158 Preamble += prettyBuf.str();
2159 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002160 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002161 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002162
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002163 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002164 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002165 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002166 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2167 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002168 Context->getPointerType(DRE->getType()),
2169 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002170 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002171 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002172 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002173 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002174 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002175 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002176}
2177
Steve Naroffb29b4272008-04-14 22:03:09 +00002178ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002179 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002180 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002181
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002182 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2183 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002184 assert(PT);
2185 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2186 return IT->getDecl();
2187 }
2188 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002189}
2190
2191// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002192QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002193 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002194 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002195 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002196 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002197 QualType FieldTypes[2];
2198
2199 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002200 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002201 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002202 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002203
Steve Naroff874e2322007-11-15 10:28:18 +00002204 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002205 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002206 SuperStructDecl->addDecl(*Context,
2207 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002208 SourceLocation(), 0,
2209 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002210 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002211 }
Steve Naroff874e2322007-11-15 10:28:18 +00002212
Douglas Gregor44b43212008-12-11 16:49:14 +00002213 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002214 }
2215 return Context->getTagDeclType(SuperStructDecl);
2216}
2217
Steve Naroffb29b4272008-04-14 22:03:09 +00002218QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002219 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002220 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002221 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002222 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002223 QualType FieldTypes[4];
2224
2225 // struct objc_object *receiver;
2226 FieldTypes[0] = Context->getObjCIdType();
2227 // int flags;
2228 FieldTypes[1] = Context->IntTy;
2229 // char *str;
2230 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2231 // long length;
2232 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002233
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002234 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002235 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002236 ConstantStringDecl->addDecl(*Context,
2237 FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002238 ConstantStringDecl,
2239 SourceLocation(), 0,
2240 FieldTypes[i],
2241 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002242 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002243 }
2244
2245 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002246 }
2247 return Context->getTagDeclType(ConstantStringDecl);
2248}
2249
Steve Naroffb29b4272008-04-14 22:03:09 +00002250Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002251 if (!SelGetUidFunctionDecl)
2252 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002253 if (!MsgSendFunctionDecl)
2254 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002255 if (!MsgSendSuperFunctionDecl)
2256 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257 if (!MsgSendStretFunctionDecl)
2258 SynthMsgSendStretFunctionDecl();
2259 if (!MsgSendSuperStretFunctionDecl)
2260 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002261 if (!MsgSendFpretFunctionDecl)
2262 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002263 if (!GetClassFunctionDecl)
2264 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002265 if (!GetMetaClassFunctionDecl)
2266 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267
Steve Naroff874e2322007-11-15 10:28:18 +00002268 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002269 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2270 // May need to use objc_msgSend_stret() as well.
2271 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner89951a82009-02-20 18:43:26 +00002272 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2273 QualType resultType = OMD->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002274 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002275 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002276 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002277 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002278 }
Steve Naroff874e2322007-11-15 10:28:18 +00002279
Steve Naroff934f2762007-10-24 22:48:43 +00002280 // Synthesize a call to objc_msgSend().
2281 llvm::SmallVector<Expr*, 8> MsgExprs;
2282 IdentifierInfo *clsName = Exp->getClassName();
2283
2284 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2285 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002286 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2287 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 if (!strcmp(clsName->getName(), "super")) {
2289 MsgSendFlavor = MsgSendSuperFunctionDecl;
2290 if (MsgSendStretFlavor)
2291 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2292 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2293
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002294 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002295 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002296
2297 llvm::SmallVector<Expr*, 4> InitExprs;
2298
2299 // set the receiver to self, the first argument to all methods.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002300 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002301 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002302 Context->getObjCIdType(),
2303 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002304 llvm::SmallVector<Expr*, 8> ClsExprs;
2305 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002306 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002307 SuperDecl->getIdentifier()->getName(),
2308 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002309 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002310 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2311 &ClsExprs[0],
2312 ClsExprs.size());
2313 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002314 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002315 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002316 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002317 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002318 // struct objc_super
2319 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002320 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002321
Steve Naroff23f41272008-03-11 18:14:26 +00002322 if (LangOpts.Microsoft) {
2323 SynthSuperContructorFunctionDecl();
2324 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002325 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002326 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002327 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2328 InitExprs.size(),
2329 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002330 // The code for super is a little tricky to prevent collision with
2331 // the structure definition in the header. The rewriter has it's own
2332 // internal definition (__rw_objc_super) that is uses. This is why
2333 // we need the cast below. For example:
2334 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2335 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002336 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002337 Context->getPointerType(SuperRep->getType()),
2338 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002339 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002340 SuperRep, Context->getPointerType(superType),
2341 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002342 } else {
2343 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002344 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002345 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002346 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002347 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002348 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002349 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002350 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002351 Context->getPointerType(SuperRep->getType()),
2352 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002353 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002354 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002355 } else {
2356 llvm::SmallVector<Expr*, 8> ClsExprs;
2357 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002358 ClsExprs.push_back(StringLiteral::Create(*Context,
2359 clsName->getName(),
2360 clsName->getLength(),
2361 false, argType,
2362 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002363 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2364 &ClsExprs[0],
2365 ClsExprs.size());
2366 MsgExprs.push_back(Cls);
2367 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002368 } else { // instance message.
2369 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002370
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002372 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002373 if (MsgSendStretFlavor)
2374 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002375 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2376
2377 llvm::SmallVector<Expr*, 4> InitExprs;
2378
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002379 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002380 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2381 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002382 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002383 SourceLocation()),
2384 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002385 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002386
2387 llvm::SmallVector<Expr*, 8> ClsExprs;
2388 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002389 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002390 SuperDecl->getIdentifier()->getName(),
2391 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002392 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002393 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002394 &ClsExprs[0],
2395 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002396 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002397 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002398 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002399 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002400 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002401 // struct objc_super
2402 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002403 Expr *SuperRep;
2404
2405 if (LangOpts.Microsoft) {
2406 SynthSuperContructorFunctionDecl();
2407 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002408 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002409 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002410 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2411 InitExprs.size(),
2412 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002413 // The code for super is a little tricky to prevent collision with
2414 // the structure definition in the header. The rewriter has it's own
2415 // internal definition (__rw_objc_super) that is uses. This is why
2416 // we need the cast below. For example:
2417 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2418 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002419 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002420 Context->getPointerType(SuperRep->getType()),
2421 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002422 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002423 SuperRep, Context->getPointerType(superType),
2424 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002425 } else {
2426 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002427 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002428 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002429 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002430 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002431 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002432 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002433 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002434 // Remove all type-casts because it may contain objc-style types; e.g.
2435 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002436 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002437 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002438 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002439 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002440 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002441 MsgExprs.push_back(recExpr);
2442 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002443 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002444 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002445 llvm::SmallVector<Expr*, 8> SelExprs;
2446 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002447 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002448 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002449 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002450 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002451 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2452 &SelExprs[0], SelExprs.size());
2453 MsgExprs.push_back(SelExp);
2454
2455 // Now push any user supplied arguments.
2456 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002457 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002458 // Make all implicit casts explicit...ICE comes in handy:-)
2459 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2460 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002461 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002462 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002463 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002464 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002465 }
2466 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002467 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002469 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002470 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002471 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002472 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002473 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002474 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002475 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002476 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002477 // We've transferred the ownership to MsgExprs. Null out the argument in
2478 // the original expression, since we will delete it below.
2479 Exp->setArg(i, 0);
2480 }
Steve Naroffab972d32007-11-04 22:37:50 +00002481 // Generate the funky cast.
2482 CastExpr *cast;
2483 llvm::SmallVector<QualType, 8> ArgTypes;
2484 QualType returnType;
2485
2486 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002487 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2488 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2489 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002490 ArgTypes.push_back(Context->getObjCIdType());
2491 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002492 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002493 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002494 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2495 E = OMD->param_end(); PI != E; ++PI) {
2496 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002498 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002499 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002500 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002501 const BlockPointerType *BPT = t->getAsBlockPointerType();
2502 t = Context->getPointerType(BPT->getPointeeType());
2503 }
Steve Naroff352336b2007-11-05 14:36:37 +00002504 ArgTypes.push_back(t);
2505 }
Chris Lattner89951a82009-02-20 18:43:26 +00002506 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2507 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002508 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002509 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002510 }
2511 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002512 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002513
2514 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002515 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002517
2518 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2519 // If we don't do this cast, we get the following bizarre warning/note:
2520 // xx.m:13: warning: function called through a non-compatible type
2521 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002522 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002523 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002524 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002525
Steve Naroffab972d32007-11-04 22:37:50 +00002526 // Now do the "normal" pointer to function cast.
2527 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002528 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002529 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002530 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002531 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002532 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002533
2534 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002535 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002536
2537 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002538 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2539 MsgExprs.size(),
2540 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002541 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 if (MsgSendStretFlavor) {
2543 // We have the method which returns a struct/union. Must also generate
2544 // call to objc_msgSend_stret and hang both varieties on a conditional
2545 // expression which dictate which one to envoke depending on size of
2546 // method's return type.
2547
2548 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002549 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002550 SourceLocation());
2551 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002552 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002553 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002554 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002555 // Now do the "normal" pointer to function cast.
2556 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002557 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002558 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002560 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002561
2562 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002563 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564
2565 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002566 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2567 MsgExprs.size(),
2568 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569
2570 // Build sizeof(returnType)
Douglas Gregorba498172009-03-13 21:01:28 +00002571 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2572 returnType,
Sebastian Redl05189992008-11-11 17:56:53 +00002573 Context->getSizeType(),
2574 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2576 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2577 // For X86 it is more complicated and some kind of target specific routine
2578 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002579 unsigned IntSize =
2580 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002581 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002582 Context->IntTy,
2583 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002584 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002585 BinaryOperator::LE,
2586 Context->IntTy,
2587 SourceLocation());
2588 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2589 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002590 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2591 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002592 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002593 return ReplacingStmt;
2594}
2595
Steve Naroffb29b4272008-04-14 22:03:09 +00002596Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002597 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002598
Steve Naroffc77a6362008-12-04 16:24:46 +00002599 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002600 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002601 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002602
Steve Naroff4c3580e2008-12-04 23:50:32 +00002603 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002604 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002605}
2606
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002607/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2608/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002609Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002610 if (!GetProtocolFunctionDecl)
2611 SynthGetProtocolFunctionDecl();
2612 // Create a call to objc_getProtocol("ProtocolName").
2613 llvm::SmallVector<Expr*, 8> ProtoExprs;
2614 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002615 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002616 Exp->getProtocol()->getNameAsCString(),
2617 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattner726e1682009-02-18 05:49:11 +00002618 false, argType, SourceLocation()));
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002619 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2620 &ProtoExprs[0],
2621 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002622 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002623 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002624 return ProtoExp;
2625
2626}
2627
Steve Naroffbaf58c32008-05-31 14:15:04 +00002628bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2629 const char *endBuf) {
2630 while (startBuf < endBuf) {
2631 if (*startBuf == '#') {
2632 // Skip whitespace.
2633 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2634 ;
2635 if (!strncmp(startBuf, "if", strlen("if")) ||
2636 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2637 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2638 !strncmp(startBuf, "define", strlen("define")) ||
2639 !strncmp(startBuf, "undef", strlen("undef")) ||
2640 !strncmp(startBuf, "else", strlen("else")) ||
2641 !strncmp(startBuf, "elif", strlen("elif")) ||
2642 !strncmp(startBuf, "endif", strlen("endif")) ||
2643 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2644 !strncmp(startBuf, "include", strlen("include")) ||
2645 !strncmp(startBuf, "import", strlen("import")) ||
2646 !strncmp(startBuf, "include_next", strlen("include_next")))
2647 return true;
2648 }
2649 startBuf++;
2650 }
2651 return false;
2652}
2653
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002654/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002655/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002656void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002657 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002658 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002659 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002660 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002661 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002663 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002664 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002665 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002666 SourceLocation LocStart = CDecl->getLocStart();
2667 SourceLocation LocEnd = CDecl->getLocEnd();
2668
2669 const char *startBuf = SM->getCharacterData(LocStart);
2670 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002671
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002672 // If no ivars and no root or if its root, directly or indirectly,
2673 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002674 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2675 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002676 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002677 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002678 return;
2679 }
2680
2681 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002682 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002683 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002684 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002685 if (LangOpts.Microsoft)
2686 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002687
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002688 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002689 const char *cursor = strchr(startBuf, '{');
2690 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002691 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002692 // If the buffer contains preprocessor directives, we do more fine-grained
2693 // rewrites. This is intended to fix code that looks like (which occurs in
2694 // NSURL.h, for example):
2695 //
2696 // #ifdef XYZ
2697 // @interface Foo : NSObject
2698 // #else
2699 // @interface FooBar : NSObject
2700 // #endif
2701 // {
2702 // int i;
2703 // }
2704 // @end
2705 //
2706 // This clause is segregated to avoid breaking the common case.
2707 if (BufferContainsPPDirectives(startBuf, cursor)) {
2708 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2709 CDecl->getClassLoc();
2710 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002711 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002712
Chris Lattnercafeb352009-02-20 18:18:36 +00002713 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002714 // advance to the end of the referenced protocols.
2715 while (endHeader < cursor && *endHeader != '>') endHeader++;
2716 endHeader++;
2717 }
2718 // rewrite the original header
2719 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2720 } else {
2721 // rewrite the original header *without* disturbing the '{'
2722 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2723 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002724 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002725 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002726 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002727 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002728 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002729 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002730
2731 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002732 SourceLocation OnePastCurly =
2733 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2734 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002735 }
2736 cursor++; // past '{'
2737
2738 // Now comment out any visibility specifiers.
2739 while (cursor < endBuf) {
2740 if (*cursor == '@') {
2741 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002742 // Skip whitespace.
2743 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2744 /*scan*/;
2745
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002746 // FIXME: presence of @public, etc. inside comment results in
2747 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002748 if (!strncmp(cursor, "public", strlen("public")) ||
2749 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002750 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002751 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002752 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002753 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002754 // FIXME: If there are cases where '<' is used in ivar declaration part
2755 // of user code, then scan the ivar list and use needToScanForQualifiers
2756 // for type checking.
2757 else if (*cursor == '<') {
2758 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002759 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002760 cursor = strchr(cursor, '>');
2761 cursor++;
2762 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002763 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002764 } else if (*cursor == '^') { // rewrite block specifier.
2765 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2766 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002767 }
Steve Narofffea763e82007-11-14 19:25:57 +00002768 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002769 }
Steve Narofffea763e82007-11-14 19:25:57 +00002770 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002771 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002772 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002773 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002774 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002775 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002776 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002777 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002778 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002779 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002780 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002781 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002782 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002783 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002784}
2785
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002786// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002788void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002789 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002790 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002791 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002792 const char *ClassName,
2793 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002794 if (MethodBegin == MethodEnd) return;
2795
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002796 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002797 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002798 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002799 SEL _cmd;
2800 char *method_types;
2801 void *_imp;
2802 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002803 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002804 Result += "\nstruct _objc_method {\n";
2805 Result += "\tSEL _cmd;\n";
2806 Result += "\tchar *method_types;\n";
2807 Result += "\tvoid *_imp;\n";
2808 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002809
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002810 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002811 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002812
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002813 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002814
2815 /* struct {
2816 struct _objc_method_list *next_method;
2817 int method_count;
2818 struct _objc_method method_list[];
2819 }
2820 */
2821 Result += "\nstatic struct {\n";
2822 Result += "\tstruct _objc_method_list *next_method;\n";
2823 Result += "\tint method_count;\n";
2824 Result += "\tstruct _objc_method method_list[";
2825 Result += utostr(MethodEnd-MethodBegin);
2826 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002827 Result += prefix;
2828 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2829 Result += "_METHODS_";
2830 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002831 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002832 Result += IsInstanceMethod ? "inst" : "cls";
2833 Result += "_meth\")))= ";
2834 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002835
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002836 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002837 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002838 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002839 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002840 Result += "\", \"";
2841 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002842 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002843 Result += MethodInternalNames[*MethodBegin];
2844 Result += "}\n";
2845 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2846 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002847 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002848 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002849 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002850 Result += "\", \"";
2851 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002852 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002853 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002854 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002855 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002856 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002857}
2858
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002860void RewriteObjC::
2861RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2862 const char *prefix,
2863 const char *ClassName,
2864 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002865 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002866 if (Protocols.empty()) return;
2867
2868 for (unsigned i = 0; i != Protocols.size(); i++) {
2869 ObjCProtocolDecl *PDecl = Protocols[i];
2870 // Output struct protocol_methods holder of method selector and type.
2871 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2872 /* struct protocol_methods {
2873 SEL _cmd;
2874 char *method_types;
2875 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002876 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002877 Result += "\nstruct protocol_methods {\n";
2878 Result += "\tSEL _cmd;\n";
2879 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002881
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002882 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002883 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002884 // Do not synthesize the protocol more than once.
2885 if (ObjCSynthesizedProtocols.count(PDecl))
2886 continue;
2887
Douglas Gregor6ab35242009-04-09 21:40:53 +00002888 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2889 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2890 PDecl->instmeth_end(*Context));
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002891 /* struct _objc_protocol_method_list {
2892 int protocol_method_count;
2893 struct protocol_methods protocols[];
2894 }
2895 */
2896 Result += "\nstatic struct {\n";
2897 Result += "\tint protocol_method_count;\n";
2898 Result += "\tstruct protocol_methods protocols[";
2899 Result += utostr(NumMethods);
2900 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002901 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002902 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2903 "{\n\t" + utostr(NumMethods) + "\n";
2904
2905 // Output instance methods declared in this protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002906 for (ObjCProtocolDecl::instmeth_iterator
2907 I = PDecl->instmeth_begin(*Context),
2908 E = PDecl->instmeth_end(*Context);
2909 I != E; ++I) {
2910 if (I == PDecl->instmeth_begin(*Context))
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002911 Result += "\t ,{{(SEL)\"";
2912 else
2913 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002914 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002915 std::string MethodTypeString;
2916 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2917 Result += "\", \"";
2918 Result += MethodTypeString;
2919 Result += "\"}\n";
2920 }
2921 Result += "\t }\n};\n";
2922 }
2923
2924 // Output class methods declared in this protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002925 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2926 PDecl->classmeth_end(*Context));
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002927 if (NumMethods > 0) {
2928 /* struct _objc_protocol_method_list {
2929 int protocol_method_count;
2930 struct protocol_methods protocols[];
2931 }
2932 */
2933 Result += "\nstatic struct {\n";
2934 Result += "\tint protocol_method_count;\n";
2935 Result += "\tstruct protocol_methods protocols[";
2936 Result += utostr(NumMethods);
2937 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002938 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002939 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2940 "{\n\t";
2941 Result += utostr(NumMethods);
2942 Result += "\n";
2943
2944 // Output instance methods declared in this protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002945 for (ObjCProtocolDecl::classmeth_iterator
2946 I = PDecl->classmeth_begin(*Context),
2947 E = PDecl->classmeth_end(*Context);
2948 I != E; ++I) {
2949 if (I == PDecl->classmeth_begin(*Context))
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002950 Result += "\t ,{{(SEL)\"";
2951 else
2952 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002953 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002954 std::string MethodTypeString;
2955 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2956 Result += "\", \"";
2957 Result += MethodTypeString;
2958 Result += "\"}\n";
2959 }
2960 Result += "\t }\n};\n";
2961 }
2962
2963 // Output:
2964 /* struct _objc_protocol {
2965 // Objective-C 1.0 extensions
2966 struct _objc_protocol_extension *isa;
2967 char *protocol_name;
2968 struct _objc_protocol **protocol_list;
2969 struct _objc_protocol_method_list *instance_methods;
2970 struct _objc_protocol_method_list *class_methods;
2971 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002972 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002973 static bool objc_protocol = false;
2974 if (!objc_protocol) {
2975 Result += "\nstruct _objc_protocol {\n";
2976 Result += "\tstruct _objc_protocol_extension *isa;\n";
2977 Result += "\tchar *protocol_name;\n";
2978 Result += "\tstruct _objc_protocol **protocol_list;\n";
2979 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2980 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2981 Result += "};\n";
2982
2983 objc_protocol = true;
2984 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002985
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002986 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002987 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002988 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2989 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002990 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002991 Result += "\", 0, ";
Douglas Gregor6ab35242009-04-09 21:40:53 +00002992 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002993 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002994 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002995 Result += ", ";
2996 }
2997 else
2998 Result += "0, ";
Douglas Gregor6ab35242009-04-09 21:40:53 +00002999 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003000 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003003 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003004 else
3005 Result += "0\n";
3006 Result += "};\n";
3007
3008 // Mark this protocol as having been generated.
3009 if (!ObjCSynthesizedProtocols.insert(PDecl))
3010 assert(false && "protocol already synthesized");
3011 }
3012 // Output the top lovel protocol meta-data for the class.
3013 /* struct _objc_protocol_list {
3014 struct _objc_protocol_list *next;
3015 int protocol_count;
3016 struct _objc_protocol *class_protocols[];
3017 }
3018 */
3019 Result += "\nstatic struct {\n";
3020 Result += "\tstruct _objc_protocol_list *next;\n";
3021 Result += "\tint protocol_count;\n";
3022 Result += "\tstruct _objc_protocol *class_protocols[";
3023 Result += utostr(Protocols.size());
3024 Result += "];\n} _OBJC_";
3025 Result += prefix;
3026 Result += "_PROTOCOLS_";
3027 Result += ClassName;
3028 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3029 "{\n\t0, ";
3030 Result += utostr(Protocols.size());
3031 Result += "\n";
3032
3033 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003034 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003035 Result += " \n";
3036
3037 for (unsigned i = 1; i != Protocols.size(); i++) {
3038 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003039 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003040 Result += "\n";
3041 }
3042 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003043}
3044
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003045/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003046/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003047void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003048 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003049 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003050 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003051 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003052 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3053 CDecl = CDecl->getNextClassCategory())
3054 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3055 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003056
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003057 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003058 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003059 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003060
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003061 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003063 true, "CATEGORY_", FullCategoryName.c_str(),
3064 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003065
3066 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003067 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003068 false, "CATEGORY_", FullCategoryName.c_str(),
3069 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003070
3071 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003072 // Null CDecl is case of a category implementation with no category interface
3073 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003074 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003075 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003076
3077 /* struct _objc_category {
3078 char *category_name;
3079 char *class_name;
3080 struct _objc_method_list *instance_methods;
3081 struct _objc_method_list *class_methods;
3082 struct _objc_protocol_list *protocols;
3083 // Objective-C 1.0 extensions
3084 uint32_t size; // sizeof (struct _objc_category)
3085 struct _objc_property_list *instance_properties; // category's own
3086 // @property decl.
3087 };
3088 */
3089
3090 static bool objc_category = false;
3091 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003092 Result += "\nstruct _objc_category {\n";
3093 Result += "\tchar *category_name;\n";
3094 Result += "\tchar *class_name;\n";
3095 Result += "\tstruct _objc_method_list *instance_methods;\n";
3096 Result += "\tstruct _objc_method_list *class_methods;\n";
3097 Result += "\tstruct _objc_protocol_list *protocols;\n";
3098 Result += "\tunsigned int size;\n";
3099 Result += "\tstruct _objc_property_list *instance_properties;\n";
3100 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003101 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003102 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003103 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3104 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003105 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003106 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003107 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003108 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003110
Chris Lattnercafeb352009-02-20 18:18:36 +00003111 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003112 Result += "\t, (struct _objc_method_list *)"
3113 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3114 Result += FullCategoryName;
3115 Result += "\n";
3116 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003117 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003118 Result += "\t, 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003119 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003120 Result += "\t, (struct _objc_method_list *)"
3121 "&_OBJC_CATEGORY_CLASS_METHODS_";
3122 Result += FullCategoryName;
3123 Result += "\n";
3124 }
3125 else
3126 Result += "\t, 0\n";
3127
Chris Lattnercafeb352009-02-20 18:18:36 +00003128 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003129 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3130 Result += FullCategoryName;
3131 Result += "\n";
3132 }
3133 else
3134 Result += "\t, 0\n";
3135 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003136}
3137
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003138/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3139/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003140void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003142 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003143 if (ivar->isBitField()) {
3144 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3145 // place all bitfields at offset 0.
3146 Result += "0";
3147 } else {
3148 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003149 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003150 if (LangOpts.Microsoft)
3151 Result += "_IMPL";
3152 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003153 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003154 Result += ")";
3155 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003156}
3157
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003158//===----------------------------------------------------------------------===//
3159// Meta Data Emission
3160//===----------------------------------------------------------------------===//
3161
Steve Naroffb29b4272008-04-14 22:03:09 +00003162void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003163 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003164 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003165
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003166 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003167 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003168 // FIXME: Implementation of a class with no @interface (legacy) doese not
3169 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003171 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003172
Chris Lattnerbe6df082007-12-12 07:56:42 +00003173 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003174 unsigned NumIvars = !IDecl->ivar_empty()
3175 ? IDecl->ivar_size()
3176 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003177 if (NumIvars > 0) {
3178 static bool objc_ivar = false;
3179 if (!objc_ivar) {
3180 /* struct _objc_ivar {
3181 char *ivar_name;
3182 char *ivar_type;
3183 int ivar_offset;
3184 };
3185 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003186 Result += "\nstruct _objc_ivar {\n";
3187 Result += "\tchar *ivar_name;\n";
3188 Result += "\tchar *ivar_type;\n";
3189 Result += "\tint ivar_offset;\n";
3190 Result += "};\n";
3191
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003192 objc_ivar = true;
3193 }
3194
Steve Naroff946a6932008-03-11 00:12:29 +00003195 /* struct {
3196 int ivar_count;
3197 struct _objc_ivar ivar_list[nIvars];
3198 };
3199 */
3200 Result += "\nstatic struct {\n";
3201 Result += "\tint ivar_count;\n";
3202 Result += "\tstruct _objc_ivar ivar_list[";
3203 Result += utostr(NumIvars);
3204 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003205 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003206 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 "{\n\t";
3208 Result += utostr(NumIvars);
3209 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003210
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003212 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003213 IVI = IDecl->ivar_begin();
3214 IVE = IDecl->ivar_end();
3215 } else {
3216 IVI = CDecl->ivar_begin();
3217 IVE = CDecl->ivar_end();
3218 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003220 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003221 Result += "\", \"";
3222 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003223 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003224 Result += StrEncoding;
3225 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003226 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003227 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003228 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003229 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003230 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003231 Result += "\", \"";
3232 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003233 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003234 Result += StrEncoding;
3235 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003236 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003237 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003238 }
3239
3240 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003241 }
3242
3243 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003244 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003245 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003246
3247 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003248 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003249 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003250
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003251 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003252 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003253 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003254
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003255
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003256 // Declaration of class/meta-class metadata
3257 /* struct _objc_class {
3258 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003259 const char *super_class_name;
3260 char *name;
3261 long version;
3262 long info;
3263 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003264 struct _objc_ivar_list *ivars;
3265 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003266 struct objc_cache *cache;
3267 struct objc_protocol_list *protocols;
3268 const char *ivar_layout;
3269 struct _objc_class_ext *ext;
3270 };
3271 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003272 static bool objc_class = false;
3273 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003274 Result += "\nstruct _objc_class {\n";
3275 Result += "\tstruct _objc_class *isa;\n";
3276 Result += "\tconst char *super_class_name;\n";
3277 Result += "\tchar *name;\n";
3278 Result += "\tlong version;\n";
3279 Result += "\tlong info;\n";
3280 Result += "\tlong instance_size;\n";
3281 Result += "\tstruct _objc_ivar_list *ivars;\n";
3282 Result += "\tstruct _objc_method_list *methods;\n";
3283 Result += "\tstruct objc_cache *cache;\n";
3284 Result += "\tstruct _objc_protocol_list *protocols;\n";
3285 Result += "\tconst char *ivar_layout;\n";
3286 Result += "\tstruct _objc_class_ext *ext;\n";
3287 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003288 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003289 }
3290
3291 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003292 ObjCInterfaceDecl *RootClass = 0;
3293 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003294 while (SuperClass) {
3295 RootClass = SuperClass;
3296 SuperClass = SuperClass->getSuperClass();
3297 }
3298 SuperClass = CDecl->getSuperClass();
3299
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003301 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003302 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003303 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003304 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003305 Result += "\"";
3306
3307 if (SuperClass) {
3308 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003309 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003311 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003312 Result += "\"";
3313 }
3314 else {
3315 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003316 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003317 Result += "\"";
3318 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003319 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003320 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003321 Result += ", 0,2, sizeof(struct _objc_class), 0";
Chris Lattner89951a82009-02-20 18:43:26 +00003322 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003323 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003324 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003325 Result += "\n";
3326 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003327 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003329 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003330 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003332 Result += ",0,0\n";
3333 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003334 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003335 Result += "\t,0,0,0,0\n";
3336 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003337
3338 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003341 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003342 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003343 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003344 if (SuperClass) {
3345 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003346 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003347 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003348 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003349 Result += "\"";
3350 }
3351 else {
3352 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003353 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003354 Result += "\"";
3355 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003356 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003357 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003358 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003359 Result += ",0";
3360 else {
3361 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003362 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003363 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003364 if (LangOpts.Microsoft)
3365 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003366 Result += ")";
3367 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003368 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003369 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003370 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003371 Result += "\n\t";
3372 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003373 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003374 Result += ",0";
Chris Lattner89951a82009-02-20 18:43:26 +00003375 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003376 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003378 Result += ", 0\n\t";
3379 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003380 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003381 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003382 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003383 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003385 Result += ", 0,0\n";
3386 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003387 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += ",0,0,0\n";
3389 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003390}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003391
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003392/// RewriteImplementations - This routine rewrites all method implementations
3393/// and emits meta-data.
3394
Steve Narofface66252008-11-13 20:07:04 +00003395void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003396 int ClsDefCount = ClassImplementation.size();
3397 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003398
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003399 // Rewrite implemented methods
3400 for (int i = 0; i < ClsDefCount; i++)
3401 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003402
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003403 for (int i = 0; i < CatDefCount; i++)
3404 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003405}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003406
Steve Narofface66252008-11-13 20:07:04 +00003407void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3408 int ClsDefCount = ClassImplementation.size();
3409 int CatDefCount = CategoryImplementation.size();
3410
Steve Naroff5df5b762008-05-07 21:23:49 +00003411 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003412 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003413 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003414 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003415 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003416
3417 // For each implemented category, write out all its meta data.
3418 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003419 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003420
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003421 // Write objc_symtab metadata
3422 /*
3423 struct _objc_symtab
3424 {
3425 long sel_ref_cnt;
3426 SEL *refs;
3427 short cls_def_cnt;
3428 short cat_def_cnt;
3429 void *defs[cls_def_cnt + cat_def_cnt];
3430 };
3431 */
3432
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003433 Result += "\nstruct _objc_symtab {\n";
3434 Result += "\tlong sel_ref_cnt;\n";
3435 Result += "\tSEL *refs;\n";
3436 Result += "\tshort cls_def_cnt;\n";
3437 Result += "\tshort cat_def_cnt;\n";
3438 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3439 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003440
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003441 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003442 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003443 Result += "\t0, 0, " + utostr(ClsDefCount)
3444 + ", " + utostr(CatDefCount) + "\n";
3445 for (int i = 0; i < ClsDefCount; i++) {
3446 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003447 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003448 Result += "\n";
3449 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003450
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003451 for (int i = 0; i < CatDefCount; i++) {
3452 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003453 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003454 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003456 Result += "\n";
3457 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003458
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003459 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003460
3461 // Write objc_module metadata
3462
3463 /*
3464 struct _objc_module {
3465 long version;
3466 long size;
3467 const char *name;
3468 struct _objc_symtab *symtab;
3469 }
3470 */
3471
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003472 Result += "\nstruct _objc_module {\n";
3473 Result += "\tlong version;\n";
3474 Result += "\tlong size;\n";
3475 Result += "\tconst char *name;\n";
3476 Result += "\tstruct _objc_symtab *symtab;\n";
3477 Result += "};\n\n";
3478 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003479 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003480 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3481 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003482 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003483
3484 if (LangOpts.Microsoft) {
3485 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003486 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003487 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3488 Result += "&_OBJC_MODULES;\n";
3489 Result += "#pragma data_seg(pop)\n\n";
3490 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003491}
Chris Lattner311ff022007-10-16 22:36:42 +00003492
Steve Naroff54055232008-10-27 17:20:55 +00003493std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3494 const char *funcName,
3495 std::string Tag) {
3496 const FunctionType *AFT = CE->getFunctionType();
3497 QualType RT = AFT->getResultType();
3498 std::string StructRef = "struct " + Tag;
3499 std::string S = "static " + RT.getAsString() + " __" +
3500 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003501
Steve Naroff54055232008-10-27 17:20:55 +00003502 BlockDecl *BD = CE->getBlockDecl();
3503
Douglas Gregor72564e72009-02-26 23:50:07 +00003504 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003505 // No user-supplied arguments. Still need to pass in a pointer to the
3506 // block (to reference imported block decl refs).
3507 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003508 } else if (BD->param_empty()) {
3509 S += "(" + StructRef + " *__cself)";
3510 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003511 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003512 assert(FT && "SynthesizeBlockFunc: No function proto");
3513 S += '(';
3514 // first add the implicit argument.
3515 S += StructRef + " *__cself, ";
3516 std::string ParamStr;
3517 for (BlockDecl::param_iterator AI = BD->param_begin(),
3518 E = BD->param_end(); AI != E; ++AI) {
3519 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003520 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003521 (*AI)->getType().getAsStringInternal(ParamStr);
3522 S += ParamStr;
3523 }
3524 if (FT->isVariadic()) {
3525 if (!BD->param_empty()) S += ", ";
3526 S += "...";
3527 }
3528 S += ')';
3529 }
3530 S += " {\n";
3531
3532 // Create local declarations to avoid rewriting all closure decl ref exprs.
3533 // First, emit a declaration for all "by ref" decls.
3534 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3535 E = BlockByRefDecls.end(); I != E; ++I) {
3536 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003537 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003538 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003540 }
3541 // Next, emit a declaration for all "by copy" declarations.
3542 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3543 E = BlockByCopyDecls.end(); I != E; ++I) {
3544 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003545 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003546 // Handle nested closure invocation. For example:
3547 //
3548 // void (^myImportedClosure)(void);
3549 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3550 //
3551 // void (^anotherClosure)(void);
3552 // anotherClosure = ^(void) {
3553 // myImportedClosure(); // import and invoke the closure
3554 // };
3555 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003556 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003557 S += "struct __block_impl *";
3558 else
3559 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003561 }
3562 std::string RewrittenStr = RewrittenBlockExprs[CE];
3563 const char *cstr = RewrittenStr.c_str();
3564 while (*cstr++ != '{') ;
3565 S += cstr;
3566 S += "\n";
3567 return S;
3568}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003569
Steve Naroff54055232008-10-27 17:20:55 +00003570std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3571 const char *funcName,
3572 std::string Tag) {
3573 std::string StructRef = "struct " + Tag;
3574 std::string S = "static void __";
3575
3576 S += funcName;
3577 S += "_block_copy_" + utostr(i);
3578 S += "(" + StructRef;
3579 S += "*dst, " + StructRef;
3580 S += "*src) {";
3581 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3582 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003583 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003584 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003585 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003586 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003587 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003588 }
3589 S += "\nstatic void __";
3590 S += funcName;
3591 S += "_block_dispose_" + utostr(i);
3592 S += "(" + StructRef;
3593 S += "*src) {";
3594 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3595 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003596 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003598 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003599 }
3600 S += "}\n";
3601 return S;
3602}
3603
3604std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3605 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003606 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003607 std::string Constructor = " " + Tag;
3608
3609 S += " {\n struct __block_impl impl;\n";
3610
3611 if (hasCopyDisposeHelpers)
3612 S += " void *copy;\n void *dispose;\n";
3613
3614 Constructor += "(void *fp";
3615
3616 if (hasCopyDisposeHelpers)
3617 Constructor += ", void *copyHelp, void *disposeHelp";
3618
3619 if (BlockDeclRefs.size()) {
3620 // Output all "by copy" declarations.
3621 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3622 E = BlockByCopyDecls.end(); I != E; ++I) {
3623 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003624 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003625 std::string ArgName = "_" + FieldName;
3626 // Handle nested closure invocation. For example:
3627 //
3628 // void (^myImportedBlock)(void);
3629 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3630 //
3631 // void (^anotherBlock)(void);
3632 // anotherBlock = ^(void) {
3633 // myImportedBlock(); // import and invoke the closure
3634 // };
3635 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003636 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003637 S += "struct __block_impl *";
3638 Constructor += ", void *" + ArgName;
3639 } else {
3640 (*I)->getType().getAsStringInternal(FieldName);
3641 (*I)->getType().getAsStringInternal(ArgName);
3642 Constructor += ", " + ArgName;
3643 }
3644 S += FieldName + ";\n";
3645 }
3646 // Output all "by ref" declarations.
3647 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3648 E = BlockByRefDecls.end(); I != E; ++I) {
3649 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003650 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003651 std::string ArgName = "_" + FieldName;
3652 // Handle nested closure invocation. For example:
3653 //
3654 // void (^myImportedBlock)(void);
3655 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3656 //
3657 // void (^anotherBlock)(void);
3658 // anotherBlock = ^(void) {
3659 // myImportedBlock(); // import and invoke the closure
3660 // };
3661 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003662 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003663 S += "struct __block_impl *";
3664 Constructor += ", void *" + ArgName;
3665 } else {
3666 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3667 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3668 Constructor += ", " + ArgName;
3669 }
3670 S += FieldName + "; // by ref\n";
3671 }
3672 // Finish writing the constructor.
3673 // FIXME: handle NSConcreteGlobalBlock.
3674 Constructor += ", int flags=0) {\n";
3675 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3676 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3677
3678 if (hasCopyDisposeHelpers)
3679 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3680
3681 // Initialize all "by copy" arguments.
3682 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3683 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003684 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003685 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003686 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003687 Constructor += Name + " = (struct __block_impl *)_";
3688 else
3689 Constructor += Name + " = _";
3690 Constructor += Name + ";\n";
3691 }
3692 // Initialize all "by ref" arguments.
3693 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3694 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003695 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003696 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003697 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003698 Constructor += Name + " = (struct __block_impl *)_";
3699 else
3700 Constructor += Name + " = _";
3701 Constructor += Name + ";\n";
3702 }
3703 } else {
3704 // Finish writing the constructor.
3705 // FIXME: handle NSConcreteGlobalBlock.
3706 Constructor += ", int flags=0) {\n";
3707 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3708 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3709 if (hasCopyDisposeHelpers)
3710 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3711 }
3712 Constructor += " ";
3713 Constructor += "}\n";
3714 S += Constructor;
3715 S += "};\n";
3716 return S;
3717}
3718
3719void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3720 const char *FunName) {
3721 // Insert closures that were part of the function.
3722 for (unsigned i = 0; i < Blocks.size(); i++) {
3723
3724 CollectBlockDeclRefInfo(Blocks[i]);
3725
3726 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3727
3728 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3729 ImportedBlockDecls.size() > 0);
3730
3731 InsertText(FunLocStart, CI.c_str(), CI.size());
3732
3733 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3734
3735 InsertText(FunLocStart, CF.c_str(), CF.size());
3736
3737 if (ImportedBlockDecls.size()) {
3738 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3739 InsertText(FunLocStart, HF.c_str(), HF.size());
3740 }
3741
3742 BlockDeclRefs.clear();
3743 BlockByRefDecls.clear();
3744 BlockByCopyDecls.clear();
3745 BlockCallExprs.clear();
3746 ImportedBlockDecls.clear();
3747 }
3748 Blocks.clear();
3749 RewrittenBlockExprs.clear();
3750}
3751
3752void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3753 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003754 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003755
3756 SynthesizeBlockLiterals(FunLocStart, FuncName);
3757}
3758
3759void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003760 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3761 //SourceLocation FunLocStart = MD->getLocStart();
3762 // FIXME: This hack works around a bug in Rewrite.InsertText().
3763 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003764 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003765 // Convert colons to underscores.
3766 std::string::size_type loc = 0;
3767 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3768 FuncName.replace(loc, 1, "_");
3769
3770 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3771}
3772
3773void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3774 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3775 CI != E; ++CI)
3776 if (*CI) {
3777 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3778 GetBlockDeclRefExprs(CBE->getBody());
3779 else
3780 GetBlockDeclRefExprs(*CI);
3781 }
3782 // Handle specific things.
3783 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3784 // FIXME: Handle enums.
3785 if (!isa<FunctionDecl>(CDRE->getDecl()))
3786 BlockDeclRefs.push_back(CDRE);
3787 return;
3788}
3789
3790void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3791 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3792 CI != E; ++CI)
3793 if (*CI) {
3794 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3795 GetBlockCallExprs(CBE->getBody());
3796 else
3797 GetBlockCallExprs(*CI);
3798 }
3799
3800 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3801 if (CE->getCallee()->getType()->isBlockPointerType()) {
3802 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3803 }
3804 }
3805 return;
3806}
3807
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003808Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003809 // Navigate to relevant type information.
3810 const char *closureName = 0;
3811 const BlockPointerType *CPT = 0;
3812
3813 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003814 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003815 CPT = DRE->getType()->getAsBlockPointerType();
3816 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003817 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003818 CPT = CDRE->getType()->getAsBlockPointerType();
3819 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003820 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003821 CPT = MExpr->getType()->getAsBlockPointerType();
3822 } else {
3823 assert(1 && "RewriteBlockClass: Bad type");
3824 }
3825 assert(CPT && "RewriteBlockClass: Bad type");
3826 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3827 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003828 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003829 // FTP will be null for closures that don't take arguments.
3830
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003831 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3832 SourceLocation(),
3833 &Context->Idents.get("__block_impl"));
3834 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003835
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003836 // Generate a funky cast.
3837 llvm::SmallVector<QualType, 8> ArgTypes;
3838
3839 // Push the block argument type.
3840 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003841 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003842 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003843 E = FTP->arg_type_end(); I && (I != E); ++I) {
3844 QualType t = *I;
3845 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003846 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003847 const BlockPointerType *BPT = t->getAsBlockPointerType();
3848 t = Context->getPointerType(BPT->getPointeeType());
3849 }
3850 ArgTypes.push_back(t);
3851 }
Steve Naroff54055232008-10-27 17:20:55 +00003852 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003853 // Now do the pointer to function cast.
3854 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3855 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3856
3857 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003858
Ted Kremenek8189cde2009-02-07 01:47:29 +00003859 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3860 PtrBlock, SourceLocation(),
3861 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003862 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003863 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3864 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003865 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003866
Douglas Gregor44b43212008-12-11 16:49:14 +00003867 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3868 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003869 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003870 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3871 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003872
Ted Kremenek8189cde2009-02-07 01:47:29 +00003873 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3874 PtrToFuncCastType,
3875 SourceLocation(),
3876 SourceLocation());
3877 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003878
3879 llvm::SmallVector<Expr*, 8> BlkExprs;
3880 // Add the implicit argument.
3881 BlkExprs.push_back(BlkCast);
3882 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003883 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3884 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003885 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003886 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003887 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3888 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003889 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003890 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003891}
3892
3893void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003894 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3895 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003896}
3897
3898void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3899 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003900 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00003901 Context->getPointerType(BDRE->getType()),
3902 SourceLocation());
3903 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003904 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00003905 ReplaceStmt(BDRE, PE);
Steve Naroff54055232008-10-27 17:20:55 +00003906}
3907
Steve Naroffb2f9e512008-11-03 23:29:32 +00003908void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3909 SourceLocation LocStart = CE->getLParenLoc();
3910 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003911
3912 // Need to avoid trying to rewrite synthesized casts.
3913 if (LocStart.isInvalid())
3914 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003915 // Need to avoid trying to rewrite casts contained in macros.
3916 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3917 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003918
Steve Naroff54055232008-10-27 17:20:55 +00003919 const char *startBuf = SM->getCharacterData(LocStart);
3920 const char *endBuf = SM->getCharacterData(LocEnd);
3921
3922 // advance the location to startArgList.
3923 const char *argPtr = startBuf;
3924
3925 while (*argPtr++ && (argPtr < endBuf)) {
3926 switch (*argPtr) {
3927 case '^':
3928 // Replace the '^' with '*'.
3929 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3930 ReplaceText(LocStart, 1, "*", 1);
3931 break;
3932 }
3933 }
3934 return;
3935}
3936
3937void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3938 SourceLocation DeclLoc = FD->getLocation();
3939 unsigned parenCount = 0;
3940
3941 // We have 1 or more arguments that have closure pointers.
3942 const char *startBuf = SM->getCharacterData(DeclLoc);
3943 const char *startArgList = strchr(startBuf, '(');
3944
3945 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3946
3947 parenCount++;
3948 // advance the location to startArgList.
3949 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3950 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3951
3952 const char *argPtr = startArgList;
3953
3954 while (*argPtr++ && parenCount) {
3955 switch (*argPtr) {
3956 case '^':
3957 // Replace the '^' with '*'.
3958 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3959 ReplaceText(DeclLoc, 1, "*", 1);
3960 break;
3961 case '(':
3962 parenCount++;
3963 break;
3964 case ')':
3965 parenCount--;
3966 break;
3967 }
3968 }
3969 return;
3970}
3971
3972bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003973 const FunctionProtoType *FTP;
Steve Naroff54055232008-10-27 17:20:55 +00003974 const PointerType *PT = QT->getAsPointerType();
3975 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003976 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00003977 } else {
3978 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3979 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003980 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00003981 }
3982 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003983 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003984 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003985 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003986 return true;
3987 }
3988 return false;
3989}
3990
Ted Kremenek8189cde2009-02-07 01:47:29 +00003991void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3992 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00003993 const char *argPtr = strchr(Name, '(');
3994 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3995
3996 LParen = argPtr; // output the start.
3997 argPtr++; // skip past the left paren.
3998 unsigned parenCount = 1;
3999
4000 while (*argPtr && parenCount) {
4001 switch (*argPtr) {
4002 case '(': parenCount++; break;
4003 case ')': parenCount--; break;
4004 default: break;
4005 }
4006 if (parenCount) argPtr++;
4007 }
4008 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4009 RParen = argPtr; // output the end
4010}
4011
4012void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4014 RewriteBlockPointerFunctionArgs(FD);
4015 return;
4016 }
4017 // Handle Variables and Typedefs.
4018 SourceLocation DeclLoc = ND->getLocation();
4019 QualType DeclT;
4020 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4021 DeclT = VD->getType();
4022 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4023 DeclT = TDD->getUnderlyingType();
4024 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4025 DeclT = FD->getType();
4026 else
4027 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4028
4029 const char *startBuf = SM->getCharacterData(DeclLoc);
4030 const char *endBuf = startBuf;
4031 // scan backward (from the decl location) for the end of the previous decl.
4032 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4033 startBuf--;
4034
4035 // *startBuf != '^' if we are dealing with a pointer to function that
4036 // may take block argument types (which will be handled below).
4037 if (*startBuf == '^') {
4038 // Replace the '^' with '*', computing a negative offset.
4039 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4040 ReplaceText(DeclLoc, 1, "*", 1);
4041 }
4042 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4043 // Replace the '^' with '*' for arguments.
4044 DeclLoc = ND->getLocation();
4045 startBuf = SM->getCharacterData(DeclLoc);
4046 const char *argListBegin, *argListEnd;
4047 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4048 while (argListBegin < argListEnd) {
4049 if (*argListBegin == '^') {
4050 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4051 ReplaceText(CaretLoc, 1, "*", 1);
4052 }
4053 argListBegin++;
4054 }
4055 }
4056 return;
4057}
4058
4059void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4060 // Add initializers for any closure decl refs.
4061 GetBlockDeclRefExprs(Exp->getBody());
4062 if (BlockDeclRefs.size()) {
4063 // Unique all "by copy" declarations.
4064 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4065 if (!BlockDeclRefs[i]->isByRef())
4066 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4067 // Unique all "by ref" declarations.
4068 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4069 if (BlockDeclRefs[i]->isByRef()) {
4070 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4071 }
4072 // Find any imported blocks...they will need special attention.
4073 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004074 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004075 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004076 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4077 }
4078 }
4079}
4080
Steve Narofffa15fd92008-10-28 20:29:00 +00004081FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4082 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004083 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Narofffa15fd92008-10-28 20:29:00 +00004084 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor2224f842009-02-25 16:33:18 +00004085 ID, FType, FunctionDecl::Extern, false,
4086 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004087}
4088
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004089Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004090 Blocks.push_back(Exp);
4091
4092 CollectBlockDeclRefInfo(Exp);
4093 std::string FuncName;
4094
4095 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004096 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004097 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004098 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004099 // Convert colons to underscores.
4100 std::string::size_type loc = 0;
4101 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4102 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004103 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004104 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004105
4106 std::string BlockNumber = utostr(Blocks.size()-1);
4107
4108 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4109 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4110
4111 // Get a pointer to the function type so we can cast appropriately.
4112 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4113
4114 FunctionDecl *FD;
4115 Expr *NewRep;
4116
4117 // Simulate a contructor call...
4118 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004119 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004120
4121 llvm::SmallVector<Expr*, 4> InitExprs;
4122
Steve Narofffdc03722008-10-29 21:23:59 +00004123 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004124 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004125 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4126 SourceLocation());
4127 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4128 Context->VoidPtrTy, SourceLocation(),
4129 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004130 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004131
4132 if (ImportedBlockDecls.size()) {
4133 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004134 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004135 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4136 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4137 Context->VoidPtrTy, SourceLocation(),
4138 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004139 InitExprs.push_back(castExpr);
4140
Steve Narofffa15fd92008-10-28 20:29:00 +00004141 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004142 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004143 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4144 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4145 Context->VoidPtrTy, SourceLocation(),
4146 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004147 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004148 }
4149 // Add initializers for any closure decl refs.
4150 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004151 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004152 // Output all "by copy" declarations.
4153 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4154 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004155 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004156 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004157 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004158 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004159 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004160 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004161 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4162 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4163 Context->VoidPtrTy, SourceLocation(),
4164 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004165 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004166 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004167 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004168 }
Steve Narofffdc03722008-10-29 21:23:59 +00004169 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004170 }
4171 // Output all "by ref" declarations.
4172 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4173 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004174 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004175 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4176 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004177 Context->getPointerType(Exp->getType()),
4178 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004179 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004180 }
4181 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004182 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4183 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004184 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004185 Context->getPointerType(NewRep->getType()),
4186 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004187 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4188 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004189 BlockDeclRefs.clear();
4190 BlockByRefDecls.clear();
4191 BlockByCopyDecls.clear();
4192 ImportedBlockDecls.clear();
4193 return NewRep;
4194}
4195
4196//===----------------------------------------------------------------------===//
4197// Function Body / Expression rewriting
4198//===----------------------------------------------------------------------===//
4199
Steve Naroffc77a6362008-12-04 16:24:46 +00004200// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4201// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4202// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4203// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4204// Since the rewriter isn't capable of rewriting rewritten code, it's important
4205// we get this right.
4206void RewriteObjC::CollectPropertySetters(Stmt *S) {
4207 // Perform a bottom up traversal of all children.
4208 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4209 CI != E; ++CI)
4210 if (*CI)
4211 CollectPropertySetters(*CI);
4212
4213 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4214 if (BinOp->isAssignmentOp()) {
4215 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4216 PropSetters[PRE] = BinOp;
4217 }
4218 }
4219}
4220
Steve Narofffa15fd92008-10-28 20:29:00 +00004221Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4222 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4223 isa<DoStmt>(S) || isa<ForStmt>(S))
4224 Stmts.push_back(S);
4225 else if (isa<ObjCForCollectionStmt>(S)) {
4226 Stmts.push_back(S);
4227 ObjCBcLabelNo.push_back(++BcLabelCount);
4228 }
4229
4230 SourceRange OrigStmtRange = S->getSourceRange();
4231
4232 // Perform a bottom up rewrite of all children.
4233 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4234 CI != E; ++CI)
4235 if (*CI) {
4236 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4237 if (newStmt)
4238 *CI = newStmt;
4239 }
4240
4241 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4242 // Rewrite the block body in place.
4243 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4244
4245 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004246 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4247 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004248
4249 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4250 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004251 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004252 return blockTranscribed;
4253 }
4254 // Handle specific things.
4255 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4256 return RewriteAtEncode(AtEncode);
4257
4258 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4259 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4260
Steve Naroffc77a6362008-12-04 16:24:46 +00004261 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4262 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4263 if (BinOp) {
4264 // Because the rewriter doesn't allow us to rewrite rewritten code,
4265 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004266 DisableReplaceStmt = true;
4267 // Save the source range. Even if we disable the replacement, the
4268 // rewritten node will have been inserted into the tree. If the synthesized
4269 // node is at the 'end', the rewriter will fail. Consider this:
4270 // self.errorHandler = handler ? handler :
4271 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4272 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004273 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004274 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004275 //
4276 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4277 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4278 // to see the original expression). Consider this example:
4279 //
4280 // Foo *obj1, *obj2;
4281 //
4282 // obj1.i = [obj2 rrrr];
4283 //
4284 // 'BinOp' for the previous expression looks like:
4285 //
4286 // (BinaryOperator 0x231ccf0 'int' '='
4287 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4288 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4289 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4290 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4291 //
4292 // 'newStmt' represents the rewritten message expression. For example:
4293 //
4294 // (CallExpr 0x231d300 'id':'struct objc_object *'
4295 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4296 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4297 // (CStyleCastExpr 0x231d220 'void *'
4298 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4299 //
4300 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4301 // can be used as the setter argument. ReplaceStmt() will still 'see'
4302 // the original RHS (since we haven't altered BinOp).
4303 //
4304 // This implies the Rewrite* routines can no longer delete the original
4305 // node. As a result, we now leak the original AST nodes.
4306 //
Steve Naroffb619d952008-12-09 12:56:34 +00004307 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004308 } else {
4309 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004310 }
4311 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004312 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4313 return RewriteAtSelector(AtSelector);
4314
4315 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4316 return RewriteObjCStringLiteral(AtString);
4317
4318 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004319#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004320 // Before we rewrite it, put the original message expression in a comment.
4321 SourceLocation startLoc = MessExpr->getLocStart();
4322 SourceLocation endLoc = MessExpr->getLocEnd();
4323
4324 const char *startBuf = SM->getCharacterData(startLoc);
4325 const char *endBuf = SM->getCharacterData(endLoc);
4326
4327 std::string messString;
4328 messString += "// ";
4329 messString.append(startBuf, endBuf-startBuf+1);
4330 messString += "\n";
4331
4332 // FIXME: Missing definition of
4333 // InsertText(clang::SourceLocation, char const*, unsigned int).
4334 // InsertText(startLoc, messString.c_str(), messString.size());
4335 // Tried this, but it didn't work either...
4336 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004337#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004338 return RewriteMessageExpr(MessExpr);
4339 }
4340
4341 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4342 return RewriteObjCTryStmt(StmtTry);
4343
4344 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4345 return RewriteObjCSynchronizedStmt(StmtTry);
4346
4347 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4348 return RewriteObjCThrowStmt(StmtThrow);
4349
4350 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4351 return RewriteObjCProtocolExpr(ProtocolExp);
4352
4353 if (ObjCForCollectionStmt *StmtForCollection =
4354 dyn_cast<ObjCForCollectionStmt>(S))
4355 return RewriteObjCForCollectionStmt(StmtForCollection,
4356 OrigStmtRange.getEnd());
4357 if (BreakStmt *StmtBreakStmt =
4358 dyn_cast<BreakStmt>(S))
4359 return RewriteBreakStmt(StmtBreakStmt);
4360 if (ContinueStmt *StmtContinueStmt =
4361 dyn_cast<ContinueStmt>(S))
4362 return RewriteContinueStmt(StmtContinueStmt);
4363
4364 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4365 // and cast exprs.
4366 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4367 // FIXME: What we're doing here is modifying the type-specifier that
4368 // precedes the first Decl. In the future the DeclGroup should have
4369 // a separate type-specifier that we can rewrite.
4370 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4371
4372 // Blocks rewrite rules.
4373 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4374 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004375 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004376 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004377 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004378 RewriteBlockPointerDecl(ND);
4379 else if (ND->getType()->isFunctionPointerType())
4380 CheckFunctionPointerDecl(ND->getType(), ND);
4381 }
4382 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004383 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004384 RewriteBlockPointerDecl(TD);
4385 else if (TD->getUnderlyingType()->isFunctionPointerType())
4386 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4387 }
4388 }
4389 }
4390
4391 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4392 RewriteObjCQualifiedInterfaceTypes(CE);
4393
4394 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4395 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4396 assert(!Stmts.empty() && "Statement stack is empty");
4397 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4398 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4399 && "Statement stack mismatch");
4400 Stmts.pop_back();
4401 }
4402 // Handle blocks rewriting.
4403 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4404 if (BDRE->isByRef())
4405 RewriteBlockDeclRefExpr(BDRE);
4406 }
4407 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004408 if (CE->getCallee()->getType()->isBlockPointerType()) {
4409 Stmt *BlockCall = SynthesizeBlockCall(CE);
4410 ReplaceStmt(S, BlockCall);
4411 return BlockCall;
4412 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004413 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004414 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004415 RewriteCastExpr(CE);
4416 }
4417#if 0
4418 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004419 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004420 // Get the new text.
4421 std::string SStr;
4422 llvm::raw_string_ostream Buf(SStr);
4423 Replacement->printPretty(Buf);
4424 const std::string &Str = Buf.str();
4425
4426 printf("CAST = %s\n", &Str[0]);
4427 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4428 delete S;
4429 return Replacement;
4430 }
4431#endif
4432 // Return this stmt unmodified.
4433 return S;
4434}
4435
4436/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4437/// main file of the input.
4438void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4439 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004440 if (FD->isOverloadedOperator())
4441 return;
4442
Steve Narofffa15fd92008-10-28 20:29:00 +00004443 // Since function prototypes don't have ParmDecl's, we check the function
4444 // prototype. This enables us to rewrite function declarations and
4445 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004446 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004447
Douglas Gregor72971342009-04-18 00:02:19 +00004448 if (CompoundStmt *Body = FD->getBody(*Context)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004449 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004450 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004451 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004452 Body =
4453 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4454 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004455 CurrentBody = 0;
4456 if (PropParentMap) {
4457 delete PropParentMap;
4458 PropParentMap = 0;
4459 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004460 // This synthesizes and inserts the block "impl" struct, invoke function,
4461 // and any copy/dispose helper functions.
4462 InsertBlockLiteralsWithinFunction(FD);
4463 CurFunctionDef = 0;
4464 }
4465 return;
4466 }
4467 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenekeaab2062009-03-12 18:33:24 +00004468 if (CompoundStmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004469 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004470 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004471 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004472 Body =
4473 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4474 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004475 CurrentBody = 0;
4476 if (PropParentMap) {
4477 delete PropParentMap;
4478 PropParentMap = 0;
4479 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004480 InsertBlockLiteralsWithinMethod(MD);
4481 CurMethodDef = 0;
4482 }
4483 }
4484 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4485 ClassImplementation.push_back(CI);
4486 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4487 CategoryImplementation.push_back(CI);
4488 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4489 RewriteForwardClassDecl(CD);
4490 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4491 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004492 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004493 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004494 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004495 CheckFunctionPointerDecl(VD->getType(), VD);
4496 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004497 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004498 RewriteCastExpr(CE);
4499 }
4500 }
4501 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004502 if (VD->getInit()) {
4503 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004504 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004505 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004506 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004507 CurrentBody = 0;
4508 if (PropParentMap) {
4509 delete PropParentMap;
4510 PropParentMap = 0;
4511 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004512 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004513 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004514 GlobalVarDecl = 0;
4515
4516 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004517 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004518 RewriteCastExpr(CE);
4519 }
4520 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004521 return;
4522 }
4523 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004524 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004525 RewriteBlockPointerDecl(TD);
4526 else if (TD->getUnderlyingType()->isFunctionPointerType())
4527 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4528 return;
4529 }
4530 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4531 if (RD->isDefinition()) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00004532 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4533 e = RD->field_end(*Context); i != e; ++i) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004534 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004535 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004536 RewriteBlockPointerDecl(FD);
4537 }
4538 }
4539 return;
4540 }
4541 // Nothing yet.
4542}
4543
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004544void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004545 // Get the top-level buffer that this corresponds to.
4546
4547 // Rewrite tabs if we care.
4548 //RewriteTabs();
4549
4550 if (Diags.hasErrorOccurred())
4551 return;
4552
4553 // Create the output file.
4554
4555 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4556 llvm::raw_ostream *OutFile;
4557 if (OutFileName == "-") {
4558 OutFile = &llvm::outs();
4559 } else if (!OutFileName.empty()) {
4560 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004561 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4562 // set binary mode (critical for Windoze)
4563 true,
4564 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004565 OwnedStream.reset(OutFile);
4566 } else if (InFileName == "-") {
4567 OutFile = &llvm::outs();
4568 } else {
4569 llvm::sys::Path Path(InFileName);
4570 Path.eraseSuffix();
4571 Path.appendSuffix("cpp");
4572 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004573 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4574 // set binary mode (critical for Windoze)
4575 true,
4576 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004577 OwnedStream.reset(OutFile);
4578 }
4579
4580 RewriteInclude();
4581
Chris Lattner2b2453a2009-01-17 06:22:33 +00004582 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004583 Preamble.c_str(), Preamble.size(), false);
4584
Steve Naroff0aab7962008-11-14 14:10:01 +00004585 if (ClassImplementation.size() || CategoryImplementation.size())
4586 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004587
4588 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4589 // we are done.
4590 if (const RewriteBuffer *RewriteBuf =
4591 Rewrite.getRewriteBufferFor(MainFileID)) {
4592 //printf("Changed:\n");
4593 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4594 } else {
4595 fprintf(stderr, "No changes\n");
4596 }
Steve Narofface66252008-11-13 20:07:04 +00004597
Steve Naroff0aab7962008-11-14 14:10:01 +00004598 if (ClassImplementation.size() || CategoryImplementation.size()) {
4599 // Rewrite Objective-c meta data*
4600 std::string ResultStr;
4601 SynthesizeMetaDataIntoBuffer(ResultStr);
4602 // Emit metadata.
4603 *OutFile << ResultStr;
4604 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004605 OutFile->flush();
4606}
4607